refactor: enhance markdown processing and code structure

- Updated the ConduitMarkdown class to streamline markdown rendering, improving maintainability and clarity.
- Refactored the markdown configuration to utilize new methods for building markdown blocks and handling LaTeX syntax.
- Improved the StreamingMarkdownWidget to leverage the updated markdown processing logic, ensuring a cohesive user experience.
- Enhanced the handling of Mermaid diagrams and LaTeX rendering, providing better support for complex markdown content.
This commit is contained in:
cogwheel0
2025-10-04 16:04:49 +05:30
parent e04b43949b
commit 758ed411b0
6 changed files with 453 additions and 258 deletions

View File

@@ -610,12 +610,11 @@ class AuthStateManager extends _$AuthStateManager {
/// Prime the conversations list so navigation drawers show real data after login. /// Prime the conversations list so navigation drawers show real data after login.
void _prefetchConversations() { void _prefetchConversations() {
Future.microtask(() async { Future.microtask(() {
if (!ref.mounted) return; if (!ref.mounted) return;
try { try {
refreshConversationsCache(ref, includeFolders: true); refreshConversationsCache(ref, includeFolders: true);
await ref.read(conversationsProvider.future); DebugLogger.auth('Conversations prefetch scheduled');
DebugLogger.auth('Conversations prefetch requested');
} catch (e) { } catch (e) {
if (!ref.mounted) return; if (!ref.mounted) return;
DebugLogger.warning( DebugLogger.warning(

View File

@@ -0,0 +1,49 @@
import 'package:flutter/material.dart';
import '../../theme/theme_extensions.dart';
class CodeBlockHeader extends StatelessWidget {
const CodeBlockHeader({
super.key,
required this.language,
required this.onCopy,
});
final String language;
final VoidCallback onCopy;
@override
Widget build(BuildContext context) {
final theme = context.conduitTheme;
final label = language.isEmpty ? 'code' : language;
return Container(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.sm,
vertical: Spacing.xs,
),
decoration: BoxDecoration(
color: theme.surfaceContainer.withValues(alpha: 0.35),
borderRadius: const BorderRadius.vertical(
top: Radius.circular(AppBorderRadius.sm),
),
),
child: Row(
children: [
Text(
label,
style: AppTypography.codeStyle.copyWith(
color: theme.textSecondary,
fontWeight: FontWeight.w600,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.copy_rounded, size: 18),
color: theme.iconPrimary,
tooltip: 'Copy code',
onPressed: onCopy,
),
],
),
);
}
}

View File

@@ -0,0 +1,41 @@
import 'package:flutter/material.dart';
import 'package:flutter_math_fork/flutter_math.dart';
import '../../theme/theme_extensions.dart';
class LatexBlockWidget extends StatelessWidget {
const LatexBlockWidget({
super.key,
required this.content,
required this.isInline,
required this.style,
required this.isDark,
});
final String content;
final bool isInline;
final TextStyle style;
final bool isDark;
@override
Widget build(BuildContext context) {
final mathWidget = Math.tex(
content,
mathStyle: MathStyle.text,
textStyle: style,
textScaleFactor: 1,
onErrorFallback: (error) {
return Text(content, style: style.copyWith(color: Colors.red));
},
);
if (isInline) {
return mathWidget;
}
return Padding(
padding: const EdgeInsets.symmetric(vertical: Spacing.xs),
child: Center(child: mathWidget),
);
}
}

View File

@@ -6,53 +6,73 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart'; import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_highlight/flutter_highlight.dart';
import 'package:flutter_highlight/themes/a11y-dark.dart'; import 'package:flutter_highlight/themes/a11y-dark.dart';
import 'package:flutter_highlight/themes/a11y-light.dart'; import 'package:flutter_highlight/themes/a11y-light.dart';
import 'package:markdown/markdown.dart' as m;
import 'package:markdown_widget/markdown_widget.dart'; import 'package:markdown_widget/markdown_widget.dart';
import 'package:webview_flutter/webview_flutter.dart'; import 'package:webview_flutter/webview_flutter.dart';
import '../../theme/color_tokens.dart'; import '../../theme/color_tokens.dart';
import '../../theme/theme_extensions.dart'; import '../../theme/theme_extensions.dart';
import 'code_block_header.dart';
import 'markdown_latex.dart'; import 'markdown_latex.dart';
/// Callback invoked when a markdown link is tapped.
typedef MarkdownLinkTapCallback = void Function(String url, String title); typedef MarkdownLinkTapCallback = void Function(String url, String title);
/// Bundles markdown configuration and generator metadata for the app theme. class ConduitMarkdown {
class ConduitMarkdownTheme { const ConduitMarkdown._();
const ConduitMarkdownTheme({
required this.config,
required this.inlineSyntaxes,
required this.blockSyntaxes,
required this.generators,
required this.linesMargin,
});
final MarkdownConfig config; static MarkdownWidget build({
final List<m.InlineSyntax> inlineSyntaxes; required BuildContext context,
final List<m.BlockSyntax> blockSyntaxes; required String data,
final List<SpanNodeGeneratorWithTag> generators; MarkdownLinkTapCallback? onTapLink,
final EdgeInsets linesMargin; bool selectable = true,
bool shrinkWrap = false,
MarkdownGenerator createGenerator() { ScrollPhysics? physics,
return MarkdownGenerator( }) {
inlineSyntaxList: inlineSyntaxes, final components = prepare(context, onTapLink: onTapLink);
blockSyntaxList: blockSyntaxes, return MarkdownWidget(
linesMargin: linesMargin, data: data,
generators: generators, selectable: selectable,
config: components.config,
markdownGenerator: components.generator,
shrinkWrap: shrinkWrap,
physics: physics,
padding: EdgeInsets.zero,
); );
} }
}
class ConduitMarkdownConfig { static MarkdownBlock buildBlock({
static ConduitMarkdownTheme resolve( required BuildContext context,
required String data,
MarkdownLinkTapCallback? onTapLink,
bool selectable = true,
}) {
final components = prepare(context, onTapLink: onTapLink);
return MarkdownBlock(
data: data,
selectable: selectable,
config: components.config,
generator: components.generator,
);
}
static ({MarkdownConfig config, MarkdownGenerator generator}) prepare(
BuildContext context, {
MarkdownLinkTapCallback? onTapLink,
}) {
final config = _buildConfig(context, onTapLink: onTapLink);
final generator = _buildGenerator(context);
return (config: config, generator: generator);
}
static MarkdownConfig _buildConfig(
BuildContext context, { BuildContext context, {
MarkdownLinkTapCallback? onTapLink, MarkdownLinkTapCallback? onTapLink,
}) { }) {
final theme = context.conduitTheme; final theme = context.conduitTheme;
final materialTheme = Theme.of(context); final material = Theme.of(context);
final isDark = materialTheme.brightness == Brightness.dark; final isDark = material.brightness == Brightness.dark;
final baseBody = AppTypography.bodyMediumStyle.copyWith( final baseBody = AppTypography.bodyMediumStyle.copyWith(
color: theme.textPrimary, color: theme.textPrimary,
@@ -65,132 +85,129 @@ class ConduitMarkdownConfig {
final codeBackground = theme.surfaceContainer.withValues(alpha: 0.55); final codeBackground = theme.surfaceContainer.withValues(alpha: 0.55);
final borderColor = theme.cardBorder.withValues(alpha: 0.25); final borderColor = theme.cardBorder.withValues(alpha: 0.25);
final latex = const ConduitLatex(); final highlightTheme = _codeHighlightTheme(theme, isDark: isDark);
final markdownConfig = return MarkdownConfig(
(isDark ? MarkdownConfig.darkConfig : MarkdownConfig.defaultConfig) configs: [
.copy( PConfig(textStyle: baseBody),
configs: [ H1Config(
PConfig(textStyle: baseBody), style: AppTypography.headlineLargeStyle.copyWith(
H1Config( color: theme.textPrimary,
style: AppTypography.headlineLargeStyle.copyWith( ),
color: theme.textPrimary, ),
), H2Config(
), style: AppTypography.headlineMediumStyle.copyWith(
H2Config( color: theme.textPrimary,
style: AppTypography.headlineMediumStyle.copyWith( ),
color: theme.textPrimary, ),
), H3Config(
), style: AppTypography.headlineSmallStyle.copyWith(
H3Config( color: theme.textPrimary,
style: AppTypography.headlineSmallStyle.copyWith( ),
color: theme.textPrimary, ),
), H4Config(
), style: AppTypography.bodyLargeStyle.copyWith(
H4Config( color: theme.textPrimary,
style: AppTypography.bodyLargeStyle.copyWith( ),
color: theme.textPrimary, ),
), H5Config(style: baseBody.copyWith(fontWeight: FontWeight.w600)),
), H6Config(style: secondaryBody),
H5Config(style: baseBody.copyWith(fontWeight: FontWeight.w600)), LinkConfig(
H6Config(style: secondaryBody), style: baseBody.copyWith(
LinkConfig( color: material.colorScheme.primary,
style: baseBody.copyWith( decoration: TextDecoration.underline,
color: materialTheme.colorScheme.primary, decorationColor: material.colorScheme.primary,
decoration: TextDecoration.underline, ),
decorationColor: materialTheme.colorScheme.primary, onTap: (url) => onTapLink?.call(url, url),
), ),
onTap: (url) => onTapLink?.call(url, url), CodeConfig(
), style: AppTypography.codeStyle.copyWith(
CodeConfig( color: theme.codeText,
style: AppTypography.codeStyle.copyWith( backgroundColor: codeBackground,
color: theme.codeText, ),
backgroundColor: codeBackground, ),
), PreConfig(
), textStyle: AppTypography.codeStyle.copyWith(color: theme.codeText),
PreConfig( styleNotMatched: AppTypography.codeStyle.copyWith(
padding: const EdgeInsets.all(Spacing.sm), color: theme.codeText,
margin: const EdgeInsets.symmetric(vertical: Spacing.xs), ),
decoration: BoxDecoration( theme: highlightTheme,
color: codeBackground, builder: (code, language) {
borderRadius: BorderRadius.circular(AppBorderRadius.sm), final normalizedLanguage = language.trim().isEmpty
border: Border.all( ? 'plaintext'
color: borderColor, : language.trim();
width: BorderWidth.micro, final highlight = HighlightView(
), code,
), language: normalizedLanguage == 'plaintext'
textStyle: AppTypography.codeStyle.copyWith( ? null
color: theme.codeText, : normalizedLanguage,
), theme: highlightTheme,
styleNotMatched: AppTypography.codeStyle.copyWith( textStyle: AppTypography.codeStyle.copyWith(
color: theme.codeText, color: theme.codeText,
), ),
theme: _codeHighlightTheme(theme, isDark: isDark), padding: EdgeInsets.zero,
language: 'plaintext',
),
BlockquoteConfig(
sideColor: materialTheme.colorScheme.primary.withValues(
alpha: 0.35,
),
textColor: theme.textSecondary,
sideWith: BorderWidth.micro,
padding: const EdgeInsets.symmetric(
horizontal: Spacing.md,
vertical: Spacing.sm,
),
margin: const EdgeInsets.symmetric(vertical: Spacing.sm),
),
ListConfig(marginLeft: Spacing.lg, marginBottom: Spacing.xs),
TableConfig(
border: TableBorder.all(
color: borderColor,
width: BorderWidth.micro,
),
headPadding: const EdgeInsets.symmetric(
horizontal: Spacing.sm,
vertical: Spacing.xs,
),
bodyPadding: const EdgeInsets.symmetric(
horizontal: Spacing.sm,
vertical: Spacing.xs,
),
headerStyle: secondaryBody.copyWith(
fontWeight: FontWeight.w600,
),
bodyStyle: secondaryBody,
headerRowDecoration: BoxDecoration(
color: theme.surfaceBackground.withValues(alpha: 0.35),
),
bodyRowDecoration: BoxDecoration(
color: theme.surfaceContainer.withValues(alpha: 0.2),
),
),
HrConfig(color: theme.dividerColor, height: BorderWidth.small),
ImgConfig(
builder: (url, _) {
return Builder(
builder: (context) {
final uri = Uri.tryParse(url);
if (uri == null) {
return _buildImageError(
context,
context.conduitTheme,
);
}
return _buildImage(context, uri);
},
);
},
),
],
); );
return _buildCodeWrapper(
context: context,
child: highlight,
backgroundColor: codeBackground,
borderColor: borderColor,
language: normalizedLanguage,
rawCode: code,
);
},
),
BlockquoteConfig(
sideColor: material.colorScheme.primary.withValues(alpha: 0.35),
textColor: theme.textSecondary,
sideWith: BorderWidth.small,
padding: const EdgeInsets.symmetric(
horizontal: Spacing.md,
vertical: Spacing.sm,
),
margin: const EdgeInsets.symmetric(vertical: Spacing.sm),
),
ListConfig(marginLeft: Spacing.lg, marginBottom: Spacing.xs),
TableConfig(
border: TableBorder.all(color: borderColor, width: BorderWidth.micro),
headPadding: const EdgeInsets.symmetric(
horizontal: Spacing.sm,
vertical: Spacing.xs,
),
bodyPadding: const EdgeInsets.symmetric(
horizontal: Spacing.sm,
vertical: Spacing.xs,
),
headerStyle: secondaryBody.copyWith(fontWeight: FontWeight.w600),
bodyStyle: secondaryBody,
headerRowDecoration: BoxDecoration(
color: theme.surfaceBackground.withValues(alpha: 0.35),
),
bodyRowDecoration: BoxDecoration(
color: theme.surfaceContainer.withValues(alpha: 0.2),
),
),
HrConfig(color: theme.dividerColor, height: BorderWidth.small),
ImgConfig(
builder: (url, attributes) {
final uri = Uri.tryParse(url);
if (uri == null) {
return _buildImageError(context, theme);
}
return _buildImage(context, uri);
},
),
],
);
}
return ConduitMarkdownTheme( static MarkdownGenerator _buildGenerator(BuildContext context) {
config: markdownConfig, final isDark = Theme.of(context).brightness == Brightness.dark;
inlineSyntaxes: [latex.syntax()], final latex = ConduitLatex();
blockSyntaxes: const [], return MarkdownGenerator(
inlineSyntaxList: latex.syntaxes(),
generators: [latex.generator(isDark: isDark)], generators: [latex.generator(isDark: isDark)],
linesMargin: const EdgeInsets.only(bottom: Spacing.sm), linesMargin: const EdgeInsets.symmetric(vertical: Spacing.xs),
); );
} }
@@ -212,6 +229,67 @@ class ConduitMarkdownConfig {
}; };
} }
static Widget _buildCodeWrapper({
required BuildContext context,
required Widget child,
required Color backgroundColor,
required Color borderColor,
required String language,
required String rawCode,
}) {
return LayoutBuilder(
builder: (context, constraints) {
final width = constraints.maxWidth.isFinite
? constraints.maxWidth
: MediaQuery.sizeOf(context).width;
return Container(
margin: const EdgeInsets.symmetric(vertical: Spacing.xs),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
border: Border.all(color: borderColor, width: BorderWidth.micro),
),
child: ClipRect(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CodeBlockHeader(
language: language,
onCopy: () async {
await Clipboard.setData(ClipboardData(text: rawCode));
if (!context.mounted) {
return;
}
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Code copied to clipboard.'),
),
);
},
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: IntrinsicWidth(
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: width),
child: Padding(
padding: const EdgeInsets.all(Spacing.sm),
child: child,
),
),
),
),
],
),
),
);
},
);
}
static Widget buildMermaidBlock(BuildContext context, String code) { static Widget buildMermaidBlock(BuildContext context, String code) {
final conduitTheme = context.conduitTheme; final conduitTheme = context.conduitTheme;
final materialTheme = Theme.of(context); final materialTheme = Theme.of(context);
@@ -299,6 +377,13 @@ class ConduitMarkdownConfig {
), ),
), ),
errorWidget: (context, url, error) => _buildImageError(context, theme), errorWidget: (context, url, error) => _buildImageError(context, theme),
imageBuilder: (context, imageProvider) => Container(
margin: const EdgeInsets.symmetric(vertical: Spacing.sm),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppBorderRadius.md),
image: DecorationImage(image: imageProvider, fit: BoxFit.contain),
),
),
); );
} }
@@ -486,73 +571,70 @@ class _MermaidDiagramState extends State<MermaidDiagram> {
String _buildHtml(String code, String script) { String _buildHtml(String code, String script) {
final theme = widget.brightness == Brightness.dark ? 'dark' : 'default'; final theme = widget.brightness == Brightness.dark ? 'dark' : 'default';
final encoded = jsonEncode(code);
final primary = _toHex(widget.tokens.brandTone60); final primary = _toHex(widget.tokens.brandTone60);
final secondary = _toHex(widget.tokens.accentTeal60); final secondary = _toHex(widget.tokens.accentTeal60);
final background = _toHex(widget.tokens.codeBackground); final background = _toHex(widget.tokens.codeBackground);
final onBackground = _toHex(widget.tokens.codeText); final onBackground = _toHex(widget.tokens.codeText);
final lineColor = _toHex(widget.tokens.codeAccent);
final errorColor = _toHex(widget.tokens.statusError60);
return ''' return '''
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <style>
<style> body {
html, body { margin: 0; padding: 0; background: transparent; } margin: 0;
body { color: $onBackground; font-family: -apple-system, sans-serif; } background-color: transparent;
#diagram { padding: 8px; overflow: auto; } }
svg { height: auto; display: block; } #container {
</style> width: 100%;
<script type="text/javascript"> height: 100%;
$script display: flex;
</script> justify-content: center;
</head> align-items: center;
<body> background-color: transparent;
<div id="diagram"></div> }
<script type="text/javascript"> </style>
const graphDefinition = $encoded; </head>
const themeConfig = { <body>
startOnLoad: false, <div id="container">
theme: '$theme', <div class="mermaid">$code</div>
securityLevel: 'loose', </div>
themeVariables: { <script>$script</script>
primaryColor: '$primary', <script>
secondaryColor: '$secondary', mermaid.initialize({
background: '$background', theme: '$theme',
textColor: '$onBackground', themeVariables: {
lineColor: '$lineColor' primaryColor: '$primary',
} primaryTextColor: '$onBackground',
}; primaryBorderColor: '$secondary',
background: '$background'
(async () => { },
const target = document.getElementById('diagram'); });
try { mermaid.contentLoaded();
mermaid.initialize(themeConfig); </script>
const { svg, bindFunctions } = await mermaid.render('graphDiv', graphDefinition); </body>
target.innerHTML = svg;
if (typeof bindFunctions === 'function') {
bindFunctions(target);
}
} catch (error) {
target.innerHTML = '<pre style="color:$errorColor">' + String(error) + '</pre>';
console.error('Mermaid render failed', error);
}
})();
</script>
</body>
</html> </html>
'''; ''';
} }
String _toHex(Color color) { String _toHex(Color color) {
final value = color.toARGB32(); int channel(double value) {
return '#' final scaled = (value * 255).round();
'${((value >> 16) & 0xFF).toRadixString(16).padLeft(2, '0')}' if (scaled < 0) {
'${((value >> 8) & 0xFF).toRadixString(16).padLeft(2, '0')}' return 0;
'${(value & 0xFF).toRadixString(16).padLeft(2, '0')}' }
.toUpperCase(); if (scaled > 255) {
return 255;
}
return scaled;
}
final argb =
(channel(color.a) << 24) |
(channel(color.r) << 16) |
(channel(color.g) << 8) |
channel(color.b);
return '#${argb.toRadixString(16).padLeft(8, '0')}';
} }
} }

