Skip to content

Commit de4324b

Browse files
committed
fix(mobile): preserve escaped attachment labels through rendering
Signed-off-by: kenny lopez <[email protected]>
1 parent 7843c96 commit de4324b

5 files changed

Lines changed: 168 additions & 51 deletions

File tree

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ List<MarkdownComponent> _useMessageInlineComponents({
6666
channelNames: inputs.channelNames,
6767
onChannelTap: channelTap,
6868
),
69+
_MarkdownLabelEntityMd(),
6970
...MarkdownComponent.inlineComponents,
7071
],
7172
[inputs],
@@ -141,3 +142,19 @@ class _InlineComponentInputs {
141142
int get hashCode =>
142143
Object.hash(content, finalContent, emojiSize, hasMentionHandler);
143144
}
145+
146+
// Encoded label punctuation must remain literal even inside nested formatting.
147+
class _MarkdownLabelEntityMd extends InlineMd {
148+
@override
149+
RegExp get exp => RegExp(r'&#(?:91|92|93);');
150+
151+
@override
152+
Set<MarkdownScope> get scopes => const {MarkdownScope.linkLabel};
153+
154+
@override
155+
InlineSpan span(
156+
BuildContext context,
157+
String text,
158+
GptMarkdownConfig config,
159+
) => TextSpan(text: decodeMarkdownLabelSyntax(text), style: config.style);
160+
}

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

Lines changed: 57 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
final _markdownLinkStartPattern = RegExp(r'(!?\[[^\[\]\n]*\])\(');
2-
31
/// Escapes destination characters that the mobile Markdown renderer treats as
42
/// syntax. Apply the same conversion to metadata keys to preserve media types.
53
String normalizeMarkdownDestination(String url) =>
@@ -117,13 +115,59 @@ bool _hasInlineCloser(String content, int start, int delimiterLength) {
117115
return false;
118116
}
119117

