Skip to content

Commit 57d7692

Browse files
committed
fix(mobile): render hearts with native color emoji fonts
Signed-off-by: Tom Brow <[email protected]>
1 parent ec7ea38 commit 57d7692

7 files changed

Lines changed: 306 additions & 1 deletion

File tree

‎mobile/lib/features/channels/message_content.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import '../../shared/custom_emoji/custom_emoji_provider.dart';
2727
import '../../shared/custom_emoji/custom_emoji_render.dart';
2828
import '../../shared/emoji/emoji_data_provider.dart';
2929
import '../../shared/emoji/emoji_only.dart';
30+
import '../../shared/emoji/native_emoji_md.dart';
3031
import 'channels_provider.dart';
3132
import 'media_viewer_page.dart';
3233
import 'message_content/link_normalizer.dart';

‎mobile/lib/features/channels/message_content/inline_components.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ List<MarkdownComponent> _useMessageInlineComponents({
6363
channelNames: inputs.channelNames,
6464
onChannelTap: channelTap,
6565
),
66+
NativeEmojiMd(finalContent),
6667
...MarkdownComponent.inlineComponents,
6768
],
6869
[inputs],

‎mobile/lib/shared/emoji/native_emoji_glyph.dart‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import 'package:flutter/foundation.dart';
22
import 'package:flutter/material.dart';
33

