diff --git a/dart/a2ui_flutter/CHANGELOG.md b/dart/a2ui_flutter/CHANGELOG.md index 80b4d32c54..c5554fde64 100644 --- a/dart/a2ui_flutter/CHANGELOG.md +++ b/dart/a2ui_flutter/CHANGELOG.md @@ -16,6 +16,13 @@ # [a2ui_flutter](https://pub.dev/packages/a2ui_flutter) Changelog +## Unreleased + +- `Image` renders a `data:` URL of an `image/*` type, such as an inline + base64 PNG, as the web renderers do since + [#3108](https://github.com/a2ui-project/a2ui/pull/3108). A `data:` URL of + another type, or one that does not decode, shows the broken-image icon. + ## 0.6.0 - **Breaking:** Requires `a2ui_core` `^0.10.0`, whose types this library diff --git a/dart/a2ui_flutter/lib/src/catalog/basic/image.dart b/dart/a2ui_flutter/lib/src/catalog/basic/image.dart index e2bf4f4fb9..7e65d489a1 100644 --- a/dart/a2ui_flutter/lib/src/catalog/basic/image.dart +++ b/dart/a2ui_flutter/lib/src/catalog/basic/image.dart @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +import 'dart:typed_data'; + import 'package:a2ui_core/a2ui_core.dart'; // ignore: deprecated_member_use, see https://github.com/a2ui-project/a2ui/issues/3235 import 'package:flutter/material.dart'; @@ -20,9 +22,10 @@ import '../../component_implementation.dart'; import '../../component_props.dart'; /// Builds the basic `Image` component: the image at an `http` or `https` -/// `url`, sized by `variant`, resized by `fit` (`cover` for a header without -/// one) and labelled for accessibility by `description`. Any other URL, and -/// an image that fails to load, shows a broken-image icon labelled by the +/// `url`, or inline in a `data:` URL of an `image/*` type, sized by +/// `variant`, resized by `fit` (`cover` for a header without one) and +/// labelled for accessibility by `description`. Any other URL, and an image +/// that fails to load or decode, shows a broken-image icon labelled by the /// same `description`. Widget buildImage( BuildContext context, @@ -43,17 +46,21 @@ Widget buildImage( label: description, child: const Icon(Icons.broken_image), ); - final Widget image = url.startsWith('http://') || url.startsWith('https://') - ? Image.network( - url, + final ImageProvider? provider = + url.startsWith('http://') || url.startsWith('https://') + ? NetworkImage(url) + : _DataUrlImage.tryParse(url); + final Widget image = provider == null + ? broken + : Image( + image: provider, fit: BoxFit.values.asNameMap()[props.string('fit')] ?? (variant == 'header' ? BoxFit.cover : BoxFit.fill), semanticLabel: description, excludeFromSemantics: description.isEmpty, errorBuilder: (context, error, stackTrace) => broken, - ) - : broken; + ); return switch (variant) { 'icon' => _atStart(SizedBox.square(dimension: 24, child: image)), 'avatar' => _atStart( @@ -81,3 +88,36 @@ Widget _atStart(Widget child) => Align( heightFactor: 1, child: child, ); + +/// The image inline in a `data:` URL. +/// +/// Two are equal when their URLs are, unlike [MemoryImage], so a rebuild with +/// the same URL finds the decoded image in the image cache. +class _DataUrlImage extends MemoryImage { + _DataUrlImage._(this._url, super.bytes); + + /// The image in [url], or null when [url] is not a valid `data:` URL of an + /// `image/*` type. + static _DataUrlImage? tryParse(String url) { + final UriData? data = Uri.tryParse(url)?.data; + if (data == null || !data.mimeType.toLowerCase().startsWith('image/')) { + return null; + } + final Uint8List bytes; + try { + bytes = data.contentAsBytes(); + } on FormatException { + return null; + } + return _DataUrlImage._(url, bytes); + } + + final String _url; + + @override + bool operator ==(Object other) => + other is _DataUrlImage && other._url == _url && other.scale == scale; + + @override + int get hashCode => Object.hash(_url, scale); +} diff --git a/dart/a2ui_flutter/test/catalog/basic/image_test.dart b/dart/a2ui_flutter/test/catalog/basic/image_test.dart index e7285bdd43..edd8e92fe9 100644 --- a/dart/a2ui_flutter/test/catalog/basic/image_test.dart +++ b/dart/a2ui_flutter/test/catalog/basic/image_test.dart @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +import 'dart:convert'; + import 'package:a2ui_flutter/a2ui_flutter.dart'; import 'package:a2ui_flutter/v0_9/basic_catalog.dart'; // ignore: deprecated_member_use, see https://github.com/a2ui-project/a2ui/issues/3235 @@ -33,6 +35,12 @@ const String _missing = 'https://images.test/missing.png'; final Map> _images = {_wide: widePng, _tall: tallPng}; +/// A 1x1 PNG. +const String _pixelPng = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB' + '0C8AAAAASUVORK5CYII='; +const String _pixelDataUrl = 'data:image/png;base64,$_pixelPng'; + /// Runs [body] with network images served from [_images] and an empty image /// cache. void _testImages( @@ -192,6 +200,115 @@ void main() { expect(harness.errors, isEmpty); }); + group('data URL', () { + _testImages('renders an image/* data URL from its bytes', ( + tester, + server, + ) async { + final SurfaceHarness harness = await _pumpImages(tester, [ + _image({'url': _pixelDataUrl, 'fit': 'contain'}), + ]); + + final Image image = _imageWidget(tester); + expect(image.image, isA()); + expect((image.image as MemoryImage).bytes, base64Decode(_pixelPng)); + expect(image.fit, BoxFit.contain); + expect(server.requested, isEmpty); + expect(find.byIcon(Icons.broken_image), findsNothing); + expect(tester.takeException(), isNull); + expect(harness.errors, isEmpty); + }); + + _testImages('keeps the natural size', (tester, _) async { + expect(await _sizeOf(tester, null, url: _pixelDataUrl), const Size(1, 1)); + }); + + _testImages('accepts an upper-case scheme and MIME type', ( + tester, + _, + ) async { + await _pumpImages(tester, [ + _image({'url': 'DATA:IMAGE/PNG;base64,$_pixelPng'}), + ]); + + expect(_imageWidget(tester).image, isA()); + expect(find.byIcon(Icons.broken_image), findsNothing); + }); + + _testImages('labels a data URL image for accessibility', (tester, _) async { + final SemanticsHandle semantics = tester.ensureSemantics(); + await _pumpImages(tester, [ + _image({'url': _pixelDataUrl, 'description': 'A pixel'}), + ]); + + expect(_imageWidget(tester).semanticLabel, 'A pixel'); + expect(_imageWidget(tester).excludeFromSemantics, isFalse); + expect(find.bySemanticsLabel('A pixel'), findsOneWidget); + semantics.dispose(); + }); + + _testImages('keeps the decoded image when the component rebuilds', ( + tester, + _, + ) async { + final SurfaceHarness harness = await _pumpImages( + tester, + [ + _image({ + 'url': _pixelDataUrl, + 'description': {'path': '/description'}, + }), + ], + data: {'description': 'Before'}, + ); + final ImageProvider before = _imageWidget(tester).image; + + await harness.send([updateDataModel('After', path: '/description')]); + + expect(_imageWidget(tester).semanticLabel, 'After'); + expect(_imageWidget(tester).image, before); + }); + + for (final (String description, String url) in [ + ('a non-image MIME type', 'data:text/plain;base64,aGVsbG8='), + ('no MIME type', 'data:;base64,$_pixelPng'), + ('malformed base64', 'data:image/png;base64,%%%'), + ]) { + _testImages('shows a placeholder for $description', ( + tester, + server, + ) async { + final SemanticsHandle semantics = tester.ensureSemantics(); + await _pumpImages(tester, [ + _image({'url': url, 'description': 'Not an image'}), + ]); + + expect(find.byType(Image), findsNothing); + expect(server.requested, isEmpty); + expect(find.byIcon(Icons.broken_image), findsOneWidget); + expect( + tester.getSemantics(find.bySemanticsLabel('Not an image')), + matchesSemantics(label: 'Not an image', isImage: true), + ); + expect(tester.takeException(), isNull); + semantics.dispose(); + }); + } + + _testImages('shows a placeholder for image bytes that do not decode', ( + tester, + _, + ) async { + final SurfaceHarness harness = await _pumpImages(tester, [ + _image({'url': 'data:image/png;base64,aGVsbG8='}), + ]); + + expect(find.byIcon(Icons.broken_image), findsOneWidget); + expect(tester.takeException(), isNull); + expect(harness.errors, isEmpty); + }); + }); + for (final url in ['assets/photo.png', 'file:///tmp/photo.png']) { _testImages('shows a placeholder for $url', (tester, server) async { await _pumpImages(tester, [