chore: update markdown dependency and refactor streaming handling
- Added `markdown` dependency version `^7.2.1` in `pubspec.yaml`. - Updated `pubspec.lock` to reflect the direct dependency change. - Refactored `streaming_helper.dart` to utilize `StreamingResponseController` for better stream management. - Enhanced `ChatMessagesNotifier` to handle message streams with improved formatting and error handling. - Updated `StreamingMarkdownWidget` to streamline markdown rendering and support new configurations.
This commit is contained in:
@@ -1,38 +1,87 @@
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:conduit/shared/theme/theme_extensions.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
|
||||
import 'package:markdown/markdown.dart' as md;
|
||||
|
||||
import 'package:conduit/l10n/app_localizations.dart';
|
||||
|
||||
/// Configuration for markdown styling
|
||||
class ConduitMarkdownStyleConfig {
|
||||
final TextStyle textStyle;
|
||||
import '../../theme/theme_extensions.dart';
|
||||
|
||||
const ConduitMarkdownStyleConfig({required this.textStyle});
|
||||
class ConduitMarkdownTheme {
|
||||
const ConduitMarkdownTheme({
|
||||
required this.styleSheet,
|
||||
required this.builders,
|
||||
required this.imageBuilder,
|
||||
this.inlineSyntaxes = const <md.InlineSyntax>[],
|
||||
});
|
||||
|
||||
final MarkdownStyleSheet styleSheet;
|
||||
final Map<String, MarkdownElementBuilder> builders;
|
||||
final MarkdownImageBuilder imageBuilder;
|
||||
final List<md.InlineSyntax> inlineSyntaxes;
|
||||
}
|
||||
|
||||
class ConduitMarkdownConfig {
|
||||
static ConduitMarkdownStyleConfig getStyleConfig({
|
||||
required BuildContext context,
|
||||
}) {
|
||||
static ConduitMarkdownTheme resolve(BuildContext context) {
|
||||
final theme = context.conduitTheme;
|
||||
final materialTheme = Theme.of(context);
|
||||
|
||||
return ConduitMarkdownStyleConfig(
|
||||
textStyle: AppTypography.chatMessageStyle.copyWith(
|
||||
color: theme.textPrimary,
|
||||
height: 1.45,
|
||||
final baseSheet = MarkdownStyleSheet.fromTheme(materialTheme);
|
||||
final bodyStyle = AppTypography.bodyMediumStyle.copyWith(
|
||||
color: theme.textPrimary,
|
||||
height: 1.45,
|
||||
);
|
||||
|
||||
final codeColor = theme.code?.color ?? theme.textSecondary;
|
||||
|
||||
final styleSheet = baseSheet.copyWith(
|
||||
p: bodyStyle,
|
||||
h1: AppTypography.headlineLargeStyle.copyWith(color: theme.textPrimary),
|
||||
h2: AppTypography.headlineMediumStyle.copyWith(color: theme.textPrimary),
|
||||
h3: AppTypography.headlineSmallStyle.copyWith(color: theme.textPrimary),
|
||||
strong: bodyStyle.copyWith(fontWeight: FontWeight.w600),
|
||||
em: bodyStyle.copyWith(fontStyle: FontStyle.italic),
|
||||
blockquote: bodyStyle.copyWith(
|
||||
color: theme.textSecondary,
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
code: AppTypography.codeStyle.copyWith(color: codeColor),
|
||||
listBullet: bodyStyle,
|
||||
tableBody: bodyStyle,
|
||||
tableHead: bodyStyle.copyWith(fontWeight: FontWeight.w600),
|
||||
);
|
||||
|
||||
final builders = <String, MarkdownElementBuilder>{
|
||||
'codeblock': _ConduitCodeBlockBuilder(theme),
|
||||
};
|
||||
|
||||
return ConduitMarkdownTheme(
|
||||
styleSheet: styleSheet,
|
||||
builders: builders,
|
||||
imageBuilder: (uri, title, alt) {
|
||||
final scheme = uri.scheme;
|
||||
|
||||
if (scheme == 'data') {
|
||||
return buildBase64Image(uri.toString(), context, theme);
|
||||
}
|
||||
|
||||
if (scheme.isEmpty || scheme == 'http' || scheme == 'https') {
|
||||
return buildNetworkImage(uri.toString(), context, theme);
|
||||
}
|
||||
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Legacy method for base64 image support (if needed elsewhere)
|
||||
static Widget buildBase64Image(
|
||||
String dataUrl,
|
||||
BuildContext context,
|
||||
ConduitThemeExtension theme,
|
||||
) {
|
||||
try {
|
||||
// Extract base64 part from data URL
|
||||
final commaIndex = dataUrl.indexOf(',');
|
||||
if (commaIndex == -1) {
|
||||
throw Exception('Invalid data URL format');
|
||||
@@ -50,50 +99,16 @@ class ConduitMarkdownConfig {
|
||||
imageBytes,
|
||||
fit: BoxFit.contain,
|
||||
errorBuilder: (context, error, stackTrace) {
|
||||
return Container(
|
||||
height: 100,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.surfaceBackground.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||
border: Border.all(
|
||||
color: theme.error.withValues(alpha: 0.3),
|
||||
width: BorderWidth.thin,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: theme.error, size: 32),
|
||||
const SizedBox(height: Spacing.xs),
|
||||
Text(
|
||||
AppLocalizations.of(context)!.invalidImageFormat,
|
||||
style: TextStyle(color: theme.error, fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
return _buildImageError(context, theme);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
return Container(
|
||||
height: 100,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.surfaceBackground.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
AppLocalizations.of(context)!.invalidImageFormat,
|
||||
style: TextStyle(color: theme.error, fontSize: 12),
|
||||
),
|
||||
),
|
||||
);
|
||||
return _buildImageError(context, theme);
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a cached network image widget
|
||||
static Widget buildNetworkImage(
|
||||
String url,
|
||||
BuildContext context,
|
||||
@@ -114,39 +129,82 @@ class ConduitMarkdownConfig {
|
||||
),
|
||||
),
|
||||
),
|
||||
errorWidget: (context, url, error) => Container(
|
||||
height: 100,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.surfaceBackground.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||
border: Border.all(
|
||||
color: theme.error.withValues(alpha: 0.3),
|
||||
width: BorderWidth.thin,
|
||||
errorWidget: (context, url, error) => _buildImageError(context, theme),
|
||||
);
|
||||
}
|
||||
|
||||
static Widget _buildImageError(
|
||||
BuildContext context,
|
||||
ConduitThemeExtension theme,
|
||||
) {
|
||||
return Container(
|
||||
height: 100,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.surfaceBackground.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||
border: Border.all(
|
||||
color: theme.error.withValues(alpha: 0.3),
|
||||
width: BorderWidth.thin,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.broken_image_outlined, color: theme.error, size: 32),
|
||||
const SizedBox(height: Spacing.xs),
|
||||
Text(
|
||||
AppLocalizations.of(context)!.failedToLoadImage(''),
|
||||
style: TextStyle(color: theme.error, fontSize: 12),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.broken_image_outlined, color: theme.error, size: 32),
|
||||
const SizedBox(height: Spacing.xs),
|
||||
Text(
|
||||
AppLocalizations.of(context)!.failedToLoadImage(''),
|
||||
style: TextStyle(color: theme.error, fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom wrapper for code blocks with copy functionality
|
||||
class CodeBlockWrapper extends StatelessWidget {
|
||||
final Widget child;
|
||||
final String code;
|
||||
final String? language;
|
||||
class _ConduitCodeBlockBuilder extends MarkdownElementBuilder {
|
||||
_ConduitCodeBlockBuilder(this.theme);
|
||||
|
||||
final ConduitThemeExtension theme;
|
||||
|
||||
@override
|
||||
Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {
|
||||
final rawText = element.textContent;
|
||||
final classAttribute = element.attributes['class'];
|
||||
String? language;
|
||||
if (classAttribute != null && classAttribute.startsWith('language-')) {
|
||||
language = classAttribute.substring('language-'.length);
|
||||
}
|
||||
|
||||
final textStyle = (preferredStyle ?? AppTypography.codeStyle).copyWith(
|
||||
color: theme.code?.color ?? theme.textSecondary,
|
||||
);
|
||||
|
||||
final container = Container(
|
||||
width: double.infinity,
|
||||
margin: const EdgeInsets.symmetric(vertical: Spacing.xs),
|
||||
padding: const EdgeInsets.all(Spacing.sm),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.surfaceBackground.withValues(alpha: 0.6),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||
border: Border.all(
|
||||
color: theme.cardBorder.withValues(alpha: 0.2),
|
||||
width: BorderWidth.micro,
|
||||
),
|
||||
),
|
||||
child: SelectableText(rawText, style: textStyle),
|
||||
);
|
||||
|
||||
return CodeBlockWrapper(
|
||||
code: rawText,
|
||||
language: language,
|
||||
theme: theme,
|
||||
child: container,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CodeBlockWrapper extends StatelessWidget {
|
||||
const CodeBlockWrapper({
|
||||
super.key,
|
||||
required this.child,
|
||||
@@ -155,6 +213,11 @@ class CodeBlockWrapper extends StatelessWidget {
|
||||
required this.theme,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
final String code;
|
||||
final String? language;
|
||||
final ConduitThemeExtension theme;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Stack(
|
||||
@@ -168,8 +231,7 @@ class CodeBlockWrapper extends StatelessWidget {
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
|
||||
onTap: () {
|
||||
// Copy code to clipboard
|
||||
// Implementation depends on clipboard service
|
||||
// Copy implementation provided by higher level clipboard service.
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(Spacing.xs),
|
||||
@@ -201,8 +263,9 @@ class CodeBlockWrapper extends StatelessWidget {
|
||||
),
|
||||
child: Text(
|
||||
language!,
|
||||
style: AppTypography.captionStyle.copyWith(
|
||||
style: AppTypography.bodySmallStyle.copyWith(
|
||||
color: theme.textSecondary,
|
||||
fontFamily: AppTypography.monospaceFontFamily,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,187 +1,60 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
|
||||
import 'package:conduit/shared/theme/theme_extensions.dart';
|
||||
import 'package:conduit/shared/widgets/markdown/markdown_config.dart';
|
||||
|
||||
class StreamingMarkdownWidget extends StatefulWidget {
|
||||
final Stream<String>? contentStream;
|
||||
final String? staticContent;
|
||||
final bool isStreaming;
|
||||
import 'markdown_config.dart';
|
||||
|
||||
class StreamingMarkdownWidget extends StatelessWidget {
|
||||
const StreamingMarkdownWidget({
|
||||
super.key,
|
||||
this.contentStream,
|
||||
this.staticContent,
|
||||
required this.content,
|
||||
required this.isStreaming,
|
||||
this.onTapLink,
|
||||
});
|
||||
|
||||
@override
|
||||
State<StreamingMarkdownWidget> createState() =>
|
||||
_StreamingMarkdownWidgetState();
|
||||
}
|
||||
|
||||
class _StreamingMarkdownWidgetState extends State<StreamingMarkdownWidget> {
|
||||
final _buffer = StringBuffer();
|
||||
Timer? _debounceTimer;
|
||||
String _renderedContent = '';
|
||||
StreamSubscription<String>? _streamSubscription;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (widget.contentStream != null) {
|
||||
_streamSubscription = widget.contentStream!.listen(_handleChunk);
|
||||
} else if (widget.staticContent != null) {
|
||||
_renderedContent = widget.staticContent!;
|
||||
}
|
||||
}
|
||||
|
||||
void _handleChunk(String chunk) {
|
||||
_buffer.write(chunk);
|
||||
|
||||
// Debounce rendering for performance
|
||||
_debounceTimer?.cancel();
|
||||
_debounceTimer = Timer(const Duration(milliseconds: 50), () {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_renderedContent = _fixIncompleteMarkdown(_buffer.toString());
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
String _fixIncompleteMarkdown(String content) {
|
||||
// Auto-close unclosed code blocks for valid markdown during streaming
|
||||
final fenceCount = '```'.allMatches(content).length;
|
||||
if (fenceCount % 2 != 0) {
|
||||
content += '\n```';
|
||||
}
|
||||
|
||||
// Fix incomplete bold/italic markers
|
||||
final boldCount = RegExp(r'\*\*').allMatches(content).length;
|
||||
if (boldCount % 2 != 0) {
|
||||
content += '**';
|
||||
}
|
||||
|
||||
final italicCount = RegExp(r'(?<!\*)\*(?!\*)').allMatches(content).length;
|
||||
if (italicCount % 2 != 0) {
|
||||
content += '*';
|
||||
}
|
||||
|
||||
// Fix incomplete link brackets
|
||||
final openBrackets = '['.allMatches(content).length;
|
||||
final closeBrackets = ']'.allMatches(content).length;
|
||||
if (openBrackets > closeBrackets) {
|
||||
content += ']' * (openBrackets - closeBrackets);
|
||||
}
|
||||
|
||||
final openParens = '('.allMatches(content).length;
|
||||
final closeParens = ')'.allMatches(content).length;
|
||||
if (openParens > closeParens) {
|
||||
content += ')' * (openParens - closeParens);
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(StreamingMarkdownWidget oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
|
||||
// Handle stream changes
|
||||
if (widget.contentStream != oldWidget.contentStream) {
|
||||
_streamSubscription?.cancel();
|
||||
if (widget.contentStream != null) {
|
||||
_streamSubscription = widget.contentStream!.listen(_handleChunk);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle static content changes
|
||||
if (widget.staticContent != oldWidget.staticContent) {
|
||||
setState(() {
|
||||
_renderedContent = widget.staticContent ?? '';
|
||||
});
|
||||
}
|
||||
}
|
||||
final String content;
|
||||
final bool isStreaming;
|
||||
final MarkdownTapLinkCallback? onTapLink;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final config = ConduitMarkdownConfig.getStyleConfig(context: context);
|
||||
final theme = Theme.of(context);
|
||||
final styleSheet = MarkdownStyleSheet.fromTheme(
|
||||
theme,
|
||||
).copyWith(p: config.textStyle);
|
||||
final conduitTheme = context.conduitTheme;
|
||||
final markdownTheme = ConduitMarkdownConfig.resolve(context);
|
||||
|
||||
if (_renderedContent.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
if (content.trim().isEmpty) {
|
||||
return isStreaming ? const SizedBox.shrink() : const SizedBox.shrink();
|
||||
}
|
||||
|
||||
// MarkdownBody handles both streaming and static content elegantly
|
||||
return MarkdownBody(
|
||||
data: _renderedContent,
|
||||
styleSheet: styleSheet,
|
||||
data: content,
|
||||
styleSheet: markdownTheme.styleSheet,
|
||||
softLineBreak: true,
|
||||
selectable: true,
|
||||
imageBuilder: (uri, title, alt) {
|
||||
final scheme = uri.scheme;
|
||||
|
||||
if (scheme == 'data') {
|
||||
return ConduitMarkdownConfig.buildBase64Image(
|
||||
uri.toString(),
|
||||
context,
|
||||
conduitTheme,
|
||||
);
|
||||
}
|
||||
|
||||
if (scheme.isEmpty || scheme == 'http' || scheme == 'https') {
|
||||
return ConduitMarkdownConfig.buildNetworkImage(
|
||||
uri.toString(),
|
||||
context,
|
||||
conduitTheme,
|
||||
);
|
||||
}
|
||||
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
builders: markdownTheme.builders,
|
||||
inlineSyntaxes: markdownTheme.inlineSyntaxes,
|
||||
imageBuilder: markdownTheme.imageBuilder,
|
||||
onTapLink: onTapLink,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_debounceTimer?.cancel();
|
||||
_streamSubscription?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension to provide easy access to streaming markdown
|
||||
extension StreamingMarkdownExtension on String {
|
||||
Widget toMarkdown({required BuildContext context, bool isStreaming = false}) {
|
||||
return StreamingMarkdownWidget(
|
||||
staticContent: this,
|
||||
isStreaming: isStreaming,
|
||||
);
|
||||
return StreamingMarkdownWidget(content: this, isStreaming: isStreaming);
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper widget for displaying markdown with loading state
|
||||
class MarkdownWithLoading extends StatelessWidget {
|
||||
const MarkdownWithLoading({super.key, this.content, required this.isLoading});
|
||||
|
||||
final String? content;
|
||||
final bool isLoading;
|
||||
|
||||
const MarkdownWithLoading({super.key, this.content, required this.isLoading});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (isLoading && (content == null || content!.isEmpty)) {
|
||||
final value = content ?? '';
|
||||
if (isLoading && value.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
return StreamingMarkdownWidget(
|
||||
staticContent: content ?? '',
|
||||
isStreaming: isLoading,
|
||||
);
|
||||
return StreamingMarkdownWidget(content: value, isStreaming: isLoading);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user