Files
buzz/mobile/lib/features/channels/compose_bar/markdown_editing_controller.dart
Matt Toohey 2074adaa85 fix(mobile): bring @mention typing in line with buzz-app (#9699)
## Summary

The mobile composer's @mention typing was an older port of the mention
rules that [block/buzz-app](https://github.com/block/buzz-app) follows
(`src/bundled/mentions/README.md` there), and it trailed buzz-app in
nine places. Most of them came from one difference: mobile tied a picked
person to the `@Label` text and looked for that text again at send time,
while buzz-app keeps the recipient on an atomic chip. Several of the
gaps meant a picked person was silently not notified.

This PR fixes all nine. Every change is in `mobile/`; no relay, CLI or
desktop code is touched, and the event payloads mobile writes keep the
same shape.

### Commits

| Commit | Fixes | What it changes |
|---|---|---|
| 9152e91fe | 1, 2 | Picked people are atomic chips, as agents already
were. The recipient comes from the chips, so a pick after `(`, `[` or
`{` notifies. Backspace removes the trailing space, then the whole chip;
arrows step over a chip. |
| 2cbdabdae | 3, 4 | A chip is bound to its recipient by its position in
the draft and keeps it through punctuation, apostrophes, hyphens and
slashes. Namesake chips read `@Sam · a1b2`, and the draft text never
holds a public key. |
| c4d3f2072 | 5 | A chip's `@` never opens a query, so prose typed after
a pick sends no directory searches. A query that found nobody refutes
every longer query that continues it. |
| 4e4ac3efd | 6 | Name matching folds accents, full-width letters and
ligatures, and breaks words on hyphens and apostrophes. The vendored
contract fixture moves from version 1 to version 4, and all 125 cases
pass. |
| 38e8f2e1e | 7 | Closing punctuation (`. , ! ? ; :`, `)`, `]`, `}` and
closing quotes) selects an exact, unique name as Space does, and the
character stays after the chip. |
| e008151c6 | 8 | The chooser is shown only while the text field has
focus. The query and its rows are kept while hidden, so refocusing shows
the same rows without a new search. |
| 199606969 | 9 | The edit sheet mounts the composer's chooser through a
shared hook. A pick inserts a chip, and the saved edit adds no `p` tag.
|
| a1e4d69fa | 3 | The message renderer ends a mention where the composer
does, so a sent `@Honey's report` draws Honey's pill with the suffix as
text. |
| bf34af139 | 2 | iOS reports one Backspace as two editing updates
(select the character, then delete the selection). The controller
recognises that pair and removes the whole chip and its binding. |

### How to read the videos

Each video has three columns that follow the same numbered steps with
the same people and the same typed text: mobile before this PR on the
left, mobile on this branch in the middle, and buzz-app on the right.
The bar across the top names the current step, and a column that
finishes a step early holds its frame until the others catch up.

The dark panel on each phone is a readout added for the recording. Its
`p tags (notified)` line shows who a sent message would notify, and
`directory searches sent` counts requests to the directory. The readout
under the buzz-app composer shows the same facts.

### 1. A mention picked after a bracket keeps its recipient

`see (@Honey) please` went out with nobody notified, because the
send-time scan did not accept the brackets the chooser did. The
recipient now comes from the chip, and the typed-name fallback accepts
`(`, `[` and `{` too.


https://github.com/user-attachments/assets/b1f1c76b-b991-4f90-9079-a435c4475c2b

### 2. People mentions are atomic chips

A second Backspace used to leave plain `@Hone` (and `@Scou` for the
agent), which sent with no recipient. Now the first Backspace removes
the trailing space and the second removes the whole chip, and the arrow
keys step over a chip as one unit.


https://github.com/user-attachments/assets/a198656c-d735-46a7-a954-9e0aa4af7dc3

### 3. A suffix after a mention keeps the recipient

`@Honey's report` and `@Honey-bot is back` notified nobody. A chip now
survives an apostrophe (straight or curly), a hyphen, a slash or
punctuation typed against it, and the sent bubble draws the pill with
the suffix as text. Only a letter, mark, digit or underscore typed
against the chip unbinds it.


https://github.com/user-attachments/assets/c481110d-1633-4c01-9810-a8d750ce2ae2

### 4. No raw public key in the composer

Picking two people with the same name filled the draft with two
64-character keys. Each pick is now a chip with a short label, the draft
text stays `@Honey`, and each namesake gets their own `p` tag. The key
suffixes on the labels differ between the apps only because each
recording generated its own keys.


https://github.com/user-attachments/assets/4f56cddd-a96f-43cb-820b-511eb965a77b

### 5. No directory search while typing prose

Every character of a sentence typed after a pick was sent to the
directory as a name search: 20 searches in this clip. The count now
stays at 1, the same as buzz-app. A short query with no local match
still searches, so a person outside the channel is still found.


https://github.com/user-attachments/assets/3575b2cf-e3a6-42f1-9779-6e1401f00dfc

### 6. Accent folding and contract fixture version 4

`@jose` could not find José María, so `@jose maria` went out as plain
text. Names now fold accents, the row stays listed, and the pick is a
chip that notifies José María. The vendored fixture is version 4 of the
shared contract, copied unchanged, with no case skipped.


https://github.com/user-attachments/assets/362f6b4b-a09c-4f69-910e-8903408be77e

### 7. Closing punctuation selects an exact name

A comma typed straight after `@Honey` or `@Outside Person` joined the
query and closed the chooser; for a person outside the channel the
message went out with no recipient and no prompt. The comma now selects
the exact name, and Send shows the outside-channel prompt, where Invite
adds the person and sends with their `p` tag.


https://github.com/user-attachments/assets/b43a0663-489f-4ae3-ae36-7a2a92443f9e

### 8. The chooser follows the field's focus

Dragging the keyboard away collapsed the composer but left the chooser
row floating above it. The chooser now hides when the field loses focus
and returns with the same rows when focus comes back. Step 1 of the
mobile columns is sped up three times, because the on-screen keyboard is
slow to drive in the simulator.


https://github.com/user-attachments/assets/2ce0093d-03d0-4792-9b05-fb28980830fc

### 9. The chooser works in the edit sheet

The edit sheet was a plain text field with no chooser. It now uses the
composer's chooser with the same rules, and existing mentions open as
chips. The saved edit adds no `p` tag, matching buzz-app's rule that an
edit notifies nobody.


https://github.com/user-attachments/assets/e54d5620-ae2d-49b5-8cce-99536b8d81db

### Known gaps left for follow-up

- **Typed, unpicked names.** Mobile still notifies a typed name that
equals exactly one member and refuses to send an ambiguous one. buzz-app
does not do either, and the shared contract has not settled which is
right.
- **Directory-only names selected before the search finishes.** Space or
closing punctuation selects a directory-only name as soon as it is in
the ranked rows. buzz-app waits until that query's search has finished.
This predates the PR for Space and now also applies to punctuation.
- **Undo does not restore a chip.** After a letter typed against a chip
unbinds it, Undo restores the text but not the chip. iOS shake-to-undo
also bypasses the new undo detection.
- **Edits drop existing tags.** The timeline reads mention tags from the
edit event, so editing a message that already tagged someone still loses
that pill. Carrying the original tags through an edit is a separate
change.
- **`_@Name_` italics.** `_` now counts as a name character, as in
buzz-app, so `_@Honey_` no longer draws a pill.

### Related issue

N/A. None found; #9008 made the relay's name search accent-insensitive,
and fix 6 does the same for matching on the device.

### Testing

- `dart format`, `flutter analyze`, `just file-size-check` and the full
mobile `flutter test` suite passed on every commit. Two timing-sensitive
tests unrelated to mentions (relay socket liveness, community snapshot
cleanup) each failed once under full-suite load and passed solo.
- Each fix has a widget-test journey through the real composer, chooser
and send path, and each was shown to fail with its fix removed. The
shared contract fixture runs in full.
- The videos are harness recordings on an iPhone 17 simulator (iOS
27.2): the real channel page, composer, chooser, edit sheet and send
path on an in-memory relay, not the app against a live community. The
buzz-app column is a headless WebKit recording of buzz-app's fixture
pages.
- Android and physical devices were not exercised.
- The branch was pushed with `--no-verify`, so the pre-push lanes did
not run locally.

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

---------

Signed-off-by: Matt Toohey <contact@matttoohey.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-20 21:12:49 +00:00

1182 lines
41 KiB
Dart

part of '../compose_bar.dart';
enum _MarkdownStyle { codeBlock, inlineCode, bold, italic, strikethrough }
class _MarkdownRule {
final RegExp pattern;
final _MarkdownStyle style;
final bool parsesNestedFormatting;
_MarkdownRule(
String pattern,
this.style, {
this.parsesNestedFormatting = true,
}) : pattern = RegExp(pattern);
}
class _MarkdownEditingController extends TextEditingController {
_MarkdownEditingController({this.portableProse = false});
/// Set by the message edit sheet, whose chips are rewritten as identity
/// links in a body other Markdown readers also draw. A name is then prose
/// only where those readers agree with this bubble: not in a reference
/// whose definition differs only in case, and not in an indented code
/// block. The composer leaves it unset, so a send notifies wherever this
/// bubble draws a pill.
final bool portableProse;
/// Picked mentions bound to their recipients, in text order. The editor
/// stores the literal `@Label` the relay receives; each binding is carried
/// across edits by position, so two namesakes can both read `@Sam` and
/// still notify two people, and no key ever enters the text. Holds the
/// dormant bindings too; see [bindings].
List<_ComposerMention> _mentions = const [];
/// The bindings of [_mentions] that sit in prose; see [mentions].
List<_ComposerMention> _live = const [];
/// Set when a saved draft's bindings could not be read. The send refuses
/// until no `@` is left in the text, since nothing says who it was for.
bool _mentionsInvalid = false;
/// Display labels for chips whose name another candidate shares, by
/// lowercase key, such as `Sam · a1b2`. Display only.
Map<String, String> _mentionQualifiers = const {};
/// Set while Undo (-1) or Redo (1) restores an earlier value, which must
/// stay exact rather than be widened to a chip or given a space after a
/// link. Zero for every other edit.
int _historyDirection = 0;
/// The bindings held with each text of the current draft, oldest first,
/// and where the current text sits among them; a different draft starts
/// it again ([replaceDraft]). Undo and Redo restore text
/// alone, and identical neighbouring text (`@Sam @Sam`) cannot say whose
/// chip came back, so the restored text takes its bindings from here.
final List<({String text, List<_ComposerMention> mentions})> _history = [];
int _historyAt = -1;
static const _maxHistory = 200;
TextSpan? _cachedTextSpan;
String? _cachedText;
TextRange? _cachedComposingRange;
TextStyle? _cachedBaseStyle;
Color? _cachedOnSurface;
Color? _cachedSurface;
Map<String, String> _channelNames = const {};
/// Source ranges rendered as atomic chips in [_chipRangesText], recorded
/// while building the text span so deletion matches what is on screen.
String? _chipRangesText;
List<TextRange> _chipRanges = const [];
final List<TextRange> _pendingChipRanges = [];
/// The last selection the platform set that reached into a chip, and the
/// chip-wide selection it was snapped to in [_snappedText]. iOS selects
/// the character before the caret right before Backspace removes it; the
/// removal then matches this range rather than the snapped selection.
TextSelection? _platformSelection;
TextSelection? _snappedSelection;
String? _snappedText;
/// Where [buildTextSpan] last ran, so the chip ranges can be brought up
/// to date when edits arrive faster than frames.
BuildContext? _lastBuildContext;
/// Start of the link [buildTextSpan] last drew as raw text for the caret.
int? _revealedLinkStart;
/// The revealed link's range when it is otherwise a chip, so a selection
/// that stops revealing it still snaps to its edges.
TextRange? _revealedChip;
TextRange? _pendingRevealedChip;
/// Where the composer's Buzz links sit in [text] (URL only, without
/// trailing punctuation), computed once per text.
String? _linkRangesText;
List<TextRange> _linkRanges = const [];
static final _linkPattern = RegExp(
r'''buzz://(?:message\?|channel/|(?:repo|pr|issue)\?)[^\s<>"']+''',
caseSensitive: false,
);
static final _linkTrailingPunctuation = RegExp(r'[.,!?:;)\]}*]+$');
/// Text that already ends a link: whitespace, or closing punctuation and
/// Markdown delimiters followed by whitespace or the end of the text.
static final _existingBoundary = RegExp(r'[.,!?:;)\]}*_~]*(?:\s|$)');
/// Snaps a selection that would land inside a chip out to the chip's
/// edges, so a chip is always wholly inside or outside the selection. A
/// caret inside a chip moves to its nearer edge; at a link's end the link
/// then shows as raw text.
@override
set value(TextEditingValue newValue) {
final text = newValue.text;
if (text != value.text) {
if (_mentionsInvalid && !text.contains('@')) _mentionsInvalid = false;
if (_history.isEmpty) _recordHistory(value.text);
if (_historyDirection == 0) {
_carryMentions(value, newValue);
_recordHistory(text);
} else if (!_restoreHistory(text)) {
_carryMentions(value, newValue);
}
_live = _inProse(text, _mentions);
}
super.value = _snapSelectionToChips(newValue);
}
/// The picked mentions that are live in [text], in text order: the chips
/// drawn, the recipients of a send and the identity links of a saved
/// edit. A binding inside code or a web link is dormant and not here.
List<_ComposerMention> get mentions => _live;
/// Every picked mention bound in [text], in text order: [mentions] and
/// the dormant ones inside code or a web link. A dormant binding keeps
/// its recipient and moves with the text like any other, so a pick
/// wrapped in code and then unwrapped by hand is the same person again
/// and not a typed name. Saved drafts and restored text carry these.
List<_ComposerMention> get bindings => _mentions;
/// Whether a restored draft's bindings were unreadable; see [replaceDraft].
bool get mentionsInvalid => _mentionsInvalid;
/// Moves every binding across the edit from [old] to [next]: a mention
/// the edit reached into is gone, as is one a name character now
/// continues (`@Bobby`); punctuation, quotes, hyphens and slashes typed
/// against a chip keep it and its recipient (`@Bob's`).
void _carryMentions(TextEditingValue old, TextEditingValue next) {
if (_mentions.isEmpty) return;
final replaced = editReplacedRange(
old.text,
next.text,
oldSelection: old.selection,
newSelection: next.selection,
);
final ranges = remapMentionRanges(
[for (final mention in _mentions) mention.range],
replaced: replaced,
oldLength: old.text.length,
newText: next.text,
);
_mentions = List.unmodifiable([
for (var i = 0; i < ranges.length; i++)
if (ranges[i] case final range?) _mentions[i].at(range),
]);
}
/// The [mentions] that sit in the prose of [text]: outside the code spans
/// and blocks drawn in it, and outside every Markdown link, image and URL
/// ([mentionsInsideMarkdownLinks]). Code and link text are literal: a name
/// there draws no pill in the bubble and notifies nobody, so a binding
/// that lands there is dormant, whether a command wrapped a chip, the
/// syntax was typed around it, a pick was made inside it or a saved draft
/// held it. Text without a backtick, a `]` or a `://` costs three
/// searches.
List<_ComposerMention> _inProse(
String text,
List<_ComposerMention> mentions,
) {
if (mentions.isEmpty) return mentions;
var kept = mentions;
if (text.contains('`')) {
final code = _styledCodeRanges(text);
kept = [
for (final mention in mentions)
if (!code.any((c) => c.start < mention.start && mention.end < c.end))
mention,
];
}
final linked = mentionsInsideMarkdownLinks(text, [
for (final mention in kept) mention.range,
], portable: portableProse);
if (linked.isEmpty && identical(kept, mentions)) return mentions;
return List.unmodifiable([
for (var i = 0; i < kept.length; i++)
if (!linked.contains(i)) kept[i],
]);
}
/// Sets [newValue] and the mentions bound in it in one notification, so
/// no listener sees the text without its bindings: a restored or
/// recovered draft, a prefill, or a cleared composer. [mentionsInvalid]
/// marks a draft whose saved bindings could not be read.
///
/// The value starts a different draft unless [sameDraft] is set, as a
/// command editing the current one sets it: the binding history is
/// dropped, so an Undo that brings back the text of a sent, cleared or
/// other draft brings back no pick made there.
void replaceDraft(
TextEditingValue newValue, {
required List<_ComposerMention> mentions,
bool mentionsInvalid = false,
bool sameDraft = false,
}) {
if (!sameDraft) {
_history.clear();
_historyAt = -1;
} else if (_history.isEmpty) {
_recordHistory(value.text);
}
_mentions = List.unmodifiable(
mentions.toList()..sort((a, b) => a.start.compareTo(b.start)),
);
_live = _inProse(newValue.text, _mentions);
_mentionsInvalid = mentionsInvalid;
_cachedTextSpan = null;
_recordHistory(newValue.text);
final snapped = _snapSelectionToChips(newValue);
final unchanged = value == snapped;
super.value = snapped;
if (unchanged) notifyListeners();
}
/// Replaces the `@query` at `[start, end)` with `@Label` and [separator]
/// (a space, or the closing punctuation that selected the name) bound to
/// [candidate], caret after the separator. Mentions after it move with
/// the text in the same notification.
void insertMention({
required int start,
required int end,
required MentionCandidate candidate,
String separator = ' ',
}) {
final label = candidate.label;
final replacement = '@$label$separator';
replaceRange(
start: start,
end: end,
replacement: replacement,
caret: start + replacement.length,
added: _ComposerMention(
start: start,
end: start + 1 + label.length,
candidate: candidate,
),
);
}
/// Replaces `[start, end)` with [replacement] for a composer command, the
/// caret at [caret], and moves the bound mentions in the same
/// notification. A command knows exactly what it replaced, where a typed
/// edit is inferred from the selection: formatting wrapped around a
/// selected chip keeps the chip (see [remapMentionRanges] for
/// [keptShift]), and text a share appends never takes a chip's key.
void replaceRange({
required int start,
required int end,
required String replacement,
required int caret,
int? keptShift,
_ComposerMention? added,
}) {
final next = TextEditingValue(
text: text.replaceRange(start, end, replacement),
selection: TextSelection.collapsed(offset: caret),
);
final carried = remapMentionRanges(
[for (final mention in _mentions) mention.range],
replaced: TextRange(start: start, end: end),
oldLength: text.length,
newText: next.text,
keptShift: keptShift,
);
replaceDraft(
next,
mentions: [
for (var i = 0; i < carried.length; i++)
if (carried[i] case final range?) _mentions[i].at(range),
?added,
],
mentionsInvalid: _mentionsInvalid && next.text.contains('@'),
sameDraft: true,
);
}
/// Updates the display labels of namesake chips (lowercase key to label
/// such as `Sam · a1b2`). The text keeps `@Sam`.
void setMentionQualifiers(Map<String, String> qualifiers) {
if (mapEquals(_mentionQualifiers, qualifiers)) return;
_mentionQualifiers = Map.unmodifiable(qualifiers);
_cachedTextSpan = null;
notifyListeners();
}
TextEditingValue _snapSelectionToChips(TextEditingValue next) {
_refreshChipRanges(next.text);
_platformSelection = _snappedSelection = _snappedText = null;
final selection = next.selection;
if ((_chipRanges.isEmpty && _revealedChip == null) ||
next.text != _chipRangesText ||
!selection.isValid ||
(next.composing.isValid && !next.composing.isCollapsed)) {
return next;
}
// A revealed link turns back into a chip once the selection leaves it,
// so it snaps like one when this selection reaches past it.
final revealedChip = _revealedChip;
final chips =
revealedChip != null &&
_revealedLinkFor(next.text, selection) != revealedChip
? [..._chipRanges, revealedChip]
: _chipRanges;
var start = selection.start;
var end = selection.end;
for (final chip in chips) {
if (selection.isCollapsed) {
if (chip.start < start && start < chip.end) {
// The chip draws as one glyph at its first offset, so a tap on its
// right half (or an arrow right from its start) lands just after
// that glyph and goes to the chip's end. Arrow or word moves left
// into the hidden source step over the chip to its start.
final from = value.selection.isCollapsed
? value.selection.baseOffset
: -1;
final arrowLeftFromEnd = from == chip.end && start == chip.end - 1;
final towardEnd = start == chip.start + 1 && !arrowLeftFromEnd
? true
: from >= chip.end
? false
: from >= 0 && from <= chip.start
? true
: start - chip.start > chip.end - start;
start = end = towardEnd ? chip.end : chip.start;
}
continue;
}
if (chip.start < start && start < chip.end) start = chip.start;
if (chip.start < end && end < chip.end) end = chip.end;
}
if (start == selection.start && end == selection.end) return next;
final snapped = selection.isCollapsed
? TextSelection.collapsed(offset: start)
: selection.baseOffset <= selection.extentOffset
? TextSelection(baseOffset: start, extentOffset: end)
: TextSelection(baseOffset: end, extentOffset: start);
_platformSelection = selection;
_snappedSelection = snapped;
_snappedText = next.text;
return next.copyWith(selection: snapped);
}
List<TextRange> _linkRangesIn(String source) {
if (_linkRangesText == source) return _linkRanges;
_linkRangesText = source;
return _linkRanges = List.unmodifiable(_renderedLinkRanges(source, 0));
}
/// The links [buildTextSpan] draws in [source], split by Markdown the same
/// way, so a closing `_` or `~~` stays outside the link it wraps.
List<TextRange> _renderedLinkRanges(String source, int sourceOffset) {
final ranges = <TextRange>[];
void addLinks(int start, int end) {
for (final match in _linkPattern.allMatches(
source.substring(start, end),
)) {
final trailing = _linkTrailingPunctuation
.firstMatch(match.group(0)!)
?.group(0);
ranges.add(
TextRange(
start: sourceOffset + start + match.start,
end: sourceOffset + start + match.end - (trailing?.length ?? 0),
),
);
}
}
var offset = 0;
while (offset < source.length) {
final tail = source.substring(offset);
_MarkdownRule? nextRule;
RegExpMatch? nextMatch;
for (final rule in _rules) {
final match = rule.pattern.firstMatch(tail);
if (match == null) continue;
if (nextMatch == null || match.start < nextMatch.start) {
nextRule = rule;
nextMatch = match;
}
}
if (nextRule == null || nextMatch == null) {
addLinks(offset, source.length);
break;
}
addLinks(offset, offset + nextMatch.start);
if (nextRule.parsesNestedFormatting) {
final (contentStart, _) = _contentBounds(
nextMatch.group(0)!,
nextRule.style,
);
ranges.addAll(
_renderedLinkRanges(
nextMatch.group(1)!,
sourceOffset + offset + nextMatch.start + contentStart,
),
);
}
offset += nextMatch.end;
}
return ranges;
}
/// The link shown as raw text because the selection sits in it: a caret
/// at its end (or a selection inside it, entered from there). A caret at
/// its start leaves it a chip.
TextRange? _revealedLinkFor(String source, TextSelection selection) {
if (!selection.isValid) return null;
for (final link in _linkRangesIn(source)) {
if (selection.start > link.start && selection.end <= link.end) {
return link;
}
}
return null;
}
void setChannelNames(Map<String, String> names) {
if (mapEquals(_channelNames, names)) return;
_channelNames = Map.unmodifiable(names);
_cachedTextSpan = null;
notifyListeners();
}
static final _rules = [
_MarkdownRule(
r'```(?:\r?\n)?([\s\S]*?)(?:\r?\n)?```',
_MarkdownStyle.codeBlock,
parsesNestedFormatting: false,
),
_MarkdownRule(
r'`([^`\n]*?)`',
_MarkdownStyle.inlineCode,
parsesNestedFormatting: false,
),
_MarkdownRule(r'\*\*([^\n]*?)\*\*', _MarkdownStyle.bold),
_MarkdownRule(r'~~([^\n]*?)~~', _MarkdownStyle.strikethrough),
_MarkdownRule(r'_([^_\n]*?)_', _MarkdownStyle.italic),
];
@override
TextSpan buildTextSpan({
required BuildContext context,
TextStyle? style,
required bool withComposing,
}) {
_lastBuildContext = context;
final baseStyle = style ?? const TextStyle();
final composingRange =
withComposing && value.composing.isValid && !value.composing.isCollapsed
? value.composing
: TextRange.empty;
final colors = context.colors;
final revealedLinkStart = _revealedLinkFor(text, selection)?.start;
if (_cachedTextSpan case final cached?
when _cachedText == text &&
_revealedLinkStart == revealedLinkStart &&
_cachedComposingRange == composingRange &&
_cachedBaseStyle == baseStyle &&
_cachedOnSurface == colors.onSurface &&
_cachedSurface == colors.surface) {
return cached;
}
_revealedLinkStart = revealedLinkStart;
List<InlineSpan> buildChildren(TextRange composing) {
_pendingChipRanges.clear();
_pendingRevealedChip = null;
return _buildMarkdownSpans(
context,
text,
baseStyle,
sourceOffset: 0,
composingRange: composing,
);
}
// An IME such as Gboard can compose the hidden source of a chip (the
// word before the caret). That composition stays invisible, so it must
// not split the chip back into raw text.
var children = buildChildren(TextRange.empty);
if (!composingRange.isCollapsed &&
!_withinChip(composingRange, _pendingChipRanges)) {
children = buildChildren(composingRange);
}
final span = TextSpan(style: baseStyle, children: children);
_cachedText = text;
_cachedComposingRange = composingRange;
_cachedBaseStyle = baseStyle;
_cachedOnSurface = colors.onSurface;
_cachedSurface = colors.surface;
_cachedTextSpan = span;
_chipRangesText = text;
_chipRanges = List.unmodifiable(_pendingChipRanges);
_revealedChip = _pendingRevealedChip;
return span;
}
/// Applies the composer's chip editing rules to a user edit.
TextEditingValue formatUserEdit(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
// Undo and Redo restore an earlier value exactly, and must stay exact.
if (_historyDirection != 0) return newValue;
return _spaceAfterPastedLink(
oldValue,
expandChipDeletion(oldValue, newValue),
);
}
/// Adds a space after a link pasted on its own, so it becomes a chip
/// straight away. Pasted text with anything besides one link that renders
/// as a chip, a link that already has a boundary after it (including a
/// closing Markdown delimiter), and Undo or Redo back to an earlier value
/// are unchanged.
TextEditingValue _spaceAfterPastedLink(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
final oldSelection = oldValue.selection;
if (!oldSelection.isValid ||
(newValue.composing.isValid && !newValue.composing.isCollapsed)) {
return newValue;
}
final oldText = oldValue.text;
final newText = newValue.text;
final start = oldSelection.start;
final end = oldSelection.end;
final insertedEnd = newText.length - (oldText.length - end);
if (insertedEnd - start < 2 ||
!newText.startsWith(oldText.substring(0, start)) ||
!newText.endsWith(oldText.substring(end))) {
return newValue;
}
final inserted = newText.substring(start, insertedEnd);
final match = _linkPattern.matchAsPrefix(inserted);
if (match == null ||
_composerLinkPresentation(inserted) == null ||
_isInCode(newText, start, insertedEnd) ||
match.end != inserted.length ||
_linkTrailingPunctuation.hasMatch(inserted) ||
(insertedEnd < newText.length &&
(_existingBoundary.matchAsPrefix(newText, insertedEnd) != null ||
_renderedLinkRanges(
newText,
0,
).contains(TextRange(start: start, end: insertedEnd))))) {
return newValue;
}
return TextEditingValue(
text: newText.replaceRange(insertedEnd, insertedEnd, ' '),
selection: TextSelection.collapsed(offset: insertedEnd + 1),
);
}
/// The code spans and blocks [buildTextSpan] draws in [source]: the same
/// leftmost-rule walk, so a delimiter that bold or italics consume does not
/// pair as code.
List<TextRange> _styledCodeRanges(String source, [int at = 0]) {
final ranges = <TextRange>[];
var offset = 0;
while (offset < source.length) {
final tail = source.substring(offset);
_MarkdownRule? nextRule;
RegExpMatch? nextMatch;
for (final rule in _rules) {
final match = rule.pattern.firstMatch(tail);
if (match == null) continue;
if (nextMatch == null || match.start < nextMatch.start) {
nextRule = rule;
nextMatch = match;
}
}
if (nextRule == null || nextMatch == null) break;
final start = at + offset + nextMatch.start;
if (nextRule.parsesNestedFormatting) {
final (contentStart, _) = _contentBounds(
nextMatch.group(0)!,
nextRule.style,
);
ranges.addAll(
_styledCodeRanges(nextMatch.group(1)!, start + contentStart),
);
} else {
ranges.add(TextRange(start: start, end: at + offset + nextMatch.end));
}
offset += nextMatch.end;
}
return ranges;
}
/// Whether [start, end) sits inside inline or fenced code, where links
/// stay raw text rather than chips.
static bool _isInCode(String source, int start, int end) => _rules.any(
(rule) =>
!rule.parsesNestedFormatting &&
rule.pattern
.allMatches(source)
.any((code) => code.start < start && end < code.end),
);
/// Widens a backspace or forward delete that removes part of a chip's
/// hidden source so it removes the whole chip. Each chip draws its whole
/// URL or `@label` as one glyph, so backspace right after it would
/// otherwise remove one invisible character of the source and leave a
/// broken token behind. The deletion arrives either against a collapsed
/// caret (Android, hardware keys in tests) or, as iOS reports it from the
/// hardware key and the on-screen delete key alike, as two updates: the
/// character before the caret is selected first, then that selection is
/// removed. The selection step snaps to the whole chip, so the removal is
/// recognised by matching the platform's own selection rather than the
/// snapped one. Any other edit over a selection replaces exactly that
/// selection, so typed text is kept and Cut never removes more than it
/// copies.
TextEditingValue expandChipDeletion(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
_refreshChipRanges(oldValue.text);
final oldSelection = oldValue.selection;
if (_chipRanges.isEmpty ||
_chipRangesText != oldValue.text ||
!oldSelection.isValid ||
!_withinChip(oldValue.composing, _chipRanges) ||
!_withinChip(newValue.composing, _chipRanges)) {
return newValue;
}
final newSelection = newValue.selection;
if (!newSelection.isValid || !newSelection.isCollapsed) return newValue;
final deleted = oldSelection.isCollapsed
? _caretDeletion(
oldValue.text,
newValue.text,
oldSelection.baseOffset,
newSelection.baseOffset,
)
: _platformSelectionDeletion(oldValue, newValue);
if (deleted == null) return newValue;
// A link the caret has revealed edits as raw text, even before the next
// frame drops its chip.
final revealed = _revealedLinkFor(oldValue.text, oldSelection);
var expandedStart = deleted.start;
var expandedEnd = deleted.end;
for (final chip in _chipRanges) {
if (chip == revealed) continue;
// A deletion reaching into a chip, such as backspace or a word delete
// that runs past it, takes the whole chip.
if (deleted.start < chip.end && chip.start < deleted.end) {
expandedStart = math.min(expandedStart, chip.start);
expandedEnd = math.max(expandedEnd, chip.end);
}
}
if (expandedStart == deleted.start && expandedEnd == deleted.end) {
return newValue;
}
return TextEditingValue(
text: oldValue.text.replaceRange(expandedStart, expandedEnd, ''),
selection: TextSelection.collapsed(offset: expandedStart),
);
}
/// Rebuilds the span for [text], recording its chip ranges, when an edit
/// or selection change arrives before a frame has drawn the previous
/// edit. IME batches can send two backspaces or Shift+Left presses in a
/// row.
void _refreshChipRanges(String text) {
final context = _lastBuildContext;
if (_chipRangesText == text ||
value.text != text ||
context == null ||
!context.mounted) {
return;
}
buildTextSpan(
context: context,
style: _cachedBaseStyle,
withComposing: true,
);
}
/// Whether [composing] is empty or lies inside one of [chips], where it
/// is invisible and must not keep the chip from acting as one unit.
static bool _withinChip(TextRange composing, List<TextRange> chips) =>
!composing.isValid ||
composing.isCollapsed ||
chips.any(
(chip) => chip.start <= composing.start && composing.end <= chip.end,
);
/// The run a collapsed caret deleted: one ending at it (backspace, which
/// moves the caret back) or starting at it (forward delete, which leaves
/// the caret in place), or null for any other edit. The caret's movement
/// tells the two apart when repeated characters make the text ambiguous.
static TextRange? _caretDeletion(
String oldText,
String newText,
int caret,
int newCaret,
) {
final removed = oldText.length - newText.length;
if (removed <= 0) return null;
bool removes(int start, int end) =>
start >= 0 &&
end <= oldText.length &&
newText.startsWith(oldText.substring(0, start)) &&
newText.endsWith(oldText.substring(end));
if (newCaret == caret - removed && removes(caret - removed, caret)) {
return TextRange(start: caret - removed, end: caret);
}
if (newCaret == caret && removes(caret, caret + removed)) {
return TextRange(start: caret, end: caret + removed);
}
return null;
}
/// The range the platform removed when [oldValue] carries the snapped
/// form of a selection the platform set inside a chip and [newValue] is
/// [oldValue] with exactly that platform selection gone, caret at its
/// start. Null for any other edit, including text typed over a selection.
TextRange? _platformSelectionDeletion(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
final platform = _platformSelection;
if (platform == null ||
_snappedText != oldValue.text ||
_snappedSelection != oldValue.selection) {
return null;
}
final oldText = oldValue.text;
final start = platform.start;
final end = platform.end;
if (newValue.selection.baseOffset != start ||
newValue.text != oldText.replaceRange(start, end, '')) {
return null;
}
return TextRange(start: start, end: end);
}
List<InlineSpan> _buildMarkdownSpans(
BuildContext context,
String source,
TextStyle inheritedStyle, {
required int sourceOffset,
required TextRange composingRange,
}) {
final spans = <InlineSpan>[];
var offset = 0;
while (offset < source.length) {
final tail = source.substring(offset);
_MarkdownRule? nextRule;
RegExpMatch? nextMatch;
for (final rule in _rules) {
final match = rule.pattern.firstMatch(tail);
if (match == null) continue;
if (nextMatch == null || match.start < nextMatch.start) {
nextRule = rule;
nextMatch = match;
}
}
if (nextRule == null || nextMatch == null) {
spans.addAll(
_buildTextSpans(
context,
source.substring(offset),
inheritedStyle,
sourceOffset + offset,
composingRange,
),
);
break;
}
if (nextMatch.start > 0) {
spans.addAll(
_buildTextSpans(
context,
tail.substring(0, nextMatch.start),
inheritedStyle,
sourceOffset + offset,
composingRange,
),
);
}
final fullMatch = nextMatch.group(0)!;
final content = nextMatch.group(1)!;
final (contentStart, contentEnd) = _contentBounds(
fullMatch,
nextRule.style,
);
final contentStyle = _styleFor(context, inheritedStyle, nextRule.style);
final matchOffset = sourceOffset + offset + nextMatch.start;
spans.add(
TextSpan(
text: fullMatch.substring(0, contentStart),
style: _hiddenSyntaxStyle(inheritedStyle),
),
);
if (nextRule.parsesNestedFormatting) {
spans.addAll(
_buildMarkdownSpans(
context,
content,
contentStyle,
sourceOffset: matchOffset + contentStart,
composingRange: composingRange,
),
);
} else {
spans.addAll(
_buildTextSpans(
context,
content,
contentStyle,
matchOffset + contentStart,
composingRange,
renderMentions: false,
),
);
}
spans.add(
TextSpan(
text: fullMatch.substring(contentEnd),
style: _hiddenSyntaxStyle(inheritedStyle),
),
);
offset += nextMatch.end;
}
return spans;
}
List<InlineSpan> _buildTextSpans(
BuildContext context,
String source,
TextStyle style,
int sourceOffset,
TextRange composingRange, {
bool renderMentions = true,
}) {
List<InlineSpan> buildTextSegment(
String text,
TextStyle segmentStyle,
int segmentOffset,
) => renderMentions
? _buildMentionSpans(
context,
text,
segmentStyle,
sourceOffset: segmentOffset,
)
: [TextSpan(text: text, style: segmentStyle)];
if (source.isEmpty) return const [];
final localStart = (composingRange.start - sourceOffset)
.clamp(0, source.length)
.toInt();
final localEnd = (composingRange.end - sourceOffset)
.clamp(0, source.length)
.toInt();
if (!composingRange.isValid ||
composingRange.isCollapsed ||
localStart >= localEnd) {
return buildTextSegment(source, style, sourceOffset);
}
final composingDecorations = [
if (style.decoration != null && style.decoration != TextDecoration.none)
style.decoration!,
TextDecoration.underline,
];
final composingStyle = style.copyWith(
decoration: TextDecoration.combine(composingDecorations),
);
return [
if (localStart > 0)
...buildTextSegment(
source.substring(0, localStart),
style,
sourceOffset,
),
TextSpan(
text: source.substring(localStart, localEnd),
style: composingStyle,
),
if (localEnd < source.length)
...buildTextSegment(
source.substring(localEnd),
style,
sourceOffset + localEnd,
),
];
}
/// Draws each bound mention inside [source] as one chip over its hidden
/// `@Label` source, so the span keeps one character per source character
/// for native caret movement and deletion. A namesake's chip reads its
/// qualified display label while the source stays the plain name.
List<InlineSpan> _buildMentionSpans(
BuildContext context,
String source,
TextStyle style, {
required int sourceOffset,
bool renderLinks = true,
}) {
final tokenSpans = renderLinks
? _buildComposerTokenSpans(context, source, style, sourceOffset)
: null;
if (tokenSpans != null) return tokenSpans;
final segmentEnd = sourceOffset + source.length;
final inSegment = [
for (final mention in _live)
if (mention.start >= sourceOffset && mention.end <= segmentEnd) mention,
];
if (inSegment.isEmpty) return [TextSpan(text: source, style: style)];
final spans = <InlineSpan>[];
var offset = 0;
for (final mention in inSegment) {
final start = mention.start - sourceOffset;
final end = mention.end - sourceOffset;
if (start > offset) {
spans.add(
TextSpan(text: source.substring(offset, start), style: style),
);
}
final hidden = source.substring(start + 1, end);
spans.add(
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: _ComposerMentionChip(
label:
_mentionQualifiers[mention.pubkey] ?? mention.candidate.label,
isAgent: mention.candidate.isAgent,
textStyle: style,
),
),
);
_pendingChipRanges.add(TextRange(start: mention.start, end: mention.end));
// The visual chip replaces the `@` placeholder. Keep the label as
// invisible source text so the text span still has one character per
// source character, preserving native cursor and deletion behavior.
spans.add(
TextSpan(
text: hidden,
semanticsLabel: '',
style: _hiddenMentionTextStyle(style),
),
);
offset = end;
}
if (offset < source.length) {
spans.add(TextSpan(text: source.substring(offset), style: style));
}
return spans.isEmpty ? [TextSpan(text: source, style: style)] : spans;
}
List<InlineSpan>? _buildComposerTokenSpans(
BuildContext context,
String source,
TextStyle style,
int sourceOffset,
) {
final matches = _linkPattern.allMatches(source).toList();
if (matches.isEmpty) return null;
final spans = <InlineSpan>[];
var offset = 0;
for (final match in matches) {
if (match.start > offset) {
spans.addAll(
_buildMentionSpans(
context,
source.substring(offset, match.start),
style,
sourceOffset: sourceOffset + offset,
renderLinks: false,
),
);
}
final raw = match.group(0)!;
final url = raw.replaceFirst(_linkTrailingPunctuation, '');
final trailing = raw.substring(url.length);
final linkStart = sourceOffset + match.start;
// A link shows as raw text while the caret sits at its end, so it can
// be edited. The match runs to whitespace or the end of the text, so
// everywhere else a boundary follows it and it is a chip.
final chipPresentation = _composerLinkPresentation(url);
final revealed = linkStart == _revealedLinkStart;
if (revealed && chipPresentation != null) {
_pendingRevealedChip = TextRange(
start: linkStart,
end: linkStart + url.length,
);
}
final presentation = revealed ? null : chipPresentation;
if (presentation == null) {
spans.add(TextSpan(text: raw, style: style));
} else {
spans.add(
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: _ComposerBuzzLinkChip(
icon: presentation.$1,
label: presentation.$2,
semanticLabel: presentation.$3,
textStyle: style,
),
),
);
_pendingChipRanges.add(
TextRange(
start: sourceOffset + match.start,
end: sourceOffset + match.start + url.length,
),
);
// Preserve one source character per input character for native cursor
// movement while the visible atomic chip replaces the URL.
spans.add(
TextSpan(
text: url.substring(1),
semanticsLabel: '',
style: _hiddenMentionTextStyle(style),
),
);
if (trailing.isNotEmpty) {
spans.add(TextSpan(text: trailing, style: style));
}
}
offset = match.end;
}
if (offset < source.length) {
spans.addAll(
_buildMentionSpans(
context,
source.substring(offset),
style,
sourceOffset: sourceOffset + offset,
renderLinks: false,
),
);
}
return spans;
}
(IconData, String, String)? _composerLinkPresentation(String raw) {
final uri = Uri.tryParse(raw);
if (uri == null) return null;
final link = parseBuzzDeepLink(uri) ?? parseEntityDeepLink(uri);
return switch (link) {
ChannelDeepLink(:final channelId) => (
BuzzIcons.hash,
_resolvedChannelName(channelId),
'Channel ${_resolvedChannelName(channelId)}',
),
MessageDeepLink(:final channelId, :final messageId) => (
BuzzIcons.messageSquare,
'${_resolvedChannelName(channelId)} · ${messageId.substring(0, 8)}',
'Message ${messageId.substring(0, 8)} in channel ${_resolvedChannelName(channelId)}',
),
EntityDeepLink(:final type, :final repository, :final eventId) => (
switch (type) {
'repo' => BuzzIcons.folderGit2,
'pr' => BuzzIcons.gitPullRequest,
_ => BuzzIcons.circleDot,
},
type == 'repo'
? repository
: '$repository · ${eventId!.substring(0, 8)}',
switch (type) {
'repo' => 'Repository $repository',
'pr' =>
'Pull request ${eventId!.substring(0, 8)} in repository $repository',
_ => 'Issue ${eventId!.substring(0, 8)} in repository $repository',
},
),
_ => null,
};
}
String _resolvedChannelName(String channelId) {
for (final entry in _channelNames.entries) {
if (entry.value == channelId) return entry.key;
}
return channelId.substring(0, math.min(8, channelId.length));
}
TextStyle _hiddenMentionTextStyle(TextStyle inheritedStyle) =>
inheritedStyle.copyWith(
color: Colors.transparent,
fontSize: 0.01,
height: 0.01,
letterSpacing: 0,
decoration: TextDecoration.none,
);
(int, int) _contentBounds(String fullMatch, _MarkdownStyle markdownStyle) {
final delimiterLength = switch (markdownStyle) {
_MarkdownStyle.bold || _MarkdownStyle.strikethrough => 2,
_MarkdownStyle.italic || _MarkdownStyle.inlineCode => 1,
_MarkdownStyle.codeBlock => 3,
};
if (markdownStyle != _MarkdownStyle.codeBlock) {
return (delimiterLength, fullMatch.length - delimiterLength);
}
final openingLength = fullMatch.startsWith('```\r\n')
? 5
: fullMatch.startsWith('```\n')
? 4
: delimiterLength;
final closingLength = fullMatch.endsWith('\r\n```')
? 5
: fullMatch.endsWith('\n```')
? 4
: delimiterLength;
return (openingLength, fullMatch.length - closingLength);
}
TextStyle _styleFor(
BuildContext context,
TextStyle inheritedStyle,
_MarkdownStyle markdownStyle,
) {
return switch (markdownStyle) {
_MarkdownStyle.bold => inheritedStyle.merge(
const TextStyle(fontWeight: FontWeight.w700),
),
_MarkdownStyle.italic => inheritedStyle.merge(
const TextStyle(fontStyle: FontStyle.italic),
),
_MarkdownStyle.strikethrough => inheritedStyle.merge(
const TextStyle(decoration: TextDecoration.lineThrough),
),
_MarkdownStyle.inlineCode ||
_MarkdownStyle.codeBlock => inheritedStyle.merge(
TextStyle(
fontFamily: 'GeistMono',
color: context.colors.onSurface,
backgroundColor: context.colors.surface,
),
),
};
}
TextStyle _hiddenSyntaxStyle(TextStyle inheritedStyle) {
return inheritedStyle.copyWith(
color: Colors.transparent,
fontSize: 0.01,
height: 0.01,
letterSpacing: 0,
decoration: TextDecoration.none,
);
}
}