feat: the files sidebar, Markdown thinking, a banner that clears
- The chat's top-right menu only repeated the per-turn menu. It now opens a files sidebar that slides in from the right, the way the official client's right panel does: browse the session directory with a breadcrumb and an up key, filter the current directory, search its subdirectories (bounded, skipping .git/node_modules/build and friends), preview text/code/Markdown/ images, edit and save text files, create files and folders, and download any file through the system save dialog. - The panel's "..." menu carries the official client's "显示被 git 忽略的文件" toggle (the listing asks the server to respect gitignore by default) and a refresh. 项目知识 and 终端 have their tabs, marked as coming later. - Thinking blocks are Markdown too (headings, lists, inline code), rendered with the shared MarkdownView at a smaller, quieter size. - The reconnect banner stayed forever: the stream loop sets it when the SSE connection drops and nothing cleared it. Any event proves the stream is back (the server greets every connection with server.connected), so it now clears the message then. - Markdown rendering moved to lib/widgets/markdown_view.dart, shared by messages, thinking, compaction summaries and file previews. Version 0.3.9 (code 309).
This commit is contained in:
1 parent
b9433c30cb
commit
9b53338908
9 files changed
+1118
-80
No files matched your search
+70
-6
@@ -355,13 +355,66 @@ class Client {
|
||||
'path': path,
|
||||
'allowOutsideWorkspace': 'true',
|
||||
},
|
||||
directory: directory);
|
||||
directory: directory,
|
||||
rawDirectory: true);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiError(res.statusCode, utf8.decode(res.body, allowMalformed: true));
|
||||
}
|
||||
return res.body;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ files
|
||||
|
||||
Future<List<FsEntry>> fsList(String path,
|
||||
{String? directory, bool respectGitignore = true}) async {
|
||||
final r = await _json('GET', '/api/fs/list',
|
||||
query: {
|
||||
'path': path,
|
||||
if (respectGitignore) 'respectGitignore': 'true',
|
||||
},
|
||||
directory: directory,
|
||||
rawDirectory: true);
|
||||
return [
|
||||
for (final e in (r['entries'] as List? ?? []))
|
||||
if (e is Map<String, dynamic>) FsEntry.fromJson(e),
|
||||
];
|
||||
}
|
||||
|
||||
Future<String> fsRead(String path, {String? directory}) async {
|
||||
final res = await _request('GET', '/api/fs/read',
|
||||
query: {'path': path}, directory: directory, rawDirectory: true);
|
||||
final text = utf8.decode(res.body, allowMalformed: true);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiError(res.statusCode, text.trim());
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
Future<FsStat?> fsStat(String path, {String? directory}) async {
|
||||
final r = await _json('GET', '/api/fs/stat',
|
||||
query: {'path': path}, directory: directory, rawDirectory: true);
|
||||
final data = r['path'] == null ? r['data'] : r;
|
||||
if (data is! Map<String, dynamic>) return null;
|
||||
return FsStat.fromJson(data);
|
||||
}
|
||||
|
||||
Future<void> fsWrite(String path, String content, {String? directory}) async {
|
||||
await _json('POST', '/api/fs/write',
|
||||
body: {'path': path, 'content': content},
|
||||
directory: directory,
|
||||
rawDirectory: true);
|
||||
}
|
||||
|
||||
Future<void> fsMkdir(String path, {String? directory}) async {
|
||||
await _json('POST', '/api/fs/mkdir',
|
||||
body: {'path': path}, directory: directory, rawDirectory: true);
|
||||
}
|
||||
|
||||
Future<void> fsDelete(String path, {String? directory}) async {
|
||||
await _json('POST', '/api/fs/delete',
|
||||
body: {'path': path}, directory: directory, rawDirectory: true);
|
||||
}
|
||||
|
||||
/// Subscribes to GET /api/event, yielding each SSE event. The stream ends
|
||||
/// when the connection drops; the caller restarts it with backoff.
|
||||
Stream<Map<String, dynamic>> streamEvents({List<String>? types}) async* {
|
||||
@@ -410,9 +463,14 @@ class Client {
|
||||
{Map<String, String>? query,
|
||||
Map<String, dynamic>? body,
|
||||
String? directory,
|
||||
bool partShells = false}) async {
|
||||
bool partShells = false,
|
||||
bool rawDirectory = false}) async {
|
||||
final res = await _request(method, path,
|
||||
query: query, body: body, directory: directory, partShells: partShells);
|
||||
query: query,
|
||||
body: body,
|
||||
directory: directory,
|
||||
partShells: partShells,
|
||||
rawDirectory: rawDirectory);
|
||||
final text = utf8.decode(res.body, allowMalformed: true);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
String msg = text;
|
||||
@@ -434,7 +492,8 @@ class Client {
|
||||
{Map<String, String>? query,
|
||||
Map<String, dynamic>? body,
|
||||
String? directory,
|
||||
bool partShells = false}) async {
|
||||
bool partShells = false,
|
||||
bool rawDirectory = false}) async {
|
||||
final q = Uri(queryParameters: query ?? {});
|
||||
final uri = base.resolve(path).replace(queryParameters: q.queryParameters.isEmpty ? null : q.queryParameters);
|
||||
final req = await _http.openUrl(method, uri);
|
||||
@@ -445,8 +504,13 @@ class Client {
|
||||
req.headers.set('Authorization', 'Bearer $token');
|
||||
}
|
||||
if (directory != null && directory.isNotEmpty) {
|
||||
req.headers.set('x-opencode-directory', Uri.encodeComponent(directory));
|
||||
req.headers.set('x-opencode-directory-encoding', 'uri');
|
||||
// The file routes compare this header with the workspace path, so they
|
||||
// need it as written; the rest of the API wants it URI-encoded.
|
||||
req.headers.set('x-opencode-directory',
|
||||
rawDirectory ? directory : Uri.encodeComponent(directory));
|
||||
if (!rawDirectory) {
|
||||
req.headers.set('x-opencode-directory-encoding', 'uri');
|
||||
}
|
||||
}
|
||||
if (partShells) {
|
||||
req.headers.set('x-openchamber-part-shells', 'v1');
|
||||
|
||||
@@ -160,6 +160,36 @@ class ToolState {
|
||||
|
||||
/// The error OpenCode recorded on a message (a failed step, a failed
|
||||
/// compaction). `body` is the provider's raw response, when there was one.
|
||||
/// One row of a directory listing (`/api/fs/list`).
|
||||
class FsEntry {
|
||||
final String name;
|
||||
final String path;
|
||||
final bool isDirectory;
|
||||
const FsEntry({required this.name, required this.path, this.isDirectory = false});
|
||||
factory FsEntry.fromJson(Map<String, dynamic> j) => FsEntry(
|
||||
name: j['name'] as String? ?? '',
|
||||
path: j['path'] as String? ?? '',
|
||||
isDirectory: j['isDirectory'] as bool? ?? false,
|
||||
);
|
||||
String get extension {
|
||||
final dot = name.lastIndexOf('.');
|
||||
return dot <= 0 ? '' : name.substring(dot + 1).toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
/// `/api/fs/stat` answer (only what the file browser uses).
|
||||
class FsStat {
|
||||
final String path;
|
||||
final bool isFile;
|
||||
final int size;
|
||||
const FsStat({required this.path, this.isFile = false, this.size = 0});
|
||||
factory FsStat.fromJson(Map<String, dynamic> j) => FsStat(
|
||||
path: j['path'] as String? ?? '',
|
||||
isFile: j['isFile'] as bool? ?? false,
|
||||
size: (j['size'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
class MessageError {
|
||||
final String type;
|
||||
final String message;
|
||||
|
||||
@@ -7,15 +7,12 @@ import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:gpt_markdown/gpt_markdown.dart';
|
||||
// gpt_markdown renders through its own Material port; its colours come from
|
||||
// that port's theme, so the chat has to hand it ours.
|
||||
import 'package:material_ui/material_ui.dart' as mui;
|
||||
|
||||
import '../api/client.dart';
|
||||
import '../api/models.dart';
|
||||
import '../state.dart';
|
||||
import '../widgets/markdown_view.dart';
|
||||
import '../widgets/usage_ring.dart';
|
||||
import 'files_panel.dart';
|
||||
|
||||
/// The chat: streaming Markdown, tool rows, composer and sheets.
|
||||
class ChatScreen extends StatefulWidget {
|
||||
@@ -110,9 +107,9 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.more_vert),
|
||||
tooltip: '更多操作',
|
||||
onPressed: _footerMenu,
|
||||
icon: const Icon(Icons.view_sidebar_outlined),
|
||||
tooltip: '文件',
|
||||
onPressed: () => showFilesPanel(context, widget.app, widget.session),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -467,37 +464,15 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
/// gpt_markdown builds its widgets with `material_ui`, whose Theme.of has a
|
||||
/// light fallback: without this the code panel and inline chips stayed light
|
||||
/// (and their text dark) in the dark theme.
|
||||
static mui.ThemeData _mdTheme(ThemeData theme) => mui.ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: theme.brightness,
|
||||
colorScheme: mui.ColorScheme.fromSeed(
|
||||
seedColor: theme.colorScheme.primary,
|
||||
brightness: theme.brightness,
|
||||
),
|
||||
);
|
||||
|
||||
Widget _textRow(String id, int part) {
|
||||
final m = chat.byId[id]!;
|
||||
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
|
||||
child: _markdown(m.content[part].text),
|
||||
child: MarkdownView(m.content[part].text),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _markdown(String text) => mui.Theme(
|
||||
data: _mdTheme(Theme.of(context)),
|
||||
child: GptMarkdown(
|
||||
text,
|
||||
// The server already streams deltas; show them as they arrive.
|
||||
isStreaming: false,
|
||||
style: const TextStyle(fontSize: 15, height: 1.45),
|
||||
),
|
||||
);
|
||||
|
||||
/// A run of steps: the header, then its rows revealed with an animation.
|
||||
/// Revealing grows the list below the header, so [_Reveal] reports the
|
||||
/// height it just added and the list scrolls by it, keeping the header
|
||||
@@ -758,11 +733,11 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
final theme = Theme.of(context);
|
||||
if (reasoning) {
|
||||
if (p.text.isEmpty) return const SizedBox.shrink();
|
||||
// The model writes Markdown here too; render it as such, a touch
|
||||
// smaller and quieter than the answer.
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(10, 2, 10, 8),
|
||||
child: SelectableText(p.text,
|
||||
style: TextStyle(
|
||||
fontSize: 12.5, height: 1.45, color: theme.hintColor)),
|
||||
child: MarkdownView(p.text, fontSize: 12.5, color: theme.hintColor),
|
||||
);
|
||||
}
|
||||
final input = p.state?.input ?? const <String, dynamic>{};
|
||||
@@ -1094,7 +1069,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
child: summary.isEmpty
|
||||
? Text(running ? '正在生成摘要…' : '(摘要为空)',
|
||||
style: TextStyle(fontSize: 13, color: theme.hintColor))
|
||||
: _markdown(summary),
|
||||
: MarkdownView(summary, fontSize: 14),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -1201,43 +1176,6 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
void _footerMenu() {
|
||||
final chat_ = chat;
|
||||
Message? last;
|
||||
for (var i = chat_.msgs.length - 1; i >= 0; i--) {
|
||||
if (chat_.msgs[i].type == 'assistant' && chat_.msgs[i].completed > 0) {
|
||||
last = chat_.msgs[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (last == null) return;
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ListTile(
|
||||
title: const Text('复制回答'),
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
_copyText(last!.partText);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
title: const Text('从这里分叉'),
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
chat_.fork();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _copyText(String text) async {
|
||||
if (text.trim().isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('没有可复制的文字')));
|
||||
|
||||
@@ -0,0 +1,937 @@
|
||||
// The right-side panel: files of the session's directory (browse, preview,
|
||||
// search, create, download). Project knowledge and the terminal are planned
|
||||
// and get their places in the tab row already.
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../api/client.dart';
|
||||
import '../api/models.dart';
|
||||
import '../state.dart';
|
||||
import '../widgets/markdown_view.dart';
|
||||
|
||||
Future<void> showFilesPanel(
|
||||
BuildContext context, AppState app, Session session) {
|
||||
return showGeneralDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
barrierLabel: '文件',
|
||||
barrierColor: Colors.black54,
|
||||
transitionDuration: const Duration(milliseconds: 220),
|
||||
pageBuilder: (context, _, __) {
|
||||
final width = MediaQuery.of(context).size.width;
|
||||
return Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: SizedBox(
|
||||
width: width * 0.92,
|
||||
height: double.infinity,
|
||||
child: FilesPanel(app: app, session: session),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
transitionBuilder: (context, animation, _, child) => SlideTransition(
|
||||
position: Tween(begin: const Offset(1, 0), end: Offset.zero).animate(
|
||||
CurvedAnimation(parent: animation, curve: Curves.easeOutCubic)),
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class FilesPanel extends StatefulWidget {
|
||||
final AppState app;
|
||||
final Session session;
|
||||
const FilesPanel({super.key, required this.app, required this.session});
|
||||
|
||||
@override
|
||||
State<FilesPanel> createState() => _FilesPanelState();
|
||||
}
|
||||
|
||||
const _imageExts = {
|
||||
'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'avif', 'ico',
|
||||
};
|
||||
|
||||
const _markdownExts = {'md', 'markdown', 'mdx'};
|
||||
|
||||
/// Walks skip these: they are huge and never what a phone search wants.
|
||||
const _skipDirs = {
|
||||
'.git', 'node_modules', 'build', '.dart_tool', '.gradle', '.idea',
|
||||
'dist', 'target', 'vendor', 'Pods', '.venv', '__pycache__', '.next',
|
||||
};
|
||||
|
||||
class _FilesPanelState extends State<FilesPanel> {
|
||||
String get _root => widget.session.directory;
|
||||
Client? get _client => widget.app.client;
|
||||
|
||||
String _path = '';
|
||||
List<FsEntry> _entries = [];
|
||||
bool _loading = false;
|
||||
String? _error;
|
||||
String _query = '';
|
||||
|
||||
/// A project listing hides what git ignores; the menu can show it.
|
||||
bool _showIgnored = false;
|
||||
|
||||
List<FsEntry> _deepResults = [];
|
||||
bool _deepDone = false;
|
||||
bool _searching = false;
|
||||
|
||||
/// Preview state. `_previewPath == null` shows the browser.
|
||||
String? _previewPath;
|
||||
String _previewName = '';
|
||||
bool _previewLoading = false;
|
||||
String? _previewError;
|
||||
Uint8List? _previewBytes;
|
||||
String? _previewText;
|
||||
bool _previewBinary = false;
|
||||
bool _previewImage = false;
|
||||
bool _editing = false;
|
||||
bool _saving = false;
|
||||
|
||||
final TextEditingController _editor = TextEditingController();
|
||||
final TextEditingController _search = TextEditingController();
|
||||
|
||||
int _tab = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_path = _root;
|
||||
if (_root.isNotEmpty) _load();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_editor.dispose();
|
||||
_search.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- files
|
||||
|
||||
Future<void> _load([String? path]) async {
|
||||
final client = _client;
|
||||
if (client == null) return;
|
||||
final target = path ?? _path;
|
||||
setState(() {
|
||||
_path = target;
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_previewPath = null;
|
||||
_deepResults = [];
|
||||
_deepDone = false;
|
||||
});
|
||||
try {
|
||||
final list = await client
|
||||
.fsList(target, directory: _root, respectGitignore: !_showIgnored)
|
||||
..removeWhere((e) => e.name == '.git');
|
||||
list.sort((a, b) {
|
||||
if (a.isDirectory != b.isDirectory) return a.isDirectory ? -1 : 1;
|
||||
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
|
||||
});
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_entries = list;
|
||||
_loading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_loading = false;
|
||||
_error = e is ApiError ? e.message : '$e';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _up() {
|
||||
if (_path == _root) return;
|
||||
final cut = _path.lastIndexOf('/');
|
||||
if (cut <= _root.length) {
|
||||
_load(_root);
|
||||
} else {
|
||||
_load(_path.substring(0, cut));
|
||||
}
|
||||
}
|
||||
|
||||
List<String> get _crumbs {
|
||||
if (_path == _root) return const [];
|
||||
final rel = _path.startsWith(_root) ? _path.substring(_root.length) : _path;
|
||||
return rel.split('/').where((s) => s.isNotEmpty).toList();
|
||||
}
|
||||
|
||||
String get _rootName {
|
||||
final parts = _root.split('/').where((s) => s.isNotEmpty).toList();
|
||||
return parts.isEmpty ? _root : parts.last;
|
||||
}
|
||||
|
||||
Future<void> _goToCrumb(int index) async {
|
||||
final crumbs = _crumbs;
|
||||
final target = '$_root/${crumbs.take(index + 1).join('/')}';
|
||||
await _load(target == '$_root/' ? _root : target);
|
||||
}
|
||||
|
||||
Future<void> _deepSearch() async {
|
||||
final client = _client;
|
||||
final q = _query.trim().toLowerCase();
|
||||
if (client == null || q.isEmpty) return;
|
||||
setState(() {
|
||||
_searching = true;
|
||||
_deepResults = [];
|
||||
_deepDone = false;
|
||||
});
|
||||
final found = <FsEntry>[];
|
||||
final queue = <String>[_path];
|
||||
var dirs = 0;
|
||||
while (queue.isNotEmpty && dirs < 400 && found.length < 200) {
|
||||
if (!mounted) return;
|
||||
final dir = queue.removeAt(0);
|
||||
dirs++;
|
||||
List<FsEntry> list;
|
||||
try {
|
||||
list = await client.fsList(dir, directory: _root);
|
||||
} catch (_) {
|
||||
continue;
|
||||
}
|
||||
for (final e in list) {
|
||||
if (e.isDirectory) {
|
||||
if (!_skipDirs.contains(e.name)) queue.add(e.path);
|
||||
} else if (e.name.toLowerCase().contains(q) && found.length < 200) {
|
||||
found.add(e);
|
||||
}
|
||||
}
|
||||
if (found.length != _deepResults.length) {
|
||||
setState(() => _deepResults = List.of(found));
|
||||
}
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_searching = false;
|
||||
_deepDone = true;
|
||||
_deepResults = found;
|
||||
});
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------- preview
|
||||
|
||||
Future<void> _openPreview(FsEntry entry) async {
|
||||
setState(() {
|
||||
_previewPath = entry.path;
|
||||
_previewName = entry.name;
|
||||
_previewLoading = true;
|
||||
_previewError = null;
|
||||
_previewBytes = null;
|
||||
_previewText = null;
|
||||
_previewBinary = false;
|
||||
_previewImage = false;
|
||||
_editing = false;
|
||||
});
|
||||
final client = _client;
|
||||
if (client == null) return;
|
||||
try {
|
||||
final stat = await client.fsStat(entry.path, directory: _root);
|
||||
if (stat != null && stat.size > 2 * 1024 * 1024) {
|
||||
if (!mounted || _previewPath != entry.path) return;
|
||||
setState(() {
|
||||
_previewLoading = false;
|
||||
_previewError = '文件较大(${_fmtSize(stat.size)}),请下载后查看';
|
||||
});
|
||||
return;
|
||||
}
|
||||
final bytes =
|
||||
Uint8List.fromList(await client.rawFile(entry.path, directory: _root));
|
||||
if (!mounted || _previewPath != entry.path) return;
|
||||
final image = _imageExts.contains(entry.extension);
|
||||
final text = image ? null : _decodeText(bytes);
|
||||
setState(() {
|
||||
_previewBytes = bytes;
|
||||
_previewImage = image;
|
||||
_previewText = text;
|
||||
_previewBinary = !image && text == null;
|
||||
_previewLoading = false;
|
||||
_editor.text = text ?? '';
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted || _previewPath != entry.path) return;
|
||||
setState(() {
|
||||
_previewLoading = false;
|
||||
_previewError = e is ApiError ? e.message : '$e';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final client = _client;
|
||||
final path = _previewPath;
|
||||
if (client == null || path == null) return;
|
||||
setState(() => _saving = true);
|
||||
try {
|
||||
await client.fsWrite(path, _editor.text, directory: _root);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_editing = false;
|
||||
_previewText = _editor.text;
|
||||
_previewBinary = false;
|
||||
});
|
||||
_toast('已保存');
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() => _saving = false);
|
||||
_toast(e is ApiError ? e.message : '$e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _download() async {
|
||||
final client = _client;
|
||||
final path = _previewPath;
|
||||
if (client == null || path == null) return;
|
||||
try {
|
||||
final bytes = _previewBytes ??
|
||||
Uint8List.fromList(await client.rawFile(path, directory: _root));
|
||||
final uri = await FilePicker.saveFile(
|
||||
fileName: _previewName,
|
||||
bytes: bytes,
|
||||
);
|
||||
if (uri != null) _toast('已保存');
|
||||
} catch (e) {
|
||||
_toast('下载失败:$e');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------- new file
|
||||
|
||||
Future<void> _newEntry({required bool directory}) async {
|
||||
final client = _client;
|
||||
if (client == null || _path.isEmpty) return;
|
||||
final name = await _askName(directory ? '新建文件夹' : '新建文件');
|
||||
if (name == null) return;
|
||||
final target = '$_path/$name';
|
||||
try {
|
||||
if (directory) {
|
||||
await client.fsMkdir(target, directory: _root);
|
||||
} else {
|
||||
await client.fsWrite(target, '', directory: _root);
|
||||
}
|
||||
if (!mounted) return;
|
||||
await _load();
|
||||
if (!directory) {
|
||||
await _openPreview(FsEntry(name: name, path: target));
|
||||
}
|
||||
} catch (e) {
|
||||
_toast(e is ApiError ? e.message : '$e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> _askName(String title) async {
|
||||
final controller = TextEditingController();
|
||||
final name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(title),
|
||||
content: TextField(
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
decoration: InputDecoration(
|
||||
labelText: '名称',
|
||||
hintText: title == '新建文件夹' ? '例如 docs' : '例如 notes.md',
|
||||
),
|
||||
onSubmitted: (v) => Navigator.of(context).pop(v),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('取消')),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(controller.text),
|
||||
child: const Text('创建')),
|
||||
],
|
||||
),
|
||||
);
|
||||
controller.dispose();
|
||||
final trimmed = name?.trim() ?? '';
|
||||
if (trimmed.isEmpty) return null;
|
||||
if (trimmed.contains('/') || trimmed.contains('\\')) {
|
||||
_toast('名称里不能有斜杠');
|
||||
return null;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
void _toast(String message) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- build
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return SafeArea(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_header(theme),
|
||||
_tabs(theme),
|
||||
const Divider(height: 1),
|
||||
Expanded(child: _body(theme)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _header(ThemeData theme) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(6, 6, 6, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
if (_previewPath != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
tooltip: '返回',
|
||||
onPressed: () => setState(() => _previewPath = null),
|
||||
)
|
||||
else
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(_previewPath != null ? _previewName : '文件',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
if (_previewPath == null && _root.isNotEmpty)
|
||||
Text(_rootName,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 12, color: theme.hintColor)),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_previewPath != null) ...[
|
||||
if (_previewText != null)
|
||||
IconButton(
|
||||
icon: Icon(_editing ? Icons.visibility_outlined : Icons.edit_outlined),
|
||||
tooltip: _editing ? '预览' : '编辑',
|
||||
onPressed: _saving
|
||||
? null
|
||||
: () => setState(() => _editing = !_editing),
|
||||
),
|
||||
if (_editing)
|
||||
IconButton(
|
||||
icon: _saving
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Icon(Icons.check),
|
||||
tooltip: '保存',
|
||||
onPressed: _saving ? null : _save,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.download_outlined),
|
||||
tooltip: '下载',
|
||||
onPressed: _download,
|
||||
),
|
||||
] else if (_root.isNotEmpty) ...[
|
||||
PopupMenuButton<bool>(
|
||||
icon: const Icon(Icons.add),
|
||||
tooltip: '新建',
|
||||
onSelected: (directory) => _newEntry(directory: directory),
|
||||
itemBuilder: (_) => const [
|
||||
PopupMenuItem(value: false, child: Text('新建文件')),
|
||||
PopupMenuItem(value: true, child: Text('新建文件夹')),
|
||||
],
|
||||
),
|
||||
PopupMenuButton<String>(
|
||||
icon: const Icon(Icons.more_horiz),
|
||||
tooltip: '更多',
|
||||
onSelected: (value) {
|
||||
if (value == 'ignored') {
|
||||
setState(() => _showIgnored = !_showIgnored);
|
||||
_load();
|
||||
} else if (value == 'refresh') {
|
||||
_load();
|
||||
}
|
||||
},
|
||||
itemBuilder: (_) => [
|
||||
CheckedPopupMenuItem(
|
||||
value: 'ignored',
|
||||
checked: _showIgnored,
|
||||
child: const Text('显示被 git 忽略的文件'),
|
||||
),
|
||||
const PopupMenuItem(
|
||||
value: 'refresh',
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.refresh, size: 18),
|
||||
SizedBox(width: 10),
|
||||
Text('刷新'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: '关闭',
|
||||
onPressed: () => Navigator.of(context).maybePop(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _tabs(ThemeData theme) {
|
||||
const labels = ['文件', '项目知识', '终端'];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 4, 12, 8),
|
||||
child: SegmentedButton<int>(
|
||||
showSelectedIcon: false,
|
||||
style: const ButtonStyle(
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
segments: [
|
||||
for (var i = 0; i < labels.length; i++)
|
||||
ButtonSegment(value: i, label: Text(labels[i])),
|
||||
],
|
||||
selected: {_tab},
|
||||
onSelectionChanged: (v) => setState(() => _tab = v.first),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(ThemeData theme) {
|
||||
if (_root.isEmpty) {
|
||||
return const Center(child: Text('这个会话没有关联目录'));
|
||||
}
|
||||
switch (_tab) {
|
||||
case 1:
|
||||
return _placeholder(theme, Icons.menu_book_outlined, '项目知识',
|
||||
'笔记、待办与计划会在这里。');
|
||||
case 2:
|
||||
return _placeholder(
|
||||
theme, Icons.terminal, '终端', '在服务器上运行的终端会在这里。');
|
||||
default:
|
||||
if (_previewPath != null) return _previewBody(theme);
|
||||
return _browser(theme);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _placeholder(
|
||||
ThemeData theme, IconData icon, String title, String note) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 40, color: theme.hintColor),
|
||||
const SizedBox(height: 12),
|
||||
Text(title,
|
||||
style: const TextStyle(
|
||||
fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 6),
|
||||
Text(note,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 13, color: theme.hintColor)),
|
||||
const SizedBox(height: 10),
|
||||
Chip(
|
||||
label: const Text('即将支持'),
|
||||
visualDensity: VisualDensity.compact,
|
||||
side: BorderSide(color: theme.dividerColor),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _browser(ThemeData theme) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_pathBar(theme),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _search,
|
||||
onChanged: (v) => setState(() {
|
||||
_query = v;
|
||||
_deepResults = [];
|
||||
_deepDone = false;
|
||||
}),
|
||||
style: const TextStyle(fontSize: 14),
|
||||
decoration: InputDecoration(
|
||||
isDense: true,
|
||||
prefixIcon: const Icon(Icons.search, size: 20),
|
||||
hintText: '搜索当前目录…',
|
||||
suffixIcon: _query.trim().isEmpty
|
||||
? null
|
||||
: IconButton(
|
||||
icon: const Icon(Icons.travel_explore, size: 20),
|
||||
tooltip: '搜索子目录',
|
||||
onPressed: _searching ? null : _deepSearch,
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding:
|
||||
const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_searching)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2)),
|
||||
const SizedBox(width: 8),
|
||||
Text('正在搜索子目录…(${_deepResults.length})',
|
||||
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(child: _list(theme)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _pathBar(ThemeData theme) {
|
||||
final crumbs = _crumbs;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(4, 0, 8, 4),
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.arrow_upward, size: 20),
|
||||
tooltip: '上一级',
|
||||
onPressed: _path == _root ? null : _up,
|
||||
),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: [
|
||||
_crumb(theme, _rootName, () => _load(_root), last: crumbs.isEmpty),
|
||||
for (var i = 0; i < crumbs.length; i++) ...[
|
||||
Text(' / ', style: TextStyle(color: theme.hintColor)),
|
||||
_crumb(theme, crumbs[i], () => _goToCrumb(i),
|
||||
last: i == crumbs.length - 1),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _crumb(ThemeData theme, String text, VoidCallback onTap,
|
||||
{required bool last}) {
|
||||
return InkWell(
|
||||
onTap: last ? null : onTap,
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: last ? theme.colorScheme.onSurface : theme.colorScheme.primary,
|
||||
fontWeight: last ? FontWeight.w600 : FontWeight.w400,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _list(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),
|
||||
const SizedBox(height: 8),
|
||||
TextButton(onPressed: () => _load(), child: const Text('重试')),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final filtered = _query.trim().isEmpty
|
||||
? _entries
|
||||
: _entries
|
||||
.where((e) =>
|
||||
e.name.toLowerCase().contains(_query.trim().toLowerCase()))
|
||||
.toList();
|
||||
if (filtered.isEmpty && _deepResults.isEmpty) {
|
||||
return Center(
|
||||
child: Text(_query.trim().isEmpty ? '目录为空' : '没有匹配的文件',
|
||||
style: TextStyle(color: theme.hintColor)),
|
||||
);
|
||||
}
|
||||
return ListView(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
children: [
|
||||
for (final e in filtered) _tile(theme, e),
|
||||
if (_query.trim().isNotEmpty && _deepResults.isNotEmpty) ...[
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
|
||||
child: Text('子目录结果',
|
||||
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||
),
|
||||
for (final e in _deepResults) _tile(theme, e, showPath: true),
|
||||
],
|
||||
if (_query.trim().isNotEmpty &&
|
||||
_deepDone &&
|
||||
_deepResults.isEmpty &&
|
||||
!_searching &&
|
||||
filtered.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
|
||||
child: Text('子目录里没有匹配的文件',
|
||||
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _tile(ThemeData theme, FsEntry entry, {bool showPath = false}) {
|
||||
final icon = entry.isDirectory
|
||||
? Icons.folder_outlined
|
||||
: _fileIcon(entry.extension);
|
||||
return ListTile(
|
||||
dense: true,
|
||||
leading: Icon(icon,
|
||||
color: entry.isDirectory
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant),
|
||||
title: Text(entry.name,
|
||||
maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 14)),
|
||||
subtitle: showPath
|
||||
? Text(_relative(entry.path),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 11, color: theme.hintColor))
|
||||
: null,
|
||||
trailing: entry.isDirectory
|
||||
? Icon(Icons.chevron_right, size: 18, color: theme.hintColor)
|
||||
: null,
|
||||
onTap: () {
|
||||
if (entry.isDirectory) {
|
||||
_load(entry.path);
|
||||
} else {
|
||||
_openPreview(entry);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
String _relative(String path) {
|
||||
if (path.startsWith(_root)) {
|
||||
final rel = path.substring(_root.length);
|
||||
return rel.startsWith('/') ? rel.substring(1) : rel;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
Widget _previewBody(ThemeData theme) {
|
||||
if (_previewLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (_previewError != null) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(_previewError!, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 8),
|
||||
if (_previewBytes != null || _previewError != null)
|
||||
TextButton(onPressed: _download, child: const Text('下载')),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (_previewImage && _previewBytes != null) {
|
||||
return InteractiveViewer(
|
||||
maxScale: 6,
|
||||
child: Center(
|
||||
child: Image.memory(_previewBytes!, fit: BoxFit.contain),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (_previewBinary) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.insert_drive_file_outlined,
|
||||
size: 40, color: theme.hintColor),
|
||||
const SizedBox(height: 10),
|
||||
Text('这个文件无法预览',
|
||||
style: TextStyle(color: theme.hintColor)),
|
||||
const SizedBox(height: 6),
|
||||
Text(_fmtSize(_previewBytes?.length ?? 0),
|
||||
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||
const SizedBox(height: 8),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _download,
|
||||
icon: const Icon(Icons.download_outlined, size: 18),
|
||||
label: const Text('下载'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
if (_editing) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: TextField(
|
||||
controller: _editor,
|
||||
maxLines: null,
|
||||
expands: true,
|
||||
style: const TextStyle(fontSize: 13, fontFamily: 'monospace', height: 1.4),
|
||||
textAlignVertical: TextAlignVertical.top,
|
||||
decoration: InputDecoration(
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
|
||||
contentPadding: const EdgeInsets.all(10),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final text = _previewText ?? '';
|
||||
if (_markdownExts.contains(_fileExt(_previewName))) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
|
||||
child: MarkdownView(text, fontSize: 14),
|
||||
);
|
||||
}
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(14, 10, 14, 24),
|
||||
child: SelectableText(
|
||||
text,
|
||||
style: const TextStyle(
|
||||
fontSize: 12.5, height: 1.45, fontFamily: 'monospace'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static String _fileExt(String name) {
|
||||
final dot = name.lastIndexOf('.');
|
||||
return dot <= 0 ? '' : name.substring(dot + 1).toLowerCase();
|
||||
}
|
||||
|
||||
static IconData _fileIcon(String ext) {
|
||||
if (_imageExts.contains(ext)) return Icons.image_outlined;
|
||||
if (_markdownExts.contains(ext)) return Icons.description_outlined;
|
||||
switch (ext) {
|
||||
case 'json':
|
||||
case 'yaml':
|
||||
case 'yml':
|
||||
case 'toml':
|
||||
case 'ini':
|
||||
case 'conf':
|
||||
return Icons.tune;
|
||||
case 'dart':
|
||||
case 'kt':
|
||||
case 'java':
|
||||
case 'js':
|
||||
case 'ts':
|
||||
case 'tsx':
|
||||
case 'jsx':
|
||||
case 'py':
|
||||
case 'go':
|
||||
case 'rs':
|
||||
case 'c':
|
||||
case 'h':
|
||||
case 'cpp':
|
||||
case 'cc':
|
||||
case 'hpp':
|
||||
case 'cs':
|
||||
case 'swift':
|
||||
case 'rb':
|
||||
case 'php':
|
||||
case 'lua':
|
||||
return Icons.code;
|
||||
case 'sh':
|
||||
case 'bash':
|
||||
case 'zsh':
|
||||
case 'fish':
|
||||
return Icons.terminal;
|
||||
case 'html':
|
||||
case 'css':
|
||||
case 'scss':
|
||||
case 'less':
|
||||
case 'xml':
|
||||
return Icons.web_outlined;
|
||||
case 'png':
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
case 'gif':
|
||||
case 'webp':
|
||||
case 'svg':
|
||||
return Icons.image_outlined;
|
||||
case 'pdf':
|
||||
return Icons.picture_as_pdf_outlined;
|
||||
case 'zip':
|
||||
case 'tar':
|
||||
case 'gz':
|
||||
case 'tgz':
|
||||
case 'xz':
|
||||
case '7z':
|
||||
return Icons.folder_zip_outlined;
|
||||
default:
|
||||
return Icons.insert_drive_file_outlined;
|
||||
}
|
||||
}
|
||||
|
||||
static String? _decodeText(Uint8List bytes) {
|
||||
if (bytes.isEmpty) return '';
|
||||
final n = bytes.length < 8000 ? bytes.length : 8000;
|
||||
var control = 0;
|
||||
for (var i = 0; i < n; i++) {
|
||||
final b = bytes[i];
|
||||
if (b == 0) return null;
|
||||
if (b < 8 || (b > 13 && b < 32)) control++;
|
||||
}
|
||||
if (control > n * 0.02) return null;
|
||||
try {
|
||||
return utf8.decode(bytes);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static String _fmtSize(int bytes) {
|
||||
if (bytes < 1024) return '$bytes B';
|
||||
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
|
||||
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
|
||||
}
|
||||
}
|
||||
@@ -290,6 +290,10 @@ class AppState extends ChangeNotifier {
|
||||
_events = cl.streamEvents(types: _eventTypes).listen(
|
||||
(ev) {
|
||||
if (client != cl) return;
|
||||
// Anything arriving means the stream is back (the server greets
|
||||
// every connection with `server.connected`), so the "reconnecting"
|
||||
// banner has done its job.
|
||||
if (error == '连接中断,正在重连…') error = null;
|
||||
_applyEvent(ev);
|
||||
},
|
||||
onError: (Object _) {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// The chat's Markdown renderer, shared by message text, thinking blocks,
|
||||
// compaction summaries and file previews.
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gpt_markdown/gpt_markdown.dart';
|
||||
// gpt_markdown renders through its own Material port; its colours come from
|
||||
// that port's theme, so it has to be handed ours.
|
||||
import 'package:material_ui/material_ui.dart' as mui;
|
||||
|
||||
/// gpt_markdown builds its widgets with `material_ui`, whose `Theme.of` falls
|
||||
/// back to a light theme: without this the code panel and inline chips stayed
|
||||
/// light (and their text dark) in the dark theme.
|
||||
mui.ThemeData markdownThemeData(ThemeData theme) => mui.ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: theme.brightness,
|
||||
colorScheme: mui.ColorScheme.fromSeed(
|
||||
seedColor: theme.colorScheme.primary,
|
||||
brightness: theme.brightness,
|
||||
),
|
||||
);
|
||||
|
||||
class MarkdownView extends StatelessWidget {
|
||||
final String text;
|
||||
final double fontSize;
|
||||
final Color? color;
|
||||
|
||||
/// A little air around headings; messages use the default, thinking blocks
|
||||
/// and previews a tighter one.
|
||||
final double height;
|
||||
|
||||
const MarkdownView(
|
||||
this.text, {
|
||||
super.key,
|
||||
this.fontSize = 15,
|
||||
this.color,
|
||||
this.height = 1.45,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return mui.Theme(
|
||||
data: markdownThemeData(Theme.of(context)),
|
||||
child: GptMarkdown(
|
||||
text,
|
||||
// The server already streams deltas; show them as they arrive.
|
||||
isStreaming: false,
|
||||
style: TextStyle(fontSize: fontSize, height: height, color: color),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user