84 lines
2.5 KiB
Dart
84 lines
2.5 KiB
Dart
import 'dart:async';
|
|
|
|
import '../shell/destination.dart';
|
|
import '../core/storage/ordered_local_storage.dart';
|
|
import 'app_route.dart';
|
|
import 'tab_locations_store.dart';
|
|
import 'tab_location_routes.dart';
|
|
|
|
export 'tab_location_routes.dart';
|
|
|
|
class TabLocations {
|
|
TabLocations(this.store);
|
|
final TabLocationsStore store;
|
|
final routes = <AppDestination, AppRoute>{};
|
|
final _touched = <AppDestination>{};
|
|
AppDestination active = AppDestination.pipelines;
|
|
int revision = 0;
|
|
bool _loaded = false;
|
|
bool _disposed = false;
|
|
bool persistenceFailed = false;
|
|
Future<void> _writes = Future<void>.value();
|
|
|
|
Object get _storageKey => store is SharedPreferencesTabLocationsStore
|
|
? (store as SharedPreferencesTabLocationsStore).key
|
|
: store;
|
|
|
|
void record(AppRoute route, {bool visited = true}) {
|
|
if (_disposed) return;
|
|
active = tabForRoute(route);
|
|
routes[active] = route;
|
|
if (visited) {
|
|
_touched.add(active);
|
|
revision++;
|
|
}
|
|
if (_loaded) _save();
|
|
}
|
|
|
|
/// Slow storage never overwrites navigation made while it was loading.
|
|
Future<AppRoute?> restore({required bool restoreActive}) async {
|
|
TabLocationsSnapshot saved;
|
|
try {
|
|
saved = await orderedLocalStorage(_storageKey, store.load);
|
|
} catch (_) {
|
|
// Keep in-memory navigation, but never overwrite unread stored history.
|
|
persistenceFailed = true;
|
|
return null;
|
|
}
|
|
if (_disposed) return null;
|
|
for (final entry in saved.routes.entries) {
|
|
if (!_touched.contains(entry.key)) routes[entry.key] = entry.value;
|
|
}
|
|
AppRoute? restored;
|
|
if (restoreActive && _touched.isEmpty) {
|
|
active = saved.active;
|
|
restored = routes[active];
|
|
}
|
|
_loaded = true;
|
|
_save();
|
|
return restored;
|
|
}
|
|
|
|
void _save() {
|
|
final snapshot = TabLocationsSnapshot(
|
|
active: active,
|
|
routes: {
|
|
for (final entry in routes.entries)
|
|
entry.key: durableTabRoute(entry.value),
|
|
},
|
|
);
|
|
// Queue the accepted snapshot immediately, before a replacement owner's
|
|
// load can enter the same key's order. Disposal prevents new records, but
|
|
// must not discard the last valid move already accepted from the user.
|
|
_writes = orderedLocalStorage(_storageKey, () => store.save(snapshot))
|
|
.then<void>(
|
|
(saved) => persistenceFailed = !saved,
|
|
onError: (Object _, StackTrace _) => persistenceFailed = true,
|
|
);
|
|
}
|
|
|
|
void dispose() => _disposed = true;
|
|
|
|
Future<void> get settled => _writes;
|
|
}
|