refactor: 重构聊天模块支持 SSE 断线重连及用户上下文隔离

This commit is contained in:
zl-q
2026-03-30 09:06:10 +08:00
parent 1aac62f39e
commit 4285b4ec80
28 changed files with 1624 additions and 658 deletions
@@ -1,12 +1,26 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:social_app/core/l10n/l10n.dart';
import 'package:social_app/core/ui_schema/navigation/ui_schema_navigation.dart';
import 'package:social_app/core/theme/design_tokens.dart';
import 'package:social_app/shared/widgets/toast/toast.dart';
import 'package:social_app/shared/widgets/toast/toast_type.dart';
const _titleFontSize = AppSpacing.lg + 1;
const _bodyFontSize = AppSpacing.md;
const _captionFontSize = AppSpacing.sm + AppSpacing.xs / 2;
const _codeFontSize = AppSpacing.sm + AppSpacing.xs;
const _buttonFontSize = AppSpacing.sm + AppSpacing.xs;
const _statusLabelTokenPrefix = 'ui.status.';
class UiSchemaRenderer {
final BuildContext context;
final ColorScheme colorScheme;
UiSchemaRenderer(this.colorScheme);
UiSchemaRenderer(this.context, this.colorScheme);
Widget renderSchema(Map<String, dynamic>? schema) {
if (schema == null || schema.isEmpty) {
@@ -96,30 +110,30 @@ class UiSchemaRenderer {
final status = _asString(node['status']);
final style = switch (role) {
'title' => TextStyle(
fontSize: 18,
fontWeight: FontWeight.w700,
fontSize: _titleFontSize,
fontWeight: FontWeight.w600,
color: colorScheme.onSurface,
height: 1.2,
height: 1.25,
),
'subtitle' => TextStyle(
fontSize: 14,
fontSize: AppSpacing.md,
fontWeight: FontWeight.w600,
color: colorScheme.onSurface,
),
'caption' => TextStyle(
fontSize: 11,
fontSize: _captionFontSize,
color: colorScheme.onSurfaceVariant,
height: 1.4,
),
'code' => TextStyle(
fontSize: 12,
fontSize: _codeFontSize,
color: colorScheme.onSurfaceVariant,
fontFamily: 'monospace',
),
_ => TextStyle(
fontSize: 13,
fontSize: _bodyFontSize,
color: colorScheme.onSurfaceVariant,
height: 1.35,
height: 1.4,
),
};
return Text(
@@ -140,23 +154,35 @@ class UiSchemaRenderer {
Widget _renderBadge(Map<String, dynamic> node) {
final status = _asString(node['status']);
final fg =
_statusTextColor(status, colorScheme.onSurfaceVariant) ??
colorScheme.onSurfaceVariant;
final bg = _statusBackground(status);
return Container(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.md,
vertical: AppSpacing.xs,
),
decoration: BoxDecoration(
color: bg,
borderRadius: BorderRadius.circular(AppRadius.full),
border: Border.all(color: _statusBorder(status)),
),
child: Text(
_asString(node['label']),
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700, color: fg),
final resolvedLabel = _resolveStatusLabel(
rawLabel: _asString(node['label']),
status: status,
);
final statusDotColor = _statusBorder(status);
return Padding(
padding: const EdgeInsets.only(left: AppSpacing.xs / 2),
child: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: AppSpacing.xs,
height: AppSpacing.xs,
decoration: BoxDecoration(
color: statusDotColor,
shape: BoxShape.circle,
),
),
const SizedBox(width: AppSpacing.xs),
Text(
resolvedLabel,
style: TextStyle(
fontSize: _captionFontSize,
fontWeight: FontWeight.w600,
color: colorScheme.onSurfaceVariant,
),
),
],
),
);
}
@@ -165,39 +191,269 @@ class UiSchemaRenderer {
final style = _asString(node['style'], fallback: 'secondary');
final action = _asMap(node['action']);
final disabled = node['disabled'] == true;
final isPrimary = style == 'primary';
final isGhost = style == 'ghost';
final isDanger = style == 'danger';
final backgroundColor = isPrimary
? colorScheme.primaryContainer
: isGhost
? colorScheme.surface
: isDanger
? colorScheme.errorContainer
: colorScheme.surfaceContainerLow;
final foregroundColor = isPrimary
? colorScheme.onPrimaryContainer
: isDanger
? colorScheme.onErrorContainer
: isGhost
? colorScheme.onSurfaceVariant
: colorScheme.onSurfaceVariant;
final borderColor = isPrimary
? colorScheme.primary.withValues(alpha: 0.3)
: isGhost
? colorScheme.outlineVariant.withValues(alpha: 0.4)
: isDanger
? colorScheme.error.withValues(alpha: 0.35)
: colorScheme.outlineVariant.withValues(alpha: 0.4);
return ElevatedButton(
onPressed: disabled
? null
: () {
_handleAction(action);
: () async {
await _handleAction(action);
},
style: ElevatedButton.styleFrom(
elevation: 0,
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.lg,
horizontal: AppSpacing.md + AppSpacing.xs,
vertical: AppSpacing.sm,
),
backgroundColor: style == 'primary'
? colorScheme.primary
: colorScheme.surfaceContainerHighest,
foregroundColor: style == 'primary'
? colorScheme.onPrimary
: colorScheme.onSurfaceVariant,
minimumSize: const Size(0, AppSpacing.xxl + AppSpacing.xs),
backgroundColor: backgroundColor,
foregroundColor: foregroundColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppRadius.full),
side: style == 'primary'
? BorderSide.none
: BorderSide(color: colorScheme.outlineVariant),
side: BorderSide(color: borderColor),
),
),
child: Text(
_asString(node['label'], fallback: L10n.current.uiSchemaActionFallback),
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
style: TextStyle(
fontSize: _buttonFontSize,
fontWeight: isPrimary ? FontWeight.w700 : FontWeight.w600,
),
),
);
}
void _handleAction(Map<String, dynamic>? action) {}
Future<void> _handleAction(Map<String, dynamic>? action) async {
if (action == null || action.isEmpty) {
Toast.show(
context,
L10n.current.uiSchemaActionNotImplemented,
type: ToastType.warning,
);
return;
}
final type = _asString(action['type']);
switch (type) {
case 'navigation':
_handleNavigationAction(action);
return;
case 'url':
await _handleUrlAction(action);
return;
case 'copy':
_handleCopyAction(action);
return;
case 'event':
case 'tool':
case 'payload':
default:
Toast.show(
context,
L10n.current.uiSchemaActionNotImplemented,
type: ToastType.info,
);
}
}
Future<void> _handleUrlAction(Map<String, dynamic> action) async {
final rawUrl = _asString(action['url']).trim();
if (!_isValidExternalUrl(rawUrl)) {
Toast.show(
context,
L10n.current.uiSchemaUrlInvalid,
type: ToastType.error,
);
return;
}
final uri = Uri.tryParse(rawUrl);
if (uri == null) {
Toast.show(
context,
L10n.current.uiSchemaUrlInvalid,
type: ToastType.error,
);
return;
}
final target = _asString(action['target'], fallback: '_blank');
final mode = target == '_self'
? LaunchMode.platformDefault
: LaunchMode.externalApplication;
try {
final launched = await launchUrl(uri, mode: mode);
if (!context.mounted) {
return;
}
if (!launched) {
debugPrint('UiSchemaRenderer: failed to launch URL: $rawUrl');
Toast.show(
context,
L10n.current.uiSchemaUrlOpenFailed,
type: ToastType.error,
);
}
} catch (error) {
debugPrint('UiSchemaRenderer: URL launch error for $rawUrl: $error');
if (!context.mounted) {
return;
}
Toast.show(
context,
L10n.current.uiSchemaUrlOpenFailed,
type: ToastType.error,
);
}
}
void _handleNavigationAction(Map<String, dynamic> action) {
final path = _asString(action['path']).trim();
if (!isValidInternalNavigationPath(path)) {
Toast.show(
context,
L10n.current.uiSchemaNavigationInvalidPath,
type: ToastType.error,
);
return;
}
final params = _asMap(action['params']);
if (params != null && !_areScalarNavigationParams(params)) {
Toast.show(
context,
L10n.current.uiSchemaNavigationInvalidParams,
type: ToastType.error,
);
return;
}
final target = buildUiSchemaNavigationTarget(path: path, params: params);
try {
context.push(target);
} catch (error) {
debugPrint('UiSchemaRenderer: navigation failed for $target: $error');
Toast.show(
context,
L10n.current.uiSchemaNavigationInvalidPath,
type: ToastType.error,
);
}
}
void _handleCopyAction(Map<String, dynamic> action) {
final content = _asString(action['content']);
if (content.isEmpty) {
Toast.show(
context,
L10n.current.uiSchemaActionNotImplemented,
type: ToastType.warning,
);
return;
}
Clipboard.setData(ClipboardData(text: content));
final successMessage = _asString(
action['successMessage'],
fallback: L10n.current.commonCopySuccess,
);
Toast.show(context, successMessage, type: ToastType.success);
}
static bool _isValidExternalUrl(String url) {
if (url.isEmpty) return false;
final uri = Uri.tryParse(url);
if (uri == null || !uri.hasScheme) return false;
final scheme = uri.scheme.toLowerCase();
if (scheme == 'http' || scheme == 'https') {
if (uri.host.isEmpty || uri.userInfo.isNotEmpty) {
return false;
}
if (_isLocalOrPrivateHost(uri.host)) {
return false;
}
return true;
}
return scheme == 'mailto' || scheme == 'tel' || scheme == 'sms';
}
static bool _areScalarNavigationParams(Map<String, dynamic> params) {
for (final value in params.values) {
if (value is String || value is num || value is bool) {
continue;
}
return false;
}
return true;
}
static bool _isLocalOrPrivateHost(String host) {
final normalizedHost = host.toLowerCase();
if (normalizedHost.contains(':')) {
return true;
}
if (int.tryParse(normalizedHost) != null) {
return true;
}
if (normalizedHost == 'localhost' ||
normalizedHost == '127.0.0.1' ||
normalizedHost == '::1') {
return true;
}
final ipv4 = normalizedHost.split('.');
if (ipv4.length != 4) {
return false;
}
final octets = <int>[];
for (final part in ipv4) {
final parsed = int.tryParse(part);
if (parsed == null || parsed < 0 || parsed > 255) {
return false;
}
octets.add(parsed);
}
final first = octets[0];
final second = octets[1];
if (first == 10 || first == 127 || first == 0) {
return true;
}
if (first == 169 && second == 254) {
return true;
}
if (first == 192 && second == 168) {
return true;
}
if (first == 172 && second >= 16 && second <= 31) {
return true;
}
return false;
}
Widget _renderKv(Map<String, dynamic> node) {
final items = _asList(
@@ -217,13 +473,13 @@ class UiSchemaRenderer {
final value = item['value']?.toString() ?? '-';
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.md,
vertical: AppSpacing.xs,
),
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(AppRadius.md),
border: Border(
bottom: BorderSide(
color: colorScheme.outlineVariant.withValues(alpha: 0.2),
),
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -233,8 +489,10 @@ class UiSchemaRenderer {
child: Text(
label,
style: TextStyle(
fontSize: 11,
color: colorScheme.onSurfaceVariant,
fontSize: _captionFontSize,
color: colorScheme.onSurfaceVariant.withValues(
alpha: 0.72,
),
),
),
),
@@ -244,9 +502,9 @@ class UiSchemaRenderer {
child: Text(
value,
style: TextStyle(
fontSize: 12,
fontSize: _bodyFontSize,
color: colorScheme.onSurface,
fontWeight: FontWeight.w600,
fontWeight: FontWeight.w400,
),
),
),
@@ -274,14 +532,17 @@ class UiSchemaRenderer {
return child;
}
final bg = switch (appearance) {
'section' => colorScheme.surfaceContainerHighest,
'card' => colorScheme.surface,
'section' => colorScheme.surfaceContainerLow,
'card' =>
status == 'success'
? colorScheme.primaryContainer.withValues(alpha: 0.05)
: colorScheme.surfaceContainerLow.withValues(alpha: 0.5),
_ => _statusBackground(status),
};
final borderColor = switch (status) {
'success' => colorScheme.tertiary,
'warning' => colorScheme.secondary,
'error' => colorScheme.error,
'success' => colorScheme.primary.withValues(alpha: 0.1),
'warning' => colorScheme.outlineVariant,
'error' => colorScheme.error.withValues(alpha: 0.22),
_ => colorScheme.outlineVariant,
};
return Container(
@@ -289,15 +550,8 @@ class UiSchemaRenderer {
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: bg,
borderRadius: BorderRadius.circular(AppRadius.lg),
border: Border.all(color: borderColor),
boxShadow: [
BoxShadow(
color: colorScheme.shadow.withValues(alpha: 0.08),
blurRadius: 12,
offset: const Offset(0, 6),
),
],
borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: borderColor.withValues(alpha: 0.4)),
),
child: child,
);
@@ -313,7 +567,10 @@ class UiSchemaRenderer {
),
child: Text(
text,
style: TextStyle(fontSize: 12, color: colorScheme.onSecondaryContainer),
style: TextStyle(
fontSize: _buttonFontSize,
color: colorScheme.onSecondaryContainer,
),
),
);
}
@@ -331,7 +588,7 @@ class UiSchemaRenderer {
Color _statusBackground(String status) {
return switch (status) {
'success' => colorScheme.tertiaryContainer,
'success' => colorScheme.primaryContainer.withValues(alpha: 0.3),
'warning' => colorScheme.secondaryContainer,
'error' => colorScheme.errorContainer,
'pending' => colorScheme.primaryContainer,
@@ -341,7 +598,7 @@ class UiSchemaRenderer {
Color _statusBorder(String status) {
return switch (status) {
'success' => colorScheme.tertiary,
'success' => colorScheme.primary,
'warning' => colorScheme.secondary,
'error' => colorScheme.error,
'pending' => colorScheme.primary,
@@ -351,7 +608,7 @@ class UiSchemaRenderer {
Color? _statusTextColor(String status, Color? fallback) {
return switch (status) {
'success' => colorScheme.onTertiaryContainer,
'success' => colorScheme.onSurfaceVariant,
'warning' => colorScheme.onSecondaryContainer,
'error' => colorScheme.onErrorContainer,
'pending' => colorScheme.onPrimaryContainer,
@@ -359,6 +616,37 @@ class UiSchemaRenderer {
};
}
String _resolveStatusLabel({
required String rawLabel,
required String status,
}) {
final normalizedStatus = status.trim().toLowerCase();
final normalizedLabel = rawLabel.trim().toLowerCase();
final bareLabel = normalizedLabel.startsWith(_statusLabelTokenPrefix)
? normalizedLabel.substring(_statusLabelTokenPrefix.length)
: normalizedLabel;
final isTokenLabel = normalizedLabel.startsWith(_statusLabelTokenPrefix);
final isLegacyStatusLabel = bareLabel == normalizedStatus;
if (isTokenLabel || isLegacyStatusLabel) {
return _tryLocalizedStatusLabel(bareLabel) ?? rawLabel;
}
return rawLabel;
}
String? _tryLocalizedStatusLabel(String status) {
final l10n = L10n.current;
return switch (status) {
'success' => l10n.uiSchemaStatusSuccess,
'warning' => l10n.uiSchemaStatusWarning,
'error' => l10n.uiSchemaStatusError,
'pending' => l10n.uiSchemaStatusPending,
'info' => l10n.uiSchemaStatusInfo,
_ => null,
};
}
static Map<String, dynamic>? _asMap(Object? value) {
if (value is Map<String, dynamic>) {
return value;