Size URL image previews to the image's aspect ratio

The preview now fills the bubble's available width and takes its height from
the loaded image, capped at 400dp for tall images. Loading and error states
are a compact full-width strip, and the error text is localized.
This commit is contained in:
zjs81 committed 2026-11-23 22:24:01 -07:00
1 parent 6748d5f0f2
commit 40fb80cf5c
23 files changed
+401 -25

No files matched your search

+143 -25
View File
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:http/http.dart' as http;
import '../l10n/l10n.dart';
import '../models/app_settings.dart';
/// Finds and renders image URLs embedded in ordinary text messages.
@@ -290,9 +291,18 @@ class _MessageUrlImageFutureBuilderState
}
class MessageUrlImagePreview extends StatelessWidget {
const MessageUrlImagePreview({super.key, required this.imageUrl});
const MessageUrlImagePreview({
super.key,
required this.imageUrl,
@visibleForTesting this.imageProvider,
});
static const double maxHeight = 400;
static const double fallbackWidth = 320;
static const double statusHeight = 130;
final String imageUrl;
final ImageProvider? imageProvider;
@override
Widget build(BuildContext context) {
@@ -347,31 +357,139 @@ class MessageUrlImagePreview extends StatelessWidget {
),
);
},
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: SizedBox(
width: 240,
height: 240,
child: CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.contain,
placeholder: (context, url) => ColoredBox(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: const Center(
child: CircularProgressIndicator(strokeWidth: 2),
),
),
errorWidget: (context, url, error) => Container(
padding: const EdgeInsets.all(12),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Text(
'Unable to load image',
style: Theme.of(context).textTheme.bodySmall,
),
),
),
),
child: _AdaptiveUrlImage(
provider: imageProvider ?? CachedNetworkImageProvider(imageUrl),
),
);
}
}
/// Fits an image of [imageWidth] x [imageHeight] into [maxWidth], keeping its
/// aspect ratio. Images taller than [maxHeight] are scaled down whole instead.
Size urlImagePreviewSize(
double imageWidth,
double imageHeight,
double maxWidth, {
double maxHeight = MessageUrlImagePreview.maxHeight,
}) {
var width = maxWidth;
var height = width * imageHeight / imageWidth;
if (height > maxHeight) {
height = maxHeight;
width = height * imageWidth / imageHeight;
}
return Size(width, height);
}
class _AdaptiveUrlImage extends StatefulWidget {
const _AdaptiveUrlImage({required this.provider});
final ImageProvider provider;
@override
State<_AdaptiveUrlImage> createState() => _AdaptiveUrlImageState();
}
class _AdaptiveUrlImageState extends State<_AdaptiveUrlImage> {
ImageStream? _stream;
late final ImageStreamListener _listener = ImageStreamListener(
(info, _) {
if (!mounted) {
info.dispose();
return;
}
setState(() {
_info?.dispose();
_info = info;
_failed = false;
});
},
onError: (_, _) {
if (mounted) setState(() => _failed = true);
},
);
ImageInfo? _info;
bool _failed = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_resolve();
}
@override
void didUpdateWidget(covariant _AdaptiveUrlImage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.provider != widget.provider) {
_info?.dispose();
_info = null;
_failed = false;
_resolve();
}
}
void _resolve() {
final stream = widget.provider.resolve(
createLocalImageConfiguration(context),
);
if (stream.key == _stream?.key) return;
_stream?.removeListener(_listener);
_stream = stream..addListener(_listener);
}
@override
void dispose() {
_stream?.removeListener(_listener);
_info?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final color = Theme.of(context).colorScheme.surfaceContainerHighest;
return LayoutBuilder(
builder: (context, constraints) {
final maxWidth = constraints.maxWidth.isFinite
? constraints.maxWidth
: MessageUrlImagePreview.fallbackWidth;
final info = _info;
final Widget child;
if (info != null) {
final size = urlImagePreviewSize(
info.image.width.toDouble(),
info.image.height.toDouble(),
maxWidth,
);
child = SizedBox.fromSize(
size: size,
child: RawImage(image: info.image, fit: BoxFit.fill),
);
} else if (_failed) {
child = Container(
width: maxWidth,
height: MessageUrlImagePreview.statusHeight,
padding: const EdgeInsets.all(12),
alignment: Alignment.centerLeft,
color: color,
child: Text(
context.l10n.messageUrlImageLoadFailed,
style: Theme.of(context).textTheme.bodySmall,
),
);
} else {
child = SizedBox(
width: maxWidth,
height: MessageUrlImagePreview.statusHeight,
child: ColoredBox(
color: color,
child: const Center(
child: CircularProgressIndicator(strokeWidth: 2),
),
),
);
}
return ClipRRect(borderRadius: BorderRadius.circular(12), child: child);
},
);
}
}
+4
View File
@@ -4871,5 +4871,9 @@
"type": "String"
}
}
},
"messageUrlImageLoadFailed": "Unable to load image",
"@messageUrlImageLoadFailed": {
"description": "Shown in a message bubble when a linked image fails to load"
}
}
+6
View File
@@ -13797,6 +13797,12 @@ abstract class AppLocalizations {
/// In en, this message translates to:
/// **'{name} claimed a win on time'**
String chess_notifyTimeout(String name);
/// Shown in a message bubble when a linked image fails to load
///
/// In en, this message translates to:
/// **'Unable to load image'**
String get messageUrlImageLoadFailed;
}
class _AppLocalizationsDelegate
+3
View File
@@ -8295,4 +8295,7 @@ class AppLocalizationsBg extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name поиска победа по време';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8270,4 +8270,7 @@ class AppLocalizationsCs extends AppLocalizations {
String chess_notifyTimeout(String name) {
return 'Hráč $name uplatnil výhru na čas';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8311,4 +8311,7 @@ class AppLocalizationsDe extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name hat den Sieg wegen Zeit beansprucht';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8180,4 +8180,7 @@ class AppLocalizationsEn extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name claimed a win on time';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8289,4 +8289,7 @@ class AppLocalizationsEs extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name reclamó la victoria por tiempo';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8314,4 +8314,7 @@ class AppLocalizationsFr extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name a réclamé la victoire au temps';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8278,4 +8278,7 @@ class AppLocalizationsHu extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name időtúllépés miatt nyerést követelt';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8301,4 +8301,7 @@ class AppLocalizationsIt extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name ha rivendicato la vittoria a tempo';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -7931,4 +7931,7 @@ class AppLocalizationsJa extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name が時間切れによる勝ちを申請しました';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -7940,4 +7940,7 @@ class AppLocalizationsKo extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name님이 시간 초과 승리를 요청했습니다';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8254,4 +8254,7 @@ class AppLocalizationsNl extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name heeft winst op tijd geclaimd';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8340,4 +8340,7 @@ class AppLocalizationsPl extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name zgłosił(a) wygraną na czas';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8277,6 +8277,9 @@ class AppLocalizationsPt extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name reivindicou vitória por tempo';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
/// The translations for Portuguese, as used in Portugal (`pt_PT`).
+3
View File
@@ -8320,4 +8320,7 @@ class AppLocalizationsRu extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name требует победу по времени';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8279,4 +8279,7 @@ class AppLocalizationsSk extends AppLocalizations {
String chess_notifyTimeout(String name) {
return 'Hráč $name uplatnil výhru na čas';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8279,4 +8279,7 @@ class AppLocalizationsSl extends AppLocalizations {
String chess_notifyTimeout(String name) {
return 'Igralec $name je zahteval zmago na čas';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8228,4 +8228,7 @@ class AppLocalizationsSv extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name krävde vinst på tid';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -8334,4 +8334,7 @@ class AppLocalizationsUk extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name вимагає перемогу за часом';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
+3
View File
@@ -7770,4 +7770,7 @@ class AppLocalizationsZh extends AppLocalizations {
String chess_notifyTimeout(String name) {
return '$name 申请超时判胜';
}
@override
String get messageUrlImageLoadFailed => 'Unable to load image';
}
@@ -0,0 +1,191 @@
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/message_url_image_helper.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
Future<ui.Image> _solid(int w, int h) {
final c = Completer<ui.Image>();
ui.decodeImageFromPixels(
Uint8List(w * h * 4),
w,
h,
ui.PixelFormat.rgba8888,
c.complete,
);
return c.future;
}
class _FailingProvider extends ImageProvider<_FailingProvider> {
@override
Future<_FailingProvider> obtainKey(ImageConfiguration c) =>
SynchronousFuture(this);
@override
ImageStreamCompleter loadImage(
_FailingProvider key,
ImageDecoderCallback decode,
) => OneFrameImageStreamCompleter(Future.error(Exception('nope')));
}
Widget _host(Widget child, {double width = 320, double scale = 1.0}) {
return MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: MediaQuery(
data: MediaQueryData(
size: Size(width, 800),
textScaler: TextScaler.linear(scale),
),
child: Scaffold(
body: Align(
alignment: Alignment.topLeft,
// Mimics a bubble: bounded width, tight-to-content otherwise.
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: width - 40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Align(alignment: Alignment.centerLeft, child: child),
const Text('caption text that follows the image'),
],
),
),
),
),
),
);
}
Future<Size> _previewSize(WidgetTester tester, int w, int h) async {
final image = await tester.runAsync(() => _solid(w, h));
await tester.pumpWidget(
_host(
MessageUrlImagePreview(
imageUrl: 'https://example.com/a.png',
imageProvider: _ImageProviderOf(image!),
),
),
);
await tester.pump();
return tester.getSize(find.byType(RawImage));
}
class _ImageProviderOf extends ImageProvider<_ImageProviderOf> {
_ImageProviderOf(this.image);
final ui.Image image;
@override
Future<_ImageProviderOf> obtainKey(ImageConfiguration c) =>
SynchronousFuture(this);
@override
ImageStreamCompleter loadImage(
_ImageProviderOf key,
ImageDecoderCallback decode,
) => OneFrameImageStreamCompleter(
SynchronousFuture(ImageInfo(image: image.clone())),
);
}
void main() {
test('urlImagePreviewSize keeps aspect ratio and caps height', () {
expect(urlImagePreviewSize(400, 100, 280), const Size(280, 70));
expect(urlImagePreviewSize(300, 300, 280), const Size(280, 280));
final tall = urlImagePreviewSize(100, 1000, 280);
expect(tall.height, MessageUrlImagePreview.maxHeight);
expect(tall.width, closeTo(40, 0.001));
});
testWidgets('4:1 image fills width with height width/4', (tester) async {
final size = await _previewSize(tester, 400, 100);
expect(size.width, 280);
expect(size.height, closeTo(70, 0.001));
});
testWidgets('square image is 1:1 at full width', (tester) async {
final size = await _previewSize(tester, 300, 300);
expect(size, const Size(280, 280));
});
testWidgets('tall image is capped and shown whole', (tester) async {
final size = await _previewSize(tester, 100, 1000);
expect(size.height, MessageUrlImagePreview.maxHeight);
expect(size.width, closeTo(40, 0.001));
});
testWidgets('unbounded width falls back to 320', (tester) async {
final image = await tester.runAsync(() => _solid(640, 320));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: MessageUrlImagePreview(
imageUrl: 'x',
imageProvider: _ImageProviderOf(image!),
),
),
),
),
);
await tester.pump();
expect(tester.getSize(find.byType(RawImage)), const Size(320, 160));
});
for (final scale in [1.3, 2.0]) {
testWidgets('error state is compact without overflow at ${scale}x', (
tester,
) async {
await tester.pumpWidget(
_host(
MessageUrlImagePreview(
imageUrl: 'x',
imageProvider: _FailingProvider(),
),
scale: scale,
),
);
await tester.pump();
await tester.pump();
expect(find.text('Unable to load image'), findsOneWidget);
expect(tester.takeException(), isNull);
});
}
testWidgets('loading placeholder is compact and full width', (tester) async {
await tester.pumpWidget(
_host(
MessageUrlImagePreview(imageUrl: 'x', imageProvider: _NeverProvider()),
),
);
final box = find.ancestor(
of: find.byType(CircularProgressIndicator),
matching: find.byType(SizedBox),
);
final size = tester.getSize(box.first);
expect(size.width, 280);
expect(size.height, MessageUrlImagePreview.statusHeight);
});
}
class _NeverProvider extends ImageProvider<_NeverProvider> {
@override
Future<_NeverProvider> obtainKey(ImageConfiguration c) =>
SynchronousFuture(this);
@override
ImageStreamCompleter loadImage(
_NeverProvider key,
ImageDecoderCallback decode,
) => OneFrameImageStreamCompleter(Completer<ImageInfo>().future);
}