Files
openchamber-android-native/lib/screens/knowledge_panel.dart
T
blumia 5f95e2da97 feat: the terminal, project knowledge, and downloads that can be cancelled
- lib/api/terminal.dart: the PTY protocol (create/resize/restart/close, and
  the /api/terminal/ws binary control frames) with a reconnecting socket
  that replays the server snapshot at the size it was drawn for.
- lib/terminal_state.dart: an xterm model plus that socket, kept per
  workspace on AppState, so closing the panel or switching tabs keeps the
  shell; the app reattaches when it returns from the background.
- lib/screens/terminal_panel.dart: TerminalView, a status bar (keyboard,
  restart, clear, close) and a Termux-style key bar whose CTRL/ALT/SHIFT
  modifiers also apply to what the phone keyboard types.
- lib/screens/knowledge_panel.dart: notes, todos and plans from
  /api/project-context, searchable, with a full page for a plan's Markdown
  and its raw editor.
- Downloads stream with a progress dialog (bytes, total, percent) and a
  cancel that aborts the request; the save dialog only opens on success.
  The request asks for `accept-encoding: identity` so Content-Length exists.
- MarkdownView renders task lists as ✅/⬜ instead of material_ui's
  Checkbox, which wants a material_ui Material ancestor the app lacks.
- Dialogs own their TextEditingControllers, so closing one no longer
  trips a framework assertion in debug builds.
- 0.3.11 (311).
2026-11-21 02:49:07 +08:00

843 lines
26 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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';
class KnowledgePanel extends StatefulWidget {
final AppState app;
final String directory;
const KnowledgePanel({super.key, required this.app, required this.directory});
@override
State<KnowledgePanel> createState() => _KnowledgePanelState();
}
class _KnowledgePanelState extends State<KnowledgePanel> {
ProjectContext? _context;
bool _loading = true;
String? _error;
int _section = 0;
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<void> _load() async {
final client = _client;
if (client == null || _projectId.isEmpty) {
setState(() {
_loading = false;
_error = '这个会话没有关联目录';
});
return;
}
setState(() {
_loading = true;
_error = null;
});
try {
final context = await client.projectContext(_projectId,
directory: widget.directory);
if (!mounted) return;
setState(() {
_context = context;
_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: Text('$error')));
}
bool _matches(Iterable<String> 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, 0, 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: '搜索笔记、待办与计划',
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: '刷新',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.refresh, size: 20),
onPressed: _load,
),
],
),
),
_sections(theme),
Expanded(child: _body(theme)),
],
);
}
Widget _sections(ThemeData theme) {
final context_ = _context;
final counts = [
context_?.notes.length ?? 0,
context_?.todos.length ?? 0,
context_?.plans.length ?? 0,
];
const names = ['笔记', '待办', '计划'];
return Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 6),
child: SegmentedButton<int>(
showSelectedIcon: false,
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: [
for (var i = 0; i < names.length; i++)
ButtonSegment(value: i, label: Text('${names[i]} ${counts[i]}')),
],
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: [
Text(_error!,
textAlign: TextAlign.center,
style: TextStyle(color: theme.colorScheme.error, fontSize: 13)),
const SizedBox(height: 8),
FilledButton(onPressed: _load, child: const Text('重试')),
],
),
),
);
}
switch (_section) {
case 1:
return _todos(theme);
case 2:
return _plans(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, '${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: [
Text(
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),
),
Text(
_stamp(note.updatedAt),
style:
TextStyle(fontSize: 11, color: theme.hintColor),
),
],
),
],
),
),
PopupMenuButton<String>(
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: Text('编辑')),
PopupMenuItem(
value: 'pin', child: Text(note.pinned ? '取消置顶' : '置顶')),
const PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
],
),
),
),
);
}
// --------------------------------------------------------------- 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, '$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: Text(
todo.text,
style: TextStyle(
fontSize: 13.5,
decoration: todo.completed
? TextDecoration.lineThrough
: null,
color: todo.completed ? theme.hintColor : null,
),
),
secondary: PopupMenuButton<String>(
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: Text('删除')),
],
),
);
},
),
),
],
);
}
Future<void> _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, '${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: Text(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),
Text('${plan.progressDone}/${plan.progressTotal}',
style:
TextStyle(fontSize: 11, color: theme.hintColor)),
],
),
],
const SizedBox(height: 2),
Text(
plan.source == 'shared' ? '团队共享' : '个人',
style: TextStyle(fontSize: 11, color: theme.hintColor),
),
],
),
trailing: PopupMenuButton<String>(
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: Text(plan.pinned ? '取消置顶' : '置顶')),
const PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
onTap: () => _viewPlan(plan),
),
);
}
// -------------------------------------------------------------- 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: Text(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: Text(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),
Text(text, style: TextStyle(fontSize: 13, color: theme.hintColor)),
],
),
);
}
Future<void> _addNote() => _editNote(null);
Future<void> _editNote(ProjectNote? note) async {
final text = await showDialog<String>(
context: context,
builder: (_) => _TextPromptDialog(
title: note == null ? '新建笔记' : '编辑笔记',
hint: '记点什么,供之后的会话参考',
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<void> _addTodo() async {
final text = await showDialog<String>(
context: context,
builder: (_) => const _TextPromptDialog(
title: '新建待办',
hint: '要做什么',
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<void> _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<void> _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<void>(
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<void> 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<void> _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: Text('$error')));
}
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title, maxLines: 1, overflow: TextOverflow.ellipsis),
actions: [
if (_editing)
TextButton(
onPressed: _saving ? null : () => setState(() => _editing = false),
child: const Text('取消'),
),
TextButton(
onPressed: _saving
? null
: (_editing ? _save : () => setState(() => _editing = true)),
child: Text(_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: Text(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 Text('取消')),
FilledButton(
onPressed: () => Navigator.pop(context, _controller.text.trim()),
child: Text(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 Text('新建计划'),
content: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _title,
autofocus: true,
maxLength: 160,
decoration: const InputDecoration(
labelText: '标题',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 8),
TextField(
controller: _body,
maxLines: 10,
minLines: 6,
decoration: const InputDecoration(
alignLabelWithHint: true,
labelText: '计划正文(Markdown)',
border: OutlineInputBorder(),
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.pop(
context, (_title.text.trim(), _body.text)),
child: const Text('创建')),
],
);
}
}