View File

@@ -1,9 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_math_fork/flutter_math.dart';
import 'package:markdown/markdown.dart' as m; import 'package:markdown/markdown.dart' as m;
import 'package:markdown_widget/markdown_widget.dart'; import 'package:markdown_widget/markdown_widget.dart';
import '../../theme/theme_extensions.dart'; import 'latex_block_widget.dart';
const String _latexTag = 'latex'; const String _latexTag = 'latex';
@@ -12,7 +11,10 @@ class ConduitLatex {
const ConduitLatex(); const ConduitLatex();
/// Returns the inline syntax used to identify LaTeX segments. /// Returns the inline syntax used to identify LaTeX segments.
m.InlineSyntax syntax() => _LatexSyntax(); List<m.InlineSyntax> syntaxes() => [
_LatexDollarSyntax(),
_LatexEscapedSyntax(),
];
/// Returns the span generator that renders LaTeX expressions. /// Returns the span generator that renders LaTeX expressions.
SpanNodeGeneratorWithTag generator({required bool isDark}) { SpanNodeGeneratorWithTag generator({required bool isDark}) {
@@ -30,28 +32,57 @@ class ConduitLatex {
} }
} }
class _LatexSyntax extends m.InlineSyntax { class _LatexDollarSyntax extends m.InlineSyntax {
_LatexSyntax() : super(r'(\$\$[\s\S]+?\$\$)|(\$[^\n]+?\$)'); _LatexDollarSyntax()
: super(
r'(\$\$[\s\S]+?\$\$)|(\$[^\n]+?\$)',
startCharacter: r'$'.codeUnitAt(0),
);
@override @override
bool onMatch(m.InlineParser parser, Match match) { bool onMatch(m.InlineParser parser, Match match) {
final raw = match.input.substring(match.start, match.end); return _handleMatch(parser, match.input.substring(match.start, match.end));
final element = m.Element.text(_latexTag, raw);
if (raw.startsWith(r'$$') && raw.endsWith(r'$$') && raw.length > 4) {
element.attributes['content'] = raw.substring(2, raw.length - 2);
element.attributes['isInline'] = 'false';
} else if (raw.startsWith(r'$') && raw.endsWith(r'$') && raw.length > 2) {
element.attributes['content'] = raw.substring(1, raw.length - 1);
element.attributes['isInline'] = 'true';
} else {
element.attributes['content'] = raw;
element.attributes['isInline'] = 'true';
}
parser.addNode(element);
return true;
} }
} }
class _LatexEscapedSyntax extends m.InlineSyntax {
_LatexEscapedSyntax()
: super(
r'(\\\\\([\s\S]+?\\\\\))|(\\\\\[[\s\S]+?\\\\\])',
startCharacter: r'\'.codeUnitAt(0),
);
@override
bool onMatch(m.InlineParser parser, Match match) {
return _handleMatch(parser, match.input.substring(match.start, match.end));
}
}
bool _handleMatch(m.InlineParser parser, String raw) {
final element = m.Element.text(_latexTag, raw);
String content = raw;
var isInline = true;
if (raw.startsWith(r'$$') && raw.endsWith(r'$$') && raw.length > 4) {
content = raw.substring(2, raw.length - 2);
isInline = false;
} else if (raw.startsWith(r'$') && raw.endsWith(r'$') && raw.length > 2) {
content = raw.substring(1, raw.length - 1);
isInline = true;
} else if (raw.startsWith(r'\\(') && raw.endsWith(r'\\)') && raw.length > 4) {
content = raw.substring(2, raw.length - 2);
isInline = true;
} else if (raw.startsWith(r'\\[') && raw.endsWith(r'\\]') && raw.length > 4) {
content = raw.substring(2, raw.length - 2);
isInline = false;
}
element.attributes['content'] = content;
element.attributes['isInline'] = '$isInline';
parser.addNode(element);
return true;
}
class _LatexNode extends SpanNode { class _LatexNode extends SpanNode {
_LatexNode({ _LatexNode({
required this.attributes, required this.attributes,
@@ -79,23 +110,14 @@ class _LatexNode extends SpanNode {
return TextSpan(text: rawText, style: baseStyle); return TextSpan(text: rawText, style: baseStyle);
} }
final latexWidget = Math.tex( return WidgetSpan(
content, alignment: PlaceholderAlignment.middle,
mathStyle: MathStyle.text, child: LatexBlockWidget(
textStyle: baseStyle, content: content,
textScaleFactor: 1, isInline: isInline,
onErrorFallback: (error) { style: baseStyle,
return Text(rawText, style: baseStyle.copyWith(color: Colors.red)); isDark: isDark,
}, ),
); );
final widget = isInline
? latexWidget
: Padding(
padding: const EdgeInsets.symmetric(vertical: Spacing.xs),
child: Center(child: latexWidget),
);
return WidgetSpan(alignment: PlaceholderAlignment.middle, child: widget);
} }
} }

View File

@@ -1,5 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:markdown_widget/markdown_widget.dart';
import '../../theme/theme_extensions.dart'; import '../../theme/theme_extensions.dart';
import 'markdown_config.dart'; import 'markdown_config.dart';
import 'markdown_preprocessor.dart'; import 'markdown_preprocessor.dart';
@@ -23,20 +25,23 @@ class StreamingMarkdownWidget extends StatelessWidget {
} }
final normalized = ConduitMarkdownPreprocessor.normalize(content); final normalized = ConduitMarkdownPreprocessor.normalize(content);
final markdownTheme = ConduitMarkdownConfig.resolve( final mermaidRegex = RegExp(r'```mermaid\s*([\s\S]*?)```', multiLine: true);
final matches = mermaidRegex.allMatches(normalized).toList();
final renderComponents = ConduitMarkdown.prepare(
context, context,
onTapLink: onTapLink, onTapLink: onTapLink,
); );
final generator = markdownTheme.createGenerator();
final mermaidRegex = RegExp(r'```mermaid\s*([\s\S]*?)```', multiLine: true);
final matches = mermaidRegex.allMatches(normalized).toList();
List<Widget> buildMarkdownBlocks(String data) { Widget buildMarkdown(String data) {
return generator.buildWidgets(data, config: markdownTheme.config); return MarkdownBlock(
data: data,
selectable: false,
config: renderComponents.config,
generator: renderComponents.generator,
);
} }
if (matches.isEmpty) { if (matches.isEmpty) {
final blocks = buildMarkdownBlocks(normalized);
return SelectionArea( return SelectionArea(
child: Theme( child: Theme(
data: Theme.of(context).copyWith( data: Theme.of(context).copyWith(
@@ -44,10 +49,7 @@ class StreamingMarkdownWidget extends StatelessWidget {
cursorColor: context.conduitTheme.buttonPrimary, cursorColor: context.conduitTheme.buttonPrimary,
), ),
), ),
child: Column( child: buildMarkdown(normalized),
crossAxisAlignment: CrossAxisAlignment.stretch,
children: blocks,
),
), ),
); );
} }
@@ -57,12 +59,12 @@ class StreamingMarkdownWidget extends StatelessWidget {
for (final match in matches) { for (final match in matches) {
final before = normalized.substring(currentIndex, match.start); final before = normalized.substring(currentIndex, match.start);
if (before.trim().isNotEmpty) { if (before.trim().isNotEmpty) {
children.addAll(buildMarkdownBlocks(before)); children.add(buildMarkdown(before));
} }
final code = match.group(1)?.trim() ?? ''; final code = match.group(1)?.trim() ?? '';
if (code.isNotEmpty) { if (code.isNotEmpty) {
children.add(ConduitMarkdownConfig.buildMermaidBlock(context, code)); children.add(ConduitMarkdown.buildMermaidBlock(context, code));
} }
currentIndex = match.end; currentIndex = match.end;
@@ -70,7 +72,7 @@ class StreamingMarkdownWidget extends StatelessWidget {
final tail = normalized.substring(currentIndex); final tail = normalized.substring(currentIndex);
if (tail.trim().isNotEmpty) { if (tail.trim().isNotEmpty) {
children.addAll(buildMarkdownBlocks(tail)); children.add(buildMarkdown(tail));
} }
return SelectionArea( return SelectionArea(