mirror of
https://github.com/block/buzz.git
synced 2026-11-29 20:52:25 +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>
154 lines
6.5 KiB
Dart
154 lines
6.5 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
|
|
import 'mention_label_index.dart';
|
|
|
|
export 'mention_label_index.dart';
|
|
|
|
/// What continues a name directly after a label, as a pattern source: a
|
|
/// letter, mark or digit, or underscores leading to one, so `@Bobby` and
|
|
/// `@Bob_smith` hold no `Bob`. Anything else ends the name: punctuation, a
|
|
/// straight or curly apostrophe, a hyphen or a slash (`@Bob's`, `@Bob-bot`,
|
|
/// `@Bob/Alice`), and underscores that close Markdown emphasis (`_@Bob_`,
|
|
/// `__@Bob__`), which the composer's Italic button writes and sent messages
|
|
/// already hold. The composer's `mentionEndsAtBoundary`, the message scan
|
|
/// and the bubble's pill pattern all read this one rule.
|
|
const mentionNameContinuation = r'(?:[\p{L}\p{M}\p{N}]|_+[\p{L}\p{M}\p{N}])';
|
|
|
|
final _typedMentionEnd = RegExp(r'^(?:\|\||[\s,;.!?:)\]}*_]|$)');
|
|
final _markdownLinkLabel = RegExp(r'\[[^\]\n]*\]\(');
|
|
|
|
/// Whether a typed, unpicked name at `[start, end)` of [text] may notify by
|
|
/// name alone. A picked chip keeps its recipient before any suffix; a name
|
|
/// nobody picked must end as it always has, at whitespace, sentence
|
|
/// punctuation, a closing bracket or a Markdown delimiter, so the `@Alice` of
|
|
/// `@Alice@example.org` or `@Alice's` is prose. The label of a Markdown link
|
|
/// (`[@Alice](url)`) is link text, not a mention.
|
|
bool typedMentionNotifies(String text, int start, int end) {
|
|
if (!_typedMentionEnd.hasMatch(text.substring(end))) return false;
|
|
return !_markdownLinkLabel
|
|
.allMatches(text)
|
|
.any((link) => link.start < start && end < link.end - 1);
|
|
}
|
|
|
|
final _opensMention = RegExp(r'[\s(\[{*_]', unicode: true);
|
|
final _nameContinues = RegExp(mentionNameContinuation, unicode: true);
|
|
final _keyQualifierNext = RegExp(r' \([0-9a-f]{64}\)', caseSensitive: false);
|
|
final _keyQualified = RegExp(r' \([0-9a-f]{64}\)$', caseSensitive: false);
|
|
final _reservationNext = RegExp(
|
|
' (?:[2-9]|[1-9][0-9]+)(?!$mentionNameContinuation)',
|
|
unicode: true,
|
|
);
|
|
|
|
/// How many candidate names [mentionOccurrences] has looked up, for tests
|
|
/// that check a scan's work does not grow with the roster.
|
|
@visibleForTesting
|
|
int mentionScanLookups = 0;
|
|
|
|
/// Longest literal ranges win, including labels containing another @ sign.
|
|
/// Recognition precedes eligibility: ambiguous labels still block shorter ones.
|
|
/// A label opens where a query does (portable mention rules, section 2): at
|
|
/// the start, after whitespace, `(`, `[` or `{`, or after a Markdown
|
|
/// delimiter, so a mention picked after a bracket keeps its recipient. It
|
|
/// ends at the composer's suffix boundary, [mentionNameContinuation].
|
|
///
|
|
/// No pattern is built from a name. Each `@` is found once, and the text
|
|
/// after it is looked up in a hash index at each length a label has, longest
|
|
/// first, as buzz-app's `typedContinuation` probes its name map. The cost
|
|
/// per `@` therefore depends on how many distinct lengths the labels have
|
|
/// and not on how many labels there are, and text with no `@` costs one
|
|
/// search for it. Names compare as a case-insensitive Unicode pattern
|
|
/// compares them ([foldMentionLabel]). [labels] are indexed on each call, so
|
|
/// a channel roster belongs in [known], built once and reused; a label in
|
|
/// [labels] wins over one in [known] that differs only by case.
|
|
List<({int start, int end, String label})> mentionOccurrences(
|
|
String text,
|
|
Iterable<String> labels, {
|
|
MentionLabelIndex? known,
|
|
}) {
|
|
final result = <({int start, int end, String label})>[];
|
|
var at = text.indexOf('@');
|
|
if (at < 0) return result;
|
|
final own = MentionLabelIndex(labels);
|
|
final lengths = known == null || known.lengths.isEmpty
|
|
? own.lengths
|
|
: own.lengths.isEmpty
|
|
? known.lengths
|
|
: ({...own.lengths, ...known.lengths}.toList()
|
|
..sort((a, b) => b.compareTo(a)));
|
|
while (at >= 0) {
|
|
var next = at + 1;
|
|
final opens =
|
|
at == 0 ||
|
|
_opensMention.matchAsPrefix(text, at - 1) != null ||
|
|
at >= 2 && text.startsWith('||', at - 2);
|
|
if (opens) {
|
|
for (final length in lengths) {
|
|
final end = at + 1 + length;
|
|
if (end > text.length) continue;
|
|
// A label never ends inside a surrogate pair or against a name
|
|
// character, and a key qualifier belongs to the literal even when no
|
|
// candidate binds it: never fall back to a shorter, different
|
|
// recipient.
|
|
if (end < text.length &&
|
|
(text.codeUnitAt(end) & 0xFC00) == 0xDC00 &&
|
|
(text.codeUnitAt(end - 1) & 0xFC00) == 0xD800) {
|
|
continue;
|
|
}
|
|
if (_nameContinues.matchAsPrefix(text, end) != null ||
|
|
_keyQualifierNext.matchAsPrefix(text, end) != null) {
|
|
continue;
|
|
}
|
|
mentionScanLookups++;
|
|
final folded = foldMentionLabel(text.substring(at + 1, end));
|
|
final label = own[folded] ?? known?[folded];
|
|
// The same holds for a qualified label's reservation suffix.
|
|
if (label == null ||
|
|
_keyQualified.hasMatch(label) &&
|
|
_reservationNext.matchAsPrefix(text, end) != null) {
|
|
continue;
|
|
}
|
|
result.add((start: at, end: end, label: label));
|
|
next = end;
|
|
break;
|
|
}
|
|
}
|
|
at = text.indexOf('@', next);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/// Bind tagged qualifiers and ordinary aliases, never historical namesakes.
|
|
/// Labels are keyed by [foldMentionLabel], as the text scan compares them,
|
|
/// so two names that fold alike are ambiguous.
|
|
Map<String, Set<String>> renderedMentionBindings(
|
|
String content,
|
|
Map<String, String> names, [
|
|
Iterable<String> signedPubkeys = const [],
|
|
]) {
|
|
final bindings = <String, Set<String>>{};
|
|
void add(String label, String key) =>
|
|
(bindings[foldMentionLabel(label)] ??= {}).add(key.toLowerCase());
|
|
for (final entry in names.entries) {
|
|
add(entry.value, entry.key);
|
|
add(entry.value.split(RegExp(r'\s+')).first, entry.key);
|
|
}
|
|
final keys = signedPubkeys.map((key) => key.toLowerCase()).toSet();
|
|
for (final match in RegExp(
|
|
r'@([^@\r\n]+) \(([0-9a-f]{64})\)(?: ((?:[1-9][0-9]+|[2-9])))?',
|
|
caseSensitive: false,
|
|
).allMatches(content)) {
|
|
final key = match.group(2)!.toLowerCase();
|
|
final label = foldMentionLabel(match.group(0)!.substring(1));
|
|
if (!mentionOccurrences(content, [
|
|
label,
|
|
]).any((range) => range.start == match.start)) {
|
|
continue;
|
|
}
|
|
// Text can deny historical aliases without a profile, never authorize keys.
|
|
bindings[label] = keys.contains(key) ? {key} : <String>{};
|
|
// Recipient tags/current names cannot establish the historical plain owner.
|
|
bindings[foldMentionLabel(match.group(1)!)] = <String>{};
|
|
}
|
|
return bindings;
|
|
}
|