Skip to content

Commit 6661d59

Browse files
browclaude
andcommitted
mobile: bound preview preprocessing to visible lines; handle underline and escapes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c77326a commit 6661d59

3 files changed

Lines changed: 104 additions & 33 deletions

File tree

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

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -37,26 +37,29 @@ class MessagePreview extends HookConsumerWidget {
3737
final channelNames = ref.watch(channelIdsByNameProvider);
3838
final palette = ref.watch(customEmojiListProvider);
3939
final pieces = useMemoized(
40-
() => messagePreviewPieces(
41-
normalizeBareLinks(content),
42-
maxLines: maxLines,
43-
mentionBindings: renderedMentionBindings(
44-
content,
45-
mentionNames,
46-
mentionedPubkeysFromTags(tags),
47-
),
48-
mentionNames: mentionNames,
49-
mentionLabels: mentionLabels,
50-
customEmoji: _referencedCustomEmoji(
51-
content,
52-
_mergeCustomEmoji(customEmojiFromTags(tags), palette),
53-
),
54-
channelNames: channelNames,
55-
imetaByUrl: {
56-
for (final entry in parseImetaTags(tags).entries)
57-
normalizeMarkdownDestination(entry.key): entry.value,
58-
},
59-
),
40+
() {
41+
final source = messagePreviewSource(content, maxLines: maxLines);
42+
return messagePreviewPieces(
43+
normalizeBareLinks(source),
44+
maxLines: maxLines,
45+
mentionBindings: renderedMentionBindings(
46+
source,
47+
mentionNames,
48+
mentionedPubkeysFromTags(tags),
49+
),
50+
mentionNames: mentionNames,
51+
mentionLabels: mentionLabels,
52+
customEmoji: _referencedCustomEmoji(
53+
source,
54+
_mergeCustomEmoji(customEmojiFromTags(tags), palette),
55+
),
56+
channelNames: channelNames,
57+
imetaByUrl: {
58+
for (final entry in parseImetaTags(tags).entries)
59+
normalizeMarkdownDestination(entry.key): entry.value,
60+
},
61+
);
62+
},
6063
[
6164
content,
6265
tags,

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

Lines changed: 64 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import 'dart:math' as math;
2+
13
import 'package:flutter/foundation.dart';
24

35
import '../../../shared/deeplink/deep_link.dart';
@@ -118,11 +120,48 @@ List<PreviewPiece> messagePreviewPieces(
118120
channelNames: channelNames,
119121
imetaByUrl: imetaByUrl,
120122
);
123+
var first = true;
124+
for (final line in _keptLines(content, maxLines)) {
125+
if (!first) builder.text('\n');
126+
first = false;
127+
if (line.code) {
128+
builder.text(line.text);
129+
} else {
130+
builder.line(line.text);
131+
}
132+
}
133+
return builder.pieces;
134+
}
135+
136+
/// The leading part of [content] that [messagePreviewPieces] reads for a
137+
/// [maxLines] preview, so whole-message preprocessing such as link
138+
/// normalization and mention binding can run on just that part.
139+
String messagePreviewSource(String content, {required int maxLines}) {
140+
var end = 0;
141+
for (final line in _keptLines(content, maxLines)) {
142+
end = line.end;
143+
}
144+
return content.substring(0, end);
145+
}
146+
147+
/// The first `maxLines + 1` lines that render, trimmed and without block
148+
/// syntax, read lazily so the rest of [content] is never scanned. [code] marks
149+
/// a line inside a fenced block, and [end] is its end offset in [content].
150+
Iterable<({String text, bool code, int end})> _keptLines(
151+
String content,
152+
int maxLines,
153+
) sync* {
121154
var kept = 0;
122155
var fenceOpen = false;
123-
for (final source in content.split('\n')) {
124-
if (kept > maxLines) break;
125-
var line = source.trim();
156+
var start = 0;
157+
while (start <= content.length && kept <= maxLines) {
158+
var end = content.indexOf('\n', start);
159+
if (end < 0) end = content.length;
160+
// A long line wraps past the visible lines well before this length.
161+
var line = content
162+
.substring(start, math.min(end, start + 2 * _maxLineLength))
163+
.trim();
164+
start = end + 1;
126165
// A fence opens at any line starting with backticks and closes only at a
127166
// line holding nothing else, as in gpt_markdown.
128167
if (!fenceOpen && line.startsWith('```') || fenceOpen && line == '```') {
@@ -135,19 +174,12 @@ List<PreviewPiece> messagePreviewPieces(
135174
line = _blockPrefix(line);
136175
if (line.isEmpty) continue;
137176
}
138-
// A long line wraps past the visible lines well before this length.
139177
if (line.length > _maxLineLength) {
140178
line = line.substring(0, _maxLineLength);
141179
}
142-
if (kept > 0) builder.text('\n');
143180
kept++;
144-
if (fenceOpen) {
145-
builder.text(line);
146-
} else {
147-
builder.line(line);
148-
}
181+
yield (text: line, code: fenceOpen, end: end);
149182
}
150-
return builder.pieces;
151183
}
152184

153185
const _maxLineLength = 2000;
@@ -190,16 +222,35 @@ final _emphasis = [
190222
RegExp(r'\*(?=\S)(.+?)(?<=\S)\*'),
191223
RegExp(r'(?<![A-Za-z0-9_])_(?=\S)(.+?)(?<=\S)_(?![A-Za-z0-9_])'),
192224
RegExp(r'~~(?=\S)(.+?)(?<=\S)~~'),
225+
RegExp(r'<u>(.+?)</u>', caseSensitive: false),
193226
];
194227

228+
/// Unwraps emphasis and resolves backslash escapes. An escaped character is
229+
/// held as a private-use stand-in while delimiters are matched, so `\*x\*`
230+
/// stays `*x*`.
195231
String _unwrapEmphasis(String text) {
196-
var result = text;
232+
if (!text.contains(_escapePrefix) && !_hasDelimiter.hasMatch(text)) {
233+
return text;
234+
}
235+
var result = text.replaceAllMapped(
236+
_escape,
237+
(m) => String.fromCharCode(_escapeBase + m[1]!.codeUnitAt(0)),
238+
);
197239
for (final pattern in _emphasis) {
198240
result = result.replaceAllMapped(pattern, (m) => m[1]!);
199241
}
200-
return result;
242+
return result.replaceAllMapped(
243+
_escaped,
244+
(m) => String.fromCharCode(m[0]!.codeUnitAt(0) - _escapeBase),
245+
);
201246
}
202247

248+
const _escapePrefix = r'\';
249+
const _escapeBase = 0xE000;
250+
final _hasDelimiter = RegExp(r'[*_~<]');
251+
final _escape = RegExp(r'\\([!-/:-@\[-`{-~])');
252+
final _escaped = RegExp('[\uE021-\uE07E]');
253+
203254
// Look ahead so adjacent tokens sharing a colon are both considered.
204255
final _shortcode = RegExp(r'(?=:([a-z0-9_-]+):)', caseSensitive: false);
205256
final _qualifier = RegExp(r'\(([0-9a-f]{64})\)');

‎mobile/test/features/channels/message_content/preview_text_test.dart‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ void main() {
5858
('rule', 'above\n---\nbelow', 'above\nbelow'),
5959
('table', '| a | b |\n|---|:-:|\n| 1 | 2 |', 'a b\n1 2'),
6060
('blank lines', 'one\n\n\ntwo', 'one\ntwo'),
61+
('underline', 'an <u>important</u> note', 'an important note'),
62+
('escaped emphasis', r'\*literal\* and \_x\_', '*literal* and _x_'),
63+
('escaped backslash', r'a \\ b', r'a \ b'),
6164
]) {
6265
test(name, () => expect(_text(source), expected));
6366
}
@@ -72,6 +75,20 @@ void main() {
7275
});
7376

7477
group('line limit', () {
78+
test('the source prefix ends with the last line the preview reads', () {
79+
const content = '# a\n\n```\ncode\n```\nb\nc\nd\ne';
80+
expect(
81+
messagePreviewSource(content, maxLines: 2),
82+
'# a\n\n```\ncode\n```\nb',
83+
);
84+
expect(_text(messagePreviewSource(content, maxLines: 2)), 'a\ncode\nb');
85+
});
86+
87+
test('the source prefix of a short message is the message', () {
88+
expect(messagePreviewSource('one\ntwo', maxLines: 2), 'one\ntwo');
89+
expect(messagePreviewSource('', maxLines: 2), '');
90+
});
91+
7592
test('reads only maxLines + 1 kept lines', () {
7693
final content = List.generate(1000, (i) => 'line $i').join('\n');
7794
expect(_text(content), 'line 0\nline 1\nline 2');

0 commit comments

Comments
 (0)