mirror of
https://github.com/block/buzz.git
synced 2026-10-31 06:21:34 +00:00
## Summary Inline code on mobile renders as **bold body text on a faint background wash** — no monospace face, no chip, and it cannot wrap. #5257 diagnosed this as a missing `highlightBuilder`. That is no longer the right fix. `gpt_markdown` 1.2.0 deprecates `highlightBuilder` (removal in 2.0.0), renders inline code as a real chip, and adds `InlineCodeStyle` for restyling it. The package author confirmed this on the issue. So this PR is an upgrade — 1.1.6 → 1.2.1 — plus one theme declaration, rather than the builder the issue originally asked for. **Where the style is declared.** `GptMarkdownThemeData` goes in `AppTheme._buildTheme`, which both `light()` and `dark()` call. That reaches all four `GptMarkdown` call sites — `message_content`, `transcript_item_widget`, `token_pill`, `custom_emoji_render` — so the style is stated once instead of per widget. A widget-level `inlineCodeStyle` would have covered channel messages only, leaving the other three on the package's defaults. **What is declared.** Face, size, ink, chip fill and outline — not the face alone. A face name on its own leaves the rest on the package's defaults, which put inline code at 14.1sp beside a fenced block's 13, on a neutral `onSurface` tint rather than the app's code surface. In dark that tint is *lighter* than the surface, while every other code surface in the app is recessed, so the chip read as a different kind of object. All of it now comes from one `CodeStyle` declaration that the fenced block reads from too, so the two cannot be edited apart. **Three adaptations the upgrade requires.** Each was found by running the gate, not by reading the changelog: 1. **`imageBuilder` widened** to `(context, url, width, height)`. This is a hard compile error, and it is **not listed in the package's migration guide**, which states "nothing here stops code compiling". Worth reporting upstream. 2. **`autolink` now defaults to `true`.** `normalizeBareLinks()` already rewrites bare URLs into Markdown links before rendering, so both would run. `message_content` opts out with `autolink: false` to keep current behaviour exactly. The migration guide argues for dropping the pre-processor instead — a better fix, but a behavioural change that belongs in its own PR. 3. **`gpt_markdown.dart` now re-exports `markdown_config.dart`**, making two direct imports redundant. `flutter analyze` reports `No issues found!` on 1.1.6 and flags both on 1.2.1, so these warnings are new, not pre-existing. **Deliberately out of scope.** The three non-message call sites now autolink bare URLs, since only `message_content` has a pre-processor to collide with. Custom inline components (`_MentionMd`, `CustomEmojiMd`, `_ChannelLinkMd`) could additionally declare `allScopesExceptLinkLabel` — 1.2.0 offers it as the fix for a `WidgetSpan` chip going blank inside a link label on iOS — but current behaviour is unchanged without it, so that stays a separate change. ### Related issue Fixes #5257 Duplicate scan: searched `gpt_markdown`, `inline code mobile`, `highlightBuilder` and `InlineCodeStyle` across both PRs and issues. No open PR touches inline code styling. #6135 (link labels) and #6166 (text selection) also touch mobile Markdown but address different defects. ### Testing Full gate, `just ci` — exit 0: | Stage | Result | |---|---| | Rust (33 suites) | 4768 passed, 0 failed | | Desktop | 5799 passed, 0 failed | | Mobile | **2011 passed**, 0 failed | | `flutter analyze` | `No issues found!` | | Desktop + web build | ok | Run on the branch with `main` merged in, so these numbers match what CI builds. **New regression test** — `renders inline code in the app code style`. It resolves the `CodeTextSpan` the package tags inline code with, which carries both the resolved `TextStyle` and the colours the chip behind it is painted with, so face, size, ink, fill and outline are all asserted rather than a widget's presence. It is negative-controlled: reverting only the theme declaration fails it with ```text Expected: a numeric value within <0.001> of <13.0> Actual: <14.1> ``` and dropping the declaration entirely falls back to `packages/gpt_markdown/JetBrainsMono` — so the test measures the real thing, and it would catch a future regression that silently drops the theme extension. The test passes `baseStyle: messageBodyTextStyle`, the style the message surfaces actually use; the widget's own fallback is the smaller `bodyMedium`, which would move the expected size. The test finds paragraphs with `find.byWidgetPredicate((widget) => widget is RichText)`, not `find.byType(RichText)`: inline code renders through `BidiRichText`, a `RichText` subclass, and `byType` matches exact runtime types. That is a hazard for any test that reads text back out of a paragraph, and one landed after this branch was cut: `message_content_custom_emoji_test.dart` arrived with #6996 and its `code keeps literal emoji while adjacent known tokens render` case reads a code span through `find.byType(RichText)`. It passes on `main` and fails on the merge result, which is what CI builds, so it went red only once CI was authorized. It now uses the same predicate. The two other `byType(RichText)` call sites — the rest of that file and `message_author_meta_test.dart` — were re-run and pass: their content carries no code span, so the exact type still matches. They were left alone. ### Screenshots Rendered through the real `MessageContent` widget with the app's own fonts loaded, at 390pt wide, 3x DPR. Sample text: ``Set `BUZZ_RELAY_URL` before launch, then run `just mobile-test` to verify.`` | | Before (1.1.6) | After (1.2.1) | |---|---|---| | Light |  |  | | Dark |  |  | Before: bold Inter on a flat wash, no chip edge, and `just mobile-test` breaks across the line with the wash simply ending. After: Geist Mono in a bordered, rounded chip, and the wrapped fragment gets its own chip on each line. --------- Signed-off-by: Tolga Cinisli <tolgacinisli@gmail.com> Co-authored-by: Tolga Cinisli <tolgacinisli@gmail.com>
124 lines
4.3 KiB
Dart
124 lines
4.3 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:gpt_markdown/gpt_markdown.dart';
|
|
|
|
import '../relay/relay.dart';
|
|
|
|
import 'custom_emoji.dart';
|
|
|
|
/// Default rendered height of an inline custom emoji, in logical pixels.
|
|
/// Roughly matches a line of body text so emoji sit on the baseline cleanly.
|
|
const double kCustomEmojiInlineSize = 20.0;
|
|
|
|
/// A single custom-emoji image rendered as a square, network-loaded glyph.
|
|
///
|
|
/// Reused everywhere a `:shortcode:` resolves to an image: inline in message
|
|
/// bodies, reaction pills, status, and the picker. Falls back to the literal
|
|
/// `:shortcode:` text if the image fails to load, so a broken URL never leaves
|
|
/// a blank gap.
|
|
class CustomEmojiImage extends StatelessWidget {
|
|
final String shortcode;
|
|
final String url;
|
|
final double size;
|
|
|
|
const CustomEmojiImage({
|
|
super.key,
|
|
required this.shortcode,
|
|
required this.url,
|
|
this.size = kCustomEmojiInlineSize,
|
|
});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final fallbackStyle = DefaultTextStyle.of(context).style;
|
|
return MediaImage(
|
|
url: url,
|
|
width: size,
|
|
height: size,
|
|
decodeWidth: size,
|
|
fit: BoxFit.contain,
|
|
filterQuality: FilterQuality.medium,
|
|
semanticLabel: ':$shortcode:',
|
|
errorBuilder: (_, _, _) => Text(':$shortcode:', style: fallbackStyle),
|
|
);
|
|
}
|
|
}
|
|
|
|
/// gpt_markdown inline component that replaces `:shortcode:` with an inline
|
|
/// [CustomEmojiImage] for *known* shortcodes only. Unknown `:foo:` is left as
|
|
/// plain text. Matched case-insensitively; resolved via the lowercase palette.
|
|
///
|
|
/// Parallel to the `_MentionMd` / `_ChannelLinkMd` components in
|
|
/// message_content.dart — add an instance to a `GptMarkdown.inlineComponents`
|
|
/// list (before the default components) to enable custom emoji in any markdown
|
|
/// surface.
|
|
class CustomEmojiMd extends InlineMd {
|
|
final Map<String, String> _urlByShortcode;
|
|
final double size;
|
|
late final RegExp _exp = _buildPattern(_urlByShortcode.keys);
|
|
|
|
/// Only include shortcodes present in the rendered [content]. gpt_markdown
|
|
/// embeds this pattern in a combined regex for every parsed text segment, so
|
|
/// unrelated community emoji must not make every message expensive to parse.
|
|
CustomEmojiMd(
|
|
List<CustomEmoji> palette, {
|
|
required String content,
|
|
this.size = kCustomEmojiInlineSize,
|
|
}) : _urlByShortcode = _referencedUrls(palette, content);
|
|
|
|
// Look ahead so adjacent tokens sharing a colon are both considered:
|
|
// :unknown:known: must still allow the known token to match.
|
|
static final _shortcodeScan = RegExp(
|
|
r'(?=:([a-z0-9_-]+):)',
|
|
caseSensitive: false,
|
|
);
|
|
|
|
static Map<String, String> _referencedUrls(
|
|
List<CustomEmoji> palette,
|
|
String content,
|
|
) {
|
|
final referenced = {
|
|
for (final match in _shortcodeScan.allMatches(content))
|
|
match.group(1)!.toLowerCase(),
|
|
};
|
|
if (referenced.isEmpty) return const {};
|
|
return {
|
|
for (final emoji in palette)
|
|
if (referenced.contains(emoji.shortcode)) emoji.shortcode: emoji.url,
|
|
};
|
|
}
|
|
|
|
@override
|
|
RegExp get exp => _exp;
|
|
|
|
@override
|
|
InlineSpan span(BuildContext context, String text, GptMarkdownConfig config) {
|
|
final raw = exp.firstMatch(text.trim())?.group(0);
|
|
if (raw == null) {
|
|
return TextSpan(text: text, style: config.style);
|
|
}
|
|
final shortcode = raw.substring(1, raw.length - 1).toLowerCase();
|
|
final url = _urlByShortcode[shortcode];
|
|
if (url == null) {
|
|
return TextSpan(text: text, style: config.style);
|
|
}
|
|
return WidgetSpan(
|
|
alignment: PlaceholderAlignment.middle,
|
|
child: CustomEmojiImage(shortcode: shortcode, url: url, size: size),
|
|
);
|
|
}
|
|
|
|
/// Build a regex matching `:shortcode:` for any known shortcode, longest
|
|
/// first so a longer name isn't shadowed by a shorter prefix. Matches nothing
|
|
/// when the palette is empty (a regex that can never match).
|
|
static RegExp _buildPattern(Iterable<String> shortcodes) {
|
|
final sorted = shortcodes.where((s) => s.trim().isNotEmpty).toSet().toList()
|
|
..sort((a, b) => b.length.compareTo(a.length));
|
|
if (sorted.isEmpty) {
|
|
// Never matches — gpt_markdown skips this component entirely.
|
|
return RegExp(r'(?!x)x');
|
|
}
|
|
final alternatives = sorted.map(RegExp.escape).join('|');
|
|
return RegExp(':(?:$alternatives):', caseSensitive: false);
|
|
}
|
|
}
|