Rename, move and delete entries from the chat Files panel

Every row and tile menu gains Rename…, Move… and Delete… (folders now
have a menu too). Rename prefills the name with the file's stem selected
and applies the server's name rules inline. Move reuses the chat folder
picker through a FolderPickerPurpose: titled for the entry, confirmed
with Move here, never offering the entry's current folder and keeping a
moved folder's own subtree out of reach. Delete confirms, and when the
server reports a folder with contents asks once more before deleting
recursively. Holding an entry and dropping it on a folder row or tile
moves it there; the target highlights and refuses itself and ancestors.

FilesController performs each request through files_mutations.dart,
shows Renaming…/Moving…/Deleting… progress, reloads the shown folder
afterwards and keeps a refusal in the server's words in the panel's
notice until dismissed.
This commit is contained in:
2026-11-09 01:46:28 +00:00
parent c61490aeb0
commit 4733d4b615
17 changed files with 1005 additions and 87 deletions
@@ -4,6 +4,7 @@ import '../../../core/transport/pipelines_client.dart';
import '../data/directory_listing.dart';
import '../domain/chat_attachment_picker.dart';
import 'files_models.dart';
import 'files_mutations.dart';
import 'files_upload.dart';
class FilesController extends ChangeNotifier {
@@ -28,6 +29,11 @@ class FilesController extends ChangeNotifier {
/// Why the last upload batch failed, until dismissed or a new batch starts.
String? uploadError;
/// The rename, move or delete in flight ("Renaming…"), and why the last one
/// was refused, in the server's words, until dismissed or the next starts.
String? mutationLabel;
String? mutationError;
bool get missingDirectory => initialPath.trim().isEmpty;
String get uploadLabel => uploadTotal <= 1
? 'Uploading…'
@@ -136,6 +142,62 @@ class FilesController extends ChangeNotifier {
_notify();
}
Future<bool> rename(DirectoryEntry entry, String name) async =>
await _mutate('Renaming…', () => renamePath(gateway, entry.path, name)) ==
null;
Future<bool> move(DirectoryEntry entry, String into) async =>
await _mutate('Moving…', () => movePath(gateway, entry.path, into)) ==
null;
/// A folder with contents is refused unless [recursive]; that refusal is
/// returned as [FilesDeleteResult.notEmpty] for the panel to ask about and
/// is not shown as an error.
Future<FilesDeleteResult> delete(
DirectoryEntry entry, {
bool recursive = false,
}) async {
final failure = await _mutate(
'Deleting…',
() => deletePath(gateway, entry.path, recursive: recursive),
report: (error) => !isFolderNotEmptyError(error),
);
if (failure == null) return FilesDeleteResult.deleted;
return isFolderNotEmptyError(failure)
? FilesDeleteResult.notEmpty
: FilesDeleteResult.failed;
}
/// Runs one mutation, then reloads the shown folder whether it succeeded or
/// not (a refusal such as "does not exist" means the listing is stale too).
/// Returns the failure, recorded in [mutationError] unless [report] declines.
Future<Object?> _mutate(
String label,
Future<String> Function() action, {
bool Function(Object error)? report,
}) async {
mutationLabel = label;
mutationError = null;
_notify();
Object? failure;
try {
await action();
} catch (error) {
failure = error;
if (report == null || report(error)) mutationError = '$error';
}
mutationLabel = null;
if (_disposed) return failure;
_notify();
await retry();
return failure;
}
void dismissMutationError() {
mutationError = null;
_notify();
}
void toggleHidden(bool value) {
showHidden = value;
_notify();
@@ -0,0 +1,78 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../data/directory_listing.dart';
import '../ui/sessions/chat_adaptive.dart';
/// Confirms deleting [entry]. A folder is described as deleted only when
/// empty; the server refuses a folder with contents and the panel then asks
/// again with [confirmDeleteRecursive].
Future<bool> confirmDeleteEntry(BuildContext context, DirectoryEntry entry) =>
_confirm(
context,
title: 'Delete “${entry.name}”?',
body: entry.isDir
? 'The folder is removed from the server if it is empty. '
'This cannot be undone.'
: 'The file is removed from the server. This cannot be undone.',
action: 'Delete',
);
/// Asks again once the server reported the folder is not empty; confirming
/// deletes the folder and everything inside it.
Future<bool> confirmDeleteRecursive(
BuildContext context,
DirectoryEntry entry,
) => _confirm(
context,
title: 'Delete “${entry.name}” and its contents?',
body:
'“${entry.name}” is not empty. Delete the folder and everything '
'inside it? This cannot be undone.',
action: 'Delete all',
);
Future<bool> _confirm(
BuildContext context, {
required String title,
required String body,
required String action,
}) async {
final confirmed = chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? await showCupertinoDialog<bool>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: Text(title),
content: Text(body),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () => Navigator.pop(context, true),
child: Text(action),
),
],
),
)
: await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: Text(body),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: Text(action),
),
],
),
);
return confirmed == true;
}
@@ -0,0 +1,74 @@
import 'package:flutter/material.dart';
import '../data/directory_listing.dart';
import 'files_icons.dart';
import 'files_models.dart';
/// Moves [entry] into another listed folder by dragging it there: a press and
/// hold starts the drag (so a touch scroll stays a scroll), the folder row
/// under the pointer highlights, and releasing hands the pair to [onDrop].
///
/// Every entry is a drag source; a folder is also a target, unless the dragged
/// entry is itself or one of its ancestors ([canDropEntryOn]). The server
/// still refuses a same-named target, which the panel's notice then shows.
class FilesDraggableEntry extends StatelessWidget {
const FilesDraggableEntry({
super.key,
required this.entry,
required this.onDrop,
required this.builder,
});
final DirectoryEntry entry;
final void Function(DirectoryEntry dragged, DirectoryEntry folder) onDrop;
/// Builds the row or tile; [targeted] is true while an acceptable entry is
/// held over this folder.
final Widget Function(BuildContext context, bool targeted) builder;
@override
Widget build(BuildContext context) {
if (!entry.isDir) return _source(context, false);
return DragTarget<DirectoryEntry>(
onWillAcceptWithDetails: (details) => canDropEntryOn(details.data, entry),
onAcceptWithDetails: (details) => onDrop(details.data, entry),
builder: (context, candidates, _) =>
_source(context, candidates.isNotEmpty),
);
}
Widget _source(BuildContext context, bool targeted) =>
LongPressDraggable<DirectoryEntry>(
data: entry,
feedback: _DragFeedback(entry: entry),
childWhenDragging: Opacity(
opacity: .4,
child: builder(context, targeted),
),
child: builder(context, targeted),
);
}
/// What travels under the pointer: the entry's icon and name on a raised
/// surface, so it reads as the row being carried.
class _DragFeedback extends StatelessWidget {
const _DragFeedback({required this.entry});
final DirectoryEntry entry;
@override
Widget build(BuildContext context) => Material(
elevation: 4,
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(fileIcon(entry)),
const SizedBox(width: 8),
Text(entry.name),
],
),
),
);
}
+50 -38
View File
@@ -1,12 +1,14 @@
import 'package:flutter/material.dart';
import '../data/directory_listing.dart';
import 'files_drag.dart';
import 'files_icons.dart';
import 'files_models.dart';
import 'files_thumbnail.dart';
/// The folder's entries as the list or the thumbnail grid. Tapping opens a
/// folder or a file through [onTap]; [menu] supplies a file's action menu.
/// folder or a file through [onTap]; [menu] supplies every entry's action
/// menu; holding and dragging an entry onto a folder row calls [onDrop].
class FilesEntries extends StatelessWidget {
const FilesEntries({
super.key,
@@ -15,12 +17,14 @@ class FilesEntries extends StatelessWidget {
required this.endpoint,
required this.onTap,
required this.menu,
required this.onDrop,
});
final List<DirectoryEntry> entries;
final FilesViewMode view;
final String endpoint;
final ValueChanged<DirectoryEntry> onTap;
final Widget Function(DirectoryEntry entry) menu;
final void Function(DirectoryEntry dragged, DirectoryEntry folder) onDrop;
@override
Widget build(BuildContext context) =>
@@ -30,21 +34,25 @@ class FilesEntries extends StatelessWidget {
itemCount: entries.length,
itemBuilder: (_, index) {
final entry = entries[index];
return ListTile(
onTap: () => onTap(entry),
leading: Icon(fileIcon(entry)),
title: Text(entry.name, maxLines: 2, overflow: TextOverflow.ellipsis),
subtitle: Text(
entry.isDir
? 'Folder'
: '${fileModifiedLabel(entry.modified)} · ${fileSizeLabel(entry.size)}',
return FilesDraggableEntry(
entry: entry,
onDrop: onDrop,
builder: (context, targeted) => ListTile(
selected: targeted,
selectedTileColor: Theme.of(context).colorScheme.primaryContainer,
onTap: () => onTap(entry),
leading: Icon(fileIcon(entry)),
title: Text(entry.name, maxLines: 2, overflow: TextOverflow.ellipsis),
subtitle: Text(
entry.isDir
? 'Folder'
: '${fileModifiedLabel(entry.modified)} · ${fileSizeLabel(entry.size)}',
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [if (!entry.isDir) Text(fileKind(entry)), menu(entry)],
),
),
trailing: entry.isDir
? null
: Row(
mainAxisSize: MainAxisSize.min,
children: [Text(fileKind(entry)), menu(entry)],
),
);
},
);
@@ -58,30 +66,34 @@ class FilesEntries extends StatelessWidget {
itemCount: entries.length,
itemBuilder: (_, index) {
final entry = entries[index];
return InkWell(
onTap: () => onTap(entry),
child: Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
children: [
Align(
alignment: Alignment.centerRight,
child: entry.isDir ? const SizedBox(height: 48) : menu(entry),
),
Expanded(
child: Center(
child: FileThumbnail(entry: entry, endpoint: endpoint),
return FilesDraggableEntry(
entry: entry,
onDrop: onDrop,
builder: (context, targeted) => InkWell(
onTap: () => onTap(entry),
child: Card(
color: targeted
? Theme.of(context).colorScheme.primaryContainer
: null,
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
children: [
Align(alignment: Alignment.centerRight, child: menu(entry)),
Expanded(
child: Center(
child: FileThumbnail(entry: entry, endpoint: endpoint),
),
),
),
const SizedBox(height: 8),
Text(
entry.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
),
],
const SizedBox(height: 8),
Text(
entry.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
),
],
),
),
),
),
@@ -0,0 +1,62 @@
import 'package:flutter/material.dart';
import '../data/directory_listing.dart';
import '../ui/folder_picker/folder_picker_purpose.dart';
import '../ui/folder_picker/folder_picker_route.dart';
import 'files_controller.dart';
import 'files_delete_dialog.dart';
import 'files_mutations.dart';
import 'files_rename_dialog.dart';
/// The Files panel's Rename…, Move… and Delete… flows: each asks, then hands
/// the confirmed request to the controller, which performs it, reloads the
/// folder and keeps any refusal for the panel's notice.
Future<void> renameEntry(
BuildContext context,
FilesController controller,
DirectoryEntry entry,
) async {
final name = await showRenameEntryDialog(context, entry);
if (name == null) return;
await controller.rename(entry, name);
}
String _moveTo(String folder) => 'Move to $folder';
/// Browses folders from the shown one. A folder cannot be moved into itself or
/// below, and nothing is offered the folder it is already in.
Future<void> moveEntry(
BuildContext context,
FilesController controller,
DirectoryEntry entry,
) async {
final into = await showFolderPicker(
context,
gateway: controller.gateway,
initialPath: controller.listing?.path,
purpose: FolderPickerPurpose(
title: 'Move “${entry.name}”',
confirmLabel: 'Move here',
describe: _moveTo,
icon: Icons.drive_file_move_outline,
excludedPath: entry.isDir ? entry.path : null,
unchoosablePath: controller.listing?.path,
),
);
if (into == null) return;
await controller.move(entry, into);
}
/// Confirms, deletes, and when the server reports a folder with contents asks
/// once more before deleting recursively.
Future<void> deleteEntry(
BuildContext context,
FilesController controller,
DirectoryEntry entry,
) async {
if (!await confirmDeleteEntry(context, entry)) return;
final result = await controller.delete(entry);
if (result != FilesDeleteResult.notEmpty || !context.mounted) return;
if (!await confirmDeleteRecursive(context, entry)) return;
await controller.delete(entry, recursive: true);
}
@@ -40,6 +40,14 @@ List<DirectoryEntry> sortFileEntries(
return result;
}
/// Whether dragging [dragged] onto [folder] may move it there: only onto a
/// folder, never onto itself, and a folder never into its own subtree. The
/// server repeats these checks and also refuses a same-named target.
bool canDropEntryOn(DirectoryEntry dragged, DirectoryEntry folder) =>
folder.isDir &&
dragged.path != folder.path &&
!(dragged.isDir && isInsideHome(dragged.path, folder.path));
String fileKind(DirectoryEntry entry) => entry.isDir
? 'Folder'
: artifactKind(fileContentType(entry.name), entry.name).name;
@@ -0,0 +1,54 @@
import '../../../core/api_gateway.dart';
/// The phrase a `delete_path` refusal carries when the folder has contents and
/// the request was not recursive (the server's `protocol.FolderNotEmpty`).
const folderNotEmptyPhrase = 'is not empty';
bool isFolderNotEmptyError(Object error) =>
'$error'.contains(folderNotEmptyPhrase);
/// How one delete ended, so the panel can offer the recursive confirmation
/// only when the server asked for it.
enum FilesDeleteResult { deleted, notEmpty, failed }
/// Sends `rename_path`; resolves to the entry's new path.
Future<String> renamePath(ApiGateway gateway, String path, String name) =>
_mutate(gateway, 'rename_path', {'path': path, 'name': name});
/// Sends `move_path`; the entry keeps its name inside [into].
Future<String> movePath(ApiGateway gateway, String path, String into) =>
_mutate(gateway, 'move_path', {'path': path, 'into': into});
/// Sends `delete_path`; a folder with contents is refused unless [recursive].
Future<String> deletePath(
ApiGateway gateway,
String path, {
bool recursive = false,
}) => _mutate(gateway, 'delete_path', {
'path': path,
if (recursive) 'recursive': true,
});
/// Every mutation replies `path_mutated: {path}`; a refusal arrives as the
/// gateway's [ProtocolError] with the server's words and is left to the caller.
Future<String> _mutate(ApiGateway gateway, String type, JsonMap body) async {
final reply = await gateway.call(type, {type: body});
final result = reply['path_mutated'];
if (result is! Map || result['path'] is! String) {
throw StateError('The server did not confirm the $type request.');
}
return result['path'] as String;
}
/// Why [name] cannot be an entry's new name, or null when it can. The same
/// rules the server applies, so a refused name never leaves the dialog.
String? renameNameError(String name) {
final trimmed = name.trim();
if (trimmed.isEmpty) return 'Enter a name.';
if (trimmed == '.' || trimmed == '..') return 'That name is reserved.';
if (trimmed.contains('/') || trimmed.contains('\\')) {
return r'A name cannot contain / or \.';
}
if (trimmed.length > 255) return 'That name is too long.';
return null;
}
+23 -7
View File
@@ -9,6 +9,7 @@ import 'files_controller.dart';
import 'files_drop.dart';
import 'files_drop_area.dart';
import 'files_entries.dart';
import 'files_entry_actions.dart';
import 'files_upload_notice.dart';
import 'files_viewer.dart';
import 'files_header.dart';
@@ -21,8 +22,9 @@ const double filesPanelFraction = .30;
double filesPanelWidth(double available) => (available * filesPanelFraction)
.clamp(filesPanelMinWidth, filesPanelMaxWidth);
/// The two explicit actions of a file's row or tile menu.
enum FileAction { open, download }
/// The actions of an entry's row or tile menu. Open and Download are for
/// files; Rename, Move and Delete apply to files and folders alike.
enum FileAction { open, download, rename, move, delete }
class FilesPanel extends StatefulWidget {
const FilesPanel({
@@ -150,6 +152,8 @@ class _FilesPanelState extends State<FilesPanel> {
? controller.open(entry.path)
: _open(entry),
menu: _menu,
onDrop: (dragged, folder) =>
controller.move(dragged, folder.path),
),
),
if (listing?.truncated == true)
@@ -165,9 +169,9 @@ class _FilesPanelState extends State<FilesPanel> {
);
}
/// Open and Download for one file; a folder has no menu (nothing to save).
/// Open and Download for a file, then Rename, Move and Delete for any entry.
Widget _menu(DirectoryEntry entry) => AppOverflowMenu<FileAction>(
label: 'File actions',
label: entry.isDir ? 'Folder actions' : 'File actions',
sheetTitle: entry.name,
onSelected: (_, action) => switch (action) {
FileAction.open => _open(entry),
@@ -176,10 +180,22 @@ class _FilesPanelState extends State<FilesPanel> {
endpoint: _endpoint,
entry: entry,
),
FileAction.rename => renameEntry(context, controller, entry),
FileAction.move => moveEntry(context, controller, entry),
FileAction.delete => deleteEntry(context, controller, entry),
},
actions: const [
AppMenuAction(value: FileAction.open, label: 'Open'),
AppMenuAction(value: FileAction.download, label: 'Download'),
actions: [
if (!entry.isDir) ...const [
AppMenuAction(value: FileAction.open, label: 'Open'),
AppMenuAction(value: FileAction.download, label: 'Download'),
],
const AppMenuAction(value: FileAction.rename, label: 'Rename…'),
const AppMenuAction(value: FileAction.move, label: 'Move…'),
const AppMenuAction(
value: FileAction.delete,
label: 'Delete…',
destructive: true,
),
],
);
@@ -0,0 +1,131 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../data/directory_listing.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'files_mutations.dart';
/// Asks for [entry]'s new name, prefilled and selected. Resolves to the
/// trimmed name, or null when cancelled. Save stays disabled while the name is
/// invalid ([renameNameError]) or unchanged; the server's refusal of a valid
/// name is reported by the panel, not here.
Future<String?> showRenameEntryDialog(
BuildContext context,
DirectoryEntry entry,
) {
final dialog = _RenameEntryDialog(entry: entry);
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? showCupertinoDialog<String>(context: context, builder: (_) => dialog)
: showDialog<String>(context: context, builder: (_) => dialog);
}
class _RenameEntryDialog extends StatefulWidget {
const _RenameEntryDialog({required this.entry});
final DirectoryEntry entry;
@override
State<_RenameEntryDialog> createState() => _RenameEntryDialogState();
}
class _RenameEntryDialogState extends State<_RenameEntryDialog> {
late final TextEditingController _name =
TextEditingController(text: widget.entry.name)
..selection = TextSelection(
baseOffset: 0,
extentOffset: _stemLength(widget.entry),
);
/// A file's selection stops before its extension, so typing replaces the
/// stem only; a folder or a dot-file is selected whole.
static int _stemLength(DirectoryEntry entry) {
final dot = entry.name.lastIndexOf('.');
return entry.isDir || dot <= 0 ? entry.name.length : dot;
}
@override
void dispose() {
_name.dispose();
super.dispose();
}
void _save() {
final name = _name.text.trim();
if (renameNameError(name) != null || name == widget.entry.name) return;
Navigator.pop(context, name);
}
@override
Widget build(BuildContext context) {
final title = widget.entry.isDir ? 'Rename folder' : 'Rename file';
return ValueListenableBuilder<TextEditingValue>(
valueListenable: _name,
builder: (context, value, _) {
final error = renameNameError(value.text);
final canSave = error == null && value.text.trim() != widget.entry.name;
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoAlertDialog(
title: Text(title),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 8),
CupertinoTextField(
key: const Key('files-rename-field'),
controller: _name,
autofocus: true,
placeholder: 'Name',
onSubmitted: (_) => _save(),
),
if (error != null) ...[
const SizedBox(height: 8),
Text(
error,
style: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
),
],
],
),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: canSave ? _save : null,
child: const Text('Save'),
),
],
);
}
return AlertDialog(
scrollable: true,
title: Text(title),
content: TextField(
key: const Key('files-rename-field'),
controller: _name,
autofocus: true,
onSubmitted: (_) => _save(),
decoration: InputDecoration(
labelText: 'Name',
errorText: error,
errorMaxLines: 2,
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: canSave ? _save : null,
child: const Text('Save'),
),
],
);
},
);
}
}
@@ -4,9 +4,10 @@ import 'package:flutter/material.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'files_controller.dart';
/// The Files panel's upload feedback: a progress strip while files are being
/// stored and the server's refusal (exists, sign in, too large) until the
/// operator dismisses it. Upload failures are separate from the folder error,
/// The Files panel's operation feedback: a progress strip while files are
/// being stored or an entry is being renamed, moved or deleted, and the
/// server's refusal (exists, sign in, too large, not empty, outside home)
/// until the operator dismisses it. These are separate from the folder error,
/// whose Retry reloads the listing.
class FilesUploadNotice extends StatelessWidget {
const FilesUploadNotice({super.key, required this.controller});
@@ -14,14 +15,16 @@ class FilesUploadNotice extends StatelessWidget {
@override
Widget build(BuildContext context) {
final error = controller.uploadError;
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final progress = controller.uploading > 0
? controller.uploadLabel
: controller.mutationLabel;
return Column(
children: [
if (controller.uploading > 0)
if (progress != null)
Semantics(
label: controller.uploadLabel,
label: progress,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Row(
@@ -32,29 +35,50 @@ class FilesUploadNotice extends StatelessWidget {
: const LinearProgressIndicator(),
),
const SizedBox(width: 12),
Text(controller.uploadLabel),
Text(progress),
],
),
),
),
if (error != null)
cupertino
? ChatCupertinoMessage(
message: error,
icon: CupertinoIcons.exclamationmark_circle,
actionLabel: 'Dismiss',
onAction: controller.dismissUploadError,
)
: MaterialBanner(
content: Text(error),
actions: [
TextButton(
onPressed: controller.dismissUploadError,
child: const Text('Dismiss'),
),
],
),
if (controller.uploadError != null)
_Refusal(
cupertino: cupertino,
message: controller.uploadError!,
onDismiss: controller.dismissUploadError,
),
if (controller.mutationError != null)
_Refusal(
cupertino: cupertino,
message: controller.mutationError!,
onDismiss: controller.dismissMutationError,
),
],
);
}
}
class _Refusal extends StatelessWidget {
const _Refusal({
required this.cupertino,
required this.message,
required this.onDismiss,
});
final bool cupertino;
final String message;
final VoidCallback onDismiss;
@override
Widget build(BuildContext context) => cupertino
? ChatCupertinoMessage(
message: message,
icon: CupertinoIcons.exclamationmark_circle,
actionLabel: 'Dismiss',
onAction: onDismiss,
)
: MaterialBanner(
content: Text(message),
actions: [
TextButton(onPressed: onDismiss, child: const Text('Dismiss')),
],
);
}
@@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart';
import '../../../../core/api_gateway.dart';
import '../../data/directory_listing.dart';
import 'folder_picker_purpose.dart';
/// The folder picker's state: the last listing, the folder being loaded, an
/// inline error, the hidden toggle and the filter. Listing goes through the
@@ -11,6 +12,7 @@ class FolderPickerController extends ChangeNotifier {
required this.gateway,
this.initialPath,
this.recentFolders = const [],
this.purpose = FolderPickerPurpose.startChat,
});
final ApiGateway gateway;
@@ -19,6 +21,9 @@ class FolderPickerController extends ChangeNotifier {
/// Every recent chat folder the server reported; [recents] filters them.
final List<String> recentFolders;
/// Which folders may be chosen or entered.
final FolderPickerPurpose purpose;
DirectoryListing? _listing;
String? _error;
String? _failedPath;
@@ -37,8 +42,18 @@ class FolderPickerController extends ChangeNotifier {
/// The home directory once any listing has arrived.
String? get home => _listing?.home;
/// The folder "Start chat here" would use: only a successfully listed one.
String? get selectable => _loading || _error != null ? null : _listing?.path;
/// The folder the confirm button would use: only a successfully listed one
/// that the purpose offers.
String? get selectable {
final path = _listing?.path;
if (_loading || _error != null || path == null) return null;
return purpose.offers(path) ? path : null;
}
/// Whether a listed folder may be entered; the purpose's excluded subtree
/// (a folder being moved) may not.
bool canEnter(DirectoryEntry entry) =>
entry.isDir && !purpose.excludes(entry.path);
bool get atHome => _listing != null && _listing!.parent == null;
@@ -49,7 +49,9 @@ class FolderPickerList extends StatelessWidget {
_EntryRow(
cupertino: cupertino,
entry: entry,
onTap: entry.isDir ? () => controller.open(entry.path) : null,
onTap: controller.canEnter(entry)
? () => controller.open(entry.path)
: null,
),
if (entries.isEmpty)
FolderPickerNote(
@@ -119,7 +121,10 @@ class _EntryRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
final folder = entry.isDir;
final trailing = folder
// A folder the picker may not enter (the one being moved) reads like a
// file: dimmed and without a chevron.
final enabled = onTap != null;
final trailing = enabled
? Row(
mainAxisSize: MainAxisSize.min,
children: [
@@ -137,19 +142,19 @@ class _EntryRow extends StatelessWidget {
key: ValueKey('folder-entry-${entry.path}'),
leading: Icon(
folder ? CupertinoIcons.folder_fill : CupertinoIcons.doc,
color: folder ? null : dim,
color: enabled ? null : dim,
),
title: Text(entry.name, style: folder ? null : TextStyle(color: dim)),
title: Text(entry.name, style: enabled ? null : TextStyle(color: dim)),
trailing: trailing,
onTap: onTap,
);
}
return ListTile(
key: ValueKey('folder-entry-${entry.path}'),
enabled: folder,
enabled: enabled,
leading: Icon(
folder ? Icons.folder : Icons.insert_drive_file_outlined,
color: folder ? Theme.of(context).colorScheme.primary : null,
color: enabled ? Theme.of(context).colorScheme.primary : null,
),
title: Text(entry.name),
trailing: trailing,
@@ -7,24 +7,28 @@ import '../sessions/chat_adaptive.dart';
import 'folder_picker_controller.dart';
import 'folder_picker_list.dart';
import 'folder_picker_parts.dart';
import 'folder_picker_purpose.dart';
const String folderPickerTitle = 'Choose folder';
const String folderPickerStartLabel = 'Start chat here';
/// The folder picker: breadcrumbs, a filter and hidden toggle, the current
/// folder's entries and a prominent "Start chat here". It pops with the chosen
/// absolute path; Back climbs one folder and leaves only at home.
/// folder's entries and a prominent confirm ("Start chat here" by default; the
/// [purpose] names it). It pops with the chosen absolute path; Back climbs one
/// folder and leaves only at home.
class FolderPickerPage extends StatefulWidget {
const FolderPickerPage({
super.key,
required this.gateway,
this.initialPath,
this.recents = const [],
this.purpose = FolderPickerPurpose.startChat,
});
final ApiGateway gateway;
final String? initialPath;
final List<String> recents;
final FolderPickerPurpose purpose;
@override
State<FolderPickerPage> createState() => _FolderPickerPageState();
@@ -35,6 +39,7 @@ class _FolderPickerPageState extends State<FolderPickerPage> {
gateway: widget.gateway,
initialPath: widget.initialPath,
recentFolders: widget.recents,
purpose: widget.purpose,
);
final _filter = TextEditingController();
String? _shownPath;
@@ -96,6 +101,7 @@ class _FolderPickerPageState extends State<FolderPickerPage> {
path: _controller.selectable,
home: _controller.home,
onStart: _start,
purpose: widget.purpose,
),
],
);
@@ -114,7 +120,7 @@ class _FolderPickerPageState extends State<FolderPickerPage> {
cupertino: cupertino,
automaticallyImplyLeading: false,
leading: SegmentedBackButton(cupertino: cupertino, onPressed: _back),
title: folderPickerTitle,
title: widget.purpose.title,
actions: [
if (cupertino)
CupertinoButton(
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import '../../data/directory_listing.dart';
import 'folder_picker_controller.dart';
import 'folder_picker_purpose.dart';
/// The path from `~` to the current folder; every crumb but the last opens
/// that folder. It scrolls so the current folder stays visible.
@@ -196,8 +197,9 @@ class FolderPickerToolbar extends StatelessWidget {
}
}
/// The prominent confirm: names the folder and starts the chat there. It is
/// disabled until a folder is listed (never while loading or after an error).
/// The prominent confirm: names the folder and confirms it for the picker's
/// purpose. It is disabled until an offered folder is listed (never while
/// loading, after an error, or in a folder the purpose does not offer).
class FolderStartBar extends StatelessWidget {
const FolderStartBar({
super.key,
@@ -205,30 +207,32 @@ class FolderStartBar extends StatelessWidget {
required this.path,
required this.home,
required this.onStart,
this.purpose = FolderPickerPurpose.startChat,
});
final bool cupertino;
final String? path;
final String? home;
final VoidCallback onStart;
final FolderPickerPurpose purpose;
@override
Widget build(BuildContext context) {
final where = path == null || home == null
? 'No folder selected'
: 'Start in ${homeRelativeLabel(home!, path!)}';
: purpose.describe(homeRelativeLabel(home!, path!));
final onPressed = path == null ? null : onStart;
final button = cupertino
? CupertinoButton.filled(
key: const Key('folder-picker-start'),
onPressed: onPressed,
child: const Text('Start chat here'),
child: Text(purpose.confirmLabel),
)
: FilledButton.icon(
key: const Key('folder-picker-start'),
onPressed: onPressed,
icon: const Icon(Icons.chat_bubble_outline),
label: const Text('Start chat here'),
icon: Icon(purpose.icon),
label: Text(purpose.confirmLabel),
);
final content = Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
@@ -0,0 +1,47 @@
import 'package:flutter/material.dart';
import '../../data/directory_listing.dart';
String _startIn(String folder) => 'Start in $folder';
/// What the folder picker is choosing a folder for: its title, the confirm
/// button's words and icon, and which listed folders it may offer.
///
/// The default picks where a chat starts. The Files panel's Move uses one that
/// keeps the moved folder's own subtree out of reach and does not offer the
/// folder the entry is already in.
class FolderPickerPurpose {
const FolderPickerPurpose({
required this.title,
required this.confirmLabel,
required this.describe,
required this.icon,
this.excludedPath,
this.unchoosablePath,
});
static const startChat = FolderPickerPurpose(
title: 'Choose folder',
confirmLabel: 'Start chat here',
describe: _startIn,
icon: Icons.chat_bubble_outline,
);
final String title;
final String confirmLabel;
/// The line above the confirm button for a listed folder's `~/…` label.
final String Function(String folderLabel) describe;
final IconData icon;
/// A folder the picker neither enters nor offers, nor anything below it.
final String? excludedPath;
/// One folder the picker enters but does not offer as the choice.
final String? unchoosablePath;
bool excludes(String path) =>
excludedPath != null && isInsideHome(excludedPath!, path);
bool offers(String path) => !excludes(path) && path != unchoosablePath;
}
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../sessions/chat_adaptive.dart';
import 'folder_picker_page.dart';
import 'folder_picker_purpose.dart';
/// At or above this window width the picker is a large dialog over the create
/// dialog; below it, a full-screen page.
@@ -17,12 +18,14 @@ const double _dialogMaxHeight = 900;
/// Opens the folder picker and resolves to the chosen absolute folder, or
/// null when the operator cancels. [initialPath] opens there when the server
/// can list it; [recents] are offered as quick picks at the home level.
/// can list it; [recents] are offered as quick picks at the home level;
/// [purpose] names the choice (a chat's start folder unless given).
Future<String?> showFolderPicker(
BuildContext context, {
required ApiGateway gateway,
String? initialPath,
List<String> recents = const [],
FolderPickerPurpose purpose = FolderPickerPurpose.startChat,
}) {
final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final size = MediaQuery.sizeOf(context);
@@ -32,6 +35,7 @@ Future<String?> showFolderPicker(
gateway: gateway,
initialPath: initialPath,
recents: recents,
purpose: purpose,
);
if (!wide) {
return navigator.push<String>(
@@ -0,0 +1,316 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/chat/data/directory_listing.dart';
import 'package:pipelines_app/features/chat/files/files_controller.dart';
import 'package:pipelines_app/features/chat/files/files_drop.dart';
import 'package:pipelines_app/features/chat/files/files_models.dart';
import 'package:pipelines_app/features/chat/files/files_panel.dart';
import 'package:pipelines_app/features/chat/files/files_urls.dart';
import 'package:pipelines_app/features/chat/files/files_viewer.dart';
const home = '/home';
const shown = '/home/demo';
JsonMap _entry(String parent, String name, {bool dir = false}) => {
'name': name,
'path': '$parent/$name',
'is_dir': dir,
if (!dir) 'size': 12,
};
/// Lists a two-level tree, records every request, and answers each mutation
/// with the path the server would report unless a refusal is queued for it.
class Gateway extends PipelinesClient {
@override
Uri get endpoint => Uri.parse('ws://example.test/connect');
final calls = <(String type, JsonMap fields)>[];
final refusals = <String, String>{};
final tree = <String, List<JsonMap>>{
shown: [
_entry(shown, 'docs', dir: true),
_entry(shown, 'notes.txt'),
_entry(shown, 'other.txt'),
],
'$shown/docs': const [],
};
@override
Stream<JsonMap> get frames => const Stream.empty();
Iterable<JsonMap> bodies(String type) =>
calls.where((c) => c.$1 == type).map((c) => c.$2[type] as JsonMap);
int get listings => calls.where((c) => c.$1 == 'list_directory').length;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type, fields));
if (type == 'list_directory') {
final path =
(fields['list_directory'] as Map?)?['path'] as String? ?? home;
final entries = tree[path];
if (entries == null) throw ProtocolError('$path does not exist');
return {
'directory_listing': {
'path': path,
'home': home,
'parent': path == home
? null
: path.substring(0, path.lastIndexOf('/')),
'entries': entries,
},
};
}
final refusal = refusals.remove(type);
if (refusal != null) throw ProtocolError(refusal);
final body = fields[type] as JsonMap;
final path = body['path'] as String;
final parent = path.substring(0, path.lastIndexOf('/'));
final name = path.substring(path.lastIndexOf('/') + 1);
final result = switch (type) {
'rename_path' => '$parent/${body['name']}',
'move_path' => '${body['into']}/$name',
_ => path,
};
return {
'path_mutated': {'path': result},
};
}
}
void main() {
late FileUrlResolver originalUrls;
setUp(() {
originalUrls = resolveFileUrls;
resolveFileUrls = (_, path) => fileUrls('ws://example.test/connect', path);
});
tearDown(() => resolveFileUrls = originalUrls);
Future<({FilesController controller, Gateway gateway})> pump(
WidgetTester tester,
) async {
final gateway = Gateway();
final controller = FilesController(gateway: gateway, initialPath: shown);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: FilesPanel(
controller: controller,
viewer: const FilesViewer(),
drop: const FilesDrop.unsupported('no drops in tests'),
),
),
),
);
await tester.pumpAndSettle();
expect(gateway.listings, 1);
return (controller: controller, gateway: gateway);
}
Future<void> pickMenu(WidgetTester tester, String menu, String item) async {
await tester.tap(find.byTooltip(menu).first);
await tester.pumpAndSettle();
await tester.tap(find.text(item));
await tester.pumpAndSettle();
}
/// Presses and holds [name], carries it over [folder] and releases.
Future<void> dragOnto(
WidgetTester tester,
String name,
String folder, {
void Function()? whileOver,
}) async {
final gesture = await tester.startGesture(
tester.getCenter(find.text(name)),
);
await tester.pump(kLongPressTimeout + const Duration(milliseconds: 50));
await gesture.moveTo(tester.getCenter(find.text(folder)));
await tester.pump();
whileOver?.call();
await gesture.up();
await tester.pumpAndSettle();
}
testWidgets('Rename… prefills the name, refuses a bad one and sends '
'rename_path, then reloads', (tester) async {
final mounted = await pump(tester);
await pickMenu(tester, 'File actions', 'Rename…');
final field = find.byKey(const Key('files-rename-field'));
expect(tester.widget<TextField>(field).controller!.text, 'notes.txt');
final save = find.widgetWithText(FilledButton, 'Save');
expect(
tester.widget<FilledButton>(save).onPressed,
isNull,
reason: 'an unchanged name is not sent',
);
await tester.enterText(field, 'bad/name');
await tester.pump();
expect(find.text(r'A name cannot contain / or \.'), findsOneWidget);
expect(tester.widget<FilledButton>(save).onPressed, isNull);
await tester.enterText(field, 'renamed.txt');
await tester.pump();
await tester.tap(save);
await tester.pumpAndSettle();
expect(find.byKey(const Key('files-rename-field')), findsNothing);
expect(mounted.gateway.bodies('rename_path').toList(), [
{'path': '$shown/notes.txt', 'name': 'renamed.txt'},
]);
expect(mounted.gateway.listings, 2);
expect(mounted.controller.mutationError, isNull);
});
testWidgets('Cancelling Rename… sends nothing', (tester) async {
final mounted = await pump(tester);
await pickMenu(tester, 'Folder actions', 'Rename…');
expect(find.text('Rename folder'), findsOneWidget);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(mounted.gateway.bodies('rename_path'), isEmpty);
expect(mounted.gateway.listings, 1);
});
testWidgets('Move… browses from the shown folder and sends move_path for '
'the folder chosen with Move here', (tester) async {
final mounted = await pump(tester);
await pickMenu(tester, 'File actions', 'Move…');
expect(find.text('Move “notes.txt”'), findsOneWidget);
final moveHere = find.byKey(const Key('folder-picker-start'));
expect(
tester.widget<FilledButton>(moveHere).onPressed,
isNull,
reason: 'the entry is already in the shown folder',
);
await tester.tap(find.byKey(const ValueKey('folder-entry-$shown/docs')));
await tester.pumpAndSettle();
expect(find.text('Move to ~/demo/docs'), findsOneWidget);
await tester.tap(moveHere);
await tester.pumpAndSettle();
expect(mounted.gateway.bodies('move_path').toList(), [
{'path': '$shown/notes.txt', 'into': '$shown/docs'},
]);
// The panel's first listing, the picker's two, then the panel's reload.
expect(mounted.gateway.listings, 4);
expect(mounted.gateway.calls.last.$2, {
'list_directory': {'path': shown},
});
});
testWidgets('Move… keeps a folder out of its own subtree', (tester) async {
await pump(tester);
await pickMenu(tester, 'Folder actions', 'Move…');
expect(find.text('Move “docs”'), findsOneWidget);
final row = find.byKey(const ValueKey('folder-entry-$shown/docs'));
expect(tester.widget<ListTile>(row).enabled, isFalse);
await tester.tap(row);
await tester.pumpAndSettle();
expect(find.text('Move “docs”'), findsOneWidget, reason: 'not entered');
});
testWidgets('Delete… confirms before sending delete_path', (tester) async {
final mounted = await pump(tester);
await pickMenu(tester, 'File actions', 'Delete…');
expect(find.text('Delete “notes.txt”?'), findsOneWidget);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(mounted.gateway.bodies('delete_path'), isEmpty);
await pickMenu(tester, 'File actions', 'Delete…');
await tester.tap(find.widgetWithText(FilledButton, 'Delete'));
await tester.pumpAndSettle();
expect(mounted.gateway.bodies('delete_path').toList(), [
{'path': '$shown/notes.txt'},
]);
expect(mounted.gateway.listings, 2);
});
testWidgets('A folder with contents asks again, then deletes recursively', (
tester,
) async {
final mounted = await pump(tester);
mounted.gateway.refusals['delete_path'] = '$shown/docs is not empty';
await pickMenu(tester, 'Folder actions', 'Delete…');
await tester.tap(find.widgetWithText(FilledButton, 'Delete'));
await tester.pumpAndSettle();
expect(find.text('Delete “docs” and its contents?'), findsOneWidget);
expect(
mounted.controller.mutationError,
isNull,
reason: 'the not-empty refusal is a question, not an error',
);
await tester.tap(find.text('Delete all'));
await tester.pumpAndSettle();
expect(mounted.gateway.bodies('delete_path').toList(), [
{'path': '$shown/docs'},
{'path': '$shown/docs', 'recursive': true},
]);
expect(mounted.gateway.listings, 3);
});
testWidgets('Holding an entry and dropping it on a folder row moves it', (
tester,
) async {
final mounted = await pump(tester);
await dragOnto(
tester,
'notes.txt',
'docs',
whileOver: () {
final row = find.ancestor(
of: find.text('docs'),
matching: find.byType(ListTile),
);
expect(tester.widget<ListTile>(row).selected, isTrue);
},
);
expect(mounted.gateway.bodies('move_path').toList(), [
{'path': '$shown/notes.txt', 'into': '$shown/docs'},
]);
expect(mounted.gateway.listings, 2);
});
testWidgets('A refused move is shown in the server\'s words until dismissed', (
tester,
) async {
final mounted = await pump(tester);
const refusal = '$shown/docs/notes.txt already exists';
mounted.gateway.refusals['move_path'] = refusal;
await dragOnto(tester, 'notes.txt', 'docs');
expect(find.text(refusal), findsOneWidget);
expect(mounted.gateway.listings, 2, reason: 'reloaded all the same');
await tester.tap(find.text('Dismiss'));
await tester.pumpAndSettle();
expect(find.text(refusal), findsNothing);
});
test('canDropEntryOn refuses files, itself and its own subtree', () {
const docs = DirectoryEntry(
name: 'docs',
path: '$shown/docs',
isDir: true,
isGitRepo: false,
hidden: false,
);
const inner = DirectoryEntry(
name: 'inner',
path: '$shown/docs/inner',
isDir: true,
isGitRepo: false,
hidden: false,
);
const file = DirectoryEntry(
name: 'notes.txt',
path: '$shown/notes.txt',
isDir: false,
isGitRepo: false,
hidden: false,
);
expect(canDropEntryOn(file, docs), isTrue);
expect(canDropEntryOn(docs, file), isFalse);
expect(canDropEntryOn(docs, docs), isFalse);
expect(canDropEntryOn(docs, inner), isFalse);
expect(canDropEntryOn(inner, docs), isTrue);
});
}