import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'app_design.dart'; /// The device's design choice. It lives in this device's (or browser's) own /// preferences and is never sent to a server. const String appDesignKey = 'pipelines.design.v1'; /// The persistence seam for the design choice: an [AppDesign.id]. abstract interface class AppDesignStore { /// The stored id; null when nothing is stored or it cannot be read. Future load(); /// Whether the choice is actually stored. Future save(String id); } /// `shared_preferences` storage. An unreadable store means the default; a /// failed save returns false rather than throwing. class SharedPreferencesAppDesignStore implements AppDesignStore { const SharedPreferencesAppDesignStore(); @override Future load() async { try { return (await SharedPreferences.getInstance()).getString(appDesignKey); } catch (_) { return null; } } @override Future save(String id) async { try { return await (await SharedPreferences.getInstance()).setString( appDesignKey, id, ); } catch (_) { return false; } } } /// An in-memory store for tests and fixtures. class MemoryAppDesignStore implements AppDesignStore { MemoryAppDesignStore([this.id]); String? id; bool failSaves = false; @override Future load() async => id; @override Future save(String id) async { if (failSaves) return false; this.id = id; return true; } } /// The device's app-wide design. The theme hosts listen to it, so a choice /// rebuilds every theme in place without a restart. class AppDesignController extends ChangeNotifier { AppDesignController({AppDesignStore? store}) : _store = store ?? const SharedPreferencesAppDesignStore(); /// The app's own controller, shared by the theme hosts and Settings. static final AppDesignController instance = AppDesignController(); final AppDesignStore _store; AppDesign _design = AppDesign.standard; int _revision = 0; bool _saveFailed = false; AppDesign get design => _design; /// The last choice could not be stored on this device. bool get saveFailed => _saveFailed; /// Reads the stored choice. A choice made while reading wins. Future restore() async { final revision = _revision; final id = await _store.load(); if (revision != _revision || id == null) return; final design = AppDesign.fromId(id); if (design == _design) return; _design = design; notifyListeners(); } /// Applies [design] now and stores it. Future select(AppDesign design) async { _revision++; final revision = _revision; if (design != _design) { _design = design; notifyListeners(); } final saved = await _store.save(design.id); if (revision != _revision || saved != _saveFailed) return; _saveFailed = !saved; notifyListeners(); } }