mirror of
https://github.com/we-promise/sure.git
synced 2026-07-19 16:25:24 +00:00
* feat(mobile): add Flutter i18n foundation (gen_l10n Phase 1)
- Wire flutter_localizations + gen_l10n (pubspec.yaml + l10n.yaml)
- Bump intl ^0.18.1 → ^0.20.2 for Flutter 3.32 pin
- Add lib/l10n/app_en.arb with 9 seed keys (appTitle, 3 common*, 4 chatSuggestion*)
- Generate AppLocalizations via flutter gen-l10n
- Replace MaterialApp title: with onGenerateTitle + localizationsDelegates + supportedLocales
- Migrate suggested_questions.dart from const list to BuildContext function
- Update chat_conversation_screen.dart call site (one-line change at pre-designed seam)
* feat(mobile): migrate all hardcoded UI strings to gen_l10n ARB (Phase 2)
Extends the i18n foundation from Phase 1 to cover every remaining
hardcoded user-facing string across the mobile app.
Files changed (21 source files + ARB/generated):
- lib/l10n/app_en.arb: 226 keys (+~80 new keys covering all screens)
- lib/screens/dashboard_screen.dart
- lib/screens/calendar_screen.dart
- lib/screens/transactions_list_screen.dart
- lib/screens/backend_config_screen.dart
- lib/screens/recent_transactions_screen.dart
- lib/screens/biometric_lock_screen.dart
- lib/screens/chat_conversation_screen.dart
- lib/screens/chat_list_screen.dart
- lib/screens/log_viewer_screen.dart
- lib/screens/login_screen.dart
- lib/screens/main_navigation_screen.dart
- lib/screens/more_screen.dart
- lib/screens/settings_screen.dart
- lib/screens/sso_onboarding_screen.dart
- lib/screens/transaction_edit_screen.dart
- lib/screens/transaction_form_screen.dart
- lib/widgets/account_detail_header.dart
- lib/widgets/category_filter.dart
- lib/widgets/connectivity_banner.dart
- lib/widgets/currency_filter.dart
- lib/widgets/custom_proxy_headers_editor.dart
Notable patterns:
- ICU plural for connectivity pending-sync count
- Parameterised keys for greeting (firstName), update dialog
(version), cash chip (amount), delete confirmation (name),
show-N menu (count), proxy-headers count, multi-delete count
- AppLocalizations captured before async gaps; dialog builders
re-obtain from their own BuildContext
- const removed only from Text/InputDecoration/SnackBar/Row
widgets that directly reference localisation getters; sibling
const widgets preserved
116/116 unit tests pass; flutter analyze --no-fatal-infos: 0 errors.
* feat(mobile): migrate the remaining secondary UI strings to gen_l10n ARB
Completes the i18n migration by covering the lower-traffic strings the
earlier passes left behind — secondary dialogs, snackbars, settings
rows, validators, helper texts, and tooltips across 11 files.
- settings_screen.dart: reset/delete-account dialogs, clear-data and
proxy-header snackbars, list-tile titles/subtitles, theme-segment
tooltips, biometric prompt reason, debug-logs semantics label
- transaction_form_screen.dart: amount validators, session/success/
failure/generic-error snackbars, More/Less toggle, date/name/category
fields + helper texts, create button
- transaction_edit_screen.dart: session/update snackbars, validators,
category/merchant/tag fallbacks, synced-only notice
- login_screen.dart: API-key dialog, demo/sign-up TextSpan, MFA info +
validator, divider, server-URL heading, API-key + backend tooltip
- chat_list_screen.dart: multi-delete plural, result snackbars, error
heading, relative-time fallback
- chat_conversation_screen.dart: edit-title dialog, refresh tooltip,
load-error heading
- connectivity_banner.dart: sign-in / sync-success / sync-failure /
auth-failure snackbars (also resolves the const removals cleanly)
- main_navigation_screen.dart: enable-AI dialog + failure snackbar
- log_viewer_screen.dart: clear-logs confirmation dialog
- biometric_lock_screen.dart, transactions_list_screen.dart: snackbar
and edit tooltip
Adds 98 ARB keys (now 324 total), reusing common* and existing
screen keys where text matched. Interpolations use String/int
placeholders; multi-delete uses an ICU plural. AppLocalizations is
captured before async gaps and re-obtained inside dialog builders;
const removed only where a localisation getter is introduced, with
const restored on still-const siblings.
116/116 unit tests pass; flutter analyze --no-fatal-infos: 0 errors
(6 pre-existing infos unchanged). No remaining hardcoded user-facing
strings (verified by grep; only a doc-comment example remains).
* fix(mobile): address i18n review feedback and prune dead ARB keys
Resolves the still-valid CodeRabbit/Codex review findings on the i18n
migration; the majority were already handled by earlier commits.
- pubspec: switch intl to `any` so flutter_localizations selects the
SDK-pinned version (0.19.x on <3.32, 0.20.x on 3.32+). Pinning
^0.20.2 conflicted with the declared `flutter: '>=3.27.0'` floor and
would break `flutter pub get` on pre-3.32 SDKs.
- sso_onboarding: localize "Signed in as {email}" / "Google account
verified" / the link- and create-form notes; fix the first/last-name
validators that wrongly returned the "Email is required" message.
- backend_config: localize _testConnection / _saveAndContinue /
_validateUrl messages and the headers helper text (validator now
takes AppLocalizations; async methods capture it before awaits).
- recent_transactions: localize "Unknown Account"; locale-aware
timestamp.
- account_detail_header: localize the unavailable-details message via a
render-time flag (avoids touching inherited widgets in the
initState-driven load path); treat empty/whitespace securityName as
missing for the holding-name fallback.
- dashboard: wrap syncing/refreshing snackbar text in Expanded to avoid
overflow with long translations; use the distinct dashboardSyncError
key on the exception path.
- chat_list: localize relative-time labels (plural keys) and use a
locale-aware fallback date; calendar: locale-aware displayed dates and
weekday letters (map-key formats left fixed; Sunday-anchored grid
preserved).
- connectivity_banner: capture ScaffoldMessenger before the async gap
(removes use_build_context_synchronously); log_viewer: const Duration.
- Prune 55 unused ARB keys (never-wired scaffolding + superseded
duplicates). ARB now 298 keys, 0 unused.
116/116 tests pass; flutter analyze --no-fatal-infos: 0 errors, only 3
pre-existing infos in the untouched intro_screen_web.dart.
* fix(mobile): localize the log viewer empty-state string
The 'No logs yet' empty state was the last hardcoded user-facing string
(the logViewerEmpty key had been pruned before this string was migrated).
Re-add the key and route the empty state through AppLocalizations.
Closes the final CodeRabbit i18n-coverage thread. 0 analyze errors,
116 tests pass, ARB at 299 keys with 0 unused.
* fix(mobile): address i18n review feedback
- sso_onboarding: the "Accept Invitation" tab and submit buttons showed
the Terms-of-Service string (ssoOnboardingAcceptTerms) when a household
invitation was pending. Add ssoOnboardingAcceptInvitation and use it in
both spots; drop the now-unused ToS key (no ToS checkbox exists).
- transaction_form: restore the required-field indicator on the amount
label ("Amount *") that the migration dropped.
- settings: localize the "a newer version" fallback used in the update
dialog when the store version is unknown.
- ARB plurals: use the CLDR `one{}` category instead of the exact-match
`=1{}` so future non-English locales pluralize correctly. English output
is unchanged.
ARB at 300 keys, 0 unused. 116 tests pass; flutter analyze: no new issues.
* fix(mobile): reconcile i18n with design-system primitives after merge
The merge of main into this branch pulled in the design-system primitive
migrations (SureCard/SureChip/SureSegmentedControl/SureTextField/
SureListGroup), which collided with the i18n string migration and left
several files broken (compile errors / un-localized text).
Re-apply the i18n migration on top of the design-system versions:
- more_screen: SureListGroup/SureListRow rows now use l.more* keys
(was a mangled mix of _buildMenuItem + SureListGroup).
- transaction_form_screen: SureSegmentedControl segments + amount/date/
name/category labels, helpers, validators, and snackbars localized;
add transactionFormAmountHelper ("Required") for the amount helper text.
- custom_proxy_headers_editor: SureTextField label/hint params localized.
- currency_filter: the "All" chip is a SureChip again (the merge had left
it as a Material FilterChip) and uses l.commonAll.
- currency_filter_test / custom_proxy_headers_editor_test: add the
localization delegates the widgets now require.
ARB at 301 keys, 0 unused. 165 tests pass; flutter analyze: 0 errors.
---------
Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
681 lines
23 KiB
Dart
681 lines
23 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:flutter_markdown/flutter_markdown.dart';
|
|
import 'package:provider/provider.dart';
|
|
import '../models/chat.dart';
|
|
import '../providers/auth_provider.dart';
|
|
import '../providers/chat_provider.dart';
|
|
import '../models/message.dart';
|
|
import '../constants/suggested_questions.dart';
|
|
import '../widgets/typing_indicator.dart';
|
|
import '../l10n/app_localizations.dart';
|
|
|
|
class _SendMessageIntent extends Intent {
|
|
const _SendMessageIntent();
|
|
}
|
|
|
|
class ChatConversationScreen extends StatefulWidget {
|
|
/// Null means this is a brand-new chat — it will be created on first send.
|
|
final String? chatId;
|
|
|
|
const ChatConversationScreen({
|
|
super.key,
|
|
required this.chatId,
|
|
});
|
|
|
|
@override
|
|
State<ChatConversationScreen> createState() => _ChatConversationScreenState();
|
|
}
|
|
|
|
class _ChatConversationScreenState extends State<ChatConversationScreen> {
|
|
final TextEditingController _messageController = TextEditingController();
|
|
final ScrollController _scrollController = ScrollController();
|
|
|
|
/// Tracks the real chat ID once the chat has been created.
|
|
String? _chatId;
|
|
|
|
ChatProvider? _chatProvider;
|
|
bool _listenerAdded = false;
|
|
bool _isSendInFlight = false;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_chatId = widget.chatId;
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (!mounted) return;
|
|
_chatProvider = Provider.of<ChatProvider>(context, listen: false);
|
|
_chatProvider!.addListener(_onChatChanged);
|
|
_listenerAdded = true;
|
|
if (_chatId == null) {
|
|
_chatProvider!.clearCurrentChat();
|
|
}
|
|
});
|
|
if (_chatId != null) {
|
|
_loadChat();
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
if (_listenerAdded && _chatProvider != null) {
|
|
_chatProvider!.removeListener(_onChatChanged);
|
|
_chatProvider = null;
|
|
_listenerAdded = false;
|
|
}
|
|
_messageController.dispose();
|
|
_scrollController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
void _onChatChanged() {
|
|
if (!mounted) return;
|
|
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
|
|
if (chatProvider.isWaitingForResponse || chatProvider.isSendingMessage || chatProvider.isPolling) {
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (mounted) _scrollToBottom();
|
|
});
|
|
}
|
|
}
|
|
|
|
void _scrollToBottom() {
|
|
if (_scrollController.hasClients) {
|
|
_scrollController.animateTo(
|
|
_scrollController.position.maxScrollExtent,
|
|
duration: const Duration(milliseconds: 300),
|
|
curve: Curves.easeOut,
|
|
);
|
|
}
|
|
}
|
|
|
|
Future<void> _sendSuggestedQuestion(String question) async {
|
|
if (!mounted) return;
|
|
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
|
|
if (chatProvider.isSendingMessage || chatProvider.isWaitingForResponse) return;
|
|
_messageController.text = question;
|
|
await _sendMessage();
|
|
}
|
|
|
|
Future<void> _loadChat({bool forceRefresh = false}) async {
|
|
if (_chatId == null) return;
|
|
|
|
final authProvider = Provider.of<AuthProvider>(context, listen: false);
|
|
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
|
|
|
|
// Skip fetch if the provider already has this chat loaded (e.g. just created).
|
|
if (!forceRefresh && chatProvider.currentChat?.id == _chatId) {
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (mounted && _scrollController.hasClients) {
|
|
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);
|
|
}
|
|
});
|
|
return;
|
|
}
|
|
|
|
final accessToken = await authProvider.getValidAccessToken();
|
|
if (accessToken == null) {
|
|
await authProvider.logout();
|
|
return;
|
|
}
|
|
|
|
await chatProvider.fetchChat(
|
|
accessToken: accessToken,
|
|
chatId: _chatId!,
|
|
);
|
|
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (mounted && _scrollController.hasClients) {
|
|
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);
|
|
}
|
|
});
|
|
}
|
|
|
|
Future<void> _sendMessage() async {
|
|
if (_isSendInFlight) return;
|
|
final content = _messageController.text.trim();
|
|
if (content.isEmpty) return;
|
|
setState(() => _isSendInFlight = true);
|
|
|
|
final l = AppLocalizations.of(context);
|
|
|
|
try {
|
|
final authProvider = Provider.of<AuthProvider>(context, listen: false);
|
|
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
|
|
|
|
final accessToken = await authProvider.getValidAccessToken();
|
|
if (accessToken == null) {
|
|
await authProvider.logout();
|
|
return;
|
|
}
|
|
|
|
_messageController.clear();
|
|
|
|
if (_chatId == null) {
|
|
// First message in a new chat — create the chat with it.
|
|
final chat = await chatProvider.createChat(
|
|
accessToken: accessToken,
|
|
title: Chat.generateTitle(content),
|
|
initialMessage: content,
|
|
);
|
|
if (!mounted) return;
|
|
if (chat == null) {
|
|
// Restore the message so the user doesn't lose it.
|
|
_messageController.text = content;
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(
|
|
content: Text(chatProvider.errorMessage ?? l.chatConversationStartFailed),
|
|
backgroundColor: Colors.red,
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
setState(() => _chatId = chat.id);
|
|
} else {
|
|
final shouldUpdateTitle =
|
|
chatProvider.currentChat?.hasDefaultTitle == true;
|
|
|
|
final delivered = await chatProvider.sendMessage(
|
|
accessToken: accessToken,
|
|
chatId: _chatId!,
|
|
content: content,
|
|
);
|
|
|
|
if (delivered && shouldUpdateTitle) {
|
|
await chatProvider.updateChatTitle(
|
|
accessToken: accessToken,
|
|
chatId: _chatId!,
|
|
title: Chat.generateTitle(content),
|
|
);
|
|
}
|
|
}
|
|
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (_scrollController.hasClients) {
|
|
_scrollController.animateTo(
|
|
_scrollController.position.maxScrollExtent,
|
|
duration: const Duration(milliseconds: 300),
|
|
curve: Curves.easeOut,
|
|
);
|
|
}
|
|
});
|
|
} finally {
|
|
if (mounted) setState(() => _isSendInFlight = false);
|
|
}
|
|
}
|
|
|
|
Future<void> _editTitle() async {
|
|
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
|
|
final currentTitle = chatProvider.currentChat?.title ?? '';
|
|
|
|
final newTitle = await showDialog<String>(
|
|
context: context,
|
|
builder: (context) {
|
|
final dl = AppLocalizations.of(context);
|
|
final controller = TextEditingController(text: currentTitle);
|
|
return AlertDialog(
|
|
title: Text(dl.chatConversationEditTitle),
|
|
content: TextField(
|
|
controller: controller,
|
|
decoration: InputDecoration(
|
|
labelText: dl.chatConversationTitleLabel,
|
|
border: const OutlineInputBorder(),
|
|
),
|
|
autofocus: true,
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(context),
|
|
child: Text(dl.commonCancel),
|
|
),
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(context, controller.text.trim()),
|
|
child: Text(dl.commonSave),
|
|
),
|
|
],
|
|
);
|
|
},
|
|
);
|
|
|
|
if (newTitle != null &&
|
|
newTitle.isNotEmpty &&
|
|
newTitle != currentTitle &&
|
|
mounted) {
|
|
if (_chatId == null) return;
|
|
final authProvider = Provider.of<AuthProvider>(context, listen: false);
|
|
final accessToken = await authProvider.getValidAccessToken();
|
|
if (accessToken != null) {
|
|
await chatProvider.updateChatTitle(
|
|
accessToken: accessToken,
|
|
chatId: _chatId!,
|
|
title: newTitle,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
String _formatTime(DateTime dateTime) {
|
|
final hour = dateTime.hour.toString().padLeft(2, '0');
|
|
final minute = dateTime.minute.toString().padLeft(2, '0');
|
|
return '$hour:$minute';
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final colorScheme = Theme.of(context).colorScheme;
|
|
final l = AppLocalizations.of(context);
|
|
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: Consumer<ChatProvider>(
|
|
builder: (context, chatProvider, _) {
|
|
final title = chatProvider.currentChat?.title ?? AppLocalizations.of(context).chatConversationNewTitle;
|
|
return GestureDetector(
|
|
onTap: _chatId != null ? _editTitle : null,
|
|
child: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Flexible(
|
|
child: Text(
|
|
title,
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
),
|
|
if (_chatId != null) ...[
|
|
const SizedBox(width: 4),
|
|
const Icon(Icons.edit, size: 18),
|
|
],
|
|
],
|
|
),
|
|
);
|
|
},
|
|
),
|
|
actions: [
|
|
if (widget.chatId != null)
|
|
IconButton(
|
|
icon: const Icon(Icons.refresh),
|
|
onPressed: () => _loadChat(forceRefresh: true),
|
|
tooltip: l.chatConversationRefreshTooltip,
|
|
),
|
|
],
|
|
),
|
|
body: Consumer<ChatProvider>(
|
|
builder: (context, chatProvider, _) {
|
|
if (chatProvider.isLoading && chatProvider.currentChat == null) {
|
|
return const Center(child: CircularProgressIndicator());
|
|
}
|
|
|
|
if (chatProvider.errorMessage != null &&
|
|
chatProvider.currentChat == null &&
|
|
_chatId != null) {
|
|
return Center(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(24),
|
|
child: Column(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
Icon(Icons.error_outline,
|
|
size: 64, color: colorScheme.error),
|
|
const SizedBox(height: 16),
|
|
Text(l.chatConversationLoadError,
|
|
style: Theme.of(context).textTheme.titleLarge),
|
|
const SizedBox(height: 8),
|
|
Text(
|
|
chatProvider.errorMessage!,
|
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
const SizedBox(height: 24),
|
|
ElevatedButton.icon(
|
|
onPressed: _loadChat,
|
|
icon: const Icon(Icons.refresh),
|
|
label: Text(l.commonTryAgain),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
final allMessages = chatProvider.currentChat?.messages ?? [];
|
|
// While waiting for the AI response, hide the last (partial/streaming)
|
|
// assistant message so the typing indicator shows instead of partial content.
|
|
// The full response is revealed once polling detects stable content.
|
|
final messages = chatProvider.isWaitingForResponse
|
|
? allMessages.where((m) {
|
|
return !(m.isAssistant && m == allMessages.lastOrNull);
|
|
}).toList()
|
|
: allMessages;
|
|
final firstName =
|
|
Provider.of<AuthProvider>(context, listen: true).user?.firstName;
|
|
|
|
return Column(
|
|
children: [
|
|
Expanded(
|
|
child: messages.isEmpty &&
|
|
!chatProvider.isLoading &&
|
|
!chatProvider.isSendingMessage &&
|
|
!chatProvider.isWaitingForResponse
|
|
? _EmptyState(
|
|
firstName: firstName,
|
|
isSending: false,
|
|
onQuestionTap: _sendSuggestedQuestion,
|
|
)
|
|
: ListView.builder(
|
|
controller: _scrollController,
|
|
padding: const EdgeInsets.all(16),
|
|
itemCount: messages.length +
|
|
(chatProvider.isWaitingForResponse ? 1 : 0),
|
|
itemBuilder: (context, index) {
|
|
if (index == messages.length) {
|
|
return const _TypingIndicatorBubble();
|
|
}
|
|
return _MessageBubble(
|
|
message: messages[index],
|
|
formatTime: _formatTime,
|
|
);
|
|
},
|
|
),
|
|
),
|
|
|
|
// Message input
|
|
Container(
|
|
padding: EdgeInsets.fromLTRB(
|
|
16,
|
|
16,
|
|
16,
|
|
16 + MediaQuery.paddingOf(context).bottom,
|
|
),
|
|
decoration: BoxDecoration(
|
|
color: colorScheme.surface,
|
|
boxShadow: [
|
|
BoxShadow(
|
|
color: Colors.black.withValues(alpha: 0.05),
|
|
blurRadius: 10,
|
|
offset: const Offset(0, -2),
|
|
),
|
|
],
|
|
),
|
|
child: Shortcuts(
|
|
shortcuts: const {
|
|
SingleActivator(LogicalKeyboardKey.enter):
|
|
_SendMessageIntent(),
|
|
},
|
|
child: Actions(
|
|
actions: <Type, Action<Intent>>{
|
|
_SendMessageIntent: CallbackAction<_SendMessageIntent>(
|
|
onInvoke: (_) {
|
|
if (!_isSendInFlight && !chatProvider.isSendingMessage && !chatProvider.isWaitingForResponse && !chatProvider.isPolling) _sendMessage();
|
|
return null;
|
|
},
|
|
),
|
|
},
|
|
child: Row(
|
|
children: [
|
|
Expanded(
|
|
child: TextField(
|
|
controller: _messageController,
|
|
decoration: InputDecoration(
|
|
hintText: l.chatConversationMessageHint,
|
|
border: OutlineInputBorder(
|
|
borderRadius: BorderRadius.circular(24),
|
|
),
|
|
contentPadding: const EdgeInsets.symmetric(
|
|
horizontal: 16,
|
|
vertical: 12,
|
|
),
|
|
),
|
|
maxLines: null,
|
|
textCapitalization: TextCapitalization.sentences,
|
|
autofocus: _chatId == null,
|
|
),
|
|
),
|
|
const SizedBox(width: 8),
|
|
IconButton(
|
|
icon: const Icon(Icons.send),
|
|
onPressed: (_isSendInFlight || chatProvider.isSendingMessage || chatProvider.isWaitingForResponse || chatProvider.isPolling)
|
|
? null
|
|
: _sendMessage,
|
|
color: colorScheme.primary,
|
|
iconSize: 28,
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _MessageBubble extends StatelessWidget {
|
|
final Message message;
|
|
final String Function(DateTime) formatTime;
|
|
|
|
const _MessageBubble({
|
|
required this.message,
|
|
required this.formatTime,
|
|
});
|
|
|
|
/// Builds the markdown stylesheet once per render context instead of inline,
|
|
/// avoiding redundant TextStyle allocations per message bubble.
|
|
MarkdownStyleSheet _markdownStyle(BuildContext context) {
|
|
final color = Theme.of(context).colorScheme.onSurfaceVariant;
|
|
return MarkdownStyleSheet.fromTheme(Theme.of(context)).copyWith(
|
|
p: TextStyle(color: color),
|
|
strong: TextStyle(color: color, fontWeight: FontWeight.bold),
|
|
em: TextStyle(color: color, fontStyle: FontStyle.italic),
|
|
listBullet: TextStyle(color: color),
|
|
h1: TextStyle(color: color, fontSize: 20, fontWeight: FontWeight.bold),
|
|
h2: TextStyle(color: color, fontSize: 18, fontWeight: FontWeight.bold),
|
|
h3: TextStyle(color: color, fontSize: 16, fontWeight: FontWeight.bold),
|
|
code: TextStyle(color: color, fontFamily: 'monospace'),
|
|
);
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final colorScheme = Theme.of(context).colorScheme;
|
|
final isUser = message.isUser;
|
|
|
|
return Padding(
|
|
padding: const EdgeInsets.only(bottom: 16),
|
|
child: Row(
|
|
mainAxisAlignment:
|
|
isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
if (!isUser)
|
|
CircleAvatar(
|
|
radius: 16,
|
|
backgroundColor: colorScheme.primaryContainer,
|
|
child: Icon(
|
|
Icons.smart_toy,
|
|
size: 18,
|
|
color: colorScheme.onPrimaryContainer,
|
|
),
|
|
),
|
|
const SizedBox(width: 8),
|
|
Flexible(
|
|
child: Column(
|
|
crossAxisAlignment:
|
|
isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start,
|
|
children: [
|
|
SelectionArea(
|
|
child: Container(
|
|
padding:
|
|
const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
|
decoration: BoxDecoration(
|
|
color: isUser
|
|
? colorScheme.primary
|
|
: colorScheme.surfaceContainerHighest,
|
|
borderRadius: BorderRadius.circular(16),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
if (isUser)
|
|
Text(
|
|
message.content,
|
|
style: TextStyle(
|
|
color: colorScheme.onPrimary,
|
|
),
|
|
)
|
|
else
|
|
MarkdownBody(
|
|
data: message.content,
|
|
selectable: false,
|
|
softLineBreak: true,
|
|
styleSheet: _markdownStyle(context),
|
|
sizedImageBuilder: (config) {
|
|
// Block remote images to prevent unsolicited network requests.
|
|
if (config.uri.scheme == 'http' || config.uri.scheme == 'https') {
|
|
return const SizedBox.shrink();
|
|
}
|
|
return Image.asset(config.uri.toString());
|
|
},
|
|
),
|
|
if (message.toolCalls != null &&
|
|
message.toolCalls!.isNotEmpty)
|
|
Padding(
|
|
padding: const EdgeInsets.only(top: 8),
|
|
child: Wrap(
|
|
spacing: 4,
|
|
runSpacing: 4,
|
|
children: message.toolCalls!.map((toolCall) {
|
|
return Chip(
|
|
label: Text(
|
|
toolCall.functionName,
|
|
style: const TextStyle(fontSize: 11),
|
|
),
|
|
padding: EdgeInsets.zero,
|
|
visualDensity: VisualDensity.compact,
|
|
);
|
|
}).toList(),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
formatTime(message.createdAt),
|
|
style: TextStyle(
|
|
fontSize: 11,
|
|
color: colorScheme.onSurfaceVariant,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
const SizedBox(width: 8),
|
|
if (isUser)
|
|
CircleAvatar(
|
|
radius: 16,
|
|
backgroundColor: colorScheme.primary,
|
|
child: Icon(
|
|
Icons.person,
|
|
size: 18,
|
|
color: colorScheme.onPrimary,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _EmptyState extends StatelessWidget {
|
|
final String? firstName;
|
|
final bool isSending;
|
|
final void Function(String) onQuestionTap;
|
|
|
|
const _EmptyState({
|
|
required this.firstName,
|
|
required this.isSending,
|
|
required this.onQuestionTap,
|
|
});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final colorScheme = Theme.of(context).colorScheme;
|
|
final l = AppLocalizations.of(context);
|
|
final name = (firstName ?? '').trim();
|
|
final greeting = name.isNotEmpty ? l.chatConversationGreetingWithName(name) : l.chatConversationGreetingNoName;
|
|
|
|
return ListView(
|
|
padding: const EdgeInsets.all(24),
|
|
children: [
|
|
const SizedBox(height: 32),
|
|
Text(
|
|
greeting,
|
|
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
const SizedBox(height: 32),
|
|
...suggestedQuestions(context).map(
|
|
(q) => Padding(
|
|
padding: const EdgeInsets.only(bottom: 12),
|
|
child: OutlinedButton.icon(
|
|
onPressed: isSending ? null : () => onQuestionTap(q.text),
|
|
icon: Icon(q.icon, size: 20),
|
|
label: Text(q.text, textAlign: TextAlign.left),
|
|
style: OutlinedButton.styleFrom(
|
|
alignment: Alignment.centerLeft,
|
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
foregroundColor: colorScheme.onSurface,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
}
|
|
|
|
class _TypingIndicatorBubble extends StatelessWidget {
|
|
const _TypingIndicatorBubble();
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final colorScheme = Theme.of(context).colorScheme;
|
|
|
|
return Padding(
|
|
padding: const EdgeInsets.only(bottom: 16),
|
|
child: Row(
|
|
mainAxisAlignment: MainAxisAlignment.start,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
CircleAvatar(
|
|
radius: 16,
|
|
backgroundColor: colorScheme.primaryContainer,
|
|
child: Icon(
|
|
Icons.smart_toy,
|
|
size: 18,
|
|
color: colorScheme.onPrimaryContainer,
|
|
),
|
|
),
|
|
const SizedBox(width: 8),
|
|
Container(
|
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
|
decoration: BoxDecoration(
|
|
color: colorScheme.surfaceContainerHighest,
|
|
borderRadius: BorderRadius.circular(16),
|
|
),
|
|
child: const TypingIndicator(),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|