Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ Widget buildStreamMessageTextPlayground(BuildContext context) {
description: 'Size to fit content vs expand to parent.',
);

final showImages = context.knobs.boolean(
label: 'Show Images',
description: 'Show markdown images from avatars.githubusercontent.com as images; others stay links.',
);

// -- Theme props ------------------------------------------------------------

final textColor = context.knobs.object.dropdown<_ColorOption>(
Expand Down Expand Up @@ -106,6 +111,7 @@ Widget buildStreamMessageTextPlayground(BuildContext context) {
selectable: selectable,
softLineBreak: softLineBreak,
fitContent: fitContent,
showImages: showImages,
),
],
),
Expand Down Expand Up @@ -250,6 +256,13 @@ const _conversationMessages = [
alignment: StreamMessageAlignment.end,
stackPosition: StreamMessageStackPosition.single,
),
_ChatMessage(
text:
'Our logo ![Flutter logo](https://avatars.githubusercontent.com/u/14101776?s=200) '
'and one from elsewhere ![a photo](https://example.com/photo.png)',
alignment: StreamMessageAlignment.start,
stackPosition: StreamMessageStackPosition.single,
),
];

class _ConversationMessage extends StatelessWidget {
Expand All @@ -258,12 +271,14 @@ class _ConversationMessage extends StatelessWidget {
required this.selectable,
required this.softLineBreak,
required this.fitContent,
required this.showImages,
});

final _ChatMessage message;
final bool selectable;
final bool softLineBreak;
final bool fitContent;
final bool showImages;

