feat(profile): Material default avatar + square photo crop

Drop the DiceBear generated avatar (and dicebear_core/dicebear_styles/
flutter_svg): the default is again a Material coloured-initial disc from
the pubkey. Picking a photo now goes through a square crop step
(crop_your_image — pure Flutter, all platforms incl. desktop, Apache-2.0,
only pulls the image package we already had) before the 24 KB thumbnail.
This commit is contained in:
vjrj 2026-07-12 23:39:56 +02:00
parent 17612b8147
commit f6967e8cbb
8 changed files with 200 additions and 175 deletions

View file

@ -2,14 +2,16 @@ import 'package:flutter/material.dart';
import '../i18n/strings.g.dart';
import '../services/offer_thumbnail.dart' show offerThumbnailDataUri;
import 'photo_crop.dart';
import 'photo_pick.dart';
import 'theme.dart';
/// Lets the user choose a profile avatar: take/pick a photo (shrunk to a tiny
/// inline thumbnail) or remove it. With no photo, a generated avatar is used.
/// Lets the user choose a profile avatar: take/pick a photo, square-crop it, and
/// keep it as a tiny inline thumbnail or remove it. With no photo, the
/// coloured-initial disc is used.
///
/// Returns the new avatar value (a `data:` photo thumbnail), an empty string to
/// clear it (falls back to the generated avatar), or null when cancelled.
/// clear it (falls back to the coloured-initial disc), or null when cancelled.
Future<String?> showAvatarPicker(
BuildContext context, {
required String current,
@ -37,11 +39,11 @@ Future<String?> showAvatarPicker(
title: Text(t.avatar.fromPhoto),
onTap: () async {
final bytes = await pickPhoto(sheetContext);
if (bytes == null) return;
final uri = offerThumbnailDataUri(bytes, maxBytes: 24000);
if (sheetContext.mounted) {
Navigator.of(sheetContext).pop(uri ?? '');
}
if (bytes == null || !sheetContext.mounted) return;
final cropped = await cropToSquare(sheetContext, bytes);
if (cropped == null || !sheetContext.mounted) return;
final uri = offerThumbnailDataUri(cropped, maxBytes: 24000);
Navigator.of(sheetContext).pop(uri ?? '');
},
),
if (current.isNotEmpty) ...[

View file

@ -1,7 +1,4 @@
import 'package:dicebear_core/dicebear_core.dart' show Avatar, Style;
import 'package:dicebear_styles/thumbs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../services/offer_thumbnail.dart' show decodeDataUri;
import '../services/profile_cache.dart';
@ -9,10 +6,11 @@ import 'avatar.dart';
import 'seed_glyph.dart';
/// A small round avatar for a person. When they've set an avatar ([picture] — a
/// `data:` photo thumbnail or a `tane:seed:<glyph>` illustration) it's shown;
/// otherwise it falls back to a [GeneratedAvatar] drawn deterministically from
/// their [pubkey]. Same pubkey same picture on every device, so a person
/// stays visually recognizable without sharing anything.
/// `data:` photo thumbnail, or a legacy `tane:seed:<glyph>` illustration) it's
/// shown; otherwise it falls back to a standard disc coloured deterministically
/// from their [pubkey], carrying the first letter of their [name] (a person icon
/// when unknown). Same pubkey same colour on every device, so a person stays
/// visually recognizable without sharing anything.
class PeerAvatar extends StatelessWidget {
const PeerAvatar({
required this.pubkey,
@ -25,7 +23,7 @@ class PeerAvatar extends StatelessWidget {
final String pubkey;
final String? name;
/// The person's chosen avatar value; null/empty → the [GeneratedAvatar].
/// The person's chosen avatar value; null/empty → the coloured-initial disc.
final String? picture;
final double radius;
@ -49,61 +47,35 @@ class PeerAvatar extends StatelessWidget {
}
}
return GeneratedAvatar(pubkey: pubkey, name: name, radius: radius);
}
}
/// The `thumbs` DiceBear style, parsed once [Style.parse] validates the style
/// definition against its schema, which is not free to repeat per build.
final _thumbsStyle = Style.parse(thumbs);
/// Rendered-SVG memo keyed by pubkey, so a person's avatar is generated once and
/// reused across every rebuild and list row rather than re-rendered each time.
final _svgCache = <String, String>{};
/// Strips the `<metadata>` block (the style's CC0 licence notice) that
/// flutter_svg cannot parse and logs a warning for; CC0 requires no attribution
/// in the rendered image, and the licence still ships with the package source.
final _metadataElement = RegExp(r'<metadata\b[^>]*>.*?</metadata>', dotAll: true);
String _renderThumbs(String pubkey) =>
Avatar(_thumbsStyle, {'seed': pubkey}).svg.replaceAll(_metadataElement, '');
/// The deterministic default avatar for a person with no chosen [picture]: a
/// friendly DiceBear "thumbs" face (CC0) seeded from their [pubkey], so the same
/// key yields the same face on every device with nothing shared. Rendered as an
/// SVG (no network, no assets). Exposes [pubkey] so call sites/tests can find it.
class GeneratedAvatar extends StatelessWidget {
const GeneratedAvatar({
required this.pubkey,
this.name,
this.radius = 14,
super.key,
});
final String pubkey;
final String? name;
final double radius;
@override
Widget build(BuildContext context) {
final svg = _svgCache[pubkey] ??= _renderThumbs(pubkey);
return Semantics(
label: name,
image: true,
child: ClipOval(
child: SizedBox.square(
dimension: radius * 2,
child: SvgPicture.string(svg, fit: BoxFit.cover),
),
),
final letter = _initial(name);
return CircleAvatar(
radius: radius,
backgroundColor: peerAvatarColor(pubkey),
child: letter == null
? Icon(Icons.person_outline, size: radius, color: Colors.white)
: Text(
letter,
style: TextStyle(
color: Colors.white,
fontSize: radius,
fontWeight: FontWeight.w600,
),
),
);
}
static String? _initial(String? name) {
if (name == null) return null;
final trimmed = name.trim();
if (trimmed.isEmpty) return null;
// characters.first handles emoji/combining marks safely.
return trimmed.characters.first.toUpperCase();
}
}
/// A [PeerAvatar] that looks the person's published avatar up from the
/// [ProfileCache] (their kind:0 `picture`), falling back to the generated
/// pattern while it loads or when none is cached / no cache is available. Use at
/// [ProfileCache] (their kind:0 `picture`), falling back to the coloured-initial
/// disc while it loads or when none is cached / no cache is available. Use at
/// list/row sites (one avatar each); for many avatars of the same few people
/// (chat bubbles) resolve the picture once into state instead.
class CachedAvatar extends StatelessWidget {

View file

@ -0,0 +1,87 @@
import 'dart:typed_data';
import 'package:crop_your_image/crop_your_image.dart';
import 'package:flutter/material.dart';
import 'theme.dart';
/// Lets the user square-crop the picked [bytes] before it's saved as an avatar.
/// Returns the cropped image bytes, or null if cancelled. Pure Flutter (works on
/// every platform, desktop included) no native cropper, no plaintext on disk.
Future<Uint8List?> cropToSquare(BuildContext context, Uint8List bytes) {
return Navigator.of(context).push<Uint8List>(
MaterialPageRoute(
fullscreenDialog: true,
builder: (context) => _CropPage(bytes: bytes),
),
);
}
class _CropPage extends StatefulWidget {
const _CropPage({required this.bytes});
final Uint8List bytes;
@override
State<_CropPage> createState() => _CropPageState();
}
class _CropPageState extends State<_CropPage> {
final _controller = CropController();
var _cropping = false;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.black,
foregroundColor: Colors.white,
leading: IconButton(
key: const Key('crop.cancel'),
icon: const Icon(Icons.close),
onPressed: () => Navigator.of(context).pop(),
),
actions: [
if (_cropping)
const Padding(
padding: EdgeInsets.all(14),
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
)
else
IconButton(
key: const Key('crop.confirm'),
icon: const Icon(Icons.check),
onPressed: () {
setState(() => _cropping = true);
_controller.crop();
},
),
],
),
body: Crop(
image: widget.bytes,
controller: _controller,
aspectRatio: 1,
withCircleUi: true,
baseColor: Colors.black,
maskColor: Colors.black.withValues(alpha: 0.6),
cornerDotBuilder: (size, edgeAlignment) =>
const DotControl(color: seedGreen),
onCropped: (result) {
if (!mounted) return;
switch (result) {
case CropSuccess(:final croppedImage):
Navigator.of(context).pop(croppedImage);
case CropFailure():
setState(() => _cropping = false);
}
},
),
);
}
}