// The project knowledge tab: notes, todos and plans stored by the server in // the project context (`/api/project-context`), with search across all three. import 'package:flutter/material.dart'; import '../api/client.dart'; import '../api/models.dart'; import '../state.dart'; import '../widgets/markdown_view.dart'; import '../l10n.dart'; class KnowledgePanel extends StatefulWidget { final AppState app; final String directory; const KnowledgePanel({super.key, required this.app, required this.directory}); @override State createState() => _KnowledgePanelState(); } class _KnowledgePanelState extends State { ProjectContext? _context; /// Null when the server has agent memory switched off, in which case the /// memory section is not offered at all. AgentMemorySnapshot? _memory; bool _loading = true; String? _error; String _section = 'notes'; String _query = ''; final TextEditingController _search = TextEditingController(); String get _projectId => Client.projectIdFor(widget.directory); Client? get _client => widget.app.client; @override void initState() { super.initState(); _load(); } @override void dispose() { _search.dispose(); super.dispose(); } Future _load() async { final client = _client; if (client == null || _projectId.isEmpty) { setState(() { _loading = false; _error = tr('这个会话没有关联目录'); }); return; } setState(() { _loading = true; _error = null; }); try { // Both reads in one go: the memory tab appears with the rest instead of // popping in a moment later. final results = await Future.wait([ client.projectContext(_projectId, directory: widget.directory), client.agentMemory(_projectId, directory: widget.directory), ]); if (!mounted) return; final context = results[0] as ProjectContext; final memory = results[1] as AgentMemorySnapshot?; setState(() { _context = context; _memory = memory; if (memory == null && _section == 'memory') _section = 'notes'; _loading = false; }); } catch (error) { if (!mounted) return; setState(() { _loading = false; _error = '$error'; }); } } /// Applies a mutation's fresh context without a second round trip. void _apply(ProjectContext context) { if (!mounted) return; setState(() => _context = context); } void _fail(Object error) { if (!mounted) return; ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: AppText('$error'))); } bool _matches(Iterable fields) { final query = _query.trim().toLowerCase(); if (query.isEmpty) return true; return fields.any((field) => field.toLowerCase().contains(query)); } @override Widget build(BuildContext context) { final theme = Theme.of(context); return Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(12, 6, 4, 0), child: Row( children: [ Expanded( child: TextField( controller: _search, onChanged: (value) => setState(() => _query = value), style: const TextStyle(fontSize: 13), decoration: InputDecoration( isDense: true, hintText: _memory == null ? tr('搜索笔记、待办与计划') : tr('搜索笔记、待办、计划与记忆'), prefixIcon: const Icon(Icons.search, size: 18), suffixIcon: _query.isEmpty ? null : IconButton( icon: const Icon(Icons.close, size: 16), onPressed: () { _search.clear(); setState(() => _query = ''); }, ), border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), ), ), ), IconButton( tooltip: tr('刷新'), visualDensity: VisualDensity.compact, icon: const Icon(Icons.refresh, size: 20), onPressed: _load, ), ], ), ), _sections(theme), Expanded(child: _body(theme)), ], ); } List<(String, String, int)> get _sectionsList { final context = _context; return [ ('notes', tr('笔记'), context?.notes.length ?? 0), ('todos', tr('待办'), context?.todos.length ?? 0), ('plans', tr('计划'), context?.plans.length ?? 0), if (_memory != null) ('memory', tr('记忆'), (_memory!.global.length + _memory!.project.length)), ]; } Widget _sections(ThemeData theme) { final sections = _sectionsList; return Padding( padding: const EdgeInsets.fromLTRB(12, 8, 12, 6), child: SegmentedButton( showSelectedIcon: false, style: const ButtonStyle( visualDensity: VisualDensity.compact, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), segments: [ for (final (key, label, count) in sections) ButtonSegment(value: key, label: AppText('$label $count')), ], selected: {_section}, onSelectionChanged: (value) => setState(() => _section = value.first), ), ); } Widget _body(ThemeData theme) { if (_loading) return const Center(child: CircularProgressIndicator()); if (_error != null) { return Center( child: Padding( padding: const EdgeInsets.all(24), child: Column( mainAxisSize: MainAxisSize.min, children: [ AppText(_error!, textAlign: TextAlign.center, style: TextStyle(color: theme.colorScheme.error, fontSize: 13)), const SizedBox(height: 8), FilledButton(onPressed: _load, child: const AppText('重试')), ], ), ), ); } switch (_section) { case 'todos': return _todos(theme); case 'plans': return _plans(theme); case 'memory': return _memoryBody(theme); default: return _notes(theme); } } // --------------------------------------------------------------- notes Widget _notes(ThemeData theme) { final notes = (_context?.notes ?? []) .where((note) => _matches([note.body])) .toList() ..sort((a, b) { if (a.pinned != b.pinned) return a.pinned ? -1 : 1; return b.updatedAt.compareTo(a.updatedAt); }); return Column( children: [ _sectionHeader(theme, trArgs('{0} 条笔记', [notes.length]), '新建笔记', _addNote), Expanded( child: notes.isEmpty ? _empty(theme, Icons.sticky_note_2_outlined, _query.isEmpty ? '还没有笔记' : '没有匹配的笔记') : ListView.builder( padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), itemCount: notes.length, itemBuilder: (context, index) { final note = notes[index]; return _noteCard(theme, note); }, ), ), ], ); } Widget _noteCard(ThemeData theme, ProjectNote note) { final scheme = theme.colorScheme; return Card( margin: const EdgeInsets.only(bottom: 8), child: InkWell( borderRadius: BorderRadius.circular(12), onTap: () => _editNote(note), child: Padding( padding: const EdgeInsets.fromLTRB(12, 8, 4, 8), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ AppText( note.body.trim(), maxLines: 5, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 13.5, height: 1.35), ), const SizedBox(height: 4), Row( children: [ if (note.pinned) Padding( padding: const EdgeInsets.only(right: 4), child: Icon(Icons.push_pin, size: 12, color: scheme.primary), ), AppText( _stamp(note.updatedAt), style: TextStyle(fontSize: 11, color: theme.hintColor), ), ], ), ], ), ), PopupMenuButton( icon: const Icon(Icons.more_vert, size: 18), onSelected: (value) async { final client = _client; if (client == null) return; try { switch (value) { case 'edit': await _editNote(note); break; case 'pin': _apply(await client.updateNote( _projectId, note.id, pinned: !note.pinned, directory: widget.directory)); break; case 'delete': _apply(await client.deleteNote(_projectId, note.id, directory: widget.directory)); break; } } catch (error) { _fail(error); } }, itemBuilder: (_) => [ const PopupMenuItem(value: 'edit', child: AppText('编辑')), PopupMenuItem( value: 'pin', child: AppText(note.pinned ? '取消置顶' : '置顶')), const PopupMenuItem(value: 'delete', child: AppText('删除')), ], ), ], ), ), ), ); } // --------------------------------------------------------------- todos Widget _todos(ThemeData theme) { final todos = (_context?.todos ?? []) .where((todo) => _matches([todo.text])) .toList(); final done = todos.where((todo) => todo.completed).length; return Column( children: [ _sectionHeader(theme, trArgs('{0}/{1} 已完成', [done, todos.length]), '新建待办', _addTodo), Expanded( child: todos.isEmpty ? _empty(theme, Icons.checklist, _query.isEmpty ? '还没有待办' : '没有匹配的待办') : ListView.builder( padding: const EdgeInsets.fromLTRB(8, 0, 8, 12), itemCount: todos.length, itemBuilder: (context, index) { final todo = todos[index]; return CheckboxListTile( dense: true, value: todo.completed, onChanged: (value) => _toggleTodo(todo, value ?? false), controlAffinity: ListTileControlAffinity.leading, title: AppText( todo.text, style: TextStyle( fontSize: 13.5, decoration: todo.completed ? TextDecoration.lineThrough : null, color: todo.completed ? theme.hintColor : null, ), ), secondary: PopupMenuButton( icon: const Icon(Icons.more_vert, size: 18), onSelected: (value) async { final client = _client; if (client == null) return; try { if (value == 'delete') { _apply(await client.deleteTodo( _projectId, todo.id, directory: widget.directory)); } } catch (error) { _fail(error); } }, itemBuilder: (_) => const [ PopupMenuItem(value: 'delete', child: AppText('删除')), ], ), ); }, ), ), ], ); } Future _toggleTodo(ProjectTodo todo, bool completed) async { final client = _client; if (client == null) return; try { _apply(await client.updateTodo(_projectId, todo.id, completed: completed, directory: widget.directory)); } catch (error) { _fail(error); } } // --------------------------------------------------------------- plans Widget _plans(ThemeData theme) { final plans = (_context?.plans ?? []) .where((plan) => _matches([plan.title, plan.file])) .toList() ..sort((a, b) { if (a.pinned != b.pinned) return a.pinned ? -1 : 1; return b.createdAt.compareTo(a.createdAt); }); return Column( children: [ _sectionHeader(theme, trArgs('{0} 份计划', [plans.length]), '新建计划', _newPlan), Expanded( child: plans.isEmpty ? _empty(theme, Icons.description_outlined, _query.isEmpty ? '还没有计划' : '没有匹配的计划') : ListView.builder( padding: const EdgeInsets.fromLTRB(8, 0, 8, 12), itemCount: plans.length, itemBuilder: (context, index) => _planTile(theme, plans[index]), ), ), ], ); } Widget _planTile(ThemeData theme, ProjectPlanLink plan) { final scheme = theme.colorScheme; return Card( margin: const EdgeInsets.only(bottom: 8), child: ListTile( dense: true, title: Row( children: [ if (plan.pinned) Padding( padding: const EdgeInsets.only(right: 4), child: Icon(Icons.push_pin, size: 13, color: scheme.primary), ), Expanded( child: AppText(plan.title.isEmpty ? plan.file : plan.title, maxLines: 2, overflow: TextOverflow.ellipsis), ), ], ), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (plan.hasProgress) ...[ const SizedBox(height: 4), Row( children: [ Expanded( child: ClipRRect( borderRadius: BorderRadius.circular(2), child: LinearProgressIndicator( value: plan.progressDone / plan.progressTotal, minHeight: 4, backgroundColor: scheme.surfaceContainerHighest, ), ), ), const SizedBox(width: 6), AppText('${plan.progressDone}/${plan.progressTotal}', style: TextStyle(fontSize: 11, color: theme.hintColor)), ], ), ], const SizedBox(height: 2), AppText( plan.source == 'shared' ? '团队共享' : '个人', style: TextStyle(fontSize: 11, color: theme.hintColor), ), ], ), trailing: PopupMenuButton( icon: const Icon(Icons.more_vert, size: 18), onSelected: (value) async { final client = _client; if (client == null) return; try { switch (value) { case 'pin': _apply(await client.setPlanPinned( _projectId, plan.id, !plan.pinned, directory: widget.directory)); break; case 'delete': _apply(await client.deletePlan(_projectId, plan.id, directory: widget.directory)); break; } } catch (error) { _fail(error); } }, itemBuilder: (_) => [ PopupMenuItem( value: 'pin', child: AppText(plan.pinned ? '取消置顶' : '置顶')), const PopupMenuItem(value: 'delete', child: AppText('删除')), ], ), onTap: () => _viewPlan(plan), ), ); } // -------------------------------------------------------------- memory Widget _memoryBody(ThemeData theme) { final snapshot = _memory; if (snapshot == null) { return _empty(theme, Icons.psychology_outlined, '记忆功能未启用'); } final global = snapshot.global .where((m) => _matches([m.title, m.body])) .toList(); final project = snapshot.project .where((m) => _matches([m.title, m.body])) .toList(); if (global.isEmpty && project.isEmpty) { return _empty( theme, Icons.psychology_outlined, _query.isEmpty ? '还没有记忆' : '没有匹配的记忆'); } return ListView( padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), children: [ _memoryGroup(theme, tr('全局记忆'), global, 'global', failed: snapshot.globalFailed), const SizedBox(height: 8), _memoryGroup(theme, tr('项目记忆'), project, 'project', failed: snapshot.projectFailed), Padding( padding: const EdgeInsets.only(top: 6), child: AppText( '记忆由 agent 在会话中记录;你可以在这里修改或删除它。', style: TextStyle(fontSize: 11.5, color: theme.hintColor), ), ), ], ); } Widget _memoryGroup( ThemeData theme, String title, List entries, String scope, {required bool failed}) { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( padding: const EdgeInsets.only(bottom: 4), child: AppText(trArgs('{0}({1})', [title, entries.length]), style: TextStyle(fontSize: 12, color: theme.hintColor)), ), if (failed) Padding( padding: const EdgeInsets.only(bottom: 4), child: AppText('读取失败,请刷新', style: TextStyle( fontSize: 12, color: theme.colorScheme.error)), ) else if (entries.isEmpty) Padding( padding: const EdgeInsets.only(bottom: 4), child: AppText('暂无', style: TextStyle(fontSize: 12, color: theme.hintColor)), ), for (final entry in entries) _memoryCard(theme, entry, scope), ], ); } Widget _memoryCard(ThemeData theme, AgentMemoryEntry entry, String scope) { final scheme = theme.colorScheme; return Card( margin: const EdgeInsets.only(bottom: 8), child: InkWell( borderRadius: BorderRadius.circular(12), onTap: () => _editMemory(entry, scope), child: Padding( padding: const EdgeInsets.fromLTRB(12, 8, 4, 8), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Flexible( child: AppText(entry.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 13.5, fontWeight: FontWeight.w600)), ), const SizedBox(width: 6), Container( padding: const EdgeInsets.symmetric( horizontal: 5, vertical: 1), decoration: BoxDecoration( color: scheme.surfaceContainerHighest, borderRadius: BorderRadius.circular(4), ), child: AppText(entry.typeLabel, style: TextStyle( fontSize: 10, color: theme.hintColor)), ), if (entry.flagged) Padding( padding: const EdgeInsets.only(left: 4), child: Icon(Icons.flag_outlined, size: 13, color: scheme.error), ), ], ), const SizedBox(height: 3), AppText(entry.body, maxLines: 4, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 12.5, height: 1.35)), ], ), ), PopupMenuButton( icon: const Icon(Icons.more_vert, size: 18), onSelected: (value) async { if (value == 'edit') { await _editMemory(entry, scope); } else if (value == 'delete') { await _deleteMemory(entry, scope); } }, itemBuilder: (_) => const [ PopupMenuItem(value: 'edit', child: AppText('编辑')), PopupMenuItem(value: 'delete', child: AppText('删除')), ], ), ], ), ), ), ); } Future _editMemory(AgentMemoryEntry entry, String scope) async { final client = _client; if (client == null) return; final result = await showDialog<(String, String, String)>( context: context, builder: (_) => _MemoryDialog(entry: entry), ); if (result == null) return; try { await client.updateMemory(entry.id, scope: scope, projectId: _projectId, title: result.$1, body: result.$2, type: result.$3, directory: widget.directory); await _reloadMemory(); } catch (error) { _fail(error); } } Future _deleteMemory(AgentMemoryEntry entry, String scope) async { final client = _client; if (client == null) return; try { await client.deleteMemory(entry.id, scope: scope, projectId: _projectId, directory: widget.directory); await _reloadMemory(); } catch (error) { _fail(error); } } Future _reloadMemory() async { final client = _client; if (client == null) return; try { final memory = await client.agentMemory(_projectId, directory: widget.directory); if (!mounted) return; setState(() => _memory = memory); } catch (error) { _fail(error); } } // -------------------------------------------------------------- dialogs Widget _sectionHeader( ThemeData theme, String summary, String action, VoidCallback onTap) { return Padding( padding: const EdgeInsets.fromLTRB(14, 0, 8, 2), child: Row( children: [ Expanded( child: AppText(summary, style: TextStyle(fontSize: 12, color: theme.hintColor)), ), TextButton.icon( style: TextButton.styleFrom( visualDensity: VisualDensity.compact, padding: const EdgeInsets.symmetric(horizontal: 8), minimumSize: const Size(0, 32), ), onPressed: onTap, icon: const Icon(Icons.add, size: 16), label: AppText(action, style: const TextStyle(fontSize: 12.5)), ), ], ), ); } Widget _empty(ThemeData theme, IconData icon, String text) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(icon, size: 36, color: theme.hintColor), const SizedBox(height: 8), AppText(text, style: TextStyle(fontSize: 13, color: theme.hintColor)), ], ), ); } Future _addNote() => _editNote(null); Future _editNote(ProjectNote? note) async { final text = await showDialog( context: context, builder: (_) => _TextPromptDialog( title: note == null ? '新建笔记' : '编辑笔记', hint: tr('记点什么,供之后的会话参考'), initial: note?.body ?? '', maxLength: 3000, maxLines: 10, minLines: 4, action: '保存', ), ); if (text == null || text.isEmpty) return; final client = _client; if (client == null) return; try { if (note == null) { _apply(await client.createNote(_projectId, text, directory: widget.directory)); } else { _apply(await client.updateNote(_projectId, note.id, body: text, directory: widget.directory)); } } catch (error) { _fail(error); } } Future _addTodo() async { final text = await showDialog( context: context, builder: (_) => _TextPromptDialog( title: '新建待办', hint: tr('要做什么'), maxLength: 1000, maxLines: 1, minLines: 1, action: '保存', ), ); if (text == null || text.isEmpty) return; final client = _client; if (client == null) return; try { _apply(await client.createTodo(_projectId, text, directory: widget.directory)); } catch (error) { _fail(error); } } Future _newPlan() async { final result = await showDialog<(String, String)>( context: context, builder: (_) => const _NewPlanDialog(), ); if (result == null || result.$2.trim().isEmpty) return; final client = _client; if (client == null) return; try { _apply(await client.createPlan(_projectId, title: result.$1, body: result.$2, directory: widget.directory)); } catch (error) { _fail(error); } } Future _viewPlan(ProjectPlanLink plan) async { final client = _client; if (client == null) return; ProjectPlanContent content; try { content = await client.planContent(_projectId, plan.id, directory: widget.directory); } catch (error) { _fail(error); return; } if (!mounted) return; // A full page, not a dialog: a plan is long, and a page keeps the editor // and the scroll view in their own hit-testable surface. await Navigator.of(context).push(MaterialPageRoute( builder: (context) => _PlanPage( title: content.title.isEmpty ? plan.file : content.title, raw: content.raw, onSave: (raw) async { _apply(await client.savePlan(_projectId, plan.id, raw, directory: widget.directory)); }, ), )); } String _stamp(int millis) { if (millis <= 0) return ''; final time = DateTime.fromMillisecondsSinceEpoch(millis); String two(int value) => value.toString().padLeft(2, '0'); return '${time.year}-${two(time.month)}-${two(time.day)} ' '${two(time.hour)}:${two(time.minute)}'; } } /// One plan, rendered; 编辑 swaps in the raw Markdown, 保存 writes it back. class _PlanPage extends StatefulWidget { final String title; final String raw; final Future Function(String raw) onSave; const _PlanPage({ required this.title, required this.raw, required this.onSave, }); @override State<_PlanPage> createState() => _PlanPageState(); } class _PlanPageState extends State<_PlanPage> { late final TextEditingController _controller = TextEditingController(text: widget.raw); bool _editing = false; bool _saving = false; @override void dispose() { _controller.dispose(); super.dispose(); } Future _save() async { setState(() => _saving = true); try { await widget.onSave(_controller.text); if (mounted) setState(() => _editing = false); } catch (error) { if (mounted) { ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: AppText('$error'))); } } finally { if (mounted) setState(() => _saving = false); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: AppText(widget.title, maxLines: 1, overflow: TextOverflow.ellipsis), actions: [ if (_editing) TextButton( onPressed: _saving ? null : () => setState(() => _editing = false), child: const AppText('取消'), ), TextButton( onPressed: _saving ? null : (_editing ? _save : () => setState(() => _editing = true)), child: AppText(_saving ? '保存中…' : (_editing ? '保存' : '编辑')), ), ], ), body: _editing ? Padding( padding: const EdgeInsets.all(12), child: TextField( controller: _controller, expands: true, maxLines: null, minLines: null, textAlignVertical: TextAlignVertical.top, style: const TextStyle(fontFamily: 'monospace', fontSize: 13), decoration: const InputDecoration( border: OutlineInputBorder(), contentPadding: EdgeInsets.all(10), ), ), ) : SingleChildScrollView( padding: const EdgeInsets.all(16), child: MarkdownView(_controller.text, fontSize: 14.5), ), ); } } /// A one-field prompt that owns its controller (a controller created outside /// a dialog is disposed while the dialog is still animating out, which trips a /// framework assertion in debug builds). class _TextPromptDialog extends StatefulWidget { final String title; final String hint; final String initial; final int maxLength; final int maxLines; final int minLines; final String action; const _TextPromptDialog({ required this.title, required this.hint, required this.maxLength, required this.maxLines, required this.minLines, required this.action, this.initial = '', }); @override State<_TextPromptDialog> createState() => _TextPromptDialogState(); } class _TextPromptDialogState extends State<_TextPromptDialog> { late final TextEditingController _controller = TextEditingController(text: widget.initial); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AlertDialog( title: AppText(widget.title), content: SizedBox( width: double.maxFinite, child: TextField( controller: _controller, autofocus: true, maxLength: widget.maxLength, maxLines: widget.maxLines, minLines: widget.minLines, decoration: InputDecoration( hintText: widget.hint, border: const OutlineInputBorder(), ), ), ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const AppText('取消')), FilledButton( onPressed: () => Navigator.pop(context, _controller.text.trim()), child: AppText(widget.action)), ], ); } } /// Title plus Markdown body, as one dialog. class _NewPlanDialog extends StatefulWidget { const _NewPlanDialog(); @override State<_NewPlanDialog> createState() => _NewPlanDialogState(); } class _NewPlanDialogState extends State<_NewPlanDialog> { final TextEditingController _title = TextEditingController(); final TextEditingController _body = TextEditingController(); @override void dispose() { _title.dispose(); _body.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AlertDialog( title: const AppText('新建计划'), content: SizedBox( width: double.maxFinite, child: Column( mainAxisSize: MainAxisSize.min, children: [ TextField( controller: _title, autofocus: true, maxLength: 160, decoration: InputDecoration( labelText: tr('标题'), border: const OutlineInputBorder(), ), ), const SizedBox(height: 8), TextField( controller: _body, maxLines: 10, minLines: 6, decoration: InputDecoration( alignLabelWithHint: true, labelText: tr('计划正文(Markdown)'), border: const OutlineInputBorder(), ), ), ], ), ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const AppText('取消')), FilledButton( onPressed: () => Navigator.pop( context, (_title.text.trim(), _body.text)), child: const AppText('创建')), ], ); } } /// Edit one memory entry: its title, its text, and what kind it is. class _MemoryDialog extends StatefulWidget { final AgentMemoryEntry entry; const _MemoryDialog({required this.entry}); @override State<_MemoryDialog> createState() => _MemoryDialogState(); } class _MemoryDialogState extends State<_MemoryDialog> { late final TextEditingController _title = TextEditingController(text: widget.entry.title); late final TextEditingController _body = TextEditingController(text: widget.entry.body); late String _type = widget.entry.type; @override void dispose() { _title.dispose(); _body.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AlertDialog( title: const AppText('编辑记忆'), content: SizedBox( width: double.maxFinite, child: Column( mainAxisSize: MainAxisSize.min, children: [ TextField( controller: _title, autofocus: true, maxLength: 120, decoration: InputDecoration( labelText: tr('标题'), border: const OutlineInputBorder(), ), ), const SizedBox(height: 8), SegmentedButton( showSelectedIcon: false, style: const ButtonStyle( visualDensity: VisualDensity.compact, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), segments: const [ ButtonSegment(value: 'fact', label: AppText('事实')), ButtonSegment(value: 'preference', label: AppText('偏好')), ButtonSegment(value: 'reference', label: AppText('参考')), ], selected: {_type}, onSelectionChanged: (value) => setState(() => _type = value.first), ), const SizedBox(height: 8), TextField( controller: _body, maxLength: 2000, maxLines: 6, minLines: 4, decoration: InputDecoration( alignLabelWithHint: true, labelText: tr('内容'), border: const OutlineInputBorder(), ), ), ], ), ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const AppText('取消')), FilledButton( onPressed: () { final title = _title.text.trim(); if (title.isEmpty) return; Navigator.pop(context, (title, _body.text.trim(), _type)); }, child: const AppText('保存'), ), ], ); } }