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']
|
.quickPills; // StringList of identifiers e.g. ['web','image','tools']
|
||||||
// Chat input behavior
|
// Chat input behavior
|
||||||
static const String _sendOnEnterKey = PreferenceKeys.sendOnEnterKey;
|
static const String _sendOnEnterKey = PreferenceKeys.sendOnEnterKey;
|
||||||
|
|
||||||
static Box<dynamic> _preferencesBox() =>
|
static Box<dynamic> _preferencesBox() =>
|
||||||
Hive.box<dynamic>(HiveBoxNames.preferences);
|
Hive.box<dynamic>(HiveBoxNames.preferences);
|
||||||
|
|
||||||
@@ -313,7 +312,6 @@ class AppSettings {
|
|||||||
final String socketTransportMode; // 'auto' or 'ws'
|
final String socketTransportMode; // 'auto' or 'ws'
|
||||||
final List<String> quickPills; // e.g., ['web','image']
|
final List<String> quickPills; // e.g., ['web','image']
|
||||||
final bool sendOnEnter;
|
final bool sendOnEnter;
|
||||||
|
|
||||||
const AppSettings({
|
const AppSettings({
|
||||||
this.reduceMotion = false,
|
this.reduceMotion = false,
|
||||||
this.animationSpeed = 1.0,
|
this.animationSpeed = 1.0,
|
||||||
|
|||||||
@@ -1,15 +1,43 @@
|
|||||||
|
import 'dart:async';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
|
||||||
import 'package:cached_network_image/cached_network_image.dart';
|
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/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'
|
import 'package:gpt_markdown/custom_widgets/markdown_config.dart'
|
||||||
show CodeBlockBuilder, ImageBuilder;
|
show CodeBlockBuilder, ImageBuilder;
|
||||||
import 'package:gpt_markdown/gpt_markdown.dart';
|
import 'package:gpt_markdown/gpt_markdown.dart';
|
||||||
|
import 'package:webview_flutter/webview_flutter.dart';
|
||||||
|
|
||||||
import 'package:conduit/l10n/app_localizations.dart';
|
import 'package:conduit/l10n/app_localizations.dart';
|
||||||
|
|
||||||
import '../../theme/theme_extensions.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 {
|
class ConduitMarkdownTheme {
|
||||||
const ConduitMarkdownTheme({
|
const ConduitMarkdownTheme({
|
||||||
required this.textStyle,
|
required this.textStyle,
|
||||||
@@ -27,7 +55,10 @@ class ConduitMarkdownTheme {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class ConduitMarkdownConfig {
|
class ConduitMarkdownConfig {
|
||||||
static ConduitMarkdownTheme resolve(BuildContext context) {
|
static ConduitMarkdownTheme resolve(
|
||||||
|
BuildContext context, {
|
||||||
|
MarkdownFeatureFlags flags = const MarkdownFeatureFlags(),
|
||||||
|
}) {
|
||||||
final theme = context.conduitTheme;
|
final theme = context.conduitTheme;
|
||||||
final materialTheme = Theme.of(context);
|
final materialTheme = Theme.of(context);
|
||||||
|
|
||||||
@@ -78,37 +109,226 @@ class ConduitMarkdownConfig {
|
|||||||
},
|
},
|
||||||
codeBuilder: (context, name, code, closed) {
|
codeBuilder: (context, name, code, closed) {
|
||||||
final conduitTheme = context.conduitTheme;
|
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 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(
|
return CodeBlockWrapper(
|
||||||
code: code,
|
code: code,
|
||||||
language: language,
|
language: language,
|
||||||
theme: conduitTheme,
|
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(
|
static Widget buildBase64Image(
|
||||||
String dataUrl,
|
String dataUrl,
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
@@ -195,73 +415,309 @@ class ConduitMarkdownConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class CodeBlockWrapper extends StatelessWidget {
|
class CodeBlockWrapper extends StatefulWidget {
|
||||||
const CodeBlockWrapper({
|
const CodeBlockWrapper({
|
||||||
super.key,
|
super.key,
|
||||||
required this.child,
|
required this.child,
|
||||||
required this.code,
|
required this.code,
|
||||||
this.language,
|
this.language,
|
||||||
required this.theme,
|
required this.theme,
|
||||||
|
required this.closed,
|
||||||
});
|
});
|
||||||
|
|
||||||
final Widget child;
|
final Widget child;
|
||||||
final String code;
|
final String code;
|
||||||
final String? language;
|
final String? language;
|
||||||
final ConduitThemeExtension theme;
|
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
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Stack(
|
final canCopy = widget.closed && widget.code.trim().isNotEmpty;
|
||||||
children: [
|
final icon = _copied
|
||||||
child,
|
? Icons.check
|
||||||
Positioned(
|
: canCopy
|
||||||
top: 8,
|
? Icons.copy
|
||||||
right: 8,
|
: Icons.hourglass_empty;
|
||||||
child: Material(
|
|
||||||
color: theme.surfaceBackground.withValues(alpha: 0.0),
|
const background = Color(0xFF0F172A);
|
||||||
child: InkWell(
|
final borderColor = const Color(0xFF1E293B).withValues(alpha: 0.6);
|
||||||
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
|
final headerColor = const Color(0xFF1E293B).withValues(alpha: 0.85);
|
||||||
onTap: () {
|
|
||||||
// Copy implementation provided by higher level clipboard service.
|
final languageLabel = (widget.language?.isNotEmpty ?? false)
|
||||||
},
|
? widget.language!
|
||||||
child: Container(
|
: 'code';
|
||||||
padding: const EdgeInsets.all(Spacing.xs),
|
|
||||||
|
return Container(
|
||||||
|
width: double.infinity,
|
||||||
|
margin: const EdgeInsets.symmetric(vertical: Spacing.xs),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: theme.surfaceBackground.withValues(alpha: 0.8),
|
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||||
borderRadius: BorderRadius.circular(AppBorderRadius.sm),
|
boxShadow: const [
|
||||||
|
BoxShadow(
|
||||||
|
color: Color(0x33000000),
|
||||||
|
blurRadius: 14,
|
||||||
|
offset: Offset(0, 10),
|
||||||
),
|
),
|
||||||
child: Icon(
|
],
|
||||||
Icons.copy,
|
border: Border.all(color: borderColor, width: BorderWidth.micro),
|
||||||
size: IconSize.sm,
|
|
||||||
color: theme.iconSecondary,
|
|
||||||
),
|
),
|
||||||
),
|
child: ClipRRect(
|
||||||
),
|
borderRadius: BorderRadius.circular(AppBorderRadius.md),
|
||||||
),
|
child: Column(
|
||||||
),
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
if (language != null)
|
mainAxisSize: MainAxisSize.min,
|
||||||
Positioned(
|
children: [
|
||||||
top: 8,
|
Container(
|
||||||
left: 8,
|
color: headerColor,
|
||||||
child: Container(
|
|
||||||
padding: const EdgeInsets.symmetric(
|
padding: const EdgeInsets.symmetric(
|
||||||
horizontal: Spacing.sm,
|
horizontal: Spacing.sm,
|
||||||
vertical: Spacing.xxs,
|
vertical: Spacing.xs,
|
||||||
),
|
),
|
||||||
decoration: BoxDecoration(
|
child: Row(
|
||||||
color: theme.surfaceBackground.withValues(alpha: 0.8),
|
children: [
|
||||||
borderRadius: BorderRadius.circular(AppBorderRadius.xs),
|
Text(
|
||||||
),
|
languageLabel,
|
||||||
child: Text(
|
|
||||||
language!,
|
|
||||||
style: AppTypography.bodySmallStyle.copyWith(
|
style: AppTypography.bodySmallStyle.copyWith(
|
||||||
color: theme.textSecondary,
|
color: Colors.white.withValues(alpha: 0.85),
|
||||||
fontFamily: AppTypography.monospaceFontFamily,
|
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:flutter/material.dart';
|
||||||
import 'package:gpt_markdown/gpt_markdown.dart';
|
import 'package:gpt_markdown/gpt_markdown.dart';
|
||||||
|
|
||||||
|
import '../../theme/theme_extensions.dart';
|
||||||
import 'markdown_config.dart';
|
import 'markdown_config.dart';
|
||||||
|
import 'markdown_preprocessor.dart';
|
||||||
|
|
||||||
typedef MarkdownLinkTapCallback = void Function(String url, String title);
|
typedef MarkdownLinkTapCallback = void Function(String url, String title);
|
||||||
|
|
||||||
@@ -19,18 +21,28 @@ class StreamingMarkdownWidget extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final markdownTheme = ConduitMarkdownConfig.resolve(context);
|
|
||||||
|
|
||||||
if (content.trim().isEmpty) {
|
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;
|
final textScaler = MediaQuery.maybeOf(context)?.textScaler;
|
||||||
|
|
||||||
return GptMarkdownTheme(
|
return GptMarkdownTheme(
|
||||||
gptThemeData: markdownTheme.themeData,
|
gptThemeData: markdownTheme.themeData,
|
||||||
|
child: SelectionArea(
|
||||||
child: GptMarkdown(
|
child: GptMarkdown(
|
||||||
content,
|
normalized,
|
||||||
style: markdownTheme.textStyle,
|
style: markdownTheme.textStyle,
|
||||||
followLinkColor: markdownTheme.followLinkColor,
|
followLinkColor: markdownTheme.followLinkColor,
|
||||||
textDirection: Directionality.of(context),
|
textDirection: Directionality.of(context),
|
||||||
@@ -38,14 +50,55 @@ class StreamingMarkdownWidget extends StatelessWidget {
|
|||||||
onLinkTap: onTapLink,
|
onLinkTap: onTapLink,
|
||||||
codeBuilder: markdownTheme.codeBuilder,
|
codeBuilder: markdownTheme.codeBuilder,
|
||||||
imageBuilder: markdownTheme.imageBuilder,
|
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 {
|
extension StreamingMarkdownExtension on String {
|
||||||
Widget toMarkdown({required BuildContext context, bool isStreaming = false}) {
|
Widget toMarkdown({
|
||||||
return StreamingMarkdownWidget(content: this, isStreaming: isStreaming);
|
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
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final value = content ?? '';
|
final value = content ?? '';
|
||||||
if (isLoading && value.isEmpty) {
|
if (isLoading && value.trim().isEmpty) {
|
||||||
return const Center(child: CircularProgressIndicator());
|
return const Center(child: CircularProgressIndicator());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
48
pubspec.lock
48
pubspec.lock
@@ -430,6 +430,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.4.1"
|
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:
|
flutter_lints:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description:
|
description:
|
||||||
@@ -613,6 +621,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.3.2"
|
version: "2.3.2"
|
||||||
|
highlight:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: highlight
|
||||||
|
sha256: "5353a83ffe3e3eca7df0abfb72dcf3fa66cc56b953728e7113ad4ad88497cf21"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.7.0"
|
||||||
hive_ce:
|
hive_ce:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@@ -1706,6 +1722,38 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.2.1"
|
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:
|
win32:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ dependencies:
|
|||||||
# UI Components - GPT Markdown
|
# UI Components - GPT Markdown
|
||||||
gpt_markdown: ^1.1.4
|
gpt_markdown: ^1.1.4
|
||||||
cached_network_image: ^3.3.1
|
cached_network_image: ^3.3.1
|
||||||
|
flutter_highlight: ^0.7.0
|
||||||
|
webview_flutter: ^4.7.0
|
||||||
socket_io_client: ^3.1.2
|
socket_io_client: ^3.1.2
|
||||||
yaml: ^3.1.2
|
yaml: ^3.1.2
|
||||||
|
|
||||||
@@ -89,6 +91,7 @@ flutter:
|
|||||||
|
|
||||||
assets:
|
assets:
|
||||||
- assets/icons/
|
- assets/icons/
|
||||||
|
- assets/mermaid.min.js
|
||||||
|
|
||||||
flutter_native_splash:
|
flutter_native_splash:
|
||||||
# Splash background matches the light theme; `color_dark` handles dark mode.
|
# Splash background matches the light theme; `color_dark` handles dark mode.
|
||||||
|
|||||||
Reference in New Issue
Block a user