mirror of
https://github.com/block/buzz.git
synced 2026-11-28 20:22:39 +00:00
Follow-up to [#9699 mention typing](https://github.com/block/buzz/pull/9699), fixing two identity problems found in its review. **Identity-link pills name the key they open.** An edit writes each mention as an identity link, `[@Name](nostr:npub1…)`, and every message from any client draws such a link as a pill. Mobile showed the label written in the link, so `[@Wes](nostr:<mallory>)` drew an ordinary `@Wes` pill that opened Mallory's profile, and two namesakes in an edited message both read `Scout`. The pill now shows the name its key resolves to in the channel (with the namesake qualifier and agent icon), as buzz-app's `ProfileMention` already does. The written label shows only when the key has no name on this device (no profile, directory or roster name), never a compact npub in its place. This holds whether or not the link's key is also tagged. A pill requests its key's profile when uncached, so a written label gives way to the key's name once it loads. Edits carry no `p` tag, so an identity-link pill resolves its own key. In channel, thread and forum rows the pill watches that one key's channel label (with the namesake qualifier and agent icon) and requests the key's profile when it builds, so only links that actually draw a pill cost a lookup, whatever Markdown surrounds them. Inbox and search previews draw identity links the same way, taking keys from the preview pieces they render. These keys never feed the text bindings, so plain `@Name` text still binds only through signed tags. **Typed names group the way the text scan reads them.** The composer grouped the roster by `toLowerCase` while the scan folds names with `foldMentionLabel`. With members `Sam` and `ſam`, typing `@ſam` sent Sam's `p` tag. Grouping, lookup and the send-time key qualifier now all fold, so namesakes under folding fail as ambiguous, as other namesakes already do. **Linked lookups stay current and bounded.** Pills and preview rows request their keys through the profile cache's revalidation path. A name restored from the last launch is revalidated, so a renamed key's link shows its current name. A lookup that fails while offline is retried once the relay reconnects, including when the reconnect comes while that lookup is still on the wire. A key the relay says has no profile is not asked for again for five minutes, and the cache remembers at most 1,000 such keys per community. Previews keep tilde and quoted code fences literal and read blockquotes as the full message does, and load only the links on lines they draw. Editing a message folds historical names the way the scan does, so a name two tagged people share under folding seeds no chip. Rendering binds signed names by the same fold, so with signed `Sam` and `ſam` a plain `@Sam` stays text instead of drawing Sam's pill. Desktop (buzz-app) already names identity-link chips from the key and needs no change. ### Validation Rows add no per-message work: message bodies are no longer scanned for links. Each drawn identity-link pill adds one label watch for its own key. Added tests: - [Channel page journey step](mobile/test/features/channels/channel_detail_page_test.dart): an edited message linking `[@Wes]` to Mallory's key draws `Mallory`, and two edited `Scout` namesakes draw distinct qualified labels, through the real channel row. - [Channel page journey step](mobile/test/features/channels/channel_detail_page_test.dart): a link to a key with no name here keeps its written label. - [Preview identity link](mobile/test/features/channels/message_content/preview_text_test.dart): an inbox/search preview shows the key's resolved name, or the written label when unknown. - [Preview keys](mobile/test/features/channels/message_content/preview_text_test.dart): a preview loads only links it draws (not ones in code or past its line limit), including labels with brackets. Full-app run (iOS simulator, debug build, signed in to a test community): posted a message with a spoofed identity link, a link to a key with no profile here, and a link inside inline code. The spoofed link drew the key's real name as a pill and opened that person's profile; the unknown key kept its written label; the code span stayed raw. The same message drew matching pills in search results and in the thread view. - [Channel row loads](mobile/test/features/channels/channel_detail_page_test.dart): a row requests profiles only for links it draws as pills, not ones in a quoted code fence or an HTML comment. - [Folded chip qualifiers](mobile/test/features/channels/compose_bar_test/exact_mention_tests.dart): picked `@Sam` and `@ſam` chips both carry their keys on send. - [Ambiguous typed names table](mobile/test/features/channels/compose_bar_test/exact_mention_tests.dart): `Sam` and `ſam` in either roster order now refuse `@ſam` as ambiguous. - [Restart and reconnect journey](mobile/test/features/channels/channel_detail_page_test.dart): a restored old name and an offline first lookup both resolve after the relay reconnects, on the same mounted pills, and a key with no profile is not requested again. - [Preview fences](mobile/test/features/channels/message_content/preview_text_test.dart): tilde and quoted fences keep links and Markdown literal and load no keys. - [Overtaken lookup](mobile/test/shared/profile/user_cache_provider_test.dart): a reconnect during a link's failing lookup asks once more after it settles. - [Folded signed names](mobile/test/features/channels/message_content_exact_mentions_test.dart): signed `Sam` and `ſam` in either tag order leave `@Sam` as text in the message and its preview. - [Folded edit chips](mobile/test/features/channels/message_edit_sheet_test.dart): `Sam` and `ſam` tagged in either order open as text, with no chip. - [Non-member labels](mobile/test/shared/identity_names/identity_names_test.dart): a non-member labels the same with or without the roster shortcut, including names shaped like qualifiers. ### Regressions - **Performance:** rows do no new scanning; each drawn identity-link pill adds one label watch. A non-member whose name can't collide no longer re-resolves the whole roster. - **Mention semantics:** unchanged for tagged mentions and plain text. Only identity-link pills change, from the written label to the key's resolved name. - **Composer:** names that differ only under Unicode folding (`ſ`/`s`, `µ`/`μ`, final `ς`/`σ`) are now one name when matching typed text, so a typed one between two such members asks for a pick instead of silently choosing one. Picked chips are unaffected. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz>
541 lines
18 KiB
Dart
541 lines
18 KiB
Dart
import 'dart:math' as math;
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import '../../../shared/deeplink/deep_link.dart';
|
|
import '../../../shared/mentions/mention_bindings.dart';
|
|
import '../../../shared/mentions/mention_identity_links.dart';
|
|
import '../message_media.dart';
|
|
import 'buzz_link_label.dart';
|
|
import 'channel_token_pattern.dart';
|
|
import 'link_normalizer.dart';
|
|
import 'markdown_escapes.dart';
|
|
|
|
/// One piece of a message preview: plain text or an inline token that renders
|
|
/// as a chip or image.
|
|
@immutable
|
|
sealed class PreviewPiece {
|
|
const PreviewPiece();
|
|
}
|
|
|
|
final class PreviewText extends PreviewPiece {
|
|
final String text;
|
|
const PreviewText(this.text);
|
|
|
|
@override
|
|
bool operator ==(Object other) => other is PreviewText && other.text == text;
|
|
@override
|
|
int get hashCode => text.hashCode;
|
|
@override
|
|
String toString() => 'PreviewText($text)';
|
|
}
|
|
|
|
final class PreviewMention extends PreviewPiece {
|
|
final String pubkey;
|
|
final String label;
|
|
|
|
/// The full label, before shortening a pubkey qualifier.
|
|
final String semanticsLabel;
|
|
const PreviewMention({
|
|
required this.pubkey,
|
|
required this.label,
|
|
required this.semanticsLabel,
|
|
});
|
|
|
|
@override
|
|
bool operator ==(Object other) =>
|
|
other is PreviewMention &&
|
|
other.pubkey == pubkey &&
|
|
other.label == label &&
|
|
other.semanticsLabel == semanticsLabel;
|
|
@override
|
|
int get hashCode => Object.hash(pubkey, label, semanticsLabel);
|
|
@override
|
|
String toString() => 'PreviewMention($pubkey, $label)';
|
|
}
|
|
|
|
final class PreviewEmoji extends PreviewPiece {
|
|
final String shortcode;
|
|
final String url;
|
|
const PreviewEmoji({required this.shortcode, required this.url});
|
|
|
|
@override
|
|
bool operator ==(Object other) =>
|
|
other is PreviewEmoji && other.shortcode == shortcode && other.url == url;
|
|
@override
|
|
int get hashCode => Object.hash(shortcode, url);
|
|
@override
|
|
String toString() => 'PreviewEmoji($shortcode)';
|
|
}
|
|
|
|
final class PreviewChannel extends PreviewPiece {
|
|
final String name;
|
|
const PreviewChannel(this.name);
|
|
|
|
@override
|
|
bool operator ==(Object other) =>
|
|
other is PreviewChannel && other.name == name;
|
|
@override
|
|
int get hashCode => name.hashCode;
|
|
@override
|
|
String toString() => 'PreviewChannel($name)';
|
|
}
|
|
|
|
final class PreviewMedia extends PreviewPiece {
|
|
final MessageMediaKind kind;
|
|
const PreviewMedia(this.kind);
|
|
|
|
@override
|
|
bool operator ==(Object other) => other is PreviewMedia && other.kind == kind;
|
|
@override
|
|
int get hashCode => kind.hashCode;
|
|
@override
|
|
String toString() => 'PreviewMedia(${kind.name})';
|
|
}
|
|
|
|
/// The pieces of a [maxLines] preview of Markdown [content], without parsing
|
|
/// it as Markdown.
|
|
///
|
|
/// Block syntax is dropped line by line and inline emphasis is unwrapped, the
|
|
/// way desktop's `getMarkdownPreviewText` does, so the cost is linear in the
|
|
/// part of the message that can show. Each kept source line starts a new
|
|
/// line, so lines past the first `maxLines + 1` are never read; the extra one
|
|
/// keeps the overflow that ends the preview with an ellipsis. Inline code is
|
|
/// kept as literal text.
|
|
///
|
|
/// [mentionBindings] and [channelNames] are keyed by lowercase name,
|
|
/// [customEmoji] maps a lowercase shortcode to its image URL, and
|
|
/// [imetaByUrl] is keyed by normalized URL.
|
|
List<PreviewPiece> messagePreviewPieces(
|
|
String content, {
|
|
required int maxLines,
|
|
Map<String, Set<String>> mentionBindings = const {},
|
|
Map<String, String> mentionNames = const {},
|
|
Map<String, String> mentionLabels = const {},
|
|
Map<String, String> customEmoji = const {},
|
|
Map<String, String> channelNames = const {},
|
|
Map<String, ImetaEntry> imetaByUrl = const {},
|
|
}) {
|
|
final builder = _PreviewBuilder(
|
|
mentionBindings: mentionBindings,
|
|
mentionNames: mentionNames,
|
|
mentionLabels: mentionLabels,
|
|
customEmoji: customEmoji,
|
|
channelNames: channelNames,
|
|
imetaByUrl: imetaByUrl,
|
|
);
|
|
var first = true;
|
|
for (final line in _keptLines(content, maxLines)) {
|
|
if (!first) builder.text('\n');
|
|
first = false;
|
|
if (line.code) {
|
|
builder.text(line.text);
|
|
} else {
|
|
builder.line(line.text);
|
|
}
|
|
}
|
|
return builder.pieces;
|
|
}
|
|
|
|
/// The leading part of [content] that [messagePreviewPieces] reads for a
|
|
/// [maxLines] preview, so whole-message preprocessing such as link
|
|
/// normalization and mention binding can run on just that part.
|
|
String messagePreviewSource(String content, {required int maxLines}) {
|
|
var end = 0;
|
|
for (final line in _keptLines(content, maxLines)) {
|
|
end = line.end;
|
|
}
|
|
return content.substring(0, end);
|
|
}
|
|
|
|
/// The keys of the identity links a [maxLines] preview of [content] draws,
|
|
/// read as the preview reads them (outside code, within its source limit),
|
|
/// so a row resolves and loads only names it shows. The preview reads one
|
|
/// line past [maxLines] to know it overflows; that line is never drawn.
|
|
Set<String> messagePreviewIdentityKeys(
|
|
String content, {
|
|
required int maxLines,
|
|
}) => maxLines > 0 && content.contains('nostr:npub1')
|
|
? {
|
|
for (final piece in messagePreviewPieces(
|
|
normalizeBareLinks(
|
|
messagePreviewSource(content, maxLines: maxLines - 1),
|
|
),
|
|
maxLines: maxLines - 1,
|
|
))
|
|
if (piece is PreviewMention) piece.pubkey,
|
|
}
|
|
: const {};
|
|
|
|
/// The first `maxLines + 1` lines that render, trimmed and without block
|
|
/// syntax, read lazily so the rest of [content] is never scanned. Lines that
|
|
/// don't render still cost a scan, so reading also stops after
|
|
/// [_maxScanLength] characters. [code] marks a line inside a fenced block, and
|
|
/// [end] is its end offset in [content].
|
|
Iterable<({String text, bool code, int end})> _keptLines(
|
|
String content,
|
|
int maxLines,
|
|
) sync* {
|
|
var kept = 0;
|
|
// The open fence's run (for example ``` or ~~~~), or null outside one.
|
|
String? fence;
|
|
var fenceQuoted = false;
|
|
var inQuote = false;
|
|
var start = 0;
|
|
while (start <= content.length &&
|
|
start <= _maxScanLength &&
|
|
kept <= maxLines) {
|
|
// A long line wraps past the visible lines well before this length, so
|
|
// reading stops there rather than at the line's real end.
|
|
var cap = math.min(content.length, start + 2 * _maxLineLength);
|
|
if (cap < content.length && _isHighSurrogate(content.codeUnitAt(cap - 1))) {
|
|
cap--;
|
|
}
|
|
var end = start;
|
|
while (end < cap && content.codeUnitAt(end) != _newline) {
|
|
end++;
|
|
}
|
|
final cut = end == cap && cap < content.length;
|
|
var line = content.substring(start, end).trim();
|
|
start = cut ? content.length + 1 : end + 1;
|
|
// A backtick or tilde fence opens at a line starting with three or more
|
|
// of its character and closes only at a line holding nothing else but at
|
|
// least as many, as the full message reads it. Outside an unquoted fence,
|
|
// a quote marker enters a blockquote and only a blank line leaves it,
|
|
// closing a fence opened inside it. That quoted fence closes at a closer
|
|
// with or without the marker; an unquoted fence closes only at an
|
|
// unmarked closer, and markers and blank lines inside it are code.
|
|
if (line.isEmpty) {
|
|
if (fence == null || fenceQuoted) {
|
|
inQuote = false;
|
|
fence = null;
|
|
}
|
|
continue;
|
|
}
|
|
final unquoted = line.replaceFirst(_quote, '').trim();
|
|
if (fence == null) {
|
|
if (unquoted != line) inQuote = true;
|
|
if (_fenceRun.firstMatch(unquoted) case final open?) {
|
|
fence = open[1];
|
|
fenceQuoted = inQuote;
|
|
continue;
|
|
}
|
|
} else {
|
|
final closer = fenceQuoted ? unquoted : line;
|
|
if (closer.startsWith(fence) &&
|
|
closer.split('').every((c) => c == fence![0])) {
|
|
fence = null;
|
|
continue;
|
|
}
|
|
}
|
|
final fenceOpen = fence != null;
|
|
if (fenceOpen && fenceQuoted) line = unquoted;
|
|
if (line.isEmpty) continue;
|
|
if (!fenceOpen) {
|
|
if (_rule.hasMatch(line) || _tableDivider.hasMatch(line)) continue;
|
|
line = _blockPrefix(line);
|
|
if (line.isEmpty) continue;
|
|
}
|
|
if (line.length > _maxLineLength) {
|
|
line = line.substring(0, _maxLineLength);
|
|
}
|
|
kept++;
|
|
yield (text: line, code: fenceOpen, end: end);
|
|
}
|
|
}
|
|
|
|
const _maxLineLength = 2000;
|
|
const _maxScanLength = 8 * _maxLineLength;
|
|
const _backslash = 0x5C;
|
|
const _newline = 0x0A;
|
|
const _backtick = 0x60;
|
|
|
|
bool _isHighSurrogate(int unit) => unit >= 0xD800 && unit <= 0xDBFF;
|
|
|
|
final _rule = RegExp(r'^([-*_])(?:\s*\1){2,}$');
|
|
final _tableDivider = RegExp(r'^\|?(?:\s*:?-+:?\s*\|)+\s*:?-*:?\s*\|?$');
|
|
final _quote = RegExp(r'^(?:>\s?)+');
|
|
final _fenceRun = RegExp(r'^(`{3,}|~{3,})');
|
|
final _heading = RegExp(r'^#{1,6}\s+');
|
|
final _task = RegExp(r'^[-*+]\s+\[[ xX]\]\s+');
|
|
final _bullet = RegExp(r'^[-*+]\s+');
|
|
final _ordered = RegExp(r'^\d+[.)]\s+');
|
|
|
|
String _blockPrefix(String line) {
|
|
var result = line
|
|
.replaceFirst(_quote, '')
|
|
.replaceFirst(_heading, '')
|
|
.replaceFirst(_task, '')
|
|
.replaceFirst(_bullet, '')
|
|
.replaceFirst(_ordered, '');
|
|
if (result.startsWith('|')) {
|
|
result = result
|
|
.replaceFirst(RegExp(r'^\|'), '')
|
|
.replaceFirst(RegExp(r'\|$'), '')
|
|
.split('|')
|
|
.map((cell) => cell.trim())
|
|
.where((cell) => cell.isNotEmpty)
|
|
.join(' ');
|
|
}
|
|
return result.trim();
|
|
}
|
|
|
|
final _link = RegExp(r'(!?)\[([^\]]*)\]\(<?([^)\s>]+)>?(?:\s+"[^"]*")?\)');
|
|
|
|
// Emphasis is unwrapped only when its delimiters hug the text, and `_` only
|
|
// at word boundaries, so snake_case names and emoji shortcodes survive.
|
|
final _emphasis = [
|
|
RegExp(r'\*\*(?=\S)(.+?)(?<=\S)\*\*'),
|
|
RegExp(r'(?<![A-Za-z0-9_])__(?=\S)(.+?)(?<=\S)__(?![A-Za-z0-9_])'),
|
|
RegExp(r'\*(?=\S)(.+?)(?<=\S)\*'),
|
|
RegExp(r'(?<![A-Za-z0-9_])_(?=\S)(.+?)(?<=\S)_(?![A-Za-z0-9_])'),
|
|
RegExp(r'~~(?=\S)(.+?)(?<=\S)~~'),
|
|
RegExp(r'<u>(.+?)</u>', caseSensitive: false),
|
|
];
|
|
|
|
/// Unwraps emphasis in [shielded] text.
|
|
String _unwrapEmphasis(String shielded) {
|
|
if (!_hasDelimiter.hasMatch(shielded)) return shielded;
|
|
var result = shielded;
|
|
for (final pattern in _emphasis) {
|
|
result = result.replaceAllMapped(pattern, (m) => m[1]!);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
final _hasDelimiter = RegExp(r'[*_~<]');
|
|
|
|
// Look ahead so adjacent tokens sharing a colon are both considered.
|
|
final _shortcode = RegExp(r'(?=:([a-z0-9_-]+):)', caseSensitive: false);
|
|
final _qualifier = RegExp(r'\(([0-9a-f]{64})\)');
|
|
final _escapedPunctuation = RegExp(r'\\([!-/:-@\[-`{-~])');
|
|
|
|
class _PreviewBuilder {
|
|
final Map<String, Set<String>> mentionBindings;
|
|
final Map<String, String> mentionNames;
|
|
final Map<String, String> mentionLabels;
|
|
final Map<String, String> customEmoji;
|
|
final Map<String, String> channelNames;
|
|
final Map<String, ImetaEntry> imetaByUrl;
|
|
late final RegExp _channel = channelTokenPattern(channelNames.keys);
|
|
final pieces = <PreviewPiece>[];
|
|
|
|
_PreviewBuilder({
|
|
required this.mentionBindings,
|
|
required this.mentionNames,
|
|
required this.mentionLabels,
|
|
required this.customEmoji,
|
|
required this.channelNames,
|
|
required this.imetaByUrl,
|
|
});
|
|
|
|
void text(String text) {
|
|
if (text.isEmpty) return;
|
|
final last = pieces.isEmpty ? null : pieces.last;
|
|
if (last is PreviewText) {
|
|
pieces[pieces.length - 1] = PreviewText(last.text + text);
|
|
} else {
|
|
pieces.add(PreviewText(text));
|
|
}
|
|
}
|
|
|
|
void add(PreviewPiece piece) =>
|
|
piece is PreviewText ? text(piece.text) : pieces.add(piece);
|
|
|
|
/// One line of prose: inline code is literal, everything else is inline
|
|
/// Markdown. A code span opens at an unescaped run of backticks and closes
|
|
/// at the next run of the same length; a run with no match is literal.
|
|
void line(String line) {
|
|
var prose = 0;
|
|
var cursor = 0;
|
|
while (cursor < line.length) {
|
|
final unit = line.codeUnitAt(cursor);
|
|
if (unit == _backslash) {
|
|
cursor += 2;
|
|
continue;
|
|
}
|
|
if (unit != _backtick) {
|
|
cursor++;
|
|
continue;
|
|
}
|
|
final open = cursor;
|
|
final openEnd = _runEnd(line, open);
|
|
final run = openEnd - open;
|
|
int? close;
|
|
var scan = openEnd;
|
|
while (scan < line.length) {
|
|
if (line.codeUnitAt(scan) != _backtick) {
|
|
scan++;
|
|
continue;
|
|
}
|
|
final end = _runEnd(line, scan);
|
|
if (end - scan == run) {
|
|
close = scan;
|
|
break;
|
|
}
|
|
scan = end;
|
|
}
|
|
if (close == null) {
|
|
cursor = openEnd;
|
|
continue;
|
|
}
|
|
_inline(line.substring(prose, open));
|
|
var code = line.substring(openEnd, close);
|
|
if (code.length > 2 &&
|
|
code.startsWith(' ') &&
|
|
code.endsWith(' ') &&
|
|
code.trim().isNotEmpty) {
|
|
code = code.substring(1, code.length - 1);
|
|
}
|
|
text(code);
|
|
cursor = prose = close + run;
|
|
}
|
|
_inline(line.substring(prose));
|
|
}
|
|
|
|
static int _runEnd(String line, int start) {
|
|
var end = start;
|
|
while (end < line.length && line.codeUnitAt(end) == _backtick) {
|
|
end++;
|
|
}
|
|
return end;
|
|
}
|
|
|
|
void _inline(String text) {
|
|
final source = shieldMarkdownEscapes(text);
|
|
var start = 0;
|
|
for (final match in _link.allMatches(source)) {
|
|
_tokens(_unwrapEmphasis(source.substring(start, match.start)));
|
|
start = match.end;
|
|
final isImage = match[1]!.isNotEmpty;
|
|
final label = reescapeMarkdownEscapes(match[2]!);
|
|
final url = reescapeMarkdownEscapes(match[3]!);
|
|
final imeta = imetaByUrl[normalizeMarkdownDestination(url)];
|
|
final kind =
|
|
classifyMediaUrl(url, imeta: imeta) ??
|
|
(isImage ? MessageMediaKind.image : null);
|
|
if (kind != null) {
|
|
add(PreviewMedia(kind));
|
|
continue;
|
|
}
|
|
final identity = _identityMention(label, url);
|
|
if (identity != null) {
|
|
add(identity);
|
|
continue;
|
|
}
|
|
final uri = Uri.tryParse(url);
|
|
final deepLink = uri?.scheme == 'buzz'
|
|
? parseBuzzDeepLink(uri!) ?? parseEntityDeepLink(uri)
|
|
: null;
|
|
if (deepLink is ChannelDeepLink) {
|
|
add(PreviewChannel(buzzChannelLabel(deepLink.channelId, _channelName)));
|
|
continue;
|
|
}
|
|
final shown = label.isEmpty ? url : decodeMarkdownLabelSyntax(label);
|
|
// As in the thread view, a link showing its own URL shows a short label.
|
|
final short = shown == url ? buzzLinkLabel(deepLink, _channelName) : null;
|
|
if (short != null) {
|
|
this.text(short);
|
|
continue;
|
|
}
|
|
_tokens(_unwrapEmphasis(shieldMarkdownEscapes(shown)));
|
|
}
|
|
_tokens(_unwrapEmphasis(source.substring(start)));
|
|
}
|
|
|
|
String? _channelName(String channelId) {
|
|
for (final entry in channelNames.entries) {
|
|
if (entry.value == channelId) return entry.key;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// [shieldMarkdownEscapes]ed plain text with mention, custom emoji and channel tokens.
|
|
void _tokens(String source) {
|
|
if (source.isEmpty) return;
|
|
final found = <({int start, int end, PreviewPiece piece})>[];
|
|
if (mentionBindings.isNotEmpty && source.contains('@')) {
|
|
for (final range in mentionOccurrences(source, mentionBindings.keys)) {
|
|
final piece = _mention(
|
|
range.label,
|
|
unshieldMarkdownEscapes(source.substring(range.start + 1, range.end)),
|
|
);
|
|
if (piece != null) {
|
|
found.add((start: range.start, end: range.end, piece: piece));
|
|
}
|
|
}
|
|
}
|
|
if (customEmoji.isNotEmpty && source.contains(':')) {
|
|
for (final match in _shortcode.allMatches(source)) {
|
|
final shortcode = match[1]!.toLowerCase();
|
|
final url = customEmoji[shortcode];
|
|
if (url == null) continue;
|
|
found.add((
|
|
start: match.start,
|
|
end: match.start + shortcode.length + 2,
|
|
piece: PreviewEmoji(shortcode: shortcode, url: url),
|
|
));
|
|
}
|
|
}
|
|
if (source.contains('#')) {
|
|
for (final match in _channel.allMatches(source)) {
|
|
found.add((
|
|
start: match.start,
|
|
end: match.end,
|
|
piece: PreviewChannel(match[0]!.substring(1)),
|
|
));
|
|
}
|
|
}
|
|
found.sort((a, b) => a.start.compareTo(b.start));
|
|
var cursor = 0;
|
|
for (final token in found) {
|
|
if (token.start < cursor) continue;
|
|
text(unshieldMarkdownEscapes(source.substring(cursor, token.start)));
|
|
add(token.piece);
|
|
cursor = token.end;
|
|
}
|
|
text(unshieldMarkdownEscapes(source.substring(cursor)));
|
|
}
|
|
|
|
/// Mirrors the thread view's identity-link pill: the name its key resolves
|
|
/// to, else the label written into the link. Null for any other link.
|
|
PreviewMention? _identityMention(String label, String url) {
|
|
final pubkey = mentionIdentityLinkKey(url);
|
|
if (pubkey == null) return null;
|
|
final written = decodeMarkdownLabelSyntax(label)
|
|
.replaceAllMapped(_escapedPunctuation, (m) => m[1]!)
|
|
.replaceAll('\u00A0', ' ');
|
|
if (!isMentionIdentityLabel(written)) return null;
|
|
final name =
|
|
mentionLabels[pubkey] ??
|
|
mentionIdentityLinkName(pubkey, mentionNames[pubkey]);
|
|
final fullLabel = name ?? written.substring(1);
|
|
return PreviewMention(
|
|
pubkey: pubkey,
|
|
label: _shortQualifier(fullLabel),
|
|
semanticsLabel: fullLabel,
|
|
);
|
|
}
|
|
|
|
static String _shortQualifier(String label) => label.replaceAllMapped(
|
|
_qualifier,
|
|
(m) => '(${m[1]!.substring(0, 8)}…${m[1]!.substring(60)})',
|
|
);
|
|
|
|
/// Mirrors the thread view's mention chip: an ambiguous label stays text.
|
|
PreviewMention? _mention(String label, String typed) {
|
|
final matches = mentionBindings[label] ?? const <String>{};
|
|
if (matches.length != 1) return null;
|
|
final pubkey = matches.single;
|
|
final displayName = _qualifier.hasMatch(label)
|
|
? typed
|
|
: mentionLabels[pubkey] ?? mentionNames[pubkey];
|
|
final fullLabel = displayName ?? typed;
|
|
return PreviewMention(
|
|
pubkey: pubkey,
|
|
label: _shortQualifier(fullLabel),
|
|
semanticsLabel: fullLabel,
|
|
);
|
|
}
|
|
}
|