import 'package:shared_preferences/shared_preferences.dart'; /// One conversation's persisted composer draft, keyed by session id. /// /// The draft is stored exactly as typed (untrimmed); only the wire copy is /// trimmed. Attachments are intentionally absent: a file handle cannot be /// serialised, and the web build keeps them memory-only too. abstract interface class ChatDraftStore { /// The saved draft, or an empty string when there is none or the store is /// unavailable. Implementations may throw; the controller treats that as /// "nothing saved" and keeps its in-memory draft. Future read(String sessionId); /// Stores [text] exactly. A blank draft removes the entry so the store does /// not grow without bound. Returns false when nothing was stored. Future write(String sessionId, String text); } /// The app's per-session draft keys. Independent of the legacy web/Android /// storage: no old draft is imported or written under an old key. const String chatDraftKeyPrefix = 'pipelines.next.chatDraft.v1.'; /// `shared_preferences`-backed draft storage. /// /// Reads are tolerant and a write reports failure instead of throwing, so the /// composer can keep the in-memory draft and say plainly that it was not saved. class SharedPreferencesChatDraftStore implements ChatDraftStore { const SharedPreferencesChatDraftStore(); Future _preferences() async { try { return await SharedPreferences.getInstance(); } catch (_) { return null; } } @override Future read(String sessionId) async { final preferences = await _preferences(); if (preferences == null) return ''; try { return preferences.getString('$chatDraftKeyPrefix$sessionId') ?? ''; } catch (_) { return ''; } } @override Future write(String sessionId, String text) async { final preferences = await _preferences(); if (preferences == null) return false; try { final key = '$chatDraftKeyPrefix$sessionId'; if (text.isEmpty) return await preferences.remove(key); return await preferences.setString(key, text); } catch (_) { return false; } } } /// An in-memory store for tests and previews. It never touches the platform /// store, so no production preference can be mutated by a fixture. class MemoryChatDraftStore implements ChatDraftStore { MemoryChatDraftStore({Map? drafts}) : _drafts = {...?drafts}; final Map _drafts; bool failReads = false; bool failWrites = false; /// A snapshot of the stored entries, so a test can tell a removed key from an /// empty string. Map get entries => Map.unmodifiable(_drafts); @override Future read(String sessionId) async { if (failReads) throw StateError('Draft storage is unavailable.'); return _drafts[sessionId] ?? ''; } @override Future write(String sessionId, String text) async { if (failWrites) return false; if (text.isEmpty) { _drafts.remove(sessionId); } else { _drafts[sessionId] = text; } return true; } }