import 'package:drift/drift.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../persistence/app_database.dart'; import '../project_state.dart'; part 'recent_projects.g.dart'; @Riverpod(keepAlive: true) RecentProjectsRepository recentProjects(Ref ref) => DriftRecentProjectsRepository(ref.watch(appDatabaseProvider)); abstract interface class RecentProjectsRepository { Future lastTimeline(String projectId); Future rememberTimeline(String projectId, String timelineId); Future> load(); Future save(List projects); } class DriftRecentProjectsRepository implements RecentProjectsRepository { DriftRecentProjectsRepository(this._database); final AppDatabase _database; @override Future lastTimeline(String projectId) => (_database.select(_database.lastOpenedTimelines) ..where((table) => table.projectId.equals(projectId))) .getSingleOrNull() .then((row) => row?.timelineId); @override Future rememberTimeline(String projectId, String timelineId) => _database .into(_database.lastOpenedTimelines) .insertOnConflictUpdate( LastOpenedTimelinesCompanion.insert( projectId: projectId, timelineId: timelineId, ), ); @override Future> load() async { final rows = await (_database.select( _database.recentProjectRecords, )..orderBy([(table) => OrderingTerm.asc(table.position)])).get(); return [ for (final row in rows) RecentProject(id: row.id, name: row.name, path: row.path), ]; } @override Future save(List projects) => _database.transaction(() async { await _database.delete(_database.recentProjectRecords).go(); await _database.batch((batch) { batch.insertAll(_database.recentProjectRecords, [ for (final (position, project) in projects.indexed) RecentProjectRecordsCompanion.insert( id: project.id, name: project.name, path: project.path, position: position, ), ]); }); }); }