118+
// Numeric entities shield literal label punctuation from gpt_markdown's
119+
// bracket-blind image/link matchers and its earlier \[...\] math pass.
120+
String _normalizeMarkdownLabel(String label) => label.replaceAllMapped(
121+
RegExp(r'\\([\\\[\]])|[\[\]]'),
122+
(match) => '&#${(match[1] ?? match[0]!).codeUnitAt(0)};',
123+
);
124+
125+
/// Restores the literal punctuation encoded for Markdown attachment labels.
126+
String decodeMarkdownLabelSyntax(String label) => label.replaceAllMapped(
127+
RegExp(r'&#(91|92|93);'),
128+
(match) => String.fromCharCode(int.parse(match[1]!)),
129+
);
130+
131+
// Scan each label character once, treating escaped brackets as label text.
132+
// Nested brackets are balanced without restarting at every opening bracket.
133+
({int start, int end})? _findMarkdownLinkStart(String segment, int offset) {
134+
var start = 0;
135+
var depth = 0;
136+
for (var cursor = offset; cursor < segment.length; cursor++) {
137+
final char = segment[cursor];
138+
if (char == r'\' &&
139+
cursor + 1 < segment.length &&
140+
segment[cursor + 1] != '\n') {
141+
cursor++;
142+
continue;
143+
}
144+
if (char == '\n') {
145+
depth = 0;
146+
} else if (char == '[') {
147+
if (depth == 0) {
148+
start = cursor > 0 && segment[cursor - 1] == '!' ? cursor - 1 : cursor;
149+
}
150+
depth++;
151+
} else if (char == ']' && depth > 0) {
152+
depth--;
153+
if (depth == 0 &&
154+
cursor + 1 < segment.length &&
155+
segment[cursor + 1] == '(') {
156+
return (start: start, end: cursor + 2);
157+
}
158+
}
159+
}
160+
return null;
161+
}
162+
120163
String _normalizeLinkSegment(String segment) {
121164
final result = StringBuffer();
122165
var offset = 0;
123-
for (final match in _markdownLinkStartPattern.allMatches(segment)) {
124-
if (match.start < offset) continue;
166+
while (offset < segment.length) {
167+
final match = _findMarkdownLinkStart(segment, offset);
168+
if (match == null) break;
125169
var cursor = match.end;
126-
if (cursor >= segment.length) continue;
170+
if (cursor >= segment.length) break;
127171
final angled = segment[cursor] == '<';
128172
final start = angled ? ++cursor : cursor;
129173
var depth = 0;
@@ -157,7 +201,14 @@ String _normalizeLinkSegment(String segment) {
157201
result.write(_normalizeProseLinks(segment.substring(offset, match.start)));
158202
if (valid) {
159203
final destination = segment.substring(start, destinationEnd);
160-
result.write('${match[1]}(${normalizeMarkdownDestination(destination)})');
204+
final image = segment[match.start] == '!';
205+
final labelStart = match.start + (image ? 2 : 1);
206+
final label = _normalizeMarkdownLabel(
207+
segment.substring(labelStart, match.end - 2),
208+
);
209+
result.write(
210+
'${image ? '!' : ''}[$label](${normalizeMarkdownDestination(destination)})',
211+
);
161212
} else {
162213
// Preserve malformed source, and never scan its inspected suffix again.
163214
// This cursor advances on failure as well as success, bounding work even

‎mobile/lib/features/channels/message_gallery.dart‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import 'package:flutter/foundation.dart';
22

33
import 'message_media.dart';
4+
import 'message_content/link_normalizer.dart';
45

56
/// Image metadata shared by carousel rendering and loading projection.
67
@immutable
@@ -47,15 +48,13 @@ TrailingImageGallery? extractTrailingImageGallery(
4748
if (mediaKind != MessageMediaKind.image) {
4849
break;
4950
}
50-
final markdownLabel = match.group(1)?.trim();
51+
final markdownLabel = decodeMarkdownLabelSyntax(match.group(1)!).trim();
5152
items.add(
5253
MessageGalleryItem(
5354
url: url,
5455
semanticLabel:
5556
imeta?.alt ??
56-
(markdownLabel?.isNotEmpty == true
57-
? markdownLabel!
58-
: 'Message image'),
57+
(markdownLabel.isNotEmpty ? markdownLabel : 'Message image'),
5958
aspectRatio: imeta?.aspectRatio,
6059
),
6160
);

‎mobile/test/features/channels/message_attachment_rendering_test.dart‎

Lines changed: 61 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ void main() {
7676
);
7777
await tester.pumpWidget(
7878
_app(
79-
'Look\n![photo](${angled ? '<$url>' : url})',
79+
'Look\n![photo \\[Q4\\]](${angled ? '<$url>' : url})',
8080
tags: [
8181
[
8282
'imeta',
@@ -134,7 +134,7 @@ void main() {
134134
String? requested;
135135
await tester.pumpWidget(
136136
_app(
137-
'![clip](<$url> $title)',
137+
'![clip \\[Q4\\]](<$url> $title)',
138138
tags: [
139139
['imeta', 'url $url', 'm ${item.$2}'],
140140
],
@@ -156,44 +156,64 @@ void main() {
156156
});
157157
}
158158

159-
for (final extension in ['pdf', 'txt', 'zip', 'mp3', 'svg']) {
160-
testWidgets(
161-
'$extension attachment with title $title opens with auth and filename',
162-
(tester) async {
163-
final url = '$_base/media/report.$extension';
164-
String? opened;
165-
String? filename;
166-
Map<String, String>? headers;
167-
await tester.pumpWidget(
168-
_app(
169-
'[report.$extension](<$url> $title)',
170-
overrides: [
171-
mediaGetAuthServiceProvider.overrideWithValue(
172-
MediaGetAuthService(
173-
baseUrl: _base,
174-
nsec: nostr.Keys.generate().nsec,
159+
for (final (stem, angled) in [
160+
('report [Q4]', false),
161+
('report [Q4]', true),
162+
('report [Q4', true),
163+
('report Q4]', true),
164+
(r'report \ [Q4]', true),
165+
]) {
166+
for (final extension in ['pdf', 'txt', 'zip', 'mp3', 'svg']) {
167+
testWidgets(
168+
'$stem.$extension angled=$angled title $title opens with auth and filename',
169+
(tester) async {
170+
final url = '$_base/media/report.$extension';
171+
final blob = BlobDescriptor(
172+
url: url,
173+
sha256: 'a' * 64,
174+
size: 1,
175+
type: 'application/octet-stream',
176+
uploaded: 0,
177+
filename: '$stem.$extension',
178+
);
179+
final markdown = blob.toMarkdownImage().replaceFirst(
180+
'($url)',
181+
angled ? '(<$url> $title)' : '($url)',
182+
);
183+
String? opened;
184+
String? filename;
185+
Map<String, String>? headers;
186+
await tester.pumpWidget(
187+
_app(
188+
markdown,
189+
overrides: [
190+
mediaGetAuthServiceProvider.overrideWithValue(
191+
MediaGetAuthService(
192+
baseUrl: _base,
193+
nsec: nostr.Keys.generate().nsec,
194+
),
175195
),
176-
),
177-
openDownloadedFileProvider.overrideWithValue((
178-
url,
179-
auth,
180-
name,
181-
) async {
182-
opened = url;
183-
headers = auth;
184-
filename = name;
185-
}),
186-
],
187-
),
188-
);
189-
await tester.tap(find.text('report.$extension'));
190-
await tester.pump();
191-
expect(opened, url);
192-
expect(filename, 'report.$extension');
193-
expect(headers?['Authorization'], startsWith('Nostr '));
194-
expect(find.byType(MediaImage), findsNothing);
195-
},
196-
);
196+
openDownloadedFileProvider.overrideWithValue((
197+
url,
198+
auth,
199+
name,
200+
) async {
201+
opened = url;
202+
headers = auth;
203+
filename = name;
204+
}),
205+
],
206+
),
207+
);
208+
await tester.tap(find.text('$stem.$extension'));
209+
await tester.pump();
210+
expect(opened, url);
211+
expect(filename, '$stem.$extension');
212+
expect(headers?['Authorization'], startsWith('Nostr '));
213+
expect(find.byType(MediaImage), findsNothing);
214+
},
215+
);
216+
}
197217
}
198218
}
199219

@@ -209,7 +229,7 @@ void main() {
209229
);
210230
await tester.pumpWidget(
211231
_app(
212-
'Gallery\n![first](<$first>)\n![second]($second)',
232+
'Gallery\n![first](<$first>)\n![second \\[Q4\\]]($second)',
213233
tags: [
214234
[
215235
'imeta',
@@ -226,6 +246,7 @@ void main() {
226246
await _waitForImages(tester);
227247
await tester.pumpAndSettle();
228248
expect(find.text('2 images'), findsOneWidget);
249+
expect(find.bySemanticsLabel('Open second [Q4]'), findsOneWidget);
229250
expect(find.bySemanticsLabel('Open First photo'), findsOneWidget);
230251
expect(find.text('Image unavailable'), findsNothing);
231252
await tester.tap(

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ void main() {
6060
test('near-limit malformed openers complete without suffix rescans', () {
6161
// A generous wall-clock ceiling catches the original ~20 second freeze
6262
// while allowing slow CI hosts ample headroom for the linear scanner.
63-
for (final unit in ['[x](', '[']) {
63+
for (final unit in ['[x](', '[', r'[x\[', r'[x\]']) {
6464
final input = unit * (256 * 1024 ~/ unit.length);
6565
final watch = Stopwatch()..start();
6666
final result = normalizeBareLinks(input);
@@ -69,6 +69,35 @@ void main() {
6969
expect(watch.elapsed, lessThan(const Duration(seconds: 2)));
7070
}
7171
});
72+
for (final (label, rendered) in [
73+
(r'report \[Q4\].pdf', 'report &#91;Q4&#93;.pdf'),
74+
(r'only \[ opening', 'only &#91; opening'),
75+
(r'only \] closing', 'only &#93; closing'),
76+
(
77+
r'backslash \\ and \[brackets\]',
78+
'backslash &#92; and &#91;brackets&#93;',
79+
),
80+
('nested [label]', 'nested &#91;label&#93;'),
81+
]) {
82+
for (final prefix in ['!', '']) {
83+
test('$prefix preserves escaped label $label', () {
84+
expect(
85+
normalizeBareLinks('$prefix[$label](<$media>)'),
86+
'$prefix[$rendered]($media)',
87+
);
88+
});
89+
}
90+
}
91+
test('URL and title brackets do not capture a later attachment label', () {
92+
expect(
93+
normalizeBareLinks(
94+
'[first](<https://relay.example/file?q=[> "Title [") '
95+
r'[second \[Q4\]](<https://relay.example/file.pdf>)',
96+
),
97+
'[first](https://relay.example/file?q=[) '
98+
'[second &#91;Q4&#93;](https://relay.example/file.pdf)',
99+
);
100+
});
72101
test('escapes spaces and parentheses without double-encoding URLs', () {
73102
const raw = 'https://relay.example/media/photo (1).png?q=a%20b&v=2';
74103
const encoded =

0 commit comments

Comments
 (0)