feat: mermaid parsing
This commit is contained in:
2029
assets/mermaid.min.js
vendored
Normal file
2029
assets/mermaid.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -32,7 +32,6 @@ class SettingsService {
|
||||
.quickPills; // StringList of identifiers e.g. ['web','image','tools']
|
||||
// Chat input behavior
|
||||
static const String _sendOnEnterKey = PreferenceKeys.sendOnEnterKey;
|
||||
|
||||
static Box<dynamic> _preferencesBox() =>
|
||||
Hive.box<dynamic>(HiveBoxNames.preferences);
|
||||
|
||||
@@ -313,7 +312,6 @@ class AppSettings {
|
||||
final String socketTransportMode; // 'auto' or 'ws'
|
||||
final List<String> quickPills; // e.g., ['web','image']
|
||||
final bool sendOnEnter;
|
||||
|
||||
const AppSettings({
|
||||
this.reduceMotion = false,
|
||||
this.animationSpeed = 1.0,
|
||||
|
||||
@@ -1,15 +1,43 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_highlight/flutter_highlight.dart';
|
||||
import 'package:flutter_highlight/themes/atom-one-dark-reasonable.dart';
|
||||
import 'package:gpt_markdown/custom_widgets/markdown_config.dart'
|
||||
show CodeBlockBuilder, ImageBuilder;
|
||||
import 'package:gpt_markdown/gpt_markdown.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
|
||||
import 'package:conduit/l10n/app_localizations.dart';
|
||||
|
||||
import '../../theme/theme_extensions.dart';
|
||||
|
||||
class MarkdownFeatureFlags {
|
||||
const MarkdownFeatureFlags({
|
||||
this.enableSyntaxHighlighting = false,
|
||||
this.enableMermaid = false,
|
||||
});
|
||||
|
||||
final bool enableSyntaxHighlighting;
|
||||
final bool enableMermaid;
|
||||
|
||||
MarkdownFeatureFlags copyWith({
|
||||
bool? enableSyntaxHighlighting,
|
||||
bool? enableMermaid,
|
||||
}) {
|
||||
return MarkdownFeatureFlags(
|
||||
enableSyntaxHighlighting:
|
||||
enableSyntaxHighlighting ?? this.enableSyntaxHighlighting,
|
||||
enableMermaid: enableMermaid ?? this.enableMermaid,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ConduitMarkdownTheme {
|
||||
const ConduitMarkdownTheme({
|
||||
required this.textStyle,
|
||||
@@ -27,7 +55,10 @@ class ConduitMarkdownTheme {
|
||||
}
|
||||
|
||||
class ConduitMarkdownConfig {
|
||||
static ConduitMarkdownTheme resolve(BuildContext context) {
|
||||
static ConduitMarkdownTheme resolve(
|
||||
BuildContext context, {
|
||||
MarkdownFeatureFlags flags = const MarkdownFeatureFlags(),
|
||||
}) {
|
||||
final theme = context.conduitTheme;
|
||||
final materialTheme = Theme.of(context);
|
||||
|
||||
@@ -78,37 +109,226 @@ class ConduitMarkdownConfig {
|
||||
},
|
||||
codeBuilder: (context, name, code, closed) {
|
||||
final conduitTheme = context.conduitTheme;
|
||||
final textStyle = AppTypography.codeStyle.copyWith(
|
||||
color: conduitTheme.code?.color ?? codeColor,
|
||||
);
|
||||
|
||||
final container = Container(
|
||||
width: double.infinity,
|
||||
margin: const EdgeInsets.symmetric(vertical: Spacing.xs),
|
||||
padding: const EdgeInsets.all(Spacing.sm),
|
||||
decoration: BoxDecoration(
|
||||
color: conduitTheme.surfaceBackground.withValues(alpha: 0.6),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||
border: Border.all(
|
||||
color: conduitTheme.cardBorder.withValues(alpha: 0.2),
|
||||
width: BorderWidth.micro,
|
||||
),
|
||||
),
|
||||
child: SelectableText(code, style: textStyle),
|
||||
);
|
||||
|
||||
final language = name.trim().isEmpty ? null : name.trim();
|
||||
final isMermaid =
|
||||
flags.enableMermaid && (language?.toLowerCase() == 'mermaid');
|
||||
|
||||
if (isMermaid && !flags.enableMermaid) {
|
||||
return CodeBlockWrapper(
|
||||
code: code,
|
||||
language: language,
|
||||
theme: conduitTheme,
|
||||
closed: closed,
|
||||
child: _buildUnsupportedMermaidContainer(
|
||||
conduitTheme: conduitTheme,
|
||||
codeColor: codeColor,
|
||||
code: code,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final Widget content;
|
||||
if (isMermaid) {
|
||||
content = MermaidDiagram.isSupported
|
||||
? _buildMermaidContainer(
|
||||
context: context,
|
||||
conduitTheme: conduitTheme,
|
||||
materialTheme: materialTheme,
|
||||
code: code,
|
||||
)
|
||||
: _buildUnsupportedMermaidContainer(
|
||||
conduitTheme: conduitTheme,
|
||||
codeColor: codeColor,
|
||||
code: code,
|
||||
);
|
||||
} else {
|
||||
content = _buildCodeContainer(
|
||||
context: context,
|
||||
conduitTheme: conduitTheme,
|
||||
codeColor: codeColor,
|
||||
code: code,
|
||||
language: language,
|
||||
enableHighlight: flags.enableSyntaxHighlighting,
|
||||
);
|
||||
}
|
||||
|
||||
return CodeBlockWrapper(
|
||||
code: code,
|
||||
language: language,
|
||||
theme: conduitTheme,
|
||||
child: container,
|
||||
closed: closed,
|
||||
child: content,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
static Widget _buildCodeContainer({
|
||||
required BuildContext context,
|
||||
required ConduitThemeExtension conduitTheme,
|
||||
required Color codeColor,
|
||||
required String code,
|
||||
required String? language,
|
||||
required bool enableHighlight,
|
||||
}) {
|
||||
final textStyle = AppTypography.codeStyle.copyWith(
|
||||
color: const Color(0xFFE2E8F0),
|
||||
height: 1.55,
|
||||
fontSize: 13,
|
||||
);
|
||||
|
||||
final highlightLanguage = _normalizeLanguage(language);
|
||||
final canHighlight = enableHighlight && highlightLanguage != null;
|
||||
|
||||
final Widget baseChild;
|
||||
if (canHighlight) {
|
||||
final highlightTheme = _transparentHighlightTheme(
|
||||
atomOneDarkReasonableTheme,
|
||||
);
|
||||
baseChild = HighlightView(
|
||||
code,
|
||||
language: highlightLanguage,
|
||||
theme: highlightTheme,
|
||||
padding: EdgeInsets.zero,
|
||||
textStyle: textStyle,
|
||||
);
|
||||
} else {
|
||||
baseChild = SelectableText(
|
||||
code,
|
||||
maxLines: null,
|
||||
textAlign: TextAlign.left,
|
||||
textDirection: TextDirection.ltr,
|
||||
textWidthBasis: TextWidthBasis.parent,
|
||||
style: textStyle,
|
||||
);
|
||||
}
|
||||
|
||||
return baseChild;
|
||||
}
|
||||
|
||||
static Widget _buildMermaidContainer({
|
||||
required BuildContext context,
|
||||
required ConduitThemeExtension conduitTheme,
|
||||
required ThemeData materialTheme,
|
||||
required String code,
|
||||
}) {
|
||||
return SizedBox(
|
||||
height: 360,
|
||||
width: double.infinity,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
|
||||
child: MermaidDiagram(
|
||||
code: code,
|
||||
brightness: materialTheme.brightness,
|
||||
colorScheme: materialTheme.colorScheme,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static Widget _buildUnsupportedMermaidContainer({
|
||||
required ConduitThemeExtension conduitTheme,
|
||||
required Color codeColor,
|
||||
required String code,
|
||||
}) {
|
||||
final textStyle = AppTypography.bodySmallStyle.copyWith(
|
||||
color: Colors.white.withValues(alpha: 0.7),
|
||||
);
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'Mermaid preview is not available on this platform.',
|
||||
style: textStyle,
|
||||
),
|
||||
const SizedBox(height: Spacing.xs),
|
||||
SelectableText(
|
||||
code,
|
||||
maxLines: null,
|
||||
textAlign: TextAlign.left,
|
||||
textDirection: TextDirection.ltr,
|
||||
textWidthBasis: TextWidthBasis.parent,
|
||||
style: AppTypography.codeStyle.copyWith(
|
||||
color: conduitTheme.code?.color ?? codeColor,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
static Map<String, TextStyle> _transparentHighlightTheme(
|
||||
Map<String, TextStyle> base,
|
||||
) {
|
||||
final themed = Map<String, TextStyle>.from(base);
|
||||
final root = base['root'];
|
||||
themed['root'] = (root ?? const TextStyle()).copyWith(
|
||||
backgroundColor: Colors.transparent,
|
||||
);
|
||||
return themed;
|
||||
}
|
||||
|
||||
static String? _normalizeLanguage(String? lang) {
|
||||
if (lang == null || lang.trim().isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final value = lang.trim().toLowerCase();
|
||||
switch (value) {
|
||||
case 'js':
|
||||
case 'javascript':
|
||||
return 'javascript';
|
||||
case 'ts':
|
||||
case 'typescript':
|
||||
return 'typescript';
|
||||
case 'sh':
|
||||
case 'zsh':
|
||||
case 'bash':
|
||||
case 'shell':
|
||||
return 'bash';
|
||||
case 'yml':
|
||||
return 'yaml';
|
||||
case 'py':
|
||||
case 'python':
|
||||
return 'python';
|
||||
case 'rb':
|
||||
case 'ruby':
|
||||
return 'ruby';
|
||||
case 'kt':
|
||||
case 'kotlin':
|
||||
return 'kotlin';
|
||||
case 'java':
|
||||
return 'java';
|
||||
case 'c#':
|
||||
case 'cs':
|
||||
case 'csharp':
|
||||
return 'cs';
|
||||
case 'objc':
|
||||
case 'objectivec':
|
||||
return 'objectivec';
|
||||
case 'swift':
|
||||
return 'swift';
|
||||
case 'go':
|
||||
case 'golang':
|
||||
return 'go';
|
||||
case 'php':
|
||||
return 'php';
|
||||
case 'dart':
|
||||
return 'dart';
|
||||
case 'json':
|
||||
return 'json';
|
||||
case 'html':
|
||||
return 'xml';
|
||||
case 'md':
|
||||
case 'markdown':
|
||||
return 'markdown';
|
||||
case 'sql':
|
||||
return 'sql';
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
static Widget buildBase64Image(
|
||||
String dataUrl,
|
||||
BuildContext context,
|
||||
@@ -195,73 +415,309 @@ class ConduitMarkdownConfig {
|
||||
}
|
||||
}
|
||||
|
||||
class CodeBlockWrapper extends StatelessWidget {
|
||||
class CodeBlockWrapper extends StatefulWidget {
|
||||
const CodeBlockWrapper({
|
||||
super.key,
|
||||
required this.child,
|
||||
required this.code,
|
||||
this.language,
|
||||
required this.theme,
|
||||
required this.closed,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
final String code;
|
||||
final String? language;
|
||||
final ConduitThemeExtension theme;
|
||||
final bool closed;
|
||||
|
||||
@override
|
||||
State<CodeBlockWrapper> createState() => _CodeBlockWrapperState();
|
||||
}
|
||||
|
||||
class _CodeBlockWrapperState extends State<CodeBlockWrapper> {
|
||||
bool _copied = false;
|
||||
Timer? _resetTimer;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_resetTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _handleCopy() async {
|
||||
if (!widget.closed || widget.code.trim().isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
await Clipboard.setData(ClipboardData(text: widget.code));
|
||||
setState(() {
|
||||
_copied = true;
|
||||
});
|
||||
|
||||
_resetTimer?.cancel();
|
||||
_resetTimer = Timer(const Duration(seconds: 2), () {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_copied = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Stack(
|
||||
children: [
|
||||
child,
|
||||
Positioned(
|
||||
top: 8,
|
||||
right: 8,
|
||||
child: Material(
|
||||
color: theme.surfaceBackground.withValues(alpha: 0.0),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
|
||||
onTap: () {
|
||||
// Copy implementation provided by higher level clipboard service.
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(Spacing.xs),
|
||||
final canCopy = widget.closed && widget.code.trim().isNotEmpty;
|
||||
final icon = _copied
|
||||
? Icons.check
|
||||
: canCopy
|
||||
? Icons.copy
|
||||
: Icons.hourglass_empty;
|
||||
|
||||
const background = Color(0xFF0F172A);
|
||||
final borderColor = const Color(0xFF1E293B).withValues(alpha: 0.6);
|
||||
final headerColor = const Color(0xFF1E293B).withValues(alpha: 0.85);
|
||||
|
||||
final languageLabel = (widget.language?.isNotEmpty ?? false)
|
||||
? widget.language!
|
||||
: 'code';
|
||||
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
margin: const EdgeInsets.symmetric(vertical: Spacing.xs),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.surfaceBackground.withValues(alpha: 0.8),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Color(0x33000000),
|
||||
blurRadius: 14,
|
||||
offset: Offset(0, 10),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.copy,
|
||||
size: IconSize.sm,
|
||||
color: theme.iconSecondary,
|
||||
],
|
||||
border: Border.all(color: borderColor, width: BorderWidth.micro),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (language != null)
|
||||
Positioned(
|
||||
top: 8,
|
||||
left: 8,
|
||||
child: Container(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
color: headerColor,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: Spacing.sm,
|
||||
vertical: Spacing.xxs,
|
||||
vertical: Spacing.xs,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.surfaceBackground.withValues(alpha: 0.8),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.xs),
|
||||
),
|
||||
child: Text(
|
||||
language!,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
languageLabel,
|
||||
style: AppTypography.bodySmallStyle.copyWith(
|
||||
color: theme.textSecondary,
|
||||
color: Colors.white.withValues(alpha: 0.85),
|
||||
fontFamily: AppTypography.monospaceFontFamily,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Tooltip(
|
||||
message: canCopy
|
||||
? (_copied
|
||||
? 'Copied'
|
||||
: MaterialLocalizations.of(
|
||||
context,
|
||||
).copyButtonLabel)
|
||||
: 'Copy available after generation completes',
|
||||
child: IconButton(
|
||||
onPressed: canCopy ? _handleCopy : null,
|
||||
icon: Icon(icon, size: IconSize.sm),
|
||||
color: canCopy
|
||||
? Colors.white
|
||||
: Colors.white.withValues(alpha: 0.5),
|
||||
visualDensity: VisualDensity.compact,
|
||||
padding: const EdgeInsets.all(Spacing.xs),
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: Colors.white.withValues(
|
||||
alpha: canCopy ? 0.08 : 0.04,
|
||||
),
|
||||
disabledBackgroundColor: Colors.white.withValues(
|
||||
alpha: 0.03,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Container(
|
||||
color: background,
|
||||
padding: const EdgeInsets.all(Spacing.sm),
|
||||
child: DefaultTextStyle.merge(
|
||||
style: AppTypography.codeStyle.copyWith(
|
||||
color: const Color(0xFFE2E8F0),
|
||||
),
|
||||
child: widget.child,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MermaidDiagram extends StatefulWidget {
|
||||
const MermaidDiagram({
|
||||
super.key,
|
||||
required this.code,
|
||||
required this.brightness,
|
||||
required this.colorScheme,
|
||||
});
|
||||
|
||||
final String code;
|
||||
final Brightness brightness;
|
||||
final ColorScheme colorScheme;
|
||||
|
||||
static bool get isSupported => !kIsWeb;
|
||||
|
||||
static Future<String> _loadScript() {
|
||||
return _scriptFuture ??= rootBundle.loadString('assets/mermaid.min.js');
|
||||
}
|
||||
|
||||
static Future<String>? _scriptFuture;
|
||||
|
||||
@override
|
||||
State<MermaidDiagram> createState() => _MermaidDiagramState();
|
||||
}
|
||||
|
||||
class _MermaidDiagramState extends State<MermaidDiagram> {
|
||||
WebViewController? _controller;
|
||||
String? _script;
|
||||
final Set<Factory<OneSequenceGestureRecognizer>> _gestureRecognizers =
|
||||
<Factory<OneSequenceGestureRecognizer>>{
|
||||
Factory<OneSequenceGestureRecognizer>(() => EagerGestureRecognizer()),
|
||||
};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (!MermaidDiagram.isSupported) {
|
||||
return;
|
||||
}
|
||||
MermaidDiagram._loadScript().then((value) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
_script = value;
|
||||
_controller = WebViewController()
|
||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||
..setBackgroundColor(Colors.transparent);
|
||||
_loadHtml();
|
||||
setState(() {});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(MermaidDiagram oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (_controller == null || _script == null) {
|
||||
return;
|
||||
}
|
||||
final codeChanged = oldWidget.code != widget.code;
|
||||
final themeChanged =
|
||||
oldWidget.brightness != widget.brightness ||
|
||||
oldWidget.colorScheme != widget.colorScheme;
|
||||
if (codeChanged || themeChanged) {
|
||||
_loadHtml();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_controller == null) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
return SizedBox.expand(
|
||||
child: WebViewWidget(
|
||||
controller: _controller!,
|
||||
gestureRecognizers: _gestureRecognizers,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _loadHtml() {
|
||||
if (_controller == null || _script == null) {
|
||||
return;
|
||||
}
|
||||
_controller!.loadHtmlString(_buildHtml(widget.code, _script!));
|
||||
}
|
||||
|
||||
String _buildHtml(String code, String script) {
|
||||
final theme = widget.brightness == Brightness.dark ? 'dark' : 'default';
|
||||
final encoded = jsonEncode(code);
|
||||
final primary = _toHex(widget.colorScheme.primary);
|
||||
final secondary = _toHex(widget.colorScheme.secondary);
|
||||
final background = _toHex(widget.colorScheme.surface);
|
||||
final onBackground = _toHex(widget.colorScheme.onSurface);
|
||||
|
||||
return '''
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; background: transparent; }
|
||||
body { color: $onBackground; font-family: -apple-system, sans-serif; }
|
||||
#diagram { padding: 8px; overflow: auto; }
|
||||
svg { height: auto; display: block; }
|
||||
</style>
|
||||
<script type="text/javascript">
|
||||
$script
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="diagram"></div>
|
||||
<script type="text/javascript">
|
||||
const graphDefinition = $encoded;
|
||||
const themeConfig = {
|
||||
startOnLoad: false,
|
||||
theme: '$theme',
|
||||
securityLevel: 'loose',
|
||||
themeVariables: {
|
||||
primaryColor: '$primary',
|
||||
secondaryColor: '$secondary',
|
||||
background: '$background',
|
||||
textColor: '$onBackground',
|
||||
lineColor: '$onBackground'
|
||||
}
|
||||
};
|
||||
|
||||
(async () => {
|
||||
const target = document.getElementById('diagram');
|
||||
try {
|
||||
mermaid.initialize(themeConfig);
|
||||
const { svg, bindFunctions } = await mermaid.render('graphDiv', graphDefinition);
|
||||
target.innerHTML = svg;
|
||||
if (typeof bindFunctions === 'function') {
|
||||
bindFunctions(target);
|
||||
}
|
||||
} catch (error) {
|
||||
target.innerHTML = '<pre style="color:#ef4444">' + String(error) + '</pre>';
|
||||
console.error('Mermaid render failed', error);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
''';
|
||||
}
|
||||
|
||||
String _toHex(Color color) {
|
||||
final value = color.toARGB32();
|
||||
return '#'
|
||||
'${((value >> 16) & 0xFF).toRadixString(16).padLeft(2, '0')}'
|
||||
'${((value >> 8) & 0xFF).toRadixString(16).padLeft(2, '0')}'
|
||||
'${(value & 0xFF).toRadixString(16).padLeft(2, '0')}'
|
||||
.toUpperCase();
|
||||
}
|
||||
}
|
||||
|
||||
114
lib/shared/widgets/markdown/markdown_preprocessor.dart
Normal file
114
lib/shared/widgets/markdown/markdown_preprocessor.dart
Normal file
@@ -0,0 +1,114 @@
|
||||
/// Utility helpers for normalising markdown content before handing it to
|
||||
/// [GptMarkdown]. The goal is to keep streaming responsive while smoothing
|
||||
/// out troublesome edge-cases (e.g. nested fences inside lists).
|
||||
class ConduitMarkdownPreprocessor {
|
||||
const ConduitMarkdownPreprocessor._();
|
||||
|
||||
/// Normalises common fence and hard-break issues produced by LLMs.
|
||||
static String normalize(String input) {
|
||||
if (input.isEmpty) {
|
||||
return input;
|
||||
}
|
||||
|
||||
var output = input.replaceAll('\r\n', '\n');
|
||||
|
||||
// Move fenced code blocks that start on the same line as a list item onto
|
||||
// their own line so the parser does not treat them as list text.
|
||||
final bulletFence = RegExp(
|
||||
r'^(\s*(?:[*+-]|\d+\.)\s+)```([^\s`]*)\s*$',
|
||||
multiLine: true,
|
||||
);
|
||||
output = output.replaceAllMapped(
|
||||
bulletFence,
|
||||
(match) => '${match[1]}\n```${match[2]}',
|
||||
);
|
||||
|
||||
// Dedent opening fences to avoid partial code-block detection when the
|
||||
// model indents fences by accident.
|
||||
final dedentOpen = RegExp(r'^[ \t]+```([^\n`]*)\s*$', multiLine: true);
|
||||
output = output.replaceAllMapped(dedentOpen, (match) => '```${match[1]}');
|
||||
|
||||
// Dedent closing fences for the same reason as the opening fences.
|
||||
final dedentClose = RegExp(r'^[ \t]+```\s*$', multiLine: true);
|
||||
output = output.replaceAllMapped(dedentClose, (_) => '```');
|
||||
|
||||
// Ensure closing fences stand alone. Prevents situations like `}\n```foo`
|
||||
// from keeping trailing braces inside the code block.
|
||||
final inlineClosing = RegExp(r'([^\r\n`])```(?=\s*(?:\r?\n|$))');
|
||||
output = output.replaceAllMapped(
|
||||
inlineClosing,
|
||||
(match) => '${match[1]}\n```',
|
||||
);
|
||||
|
||||
// Insert a blank line when a "label: value" line is followed by a
|
||||
// horizontal rule so it is not treated as a Setext heading underline.
|
||||
final labelThenDash = RegExp(
|
||||
r'^(\*\*[^\n*]+\*\*.*)\n(\s*-{3,}\s*$)',
|
||||
multiLine: true,
|
||||
);
|
||||
output = output.replaceAllMapped(
|
||||
labelThenDash,
|
||||
(match) => '${match[1]}\n\n${match[2]}',
|
||||
);
|
||||
|
||||
// Allow headings like "## 1. Summary" without triggering ordered-list
|
||||
// parsing by inserting a zero-width joiner after the numeric marker.
|
||||
final atxEnum = RegExp(
|
||||
r'^(\s{0,3}#{1,6}\s+\d+)\.(\s*)(\S)',
|
||||
multiLine: true,
|
||||
);
|
||||
output = output.replaceAllMapped(
|
||||
atxEnum,
|
||||
(match) => '${match[1]}.\u200C${match[2]}${match[3]}',
|
||||
);
|
||||
|
||||
// Auto-close an unmatched opening fence at EOF to avoid the entire tail
|
||||
// of the message rendering as code.
|
||||
final fenceAtBol = RegExp(r'^\s*```', multiLine: true);
|
||||
final fenceCount = fenceAtBol.allMatches(output).length;
|
||||
if (fenceCount.isOdd) {
|
||||
if (!output.endsWith('\n')) {
|
||||
output += '\n';
|
||||
}
|
||||
output += '```';
|
||||
}
|
||||
|
||||
// Convert Markdown links followed by two trailing spaces into separate
|
||||
// paragraphs so that consecutive links do not collapse into a single
|
||||
// paragraph at render time.
|
||||
final linkWithTrailingSpaces = RegExp(r'\[[^\]]+\]\([^\)]+\)\s{2,}$');
|
||||
final lines = output.split('\n');
|
||||
if (lines.length > 1) {
|
||||
final buffer = StringBuffer();
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
final line = lines[i];
|
||||
buffer.write(line);
|
||||
if (i < lines.length - 1) {
|
||||
buffer.write('\n');
|
||||
}
|
||||
if (linkWithTrailingSpaces.hasMatch(line)) {
|
||||
buffer.write('\n');
|
||||
}
|
||||
}
|
||||
output = buffer.toString();
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/// Inserts zero-width break characters into long inline code spans so they
|
||||
/// remain readable and do not overflow narrow layouts.
|
||||
static String softenInlineCode(String input, {int chunkSize = 24}) {
|
||||
if (input.length <= chunkSize) {
|
||||
return input;
|
||||
}
|
||||
final buffer = StringBuffer();
|
||||
for (var i = 0; i < input.length; i++) {
|
||||
buffer.write(input[i]);
|
||||
if ((i + 1) % chunkSize == 0) {
|
||||
buffer.write('\u200B');
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gpt_markdown/gpt_markdown.dart';
|
||||
|
||||
import '../../theme/theme_extensions.dart';
|
||||
import 'markdown_config.dart';
|
||||
import 'markdown_preprocessor.dart';
|
||||
|
||||
typedef MarkdownLinkTapCallback = void Function(String url, String title);
|
||||
|
||||
@@ -19,18 +21,28 @@ class StreamingMarkdownWidget extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final markdownTheme = ConduitMarkdownConfig.resolve(context);
|
||||
|
||||
if (content.trim().isEmpty) {
|
||||
return isStreaming ? const SizedBox.shrink() : const SizedBox.shrink();
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final normalized = ConduitMarkdownPreprocessor.normalize(content);
|
||||
|
||||
const featureFlags = MarkdownFeatureFlags(
|
||||
enableSyntaxHighlighting: true,
|
||||
enableMermaid: true,
|
||||
);
|
||||
|
||||
final markdownTheme = ConduitMarkdownConfig.resolve(
|
||||
context,
|
||||
flags: featureFlags,
|
||||
);
|
||||
final textScaler = MediaQuery.maybeOf(context)?.textScaler;
|
||||
|
||||
return GptMarkdownTheme(
|
||||
gptThemeData: markdownTheme.themeData,
|
||||
child: SelectionArea(
|
||||
child: GptMarkdown(
|
||||
content,
|
||||
normalized,
|
||||
style: markdownTheme.textStyle,
|
||||
followLinkColor: markdownTheme.followLinkColor,
|
||||
textDirection: Directionality.of(context),
|
||||
@@ -38,14 +50,55 @@ class StreamingMarkdownWidget extends StatelessWidget {
|
||||
onLinkTap: onTapLink,
|
||||
codeBuilder: markdownTheme.codeBuilder,
|
||||
imageBuilder: markdownTheme.imageBuilder,
|
||||
useDollarSignsForLatex: true,
|
||||
highlightBuilder: (highlightContext, inline, baseStyle) {
|
||||
final softened = ConduitMarkdownPreprocessor.softenInlineCode(
|
||||
inline,
|
||||
);
|
||||
final theme = highlightContext.conduitTheme;
|
||||
final base = baseStyle;
|
||||
final fontSize = (base.fontSize ?? 13).clamp(11, 15).toDouble();
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: Spacing.xs,
|
||||
vertical: Spacing.xxs,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.surfaceBackground.withValues(alpha: 0.55),
|
||||
borderRadius: BorderRadius.circular(AppBorderRadius.xs),
|
||||
border: Border.all(
|
||||
color: theme.cardBorder.withValues(alpha: 0.2),
|
||||
width: BorderWidth.micro,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
softened,
|
||||
style: base.copyWith(
|
||||
fontFamily: AppTypography.monospaceFontFamily,
|
||||
fontSize: fontSize,
|
||||
height: 1.35,
|
||||
color: theme.code?.color ?? theme.textSecondary,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension StreamingMarkdownExtension on String {
|
||||
Widget toMarkdown({required BuildContext context, bool isStreaming = false}) {
|
||||
return StreamingMarkdownWidget(content: this, isStreaming: isStreaming);
|
||||
Widget toMarkdown({
|
||||
required BuildContext context,
|
||||
bool isStreaming = false,
|
||||
MarkdownLinkTapCallback? onTapLink,
|
||||
}) {
|
||||
return StreamingMarkdownWidget(
|
||||
content: this,
|
||||
isStreaming: isStreaming,
|
||||
onTapLink: onTapLink,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +111,7 @@ class MarkdownWithLoading extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final value = content ?? '';
|
||||
if (isLoading && value.isEmpty) {
|
||||
if (isLoading && value.trim().isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
|
||||
48
pubspec.lock
48
pubspec.lock
@@ -430,6 +430,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.4.1"
|
||||
flutter_highlight:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_highlight
|
||||
sha256: "7b96333867aa07e122e245c033b8ad622e4e3a42a1a2372cbb098a2541d8782c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.0"
|
||||
flutter_lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@@ -613,6 +621,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
highlight:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: highlight
|
||||
sha256: "5353a83ffe3e3eca7df0abfb72dcf3fa66cc56b953728e7113ad4ad88497cf21"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.0"
|
||||
hive_ce:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -1706,6 +1722,38 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.1"
|
||||
webview_flutter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: webview_flutter
|
||||
sha256: c3e4fe614b1c814950ad07186007eff2f2e5dd2935eba7b9a9a1af8e5885f1ba
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.13.0"
|
||||
webview_flutter_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webview_flutter_android
|
||||
sha256: "3c4eb4fcc252b40c2b5ce7be20d0481428b70f3ff589b0a8b8aaeb64c6bed701"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.10.2"
|
||||
webview_flutter_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webview_flutter_platform_interface
|
||||
sha256: "63d26ee3aca7256a83ccb576a50272edd7cfc80573a4305caa98985feb493ee0"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.14.0"
|
||||
webview_flutter_wkwebview:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webview_flutter_wkwebview
|
||||
sha256: fea63576b3b7e02b2df8b78ba92b48ed66caec2bb041e9a0b1cbd586d5d80bfd
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.23.1"
|
||||
win32:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -32,6 +32,8 @@ dependencies:
|
||||
# UI Components - GPT Markdown
|
||||
gpt_markdown: ^1.1.4
|
||||
cached_network_image: ^3.3.1
|
||||
flutter_highlight: ^0.7.0
|
||||
webview_flutter: ^4.7.0
|
||||
socket_io_client: ^3.1.2
|
||||
yaml: ^3.1.2
|
||||
|
||||
@@ -89,6 +91,7 @@ flutter:
|
||||
|
||||
assets:
|
||||
- assets/icons/
|
||||
- assets/mermaid.min.js
|
||||
|
||||
flutter_native_splash:
|
||||
# Splash background matches the light theme; `color_dark` handles dark mode.
|
||||
|
||||
Reference in New Issue
Block a user