4+
import 'native_emoji_style.dart';
5+
46
/// A standalone system emoji whose visual centre matches its surrounding UI.
57
///
68
/// Apple's emoji glyphs sit slightly low inside Flutter's text box. Keep the
@@ -31,7 +33,7 @@ class NativeEmojiGlyph extends StatelessWidget {
3133
maxLines: 1,
3234
softWrap: false,
3335
textScaler: TextScaler.noScaling,
34-
style: TextStyle(fontSize: size, height: 1),
36+
style: nativeEmojiTextStyle.copyWith(fontSize: size, height: 1),
3537
);
3638
if (defaultTargetPlatform == TargetPlatform.iOS) {
3739
glyph = Transform.translate(offset: const Offset(0, -1), child: glyph);
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import 'package:flutter/widgets.dart';
2+
import 'package:gpt_markdown/gpt_markdown.dart';
3+
4+
import 'native_emoji_style.dart';
5+
6+
/// Paints native emoji with color fonts while preserving surrounding typography.
7+
///
8+
/// Match complete grapheme clusters from this message so selectors, skin tones,
9+
/// flags, keycaps and ZWJ sequences stay together. Text-presentation sequences
10+
/// using VS15 and default-text symbols without VS16 keep their text appearance.
11+
class NativeEmojiMd extends InlineMd {
12+
/// Creates a component matching only the emoji present in [content].
13+
NativeEmojiMd(String content) : _exp = _pattern(content);
14+
15+
final RegExp _exp;
16+
static final _emoji = RegExp(
17+
r'\p{Emoji_Presentation}|\uFE0F|\u20E3',
18+
unicode: true,
19+
);
20+
21+
static RegExp _pattern(String content) {
22+
final clusters =
23+
content.characters
24+
.where(
25+
(cluster) =>
26+
!cluster.contains('\uFE0E') && _emoji.hasMatch(cluster),
27+
)
28+
.toSet()
29+
.toList()
30+
..sort((a, b) => b.length.compareTo(a.length));
31+
if (clusters.isEmpty) return RegExp(r'(?!x)x');
32+
// A shorter emoji elsewhere in the message must not consume the start of
33+
// an explicit text-presentation or a longer emoji sequence.
34+
return RegExp(
35+
'(?:${clusters.map(RegExp.escape).join('|')})'
36+
r'(?![\uFE0E\uFE0F\u200D\u20E3]|\uD83C[\uDFFB-\uDFFF])',
37+
);
38+
}
39+
40+
@override
41+
RegExp get exp => _exp;
42+
43+
@override
44+
InlineSpan span(BuildContext context, String text, GptMarkdownConfig config) {
45+
return TextSpan(
46+
text: text,
47+
style: (config.style ?? const TextStyle()).merge(nativeEmojiTextStyle),
48+
);
49+
}
50+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import 'package:flutter/painting.dart';
2+
3+
/// Prefer color emoji fonts over monochrome symbols in the surrounding font.
4+
///
5+
/// Inter contains a heart glyph, so a fallback after Inter never gets selected
6+
/// for it, even when the text includes the emoji presentation selector.
7+
const nativeEmojiTextStyle = TextStyle(
8+
fontFamily: 'Apple Color Emoji',
9+
fontFamilyFallback: ['Noto Color Emoji', 'Segoe UI Emoji'],
10+
);
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import 'package:buzz/features/channels/message_content.dart';
2+
import 'package:buzz/shared/emoji/native_emoji_md.dart';
3+
import 'package:buzz/shared/emoji/native_emoji_style.dart';
4+
import 'package:buzz/shared/theme/theme.dart';
5+
import 'package:buzz/shared/custom_emoji/custom_emoji_provider.dart';
6+
import 'package:flutter/material.dart';
7+
import 'package:flutter_test/flutter_test.dart';
8+
9+
import '../../helpers/widget_helpers.dart';
10+
11+
Iterable<TextSpan> _spans(InlineSpan span) sync* {
12+
if (span is TextSpan) {
13+
yield span;
14+
for (final child in span.children ?? <InlineSpan>[]) {
15+
yield* _spans(child);
16+
}
17+
}
18+
}
19+
20+
void main() {
21+
test('keeps emoji graphemes intact and respects text presentation', () {
22+
const content =
23+
'❤ ❤️ ❤️‍🔥 ❤️‍🩹 ❤︎ 👍🏽 👩‍👩‍👧‍👦 🇺🇸 1️⃣ #️⃣ © ™ ® text';
24+
final component = NativeEmojiMd(content);
25+
expect(component.exp.allMatches(content).map((match) => match.group(0)), [
26+
'❤️',
27+
'❤️‍🔥',
28+
'❤️‍🩹',
29+
'👍🏽',
30+
'👩‍👩‍👧‍👦',
31+
'🇺🇸',
32+
'1️⃣',
33+
'#️⃣',
34+
]);
35+
expect(
36+
NativeEmojiMd('plain text 123').exp.hasMatch('plain text 123'),
37+
isFalse,
38+
);
39+
});
40+
41+
testWidgets('message emoji use color fonts without changing prose or code', (
42+
tester,
43+
) async {
44+
const content =
45+
'Thanks ❤️ **great ❤️** ❤︎ `❤️` [love ❤️](https://example.com)';
46+
await tester.pumpWidget(
47+
WidgetHelpers.testable(
48+
overrides: [customEmojiListProvider.overrideWithValue(const [])],
49+
child: const AppMarkdownTheme(
50+
child: MessageContent(
51+
content: content,
52+
channelNames: {'general': 'general'},
53+
),
54+
),
55+
),
56+
);
57+
await tester.pumpAndSettle();
58+
final spans = tester
59+
.widgetList<RichText>(
60+
find.byWidgetPredicate((widget) => widget is RichText),
61+
)
62+
.expand((richText) => _spans(richText.text))
63+
.toList();
64+
final emojiSpans = spans.where(
65+
(span) => span.style?.fontFamily == nativeEmojiTextStyle.fontFamily,
66+
);
67+
expect(emojiSpans.map((span) => span.text), ['❤️', '❤️', '❤️']);
68+
expect(
69+
emojiSpans.any((span) => span.style?.fontWeight == FontWeight.bold),
70+
isTrue,
71+
);
72+
expect(
73+
spans.any(
74+
(span) =>
75+
(span.text?.contains('Thanks') ?? false) &&
76+
span.style?.fontFamily == 'Inter',
77+
),
78+
isTrue,
79+
);
80+
expect(
81+
spans.any(
82+
(span) => span.text == '❤️' && span.style?.fontFamily == 'GeistMono',
83+
),
84+
isTrue,
85+
);
86+
expect(
87+
emojiSpans.any((span) => span.text?.contains('\uFE0E') ?? false),
88+
isFalse,
89+
);
90+
});
91+
}
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
import 'dart:io';
2+
import 'dart:ui' as ui;
3+
4+
import 'package:buzz/features/channels/message_content.dart';
5+
import 'package:buzz/features/channels/reaction_row.dart';
6+
import 'package:buzz/features/channels/timeline_message.dart';
7+
import 'package:buzz/shared/theme/theme.dart';
8+
import 'package:buzz/shared/custom_emoji/custom_emoji_provider.dart';
9+
import 'package:flutter/material.dart';
10+
import 'package:flutter/rendering.dart';
11+
import 'package:flutter/services.dart';
12+
import 'package:flutter_test/flutter_test.dart';
13+
import 'package:hooks_riverpod/hooks_riverpod.dart';
14+
15+
// Run on macOS to exercise real Inter and Apple color-emoji glyphs. The normal
16+
// widget-test font (Ahem) cannot distinguish a red emoji from a black symbol.
17+
// Optionally set HEART_SCREENSHOT to a PNG path to capture the real widgets.
18+
void main() {
19+
testWidgets(
20+
'hearts render in color in reactions and message bodies',
21+
(tester) async {
22+
await tester.runAsync(() async {
23+
final inter = FontLoader('Inter')
24+
..addFont(rootBundle.load('assets/fonts/InterVariable.ttf'));
25+
await inter.load();
26+
final emoji = FontLoader('Apple Color Emoji')
27+
..addFont(
28+
File(
29+
'/System/Library/Fonts/Apple Color Emoji.ttc',
30+
).readAsBytes().then((bytes) => bytes.buffer.asByteData()),
31+
);
32+
await emoji.load();
33+
});
34+
final scene = GlobalKey();
35+
final reaction = GlobalKey();
36+
final message = GlobalKey();
37+
final emojiOnly = GlobalKey();
38+
await tester.pumpWidget(
39+
ProviderScope(
40+
overrides: [customEmojiListProvider.overrideWithValue(const [])],
41+
child: MaterialApp(
42+
theme: AppTheme.light(),
43+
home: Scaffold(
44+
body: Center(
45+
child: RepaintBoundary(
46+
key: scene,
47+
child: Container(
48+
width: 360,
49+
color: Colors.white,
50+
padding: const EdgeInsets.all(24),
51+
child: Column(
52+
mainAxisSize: MainAxisSize.min,
53+
crossAxisAlignment: CrossAxisAlignment.start,
54+
children: [
55+
const Text('Reactions'),
56+
const SizedBox(height: 8),
57+
RepaintBoundary(
58+
key: reaction,
59+
child: ReactionRow(
60+
messageId: 'heart',
61+
reactions: const [
62+
TimelineReaction(
63+
emoji: '❤️',
64+
count: 5,
65+
reactedByCurrentUser: true,
66+
userPubkeys: [],
67+
),
68+
],
69+
onToggle: (_) {},
70+
),
71+
),
72+
const SizedBox(height: 24),
73+
const Text('Message text'),
74+
const SizedBox(height: 8),
75+
RepaintBoundary(
76+
key: message,
77+
child: const MessageContent(
78+
content: 'Thanks for the release ❤️ **Love it ❤️**',
79+
channelNames: {'general': 'general'},
80+
),
81+
),
82+
const SizedBox(height: 24),
83+
const Text('Emoji-only message'),
84+
const SizedBox(height: 8),
85+
RepaintBoundary(
86+
key: emojiOnly,
87+
child: const MessageContent(
88+
content: '❤️',
89+
channelNames: {'general': 'general'},
90+
scaleEmojiOnly: true,
91+
),
92+
),
93+
],
94+
),
95+
),
96+
),
97+
),
98+
),
99+
),
100+
),
101+
);
102+
await tester.pumpAndSettle();
103+
await tester.runAsync(() async {
104+
final screenshot = Platform.environment['HEART_SCREENSHOT'];
105+
if (screenshot != null) {
106+
final image = await _capture(scene);
107+
final png = (await image.toByteData(format: ui.ImageByteFormat.png))!;
108+
await File(screenshot).parent.create(recursive: true);
109+
await File(screenshot).writeAsBytes(png.buffer.asUint8List());
110+
image.dispose();
111+
}
112+
for (final entry in {
113+
'reaction': reaction,
114+
'message': message,
115+
'emoji-only message': emojiOnly,
116+
}.entries) {
117+
final image = await _capture(entry.value);
118+
final rgba = (await image.toByteData(
119+
format: ui.ImageByteFormat.rawRgba,
120+
))!;
121+
var redPixels = 0;
122+
for (var i = 0; i < rgba.lengthInBytes; i += 4) {
123+
final red = rgba.getUint8(i);
124+
if (red > 140 &&
125+
red > rgba.getUint8(i + 1) * 1.5 &&
126+
red > rgba.getUint8(i + 2) * 1.5 &&
127+
rgba.getUint8(i + 3) > 200) {
128+
redPixels++;
129+
}
130+
}
131+
image.dispose();
132+
expect(
133+
redPixels,
134+
greaterThan(20),
135+
reason:
136+
'${entry.key} must contain red emoji, not monochrome hearts',
137+
);
138+
}
139+
});
140+
},
141+
skip: !Platform.isMacOS,
142+
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
143+
);
144+
}
145+
146+
Future<ui.Image> _capture(GlobalKey key) {
147+
final boundary =
148+
key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
149+
return boundary.toImage(pixelRatio: 3);
150+
}

0 commit comments

Comments
 (0)