Files
openchamber-android-native/lib/screens/new_session_screen.dart
T
blumia ea3b1f0f5e ui: fold the composer to one line until it has focus
dsh-Go opens the input into two rows only while focused: the text above, the
model / mode / keys below, folding back when focus leaves. ComposerBox keeps
the field across the two layouts with a GlobalKey and animates the swap.

Model and thinking level are now one control (ModelPill shows "model · effort"
and the sheet offers the level after choosing a model); Build/Plan is a
separate ModeChip. The draft page uses the same box, with its project chip
above it. 0.3.15 (315).
2026-11-21 17:47:04 +08:00

525 lines
17 KiB
Dart

// The new-session draft. Nothing exists on the server until the first message
// creates the session; this screen only holds the project, the model and what
// has been typed.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/composer_box.dart';
import '../widgets/model_controls.dart';
import '../widgets/slash_palette.dart';
import 'files_panel.dart';
class NewSessionScreen extends StatefulWidget {
final AppState app;
/// Opens the session drawer; null where the list is always on screen.
final VoidCallback? onOpenSessions;
const NewSessionScreen({
super.key,
required this.app,
this.onOpenSessions,
});
@override
State<NewSessionScreen> createState() => _NewSessionScreenState();
}
class _NewSessionScreenState extends State<NewSessionScreen> {
SessionDraft get _draft => widget.app.draft!;
final TextEditingController _text = TextEditingController();
final FocusNode _inputFocus = FocusNode();
List<ComposerAttachment> _attachments = [];
bool _attaching = false;
/// The `/` palette for the draft's directory. It carries commands and
/// skills, not the client-local `compact` that needs an existing session.
List<SlashItem> _slashItems = [];
bool _slashLoading = false;
bool _slashLoaded = false;
int _slashIndex = 0;
String? _slashDismissed;
@override
void initState() {
super.initState();
_text.text = _draft.text;
_text.addListener(_syncText);
_attachments = [];
_draft.attachments = 0;
}
@override
void dispose() {
_text.removeListener(_syncText);
_text.dispose();
_inputFocus.dispose();
super.dispose();
}
void _syncText() {
if (_draft.text == _text.text) return;
widget.app.updateDraftText(_text.text);
}
bool get _canSend =>
_text.text.trim().isNotEmpty || _attachments.isNotEmpty;
List<SlashItem>? _slashMatches() => matchSlashItems(
items: _slashItems,
text: _text.text,
dismissed: _slashDismissed,
);
Future<void> _ensureSlash() async {
if (_slashLoaded || _slashLoading) return;
_slashLoading = true;
if (mounted) setState(() {});
try {
_slashItems = await widget.app.slashItemsFor(_draft.directory,
includeLocal: false);
_slashLoaded = true;
} catch (_) {
// An empty palette; a send falls back to a plain prompt.
}
_slashLoading = false;
if (mounted) setState(() {});
}
void _moveSlash(List<SlashItem> items, int delta) {
if (items.isEmpty) return;
setState(() {
_slashIndex = (_slashIndex + delta).clamp(0, items.length - 1);
});
}
void _dismissSlash() => setState(() => _slashDismissed = _text.text);
/// A row was picked: no-argument commands run at once (creating the session
/// on the spot), the rest complete the name and wait for arguments.
void _pickSlash(SlashItem item) {
HapticFeedback.selectionClick();
final text = _text.text;
final lead = text.length - text.trimLeft().length;
final rest = text.trimLeft();
final match = RegExp(r'\s').firstMatch(rest);
final suffix = match == null ? '' : rest.substring(match.start);
final completes = item.skill || item.takesArgs;
if (!completes) {
final command = '/${item.name}';
_text.value = TextEditingValue(
text: command,
selection: TextSelection.collapsed(offset: command.length),
);
widget.app.updateDraftText(command);
setState(() {});
_send();
return;
}
final prefix = '${text.substring(0, lead)}/${item.name}';
final separator =
suffix.isEmpty || !RegExp(r'^\s').hasMatch(suffix) ? ' ' : '';
final next = '$prefix$separator$suffix';
_text.value = TextEditingValue(
text: next,
selection: TextSelection.collapsed(offset: prefix.length + 1),
);
widget.app.updateDraftText(next);
_inputFocus.requestFocus();
setState(() {});
}
Future<void> _send() async {
if (!_canSend || widget.app.sendingDraft) return;
final text = _text.text.trim();
final files = [
for (final a in _attachments) {'uri': a.dataUrl, 'name': a.name}
];
final images = [
for (final a in _attachments)
if (a.isImage && a.path != null) a.path!
];
FocusScope.of(context).unfocus();
await widget.app.sendDraft(text: text, files: files, images: images);
if (!mounted) return;
final draft = widget.app.draft;
if (draft != null) {
// The create failed: the draft is still here, keep what was typed.
_text.text = draft.text;
} else {
HapticFeedback.lightImpact();
}
}
Future<void> _pickFiles() async {
setState(() => _attaching = true);
try {
final picked = await pickComposerAttachments(context);
if (picked.isEmpty) return;
setState(() {
for (final file in picked) {
if (_attachments.length >= 5) break;
_attachments.add(file);
}
_draft.attachments = _attachments.length;
});
widget.app.touch();
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('选择失败:$e')));
}
} finally {
if (mounted) setState(() => _attaching = false);
}
}
void _removeAttachment(int index) {
setState(() {
_attachments.removeAt(index);
_draft.attachments = _attachments.length;
});
widget.app.touch();
}
@override
Widget build(BuildContext context) {
final app = widget.app;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return ListenableBuilder(
listenable: app,
builder: (context, _) {
final draft = app.draft;
if (draft == null) return const SizedBox.shrink();
return Scaffold(
appBar: AppBar(
leading: widget.onOpenSessions == null
? null
: IconButton(
icon: const Icon(Icons.menu),
tooltip: '会话',
onPressed: widget.onOpenSessions,
),
title: const Text('新会话'),
actions: [
IconButton(
icon: const Icon(Icons.folder_open_outlined),
tooltip: '文件',
onPressed: () => showFilesPanel(context, app, draft.directory),
),
],
),
body: Column(
children: [
Expanded(
child: Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Text(
'我们今天要做什么?',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (draft.error != null)
Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Text(
draft.error!,
style: TextStyle(
fontSize: 12.5, color: scheme.error),
),
),
Align(
alignment: Alignment.centerLeft,
child: _projectChip(draft),
),
const SizedBox(height: 4),
if (_attachments.isNotEmpty)
AttachmentTray(
items: _attachments,
onRemove: _removeAttachment,
),
_composer(theme),
],
),
),
],
),
);
},
);
}
Widget _projectChip(SessionDraft draft) {
final theme = Theme.of(context);
final label = widget.app.projectLabelFor(draft.directory);
return InkWell(
borderRadius: BorderRadius.circular(18),
onTap: _pickProject,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.folder_outlined,
size: 15, color: theme.hintColor),
const SizedBox(width: 5),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 170),
child: Text(
label.isEmpty ? '选择项目' : label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12.5, color: theme.hintColor),
),
),
Icon(Icons.expand_more, size: 16, color: theme.hintColor),
],
),
),
);
}
Widget _composer(ThemeData theme) {
final scheme = theme.colorScheme;
final sending = widget.app.sendingDraft;
final slash = _slashMatches();
final slashRows = slash ?? const <SlashItem>[];
Widget body = ComposerBox(
controller: _text,
focusNode: _inputFocus,
hint: '规划、构建或提问',
maxLines: 5,
textInputAction:
slash != null ? TextInputAction.send : TextInputAction.newline,
onSubmitted: slash == null || slashRows.isEmpty
? null
: (_) => _pickSlash(
slashRows[_slashIndex.clamp(0, slashRows.length - 1)]),
onChanged: (v) {
widget.app.updateDraftText(v);
_slashIndex = 0;
if (_slashDismissed != null && v != _slashDismissed) {
_slashDismissed = null;
}
if (v.trimLeft().startsWith('/')) _ensureSlash();
setState(() {});
if (slash != null && v.endsWith('\n')) {
final trimmed = v.trimRight();
_text.value = TextEditingValue(
text: trimmed,
selection: TextSelection.collapsed(offset: trimmed.length),
);
widget.app.updateDraftText(trimmed);
final rows = _slashMatches() ?? const <SlashItem>[];
if (rows.isNotEmpty) {
_pickSlash(rows[_slashIndex.clamp(0, rows.length - 1)]);
}
}
},
leading: _roundKey(
icon: Icons.attach_file,
label: '添加附件',
onTap: _pickFiles,
busy: _attaching,
),
model: ModelPill(
app: widget.app,
model: _draft.model,
onModel: (m) => widget.app.updateDraftModel(m),
),
mode: ModeChip(
app: widget.app,
agent: _draft.agent,
onAgent: (a) => widget.app.updateDraftModel(null, agent: a),
),
trailing: InkWell(
borderRadius: BorderRadius.circular(18),
onTap: sending || !_canSend ? null : _send,
child: Container(
width: 36,
height: 36,
alignment: Alignment.center,
decoration: BoxDecoration(
color: _canSend || sending ? scheme.primary : scheme.surface,
shape: BoxShape.circle,
),
child: sending
? SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2, color: scheme.onPrimary))
: Icon(Icons.arrow_upward,
size: 20,
color: _canSend ? scheme.onPrimary : theme.hintColor),
),
),
);
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (slash != null) ...[
KeyedSubtree(
key: const ValueKey('draft-slash-palette'),
child: SlashPalette(
items: slashRows,
index: _slashIndex,
loading: _slashLoading,
onPick: _pickSlash,
),
),
const SizedBox(height: 6),
],
CallbackShortcuts(
bindings: slash == null
? const {}
: {
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
_moveSlash(slashRows, 1),
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
_moveSlash(slashRows, -1),
const SingleActivator(LogicalKeyboardKey.enter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.numpadEnter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.escape):
_dismissSlash,
},
child: body,
),
],
);
}
Widget _roundKey(
{required IconData icon,
required String label,
required VoidCallback onTap,
bool busy = false}) {
final theme = Theme.of(context);
return Tooltip(
message: label,
child: InkWell(
borderRadius: BorderRadius.circular(18),
onTap: busy ? null : onTap,
child: Container(
width: 36,
height: 36,
alignment: Alignment.center,
decoration: BoxDecoration(
color: theme.colorScheme.surface,
shape: BoxShape.circle,
),
child: busy
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2))
: Icon(icon, size: 19, color: theme.hintColor),
),
),
);
}
Future<void> _pickProject() async {
final app = widget.app;
await app.refreshProjects();
if (!mounted) return;
final draft = app.draft;
if (draft == null) return;
final projects = _selectableProjects(app.projects);
await showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
expand: false,
initialChildSize: 0.6,
maxChildSize: 0.9,
builder: (context, controller) => Column(
children: [
const Padding(
padding: EdgeInsets.fromLTRB(16, 14, 16, 6),
child: Text('选择项目',
style:
TextStyle(fontSize: 17, fontWeight: FontWeight.w600)),
),
Expanded(
child: ListView(
controller: controller,
children: [
for (final project in projects)
ListTile(
dense: true,
leading: Icon(
project.vcs.isNotEmpty
? Icons.account_tree_outlined
: Icons.folder_outlined,
size: 20),
title: Text(project.label,
maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(project.canonical,
maxLines: 1, overflow: TextOverflow.ellipsis),
trailing: project.canonical == draft.directory
? Icon(Icons.check,
size: 18,
color: Theme.of(context).colorScheme.primary)
: null,
onTap: () {
app.updateDraftTarget(project.canonical);
_slashLoaded = false;
_slashItems = [];
Navigator.pop(context);
},
),
if (projects.isEmpty)
const Padding(
padding: EdgeInsets.all(24),
child: Text('没有可用的项目', textAlign: TextAlign.center),
),
],
),
),
],
),
),
);
}
/// The picker shows checkouts, not the server's chat folders (those are
/// reached by just starting a chat, not by choosing a project). The server
/// can list the same path twice (a project record and a sandbox), so one
/// path is one row, preferring the one that knows its VCS.
List<ProjectInfo> _selectableProjects(List<ProjectInfo> projects) {
final byPath = <String, ProjectInfo>{};
for (final project in projects) {
if (project.canonical.isEmpty) continue;
if (project.canonical.contains('/.config/openchamber/')) continue;
final existing = byPath[project.canonical];
if (existing == null ||
(existing.vcs.isEmpty && project.vcs.isNotEmpty)) {
byPath[project.canonical] = project;
}
}
return byPath.values.toList();
}
}