import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; import '../../../core/servers/server_scope.dart'; /// Where the chats' most-recently-used order is kept on this device. abstract interface class ChatRecencyStore { Future> read(); Future write(List ids); } /// The chats this device used, most recent first, for the quick switcher's /// order with no query. A chat counts as used when it is opened or its pane /// takes focus ([touch]). The list is read once, lazily, and written back on /// every change; a chat touched before the read finished stays in front. class ChatRecency { ChatRecency({ChatRecencyStore? store, this.limit = 200}) : _store = store ?? MemoryChatRecencyStore(); final ChatRecencyStore _store; /// How many chats are remembered. final int limit; List _ids = const []; Future? _loading; /// The remembered chats, most recent first. List get ids => _ids; /// Reads the stored order once; later calls return the same read. Future load() => _loading ??= _read(); Future _read() async { List stored; try { stored = await _store.read(); } catch (_) { stored = const []; } _ids = _merged(_ids, stored); } /// [id] was opened or focused: it moves to the front. void touch(String id) { if (id.isEmpty || (_ids.isNotEmpty && _ids.first == id)) return; _ids = _merged([id], _ids); unawaited(load().then((_) => _write())); } Future _write() async { try { await _store.write(_ids); } catch (_) { // The order is a convenience; the switcher still lists every chat. } } List _merged(List front, List rest) { final seen = {}; return [ for (final id in [...front, ...rest]) if (id.isNotEmpty && seen.add(id)) id, ].take(limit).toList(growable: false); } } class SharedPreferencesChatRecencyStore implements ChatRecencyStore { const SharedPreferencesChatRecencyStore({this.serverScope = ''}); final String serverScope; String get _key => scopedServerKey('pipelines.chat.recency.v1', serverScope); @override Future> read() async { final prefs = await SharedPreferences.getInstance(); return prefs.getStringList(_key) ?? const []; } @override Future write(List ids) async { final prefs = await SharedPreferences.getInstance(); await prefs.setStringList(_key, ids); } } /// An in-memory store for tests and hosts without preferences. class MemoryChatRecencyStore implements ChatRecencyStore { MemoryChatRecencyStore([List? ids]) : ids = ids ?? []; List ids; @override Future> read() async => List.of(ids); @override Future write(List ids) async => this.ids = List.of(ids); }