Files
openchamber-android-native/lib/widgets/directory_picker.dart
T
blumia c6b5a870c6 feat: add a project from the picker, and keep the context ring
- the project picker has an "Add project" action: a folder browser starts
  at the server user's home, navigates (typed path, up, new folder) and
  adds the chosen folder through POST /api/openchamber/directory; the new
  project becomes the draft's target at once
- refreshProjects merges settings-only projects (newest added first), so a
  project added before its first session still appears in the picker; the
  first session moves it into /api/project as usual
- usageReading no longer hides the composer's context ring when the
  session's model has left the server catalog: a 200K window is assumed,
  the percentage is prefixed with "~", and the usage sheet says the window
  is estimated. A failed model fetch at connect is retried when a chat
  opens, so a normal session shows the real percentage
- tests: the add-project browser flow, settings-only projects, and the
  estimated/known context readings
2026-11-27 09:26:14 +08:00

323 lines
9.9 KiB
Dart

// The add-project browser: walks the server's directories from the user's
// home and adds the chosen folder to OpenChamber's project list. A project
// stored only in the settings document (no session yet) is still a valid
// target; the first session in it makes OpenCode list it too.
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../l10n.dart';
import '../state.dart';
/// Opens the folder browser and returns the canonical path that was added, or
/// null when the sheet was dismissed.
Future<String?> showDirectoryPicker(BuildContext context,
{required AppState app}) {
return showModalBottomSheet<String>(
context: context,
isScrollControlled: true,
useSafeArea: true,
builder: (context) => Padding(
// Keep the sheet above the keyboard; the folder list gets the rest.
padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
child: FractionallySizedBox(
heightFactor: 0.9,
child: _DirectoryPickerSheet(app: app),
),
),
);
}
class _DirectoryPickerSheet extends StatefulWidget {
final AppState app;
const _DirectoryPickerSheet({required this.app});
@override
State<_DirectoryPickerSheet> createState() => _DirectoryPickerSheetState();
}
class _DirectoryPickerSheetState extends State<_DirectoryPickerSheet> {
final TextEditingController _pathCtrl = TextEditingController();
String _path = '';
List<FsEntry> _dirs = const [];
bool _loading = true;
bool _adding = false;
String? _error;
AppState get _app => widget.app;
@override
void initState() {
super.initState();
_start();
}
@override
void dispose() {
_pathCtrl.dispose();
super.dispose();
}
Future<void> _start() async {
var home = _app.homeDirectory.trim();
if (home.isEmpty) {
try {
home = (await _app.client?.fsHome())?.home.trim() ?? '';
} catch (_) {
// Fall back to the filesystem root; the path field still works.
}
}
await _open(home.isEmpty ? '/' : home);
}
/// trims a typed path, keeps the root and drops trailing separators.
String _normalize(String path) {
var p = path.trim();
if (p.isEmpty) return '/';
while (p.length > 1 && (p.endsWith('/') || p.endsWith('\\'))) {
p = p.substring(0, p.length - 1);
}
return p.isEmpty ? '/' : p;
}
String _parent(String path) {
final p = _normalize(path);
if (p == '/') return '/';
final index = p.lastIndexOf(RegExp(r'[/\\]'));
if (index <= 0) return '/';
return p.substring(0, index);
}
String _join(String folder) => _path == '/' ? '/$folder' : '$_path/$folder';
Future<void> _open(String path) async {
final target = _normalize(path);
setState(() {
_path = target;
_pathCtrl.text = target;
_loading = true;
_error = null;
});
final client = _app.client;
if (client == null) {
setState(() {
_loading = false;
_error = tr('Not connected to a server');
});
return;
}
try {
final entries =
await client.fsList(target, respectGitignore: false);
final dirs = [
for (final entry in entries)
if (entry.isDirectory) entry,
]..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
if (!mounted) return;
setState(() {
_dirs = dirs;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_dirs = const [];
_loading = false;
_error = trArgs('Could not load this folder: {0}', [e]);
});
}
}
Future<void> _createFolder() async {
final name = await _askFolderName();
if (name == null || !mounted) return;
final client = _app.client;
if (client == null) return;
final target = _join(name);
try {
await client.fsMkdir(target);
if (!mounted) return;
await _open(target);
} catch (e) {
if (!mounted) return;
setState(() => _error = trArgs('Could not create the folder: {0}', [e]));
}
}
Future<String?> _askFolderName() async {
final controller = TextEditingController();
final name = await showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: const AppText('New folder'),
content: TextField(
controller: controller,
autofocus: true,
decoration: InputDecoration(hintText: tr('Folder name')),
onSubmitted: (value) => Navigator.pop(context, value.trim()),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const AppText('Cancel')),
FilledButton(
onPressed: () => Navigator.pop(context, controller.text.trim()),
child: const AppText('Create')),
],
),
);
controller.dispose();
if (name == null || name.isEmpty) return null;
if (name == '.' || name == '..' || name.contains('/') || name.contains('\\')) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: AppText(tr('Enter a valid folder name'))));
}
return null;
}
return name;
}
Future<void> _add() async {
if (_adding || _loading) return;
setState(() {
_adding = true;
_error = null;
});
try {
final project = await _app.addProjectDirectory(_path);
if (!mounted) return;
Navigator.pop(context, project?.canonical ?? _path);
} catch (e) {
if (!mounted) return;
setState(() {
_adding = false;
_error = trArgs('Could not add the project: {0}', [e]);
});
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(4, 6, 12, 0),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.close),
tooltip: tr('Close'),
onPressed: () => Navigator.pop(context)),
const Expanded(
child: AppText('Add project',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 6),
child: TextField(
controller: _pathCtrl,
textInputAction: TextInputAction.go,
onSubmitted: _open,
style: const TextStyle(fontSize: 13, fontFamily: 'monospace'),
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.folder_outlined, size: 18),
hintText: tr('Folder path'),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
suffixIcon: TextButton(
onPressed: () => _open(_pathCtrl.text),
child: const AppText('Go')),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_upward, size: 18),
tooltip: tr('Up'),
onPressed: _path == '/' ? null : () => _open(_parent(_path)),
),
Expanded(
child: Text(
_path,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
),
TextButton.icon(
onPressed: _createFolder,
icon: const Icon(Icons.create_new_folder_outlined, size: 18),
label: const AppText('New folder'),
),
],
),
),
if (_error != null)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 6),
child: Text(_error!,
style: TextStyle(fontSize: 12, color: theme.colorScheme.error)),
),
Expanded(
child: _loading
? const Center(
child: SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2)))
: ListView(
children: [
for (final entry in _dirs)
ListTile(
dense: true,
leading:
const Icon(Icons.folder_outlined, size: 20),
title: Text(entry.name,
maxLines: 1, overflow: TextOverflow.ellipsis),
trailing:
const Icon(Icons.chevron_right, size: 18),
onTap: () => _open(entry.path),
),
if (_dirs.isEmpty && _error == null)
const Padding(
padding: EdgeInsets.all(24),
child: AppText('No folders here',
textAlign: TextAlign.center),
),
],
),
),
SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),
child: SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: _adding || _loading ? null : _add,
icon: _adding
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.add, size: 18),
label: const AppText('Add this folder'),
),
),
),
),
],
);
}
}