Files
buzz/mobile/test/features/channels/message_attachment_rendering_test.dart
Tom Brow 44c8206bea fix(mobile): wrap inline Markdown links with their sentence (#9462)
A link inside a sentence used to be drawn as its own little widget, so a
long label jumped to a line of its own and the words after it started
yet another line. Plain links are now text in the sentence: a long label
breaks mid-label, and the words after it continue on the same line.

Tap still opens the link, a finger on it still tints it, and a hold
still opens the link sheet (Open, Copy, Share) instead of the message
menu. Buzz chips (channel and message links), audio attachments and
repository links keep their current widget look.

| Before | After |
| --- | --- |
| <img alt="before"
src="https://github.com/user-attachments/assets/e77aa97a-6ac5-43b9-bc44-cc43fb169c8f"
width="300"> | <img alt="after"
src="https://github.com/user-attachments/assets/4c76bb23-e6df-4244-bf7e-e1753b727d7b"
width="300"> |

A finger on a text link tints it, across every line of a wrapped label:

<img alt="Pressed tint on a wrapped link"
src="https://github.com/user-attachments/assets/1cde5a1a-39aa-4bc7-90f8-8d95b15ee852"
width="400">


https://github.com/user-attachments/assets/021dd099-d24b-4370-bf75-e60f273e2a92

### Regressions

One tradeoff, accepted so links can wrap:

- **VoiceOver users lose Copy and Share on text links.** VoiceOver still
opens the link, but a text span can only expose a tap to accessibility,
so the link sheet (Copy, Share) can't be reached on text links with
VoiceOver. Chips and repository links keep it. A link nothing can open
(such as mailto) shows its sheet on a tap, so it isn't dead for
VoiceOver users.

Nothing else gets worse. The pressed tint is a translucent paint-only
layer drawn on top of the message's Markdown over the link's text boxes,
so inline code and table header backgrounds can't hide it, so a press
repaints that message and rebuilds nothing; a tint that spans a wrapped
label covers both lines, and it stays inside what's visible (a long link
in a scrolled table cell tints only inside the table). Each message
reuses one recognizer per link across rebuilds and disposes them when
its text changes or the message goes away, and a scroll that starts on a
link cancels the hold, so it never opens the sheet. Only plain links
change shape (including any inline code inside a link label, which now
taps and holds as part of the link); chips, media and code outside links
are untouched.

### Validation

Added tests:
- A long link label in a narrow message breaks across lines, and the
following words continue on the line where it ends.
- Holding a link and then sliding off it before the hold delay opens
nothing (no sheet, no message menu, no open).
- Pressing a text link tints it, and lifting or sliding off clears the
tint; lifting a second finger keeps the tint.
- A pressed link in a horizontally scrolled table cell is tinted inside
the table and nothing past its edge.
- Tapping a link nothing can open (mailto), by finger or screen reader
activate, shows Copy and Share.
- A pressed link in inline code (plain and in a bubble) or in a table
header shows its tint (these fail with the tint drawn underneath).
- Code inside a link label taps and holds as part of the link; a hold
across an edit that removes the link does nothing; a second finger
mid-hold doesn't restart it.

Existing link tests (tap, hold sheet, copy and open from the sheet,
message menu beside a link, swipe to reply from a link, attachment
links) now find links inside their paragraph. They all pass, along with
the full mobile suite and analyze.

Automated simulator run (iPhone 17 Pro, internal community, synthetic
message): pressing a wrapped link tinted all three of its lines; holding
a text link opened its sheet; holding the text right after it opened the
message menu; tapping the second line of a wrapped link opened it in
Safari; a scroll starting on a link scrolled the list and opened
nothing.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-15 09:06:30 -08:00

267 lines
8.7 KiB
Dart