@override
Widget build(BuildContext context) {
Expand Down Expand Up @@ -294,11 +309,13 @@ class _ConversationMessage extends StatelessWidget {

Widget text = StreamMessageText(
message.text,
key: ValueKey(showImages),
selectable: selectable,
softLineBreak: softLineBreak,
fitContent: fitContent,
onTapLink: (_, href, _) => _showSnack(context, 'Link: $href'),
onTapAnyMention: (displayText, type, id) => _showSnack(context, '$type: $displayText (id: $id)'),
showImage: showImages ? _isGalleryImage : null,
);

if (!hideBubble) {
Expand All @@ -315,6 +332,10 @@ class _ConversationMessage extends StatelessWidget {
}
}

bool _isGalleryImage(StreamMarkdownImage image) {
return image.uri.scheme == 'https' && image.uri.host == 'avatars.githubusercontent.com';
}

// =============================================================================
// Showcase
// =============================================================================
Expand Down Expand Up @@ -869,11 +890,36 @@ class _ExtensibilitySection extends StatelessWidget {
),
),
),
_ExampleCard(
label: 'Markdown images',
subtitle: 'Shown as links to the image unless showImage allows them.',
child: Builder(
builder: (context) => StreamMessageText(
'Here is the ![Flutter logo](https://avatars.githubusercontent.com/u/14101776?s=200) '
'and one with no alt text: '
'![](https://avatars.githubusercontent.com/u/14101776?s=200)',
onTapLink: (_, href, _) => _showSnack(context, 'Link: $href'),
),
),
),
_ExampleCard(
label: 'Allowed markdown images',
subtitle: 'showImage allows one host; images from other hosts stay links.',
child: Builder(
builder: (context) => StreamMessageText(
'![Flutter logo](https://avatars.githubusercontent.com/u/14101776?s=200)\n\n'
'From elsewhere: ![a photo](https://example.com/photo.png)',
showImage: (image) => image.uri.scheme == 'https' && image.uri.host == 'avatars.githubusercontent.com',
onTapLink: (_, href, _) => _showSnack(context, 'Link: $href'),
),
),
),
_ExampleCard(
label: 'Custom image builder',
subtitle: 'Markdown images with rounded corners and placeholder.',
subtitle: 'Images from an allowed host, with rounded corners and placeholder.',
child: StreamMessageText(
'![Flutter logo](https://storage.googleapis.com/cms-storage-bucket/c823e53b3a1a7b0d36a9.png)',
'![Flutter logo](https://avatars.githubusercontent.com/u/14101776?s=200)',
showImage: (image) => image.uri.scheme == 'https' && image.uri.host == 'avatars.githubusercontent.com',
imageBuilder: (uri, title, alt) {
return ClipRRect(
borderRadius: BorderRadius.circular(8),
Expand Down
3 changes: 3 additions & 0 deletions packages/stream_core_flutter/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
- Added the `fullscreen` icon to `StreamIcons`.
- Added the `blurOffFill`, `effectsFill`, `fullscreenExit`, `languageFill`,
`qrCodeFill` and `unflag` icons to `StreamIcons`.
- Added `showImage` and `StreamMarkdownImage` to `StreamMessageText`, to choose which markdown images are shown.

### 🐛 Bug Fixes

Expand All @@ -26,6 +27,8 @@
timestamp, then username (previously username first). Start-aligned rows
are unchanged.
- `StreamTextInput`'s default border radius is now `StreamRadius.xl` (16) instead of `StreamRadius.lg` (12).
- `StreamMessageText` shows markdown images as links labelled with their alt text unless `showImage` allows them;
`imageBuilder` builds only allowed images.
- Stream text now follows Material's default font family when the app sets
none, which can render differently on web and desktop.
- `StreamColors.transparent` is now `Colors.transparent` (transparent black)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import '../../theme/semantics/stream_color_scheme.dart';
import '../../theme/semantics/stream_text_theme.dart';
import '../../theme/stream_theme_extensions.dart';
import '../accessories/stream_emoji.dart';
import '../common/stream_network_image.dart';
import '../message_layout/stream_message_layout.dart';

/// The default protocol prefix used to identify mention links.
Expand Down Expand Up @@ -73,6 +74,36 @@ typedef MarkdownTapAnyMentionCallback =
String id,
);

/// Decides whether a markdown [image] in a [StreamMessageText] is shown as an image.
///
/// See also:
///
/// * [StreamMessageTextProps.showImage], which takes this.
typedef StreamMarkdownImagePredicate = bool Function(StreamMarkdownImage image);

/// A markdown image in a [StreamMessageText].
///
/// For `![a cat](https://example.com/cat.png "Our cat")`, [uri] is the address,
/// [alt] is `a cat` and [title] is `Our cat`.
///
/// See also:
///
/// * [StreamMessageTextProps.showImage], which decides whether it is shown as an image.
@immutable
final class StreamMarkdownImage {
/// Creates a description of a markdown image.
const StreamMarkdownImage({required this.uri, this.alt = '', this.title});

/// The address of the image.
final Uri uri;

/// The image's alt text, or empty if it has none.
final String alt;

/// The image's title, if it has one.
final String? title;
}

// Matches characters that render as emoji — either those with default emoji
// presentation, or text-default characters forced to emoji via VS16 (U+FE0F).
//
Expand Down Expand Up @@ -128,6 +159,7 @@ class StreamMessageText extends StatelessWidget {
MarkdownTapAnyMentionCallback? onTapAnyMention,
VoidCallback? onTapText,
MarkdownImageBuilder? imageBuilder,
StreamMarkdownImagePredicate? showImage,
SyntaxHighlighter? syntaxHighlighter,
Map<String, MarkdownElementBuilder>? builders,
Map<String, MarkdownPaddingBuilder>? paddingBuilders,
Expand All @@ -147,6 +179,7 @@ class StreamMessageText extends StatelessWidget {
onTapAnyMention: onTapAnyMention,
onTapText: onTapText,
imageBuilder: imageBuilder,
showImage: showImage,
syntaxHighlighter: syntaxHighlighter,
builders: builders,
paddingBuilders: paddingBuilders,
Expand Down Expand Up @@ -218,6 +251,7 @@ class StreamMessageTextProps {
this.onTapAnyMention,
this.onTapText,
this.imageBuilder,
this.showImage,
this.syntaxHighlighter,
this.builders,
this.paddingBuilders,
Expand Down Expand Up @@ -269,9 +303,25 @@ class StreamMessageTextProps {
/// Called when non-link text is tapped.
final VoidCallback? onTapText;

/// Custom image builder.
/// Builds the markdown images that [showImage] allows.
///
/// Defaults to a [StreamNetworkImage] of the image.
final MarkdownImageBuilder? imageBuilder;

/// Whether a markdown image is shown as an image rather than as a link.
///
/// Images it rejects, every image when it is null, and images that are not `http` or `https` are shown as links
/// labelled with their alt text, and are not loaded. It is called while the text is built, so consider keeping it
/// cheap and comparing [Uri.scheme] and [Uri.host] exactly. A new [showImage] applies once the text changes.
///
/// ```dart
/// StreamMessageText(
/// text,
/// showImage: (image) => image.uri.scheme == 'https' && image.uri.host == 'cdn.example.com',
/// )
/// ```
final StreamMarkdownImagePredicate? showImage;

/// Syntax highlighter for code blocks.
final SyntaxHighlighter? syntaxHighlighter;

Expand Down Expand Up @@ -355,6 +405,7 @@ class DefaultStreamMessageText extends StatelessWidget {
final effectiveInlineSyntaxes = [
_mentionSyntax,
...?props.inlineSyntaxes,
_StreamImageSyntax(showImage: props.showImage),
_linkSyntax,
];

Expand Down Expand Up @@ -385,7 +436,7 @@ class DefaultStreamMessageText extends StatelessWidget {
syntaxHighlighter: props.syntaxHighlighter,
onTapLink: props.onTapLink,
onTapText: props.onTapText,
imageBuilder: props.imageBuilder,
imageBuilder: props.imageBuilder ?? _buildImage,
builders: effectiveBuilders,
paddingBuilders: props.paddingBuilders ?? const {},
blockSyntaxes: props.blockSyntaxes,
Expand All @@ -401,6 +452,10 @@ class DefaultStreamMessageText extends StatelessWidget {
static final _mentionSyntax = _StreamMentionSyntax();
static final _linkSyntax = _StreamLinkSyntax();

static Widget _buildImage(Uri uri, String? title, String? alt) {
return StreamNetworkImage(uri.toString(), semanticLabel: alt);
}

// Shared across messages because building a sheet is costly.
// The caller's sheet is merged after the lookup, not keyed on, because
// `MarkdownStyleSheet.==` ignores some fields.
Expand Down Expand Up @@ -585,6 +640,49 @@ class _StreamLinkSyntax extends md.LinkSyntax {
}
}

// Parses markdown images as images only when [showImage] allows them, and as
// links to the image otherwise.
class _StreamImageSyntax extends md.ImageSyntax {
factory _StreamImageSyntax({StreamMarkdownImagePredicate? showImage}) {
return showImage == null ? _shared : _StreamImageSyntax._(showImage);
}

_StreamImageSyntax._(this.showImage);

static final _shared = _StreamImageSyntax._(null);

final StreamMarkdownImagePredicate? showImage;

static const _maxLabelLength = 48;

@override
md.Element createNode(
String destination,
String? title, {
required List<md.Node> Function() getChildren,
}) {
final image = super.createNode(destination, title, getChildren: getChildren);
final src = image.attributes['src']!;
final alt = image.attributes['alt'] ?? '';
final imageTitle = image.attributes['title'];
final uri = Uri.tryParse(src);

if (uri != null && (uri.isScheme('http') || uri.isScheme('https'))) {
final markdownImage = StreamMarkdownImage(uri: uri, alt: alt, title: imageTitle);
if (showImage?.call(markdownImage) ?? false) return image;
}

var label = alt;
if (label.isEmpty) {
label = src.length > _maxLabelLength ? '${src.substring(0, _maxLabelLength - 1)}…' : src;
}

return md.Element.text('a', label)
..attributes['href'] = src
..attributes.addAll({'title': ?imageTitle});
}
}

// Renders `mention` elements as tappable styled text with pointer cursor.
//
// Per-element style resolution: reads the `type` attribute set by
Expand Down
Loading
Loading