Files
buzz/mobile/lib/features/profile/profile_avatar_draft.dart
John Matthew Tennant 21802f019e Keep transparency in mobile avatar photo crops (#9319)
## Summary

Choosing a transparent PNG as a profile photo on mobile produced an
avatar with a solid background on every client. The crop step always
re-encoded to JPEG
([`profile_avatar_crop_page.dart#L507`](44b3c4823f/mobile/lib/shared/widgets/profile_avatar_crop_page.dart (L507))),
and `ProfileImageAvatarDraft` always uploaded with `mimeType:
'image/jpeg'`
([`profile_avatar_draft.dart#L51`](44b3c4823f/mobile/lib/features/profile/profile_avatar_draft.dart (L51))).

- The crop encodes PNG when the 512px result has an alpha channel and
any pixel is transparent, and JPEG otherwise. Opaque photos, including
16-bit and low-bit-depth PNGs whose decoder reports zero alpha, keep the
smaller JPEG output.
- The draft labels its upload from the bytes' signature, using the
existing detector in `media_upload.dart`, now public as
`detectImageMimeType`.

### Related issue

None found.

### Testing

- `uploads a transparent photo crop as PNG` picks a transparent PNG,
crops and saves it, and checks the upload is `image/png` with a
transparent corner pixel. It fails on `main` with `Expected: 'image/png'
Actual: 'image/jpeg'`.
- `uploads an opaque 16-bit photo crop as JPEG` fails without the
alpha-channel guard, and the existing opaque-photo test now checks the
upload stays `image/jpeg`.
- On an iOS simulator against a local relay, I picked a transparent PNG
with an opaque red disc through the native photo picker, cropped it and
saved it. On `main` the stored avatar is a 512x512 JPEG with white
corners. With this change it is a 512x512 RGBA PNG with transparent
corners and the same red center.

| Before (`main`) | After |
| --- | --- |
| ![Settings avatar: red disc on a white
square](https://github.com/user-attachments/assets/6dc7470e-d677-4357-a74b-1c9d686cc2ee)
| ![Settings avatar: red disc on the avatar
background](https://github.com/user-attachments/assets/5e4f37bc-5afc-42dd-8532-d04a77db8959)
|

buzz-review-completed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: John Tennant <jtennant@squareup.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Maeve <be734facf808af9bc7720a1cb69aeb2a3d136149938eedf4d0667a70ef433961@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-17 06:58:36 -05:00

160 lines
5.4 KiB
Dart

import 'dart:typed_data';
import '../../shared/animated_avatar.dart';
import '../../shared/relay/relay.dart';
/// A prepared profile-avatar change that is uploaded only when the user saves.
sealed class ProfileAvatarDraft {
/// Creates a prepared profile-avatar draft.
const ProfileAvatarDraft();
/// Returns the avatar URL for this draft using [service] when upload is
/// required.
///
/// Implementations cache successful uploads for the same service so a
/// profile-publish retry does not create duplicate media. Failed uploads may
/// be retried, and changing services starts a new upload for that community.
Future<String> upload(MediaUploadService service);
}
/// An avatar draft that already has its final URL and needs no media upload.
final class ProfileUrlAvatarDraft extends ProfileAvatarDraft {
/// Creates a draft backed by [url].
const ProfileUrlAvatarDraft(this.url);
/// The URL that will be written to the profile.
final String url;
@override
Future<String> upload(MediaUploadService service) async => url;
}
/// A locally prepared still image awaiting upload on Save.
final class ProfileImageAvatarDraft extends ProfileAvatarDraft {
/// Creates a still-image draft from JPEG or PNG [bytes].
ProfileImageAvatarDraft(this.bytes);
/// The prepared JPEG or PNG payload.
final Uint8List bytes;
MediaUploadService? _uploadService;
Future<String>? _uploadedUrl;
@override
Future<String> upload(MediaUploadService service) async {
if (!identical(_uploadService, service)) {
_uploadService = service;
_uploadedUrl = null;
}
final existing = _uploadedUrl;
if (existing != null) return existing;
final upload = service
.uploadBytes(bytes, mimeType: detectImageMimeType(bytes))
.then((descriptor) => descriptor.url);
_uploadedUrl = upload;
try {
return await upload;
} catch (_) {
if (identical(_uploadedUrl, upload)) _uploadedUrl = null;
rethrow;
}
}
}
/// A locally prepared animated avatar and its still poster awaiting upload.
final class ProfileAnimatedAvatarDraft extends ProfileAvatarDraft {
/// Creates an animated draft from PNG [animation] and [poster] payloads.
ProfileAnimatedAvatarDraft({required this.animation, required this.poster});
/// The animated PNG payload.
final Uint8List animation;
/// The still PNG poster shown when animation is unavailable or disabled.
final Uint8List poster;
MediaUploadService? _uploadService;
Future<String>? _uploadedUrl;
Future<BlobDescriptor>? _posterUpload;
Future<BlobDescriptor>? _animationUpload;
Future<BlobDescriptor> _uploadPoster(MediaUploadService service) {
final existing = _posterUpload;
if (existing != null) return existing;
late final Future<BlobDescriptor> upload;
upload = service.uploadBytes(poster, mimeType: 'image/png').catchError((
Object error,
StackTrace stackTrace,
) {
if (identical(_posterUpload, upload)) _posterUpload = null;
Error.throwWithStackTrace(error, stackTrace);
});
_posterUpload = upload;
return upload;
}
Future<BlobDescriptor> _uploadAnimation(MediaUploadService service) {
final existing = _animationUpload;
if (existing != null) return existing;
late final Future<BlobDescriptor> upload;
upload = service.uploadBytes(animation, mimeType: 'image/png').catchError((
Object error,
StackTrace stackTrace,
) {
if (identical(_animationUpload, upload)) _animationUpload = null;
Error.throwWithStackTrace(error, stackTrace);
});
_animationUpload = upload;
return upload;
}
@override
Future<String> upload(MediaUploadService service) async {
if (!identical(_uploadService, service)) {
_uploadService = service;
_uploadedUrl = null;
_posterUpload = null;
_animationUpload = null;
}
final existing = _uploadedUrl;
if (existing != null) return existing;
// Cache each content-addressed part independently. If one request fails,
// retry only that part so a successful counterpart remains attached to
// this draft instead of becoming an abandoned duplicate.
final upload = Future.wait(
[_uploadPoster(service), _uploadAnimation(service)],
).then((uploads) => buildAnimatedAvatarUrl(uploads[0].url, uploads[1].url));
_uploadedUrl = upload;
try {
return await upload;
} catch (_) {
if (identical(_uploadedUrl, upload)) _uploadedUrl = null;
rethrow;
}
}
}
/// Transfers only local draft data between the app and its native sheet engine.
Map<String, Object?>? encodeProfileAvatarDraft(ProfileAvatarDraft? draft) =>
switch (draft) {
ProfileImageAvatarDraft(:final bytes) => {
'type': 'image',
'bytes': bytes,
},
ProfileAnimatedAvatarDraft(:final animation, :final poster) => {
'type': 'animated',
'animation': animation,
'poster': poster,
},
ProfileUrlAvatarDraft(:final url) => {'type': 'url', 'url': url},
null => null,
};
ProfileAvatarDraft? decodeProfileAvatarDraft(Map<dynamic, dynamic>? value) =>
switch (value?['type']) {
'image' => ProfileImageAvatarDraft(value!['bytes'] as Uint8List),
'animated' => ProfileAnimatedAvatarDraft(
animation: value!['animation'] as Uint8List,
poster: value['poster'] as Uint8List,
),
'url' => ProfileUrlAvatarDraft(value!['url'] as String),
_ => null,
};