Files
pipelines/app/lib/features/chat/files/files_controller.dart
T

109 lines
2.7 KiB
Dart

import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/directory_listing.dart';
import 'files_models.dart';
class FilesController extends ChangeNotifier {
FilesController({required this.gateway, required this.initialPath});
final ApiGateway gateway;
String initialPath;
bool _started = false;
DirectoryListing? listing;
String? error;
bool loading = false;
bool showHidden = false;
String filter = '';
FilesSort sort = const FilesSort(FilesSortKey.name);
FilesViewMode view = FilesViewMode.list;
int _request = 0;
bool _disposed = false;
bool get missingDirectory => initialPath.trim().isEmpty;
List<DirectoryEntry> get entries {
final current = listing;
if (current == null) return const [];
final needle = filter.trim().toLowerCase();
return sortFileEntries(
current.entries.where(
(entry) =>
(showHidden || !entry.hidden) &&
(needle.isEmpty || entry.name.toLowerCase().contains(needle)),
),
sort,
);
}
Future<void> start() {
_started = true;
return open(initialPath);
}
/// Session metadata can arrive after the retained conversation is mounted.
/// Keep a folder the operator navigated to; otherwise load the new root.
Future<void> updateInitialPath(String path) async {
if (_disposed || path.trim().isEmpty || path == initialPath) return;
final previous = initialPath;
initialPath = path;
if (_started && (listing == null || listing!.path == previous)) {
listing = null;
await open(path);
} else {
_notify();
}
}
Future<void> open(String? path) async {
if (path == null || path.trim().isEmpty) return;
final request = ++_request;
loading = true;
error = null;
_notify();
try {
final next = await listDirectory(gateway, path);
if (_disposed || request != _request) return;
listing = next;
filter = '';
} catch (e) {
if (_disposed || request != _request) return;
error = "Couldn't load this folder.";
} finally {
if (!_disposed && request == _request) {
loading = false;
_notify();
}
}
}
Future<void> retry() => open(listing?.path ?? initialPath);
void toggleHidden(bool value) {
showHidden = value;
_notify();
}
void setFilter(String value) {
filter = value;
_notify();
}
void setSort(FilesSort value) {
sort = value;
_notify();
}
void setView(FilesViewMode value) {
view = value;
_notify();
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
_request++;
super.dispose();
}
}