import 'dart:convert';
import 'package:buzz/features/channels/message_content.dart';
import 'package:buzz/features/channels/media_viewer_page.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/theme/theme.dart';
import 'package:buzz/shared/widgets/media_loading_placeholder.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:hooks_riverpod/misc.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:nostr/nostr.dart' as nostr;
import '../../helpers/message_link_finders.dart';
import '../../helpers/media_codec_fixtures.dart';
const _base = 'https://relay.example';
Widget _app(
String content, {
List<List<String>> tags = const [],
List<Override> overrides = const [],
}) => ProviderScope(
overrides: overrides,
child: MaterialApp(
theme: AppTheme.light(),
home: Scaffold(
body: MessageContent(
content: content,
tags: tags,
channelNames: const {'general': 'channel-id'},
),
),
),
);
// Image codecs complete outside the fake test clock. Wait for actual pixels,
// rather than waiting for an indefinitely animated loading shimmer to settle.
Future<void> _waitForImages(WidgetTester tester) async {
for (var attempt = 0; attempt < 200; attempt++) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 10)),
);
await tester.pump(const Duration(milliseconds: 16));
final images = tester.widgetList<RawImage>(find.byType(RawImage));
if (images.any((image) => image.image != null) &&
find.byType(MediaLoadingPlaceholder).evaluate().isEmpty) {
return;
}
}
fail('Media did not produce a decoded image frame');
}
void main() {
setUp(() {
MediaImageProvider.debugResetCooldowns();
PaintingBinding.instance.imageCache.clear();
PaintingBinding.instance.imageCache.clearLiveImages();
});
for (final fixture in mediaCodecFixtures.entries) {
for (final angled in [false, true]) {
testWidgets(
'${fixture.key} ${angled ? 'angle' : 'plain'} image downloads and opens',
(tester) async {
final url = '$_base/media/photo.${fixture.key}?download=1&v=2';
final requests = <http.Request>[];
final client = MockClient((request) async {
requests.add(request);
return http.Response.bytes(base64Decode(fixture.value), 200);
});
final auth = MediaGetAuthService(
baseUrl: _base,
nsec: nostr.Keys.generate().nsec,
);
await tester.pumpWidget(
_app(
'${angled ? 'oops [ text ' : 'Look\n'}'
'![photo \\[Q4\\]](${angled ? '<$url>' : url})',
tags: [
[
'imeta',
'url $url',
'm image/${fixture.key}',
'dim 2x2',
'alt Photo',
],
],
overrides: [
mediaHttpClientProvider.overrideWithValue(client),
mediaGetAuthServiceProvider.overrideWithValue(auth),
],
),
);
await _waitForImages(tester);
await tester.pumpAndSettle();
expect(requests, hasLength(1));
expect(requests.single.url.toString(), url);
expect(
requests.single.headers['Authorization'],
startsWith('Nostr '),
);
expect(find.text('Image unavailable'), findsNothing);
expect(tester.takeException(), isNull);
await tester.tap(
find.byKey(ValueKey('message-media-image-preview:$url')),
);
await _waitForImages(tester);
await tester.pumpAndSettle();
expect(
tester
.widget<MediaImageViewerPage>(find.byType(MediaImageViewerPage))
.imageUrl,
url,
);
expect(find.text('Failed to load image'), findsNothing);
},
);
}
}
for (final title in ['(Video title)', r'"A \"preview\""']) {
for (final item in [
('mp4', 'video/mp4'),
('mov', 'video/quicktime'),
('webm', 'video/webm'),
('bin', 'video/mp4'),
]) {
testWidgets('${item.$1} uses video metadata with title $title', (
tester,
) async {
final url = '$_base/media/clip (1).${item.$1}';
final expected = '$_base/media/clip%20%281%29.${item.$1}';
await tester.pumpWidget(
_app(
'oops [ text ![clip \\[Q4\\]](<$url> $title)',
tags: [
['imeta', 'url $url', 'm ${item.$2}'],
],
),
);
await tester.pumpAndSettle();
expect(
find.byKey(ValueKey('message-media-video-preview:$expected')),
findsOneWidget,
);
expect(find.text('Image unavailable'), findsNothing);
});
}
for (final (stem, angled) in [
('report [Q4]', false),
('report [Q4]', true),
('report [Q4', true),
('report Q4]', true),
(r'report \ [Q4]', true),
]) {
for (final extension in ['pdf', 'txt', 'zip', 'mp3', 'svg']) {
testWidgets(
'$stem.$extension angled=$angled title $title opens with auth and filename',
(tester) async {
final url = '$_base/media/report.$extension';
final blob = BlobDescriptor(
url: url,
sha256: 'a' * 64,
size: 1,
type: 'application/octet-stream',
uploaded: 0,
filename: '$stem.$extension',
);
final markdown = blob.toMarkdownImage().replaceFirst(
'($url)',
angled ? '(<$url> $title)' : '($url)',
);
String? opened;
String? filename;
Map<String, String>? headers;
await tester.pumpWidget(
_app(
'${angled ? 'oops [ then ' : ''}$markdown',
overrides: [
mediaGetAuthServiceProvider.overrideWithValue(
MediaGetAuthService(
baseUrl: _base,
nsec: nostr.Keys.generate().nsec,
),
),
openDownloadedFileProvider.overrideWithValue((
url,
auth,
name,
) async {
opened = url;
headers = auth;
filename = name;
}),
],
),
);
await tester.tapAt(linkCenter(tester, '$stem.$extension'));
await tester.pump();
expect(opened, url);
expect(filename, '$stem.$extension');
expect(headers?['Authorization'], startsWith('Nostr '));
expect(find.byType(MediaImage), findsNothing);
},
);
}
}
}
testWidgets(
'mixed angle/plain gallery retains URLs, metadata and viewer items',
(tester) async {
const first = '$_base/media/photo(1).png';
const second = '$_base/media/photo2.png';
const normalizedFirst = '$_base/media/photo%281%29.png';
final client = MockClient(
(_) async =>
http.Response.bytes(base64Decode(mediaCodecFixtures['png']!), 200),
);
await tester.pumpWidget(
_app(
'oops [ text ![inline](<$second>)\n![first](<$first>)\n![second \\[Q4\\]]($second)',
tags: [
[
'imeta',
'url $first',
'm image/png',
'dim 2x2',
'alt First photo',
],
['imeta', 'url $second', 'm image/png', 'dim 2x2'],
],
overrides: [mediaHttpClientProvider.overrideWithValue(client)],
),
);
await _waitForImages(tester);
await tester.pumpAndSettle();
expect(
find.byKey(const ValueKey('message-media-image-preview:$second')),
findsOneWidget,
);
expect(find.text('2 images'), findsOneWidget);
expect(find.bySemanticsLabel('Open second [Q4]'), findsOneWidget);
expect(find.bySemanticsLabel('Open First photo'), findsOneWidget);
expect(find.text('Image unavailable'), findsNothing);
await tester.tap(
find.byKey(
const ValueKey('message-media-carousel-item:$normalizedFirst'),
),
);
await _waitForImages(tester);
await tester.pumpAndSettle();
final viewer = tester.widget<MediaImageViewerPage>(
find.byType(MediaImageViewerPage),
);
expect(viewer.galleryItems!.map((item) => item.url), [
normalizedFirst,
second,
]);
},
);
}