Files
pipelines/app/lib/application/tab_locations_store.dart
T

84 lines
2.7 KiB
Dart

import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../core/servers/server_scope.dart';
import '../shell/destination.dart';
import 'app_route.dart';
import 'tab_location_routes.dart';
class TabLocationsSnapshot {
const TabLocationsSnapshot({
this.active = AppDestination.pipelines,
this.routes = const {},
});
final AppDestination active;
final Map<AppDestination, AppRoute> routes;
Map<String, Object> toJson() => {
'version': 1,
'active': active.name,
'routes': {
for (final entry in routes.entries) entry.key.name: entry.value.path,
},
};
static TabLocationsSnapshot decode(String? encoded) {
if (encoded == null) return const TabLocationsSnapshot();
try {
final data = jsonDecode(encoded);
if (data is! Map || data['version'] != 1 || data['routes'] is! Map) {
return const TabLocationsSnapshot();
}
final routes = <AppDestination, AppRoute>{};
for (final entry in (data['routes'] as Map).entries) {
final tab = shellTabDestinations
.where((tab) => tab.name == entry.key)
.firstOrNull;
final path = entry.value;
if (tab == null || path is! String || !path.startsWith('/')) continue;
final route = AppRoute.parse(path);
if (route.path != path || tabForRoute(route) != tab) continue;
routes[tab] = durableTabRoute(route);
}
final active =
shellTabDestinations
.where((tab) => tab.name == data['active'])
.firstOrNull ??
AppDestination.pipelines;
return TabLocationsSnapshot(active: active, routes: routes);
} on FormatException {
return const TabLocationsSnapshot();
}
}
}
abstract interface class TabLocationsStore {
Future<TabLocationsSnapshot> load();
Future<bool> save(TabLocationsSnapshot value);
}
class SharedPreferencesTabLocationsStore implements TabLocationsStore {
const SharedPreferencesTabLocationsStore({required this.scope});
final String scope;
String get key => scopedServerKey('pipelines.next.tabLocations.v1', scope);
@override
Future<TabLocationsSnapshot> load() async {
// Throw on an unreadable store: the controller then preserves stored data
// rather than mistaking it for absent history and writing a partial map.
final preferences = await SharedPreferences.getInstance();
return TabLocationsSnapshot.decode(preferences.getString(key));
}
@override
Future<bool> save(TabLocationsSnapshot value) async {
try {
final preferences = await SharedPreferences.getInstance();
return await preferences.setString(key, jsonEncode(value.toJson()));
} catch (_) {
return false;
}
}
}