diff --git a/CLAUDE.md b/CLAUDE.md index 0146ddc..352b6ac 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1487,6 +1487,18 @@ Working rules for this repo: launcher-pumping test MUST override `interpreterServiceProvider` with the fake and set `juice.ai_offer_seen.v1: true` (unless testing the offer itself). +- **Character library (2026-08-12)** — app-global library of character COPIES + (`characterLibraryProvider`, `loreseer.charlibrary.v1`, NOT session-scoped/ + exported — bestiary posture). Pure copy helpers in + `lib/engine/character_library.dart`: `libraryCopy` (fresh id, `polarityId` + dropped), `campaignCopy` (also role→pc, star cleared). Launcher + `launcher-library` → `CharacterLibraryScreen` (rename/delete-undo + + two-step `library-copy-from-campaign` picker via + `sessionCharactersFromPrefs`); roster `new-from-library` picker → + `CharacterNotifier.addFromLibrary`; `save-library` on the lead-more + + `compact-more-` menus (compact delete gained undo). See + `docs/superpowers/specs/2026-08-12-streamline-library-exclusive-capabilities-design.md`. + ## Workflow system The Claude Code harness (commands, subagents, hooks, permissions) is documented in diff --git a/docs/superpowers/plans/2026-08-12-character-library.md b/docs/superpowers/plans/2026-08-12-character-library.md new file mode 100644 index 0000000..a277660 --- /dev/null +++ b/docs/superpowers/plans/2026-08-12-character-library.md @@ -0,0 +1,817 @@ +# Character Library (PR 1 of streamline epic) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** An app-global character library (library of copies) so heroes are reusable across campaigns — managed from the launcher, imported/saved from the roster. + +**Architecture:** Pure JSON-round-trip copy helpers in the engine; a `CharacterLibraryNotifier` mirroring the bestiary's app-global posture (`loreseer.charlibrary.v1`, NOT session-scoped, NOT exported); a launcher-level manage screen; roster hooks ("From library" in the new-character dialog, "Save to library" on row menus). + +**Tech Stack:** Flutter + flutter_riverpod + shared_preferences (existing rails only; no new deps). + +**Spec:** `docs/superpowers/specs/2026-08-12-streamline-library-exclusive-capabilities-design.md` (Part 1) + +## Global Constraints + +- Copies get FRESH ids and drop `polarityId` (Practical Magic link is campaign-local). +- Campaign import additionally resets `role` to pc and clears `starred`. +- Library key `loreseer.charlibrary.v1` must NOT appear in `sessionScopedKeys` (providers.dart) — that would export it. +- Destructive deletes get the `showUndoSnackbar` treatment (repo doctrine), never a confirm dialog. +- Tests: never construct `GemmaInterpreterService`; launcher-pumping tests MUST override `interpreterServiceProvider` with the fake and set `'loreseer.ai_offer_seen.v1': true` in mock prefs (see existing `test/launcher_welcome_test.dart` for the pattern — copy its setup). +- Widget tests pumping HomeShell/JournalScreen must override asset providers (see `test/` helpers) — the tasks below avoid that by pumping screens directly. +- Format only files you edit (`dart format `), never repo-wide. + +--- + +### Task 1: Pure copy helpers + +**Files:** +- Create: `lib/engine/character_library.dart` +- Test: `test/character_library_copy_test.dart` + +**Interfaces:** +- Consumes: `Character` (`lib/engine/models.dart`, part file `models/character.dart`; `toJson()` omits defaults, `fromJson` tolerant). +- Produces: `Character libraryCopy(Character c, String newId)`, `Character campaignCopy(Character c, String newId)` — used by Tasks 2–5. + +- [ ] **Step 1: Write the failing test** + +```dart +// test/character_library_copy_test.dart +import 'package:flutter_test/flutter_test.dart'; +import 'package:juice_oracle/engine/character_library.dart'; +import 'package:juice_oracle/engine/models.dart'; + +void main() { + final src = Character( + id: 'orig', + name: 'Brakka', + note: 'scarred', + stats: const [CharStat(label: 'STR', value: '14')], + starred: true, + role: CharacterRole.companion, + conditions: const ['poisoned'], + coins: 7, + polarityId: 'pg-1', + dnd: DndSheet.premade(), + ); + + test('libraryCopy: fresh id, polarityId dropped, rest preserved', () { + final copy = libraryCopy(src, 'lib-1'); + expect(copy.id, 'lib-1'); + expect(copy.polarityId, isNull); + expect(copy.name, 'Brakka'); + expect(copy.note, 'scarred'); + expect(copy.stats.single.label, 'STR'); + expect(copy.dnd, isNotNull); + expect(copy.starred, isTrue); // library keeps flags as captured + expect(copy.role, CharacterRole.companion); + expect(copy.conditions, ['poisoned']); + expect(copy.coins, 7); + // Source untouched. + expect(src.id, 'orig'); + expect(src.polarityId, 'pg-1'); + }); + + test('campaignCopy: also resets role to pc and clears starred', () { + final copy = campaignCopy(src, 'camp-1'); + expect(copy.id, 'camp-1'); + expect(copy.polarityId, isNull); + expect(copy.role, CharacterRole.pc); + expect(copy.starred, isFalse); + expect(copy.conditions, ['poisoned']); // play state comes along + expect(copy.dnd, isNotNull); + }); +} +``` + +Note: check `CharStat`'s actual constructor in `lib/engine/models/character.dart` (top of file) before running — if `value` is an int or the parameter names differ, adjust the test's `CharStat` literal to match. Everything else stands. + +- [ ] **Step 2: Run test to verify it fails** + +Run: `flutter test test/character_library_copy_test.dart` +Expected: FAIL — `Error: Couldn't resolve the package 'juice_oracle/engine/character_library.dart'` (file missing). + +- [ ] **Step 3: Write minimal implementation** + +```dart +// lib/engine/character_library.dart +// +// Pure copy helpers for the app-global character library. Copies go through +// JSON so every sheet type rides along without a per-field list. The library +// is a library of COPIES — play state diverges per campaign after the copy. +import 'models.dart'; + +/// Copy for saving INTO the library: fresh [newId]; the Practical-Magic link +/// is dropped because the linked magic record lives in the source campaign's +/// storage and would dangle anywhere else. +Character libraryCopy(Character c, String newId) { + final j = c.toJson() + ..['id'] = newId + ..remove('polarityId'); + return Character.fromJson(j); +} + +/// Copy for importing INTO a campaign roster: everything [libraryCopy] does, +/// plus role reset to pc and star cleared (both are campaign-local flags). +Character campaignCopy(Character c, String newId) { + final j = c.toJson() + ..['id'] = newId + ..remove('polarityId') + ..remove('role') + ..remove('starred'); + return Character.fromJson(j); +} +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `flutter test test/character_library_copy_test.dart` +Expected: PASS (2 tests). + +- [ ] **Step 5: Commit** + +```bash +git add lib/engine/character_library.dart test/character_library_copy_test.dart +git commit -m "feat(library): pure character copy helpers (fresh id, magic link dropped)" +``` + +--- + +### Task 2: CharacterLibraryNotifier (app-global store) + +**Files:** +- Modify: `lib/state/providers.dart` (add notifier + provider right after `bestiaryProvider`, ~line 2111) +- Test: `test/character_library_provider_test.dart` + +**Interfaces:** +- Consumes: `decodePersisted` (providers.dart:88), `prefsProvider`, `Character`, `libraryCopy` (Task 1). +- Produces: `characterLibraryProvider` (`AsyncNotifierProvider>`) with `add(Character)`, `remove(String id)`, `rename(String id, String name)`, `insertAt(int index, Character c)` — used by Tasks 4–5. Key `loreseer.charlibrary.v1`. + +- [ ] **Step 1: Write the failing test** + +```dart +// test/character_library_provider_test.dart +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:juice_oracle/engine/models.dart'; +import 'package:juice_oracle/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('add/remove/rename round-trip and persist app-globally', () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final notifier = container.read(characterLibraryProvider.notifier); + + await notifier.add(const Character(id: 'a', name: 'Brakka')); + await notifier.add(const Character(id: 'b', name: 'Yeva')); + expect((await container.read(characterLibraryProvider.future)).length, 2); + + await notifier.rename('a', 'Brakka the Bold'); + var list = await container.read(characterLibraryProvider.future); + expect(list.firstWhere((c) => c.id == 'a').name, 'Brakka the Bold'); + + await notifier.remove('b'); + list = await container.read(characterLibraryProvider.future); + expect(list.single.id, 'a'); + + // Key is app-global: NOT suffixed with a session id. + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getString('loreseer.charlibrary.v1'), isNotNull); + }); + + test('corrupt storage degrades to empty, corrupt row skipped', () async { + SharedPreferences.setMockInitialValues( + {'loreseer.charlibrary.v1': '[{"id":"ok","name":"Ok"},{"bad":1}]'}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final list = await container.read(characterLibraryProvider.future); + expect(list.single.id, 'ok'); + }); + + test('insertAt restores a deleted row for undo', () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final notifier = container.read(characterLibraryProvider.notifier); + await notifier.add(const Character(id: 'a', name: 'A')); + await notifier.add(const Character(id: 'b', name: 'B')); + await notifier.remove('a'); + await notifier.insertAt(0, const Character(id: 'a', name: 'A')); + final list = await container.read(characterLibraryProvider.future); + expect(list.map((c) => c.id).toList(), ['a', 'b']); + }); +} +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `flutter test test/character_library_provider_test.dart` +Expected: FAIL — `characterLibraryProvider` undefined. + +- [ ] **Step 3: Write minimal implementation** + +Insert after `bestiaryProvider`'s closing declaration (providers.dart ~line 2111), following the `BestiaryNotifier` shape exactly (same tolerant decode; `Character.fromJson` throws on bad rows, so wrap rows like `decodePersistedList` does — reuse it): + +```dart +/// App-global character library — a library of COPIES so heroes are reusable +/// across campaigns. Like [bestiaryProvider]: NOT session-scoped, NOT +/// exported. Copies in/out go through the pure helpers in +/// `lib/engine/character_library.dart` (fresh id, magic link dropped). +class CharacterLibraryNotifier extends AsyncNotifier> { + static const _key = 'loreseer.charlibrary.v1'; + + @override + Future> build() async { + final raw = (await ref.read(prefsProvider.future)).getString(_key); + if (raw == null || raw.isEmpty) return const []; + return decodePersistedList(raw, Character.fromJson); + } + + Future> get _ready async => state.valueOrNull ?? await future; + + Future _save(List list) async { + await (await ref.read(prefsProvider.future)) + .setString(_key, jsonEncode(list.map((c) => c.toJson()).toList())); + state = AsyncData(list); + } + + Future add(Character c) async { + await _save([...await _ready, c]); + } + + Future remove(String id) async { + await _save((await _ready).where((c) => c.id != id).toList()); + } + + Future rename(String id, String name) async { + await _save([ + for (final c in await _ready) c.id == id ? c.copyWith(name: name) : c, + ]); + } + + /// Re-inserts [c] at [index] (clamped) — the delete-undo restore. + Future insertAt(int index, Character c) async { + final list = [...await _ready]; + list.insert(index.clamp(0, list.length), c); + await _save(list); + } +} + +final characterLibraryProvider = + AsyncNotifierProvider>( + CharacterLibraryNotifier.new); +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `flutter test test/character_library_provider_test.dart` +Expected: PASS (3 tests). + +- [ ] **Step 5: Verify the key is NOT exported** + +Run: `grep -n "charlibrary" lib/state/providers.dart lib/state/campaign_io.dart lib/engine/models/session.dart` +Expected: hits ONLY inside `CharacterLibraryNotifier` — none in `sessionScopedKeys` or campaign IO. + +- [ ] **Step 6: Commit** + +```bash +git add lib/state/providers.dart test/character_library_provider_test.dart +git commit -m "feat(library): app-global character library store (loreseer.charlibrary.v1)" +``` + +--- + +### Task 3: Campaign-side import + cross-session roster read + +**Files:** +- Modify: `lib/state/providers.dart` (`CharacterNotifier`, after `addFunnel`; plus one top-level helper near `decodePersistedList`) +- Test: `test/character_library_import_test.dart` + +**Interfaces:** +- Consumes: `campaignCopy` (Task 1), `_newId()` (providers.dart:81), `_PersistedList._persist/_ready`, `decodePersistedList`. +- Produces: + - `Future CharacterNotifier.addFromLibrary(Character libraryEntry)` — copies in at top of roster, returns new id. Used by Task 5. + - `List sessionCharactersFromPrefs(SharedPreferences prefs, String sessionId)` (top-level, sync) — tolerant read of ANY session's roster for the library's "Copy from campaign" picker. Used by Task 4. + +- [ ] **Step 1: Write the failing test** + +```dart +// test/character_library_import_test.dart +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:juice_oracle/engine/models.dart'; +import 'package:juice_oracle/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('addFromLibrary copies with fresh id, pc role, no star/magic link', + () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + const entry = Character( + id: 'lib-1', + name: 'Brakka', + starred: true, + role: CharacterRole.npc, + polarityId: 'pg-9'); + final id = await container + .read(charactersProvider.notifier) + .addFromLibrary(entry); + final roster = await container.read(charactersProvider.future); + final added = roster.firstWhere((c) => c.id == id); + expect(id, isNot('lib-1')); + expect(added.name, 'Brakka'); + expect(added.role, CharacterRole.pc); + expect(added.starred, isFalse); + expect(added.polarityId, isNull); + }); + + test('sessionCharactersFromPrefs reads another session tolerantly', () async { + SharedPreferences.setMockInitialValues({ + 'loreseer.characters.v1.other': + '[{"id":"x","name":"Xa"},{"corrupt":true}]', + }); + final prefs = await SharedPreferences.getInstance(); + final list = sessionCharactersFromPrefs(prefs, 'other'); + expect(list.single.name, 'Xa'); + expect(sessionCharactersFromPrefs(prefs, 'missing'), isEmpty); + }); +} +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `flutter test test/character_library_import_test.dart` +Expected: FAIL — `addFromLibrary` / `sessionCharactersFromPrefs` undefined. + +- [ ] **Step 3: Write minimal implementation** + +In `CharacterNotifier` (providers.dart, after `addFunnel`), add — needs `import '../engine/character_library.dart';` at the top of providers.dart: + +```dart + /// Copies a library entry into this campaign's roster (fresh id, role reset + /// to pc, star + magic link cleared) and returns the new character's id. + Future addFromLibrary(Character libraryEntry) async { + final id = _newId(); + await _persist([campaignCopy(libraryEntry, id), ...await _ready]); + return id; + } +``` + +Top-level, next to `decodePersistedList`: + +```dart +/// Tolerant read of ANY session's roster straight from prefs — the character +/// library's "Copy from campaign" picker needs rosters of campaigns that are +/// not active (the active one comes from [charactersProvider]). +List sessionCharactersFromPrefs( + SharedPreferences prefs, String sessionId) { + final raw = prefs.getString('loreseer.characters.v1.$sessionId'); + if (raw == null || raw.isEmpty) return const []; + return decodePersistedList(raw, Character.fromJson); +} +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `flutter test test/character_library_import_test.dart` +Expected: PASS (2 tests). + +- [ ] **Step 5: Commit** + +```bash +git add lib/state/providers.dart test/character_library_import_test.dart +git commit -m "feat(library): roster import from library + cross-session roster read" +``` + +--- + +### Task 4: Library screen + launcher entry + +**Files:** +- Create: `lib/features/character_library_screen.dart` +- Modify: `lib/features/launcher_screen.dart` (non-pristine branch, after the `launcher-import` ListTile ~line 347) +- Test: `test/character_library_screen_test.dart` + +**Interfaces:** +- Consumes: `characterLibraryProvider` (Task 2), `libraryCopy` (Task 1), `sessionCharactersFromPrefs` (Task 3), `sessionsProvider`, `prefsProvider`, `showUndoSnackbar` (`lib/shared/undo_snackbar.dart`), `campaignSubtitle` (models). +- Produces: `CharacterLibraryScreen` (pushed route). Keys: `library-char-`, `library-rename-`, `library-delete-`, `library-copy-from-campaign`, `library-src-`, `library-src-char-`, launcher entry `launcher-library`. + +- [ ] **Step 1: Write the failing test** + +```dart +// test/character_library_screen_test.dart +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:juice_oracle/features/character_library_screen.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Future pumpLibrary(WidgetTester tester) async { + await tester.pumpWidget(const ProviderScope( + child: MaterialApp(home: CharacterLibraryScreen()))); + await tester.pumpAndSettle(); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('lists entries; delete has undo', (tester) async { + SharedPreferences.setMockInitialValues({ + 'loreseer.charlibrary.v1': '[{"id":"a","name":"Brakka"}]', + }); + await pumpLibrary(tester); + expect(find.text('Brakka'), findsOneWidget); + + await tester.tap(find.byKey(const Key('library-delete-a'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('library-char-a')), findsNothing); + + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('library-char-a')), findsOneWidget); + }); + + testWidgets('copy from campaign imports a copy (magic link dropped)', + (tester) async { + SharedPreferences.setMockInitialValues({ + 'loreseer.sessions.v1': + '{"active":"s1","sessions":[{"id":"s1","name":"Alpha"}]}', + 'loreseer.characters.v1.s1': + '[{"id":"c1","name":"Yeva","polarityId":"pg-1"}]', + }); + await pumpLibrary(tester); + await tester.tap(find.byKey(const Key('library-copy-from-campaign'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('library-src-s1'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('library-src-char-c1'))); + await tester.pumpAndSettle(); + expect(find.text('Yeva'), findsOneWidget); + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString('loreseer.charlibrary.v1')!; + expect(raw, contains('"Yeva"')); + expect(raw, isNot(contains('polarityId'))); + expect(raw, isNot(contains('"id":"c1"'))); // fresh id + }); +} +``` + +Note: check the exact `loreseer.sessions.v1` JSON shape against `SessionsState.toJson`/`fromJson` in `lib/engine/models/session.dart` before running; adjust the fixture keys to match (the registry may carry extra fields — extra absence is fine, key NAMES must match). + +- [ ] **Step 2: Run test to verify it fails** + +Run: `flutter test test/character_library_screen_test.dart` +Expected: FAIL — `character_library_screen.dart` missing. + +- [ ] **Step 3: Implement the screen** + +```dart +// lib/features/character_library_screen.dart +// +// App-global character library manager, opened from the launcher. A library +// of COPIES: nothing here references campaign state, and copying in/out +// always mints fresh ids (see lib/engine/character_library.dart). +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../engine/character_library.dart'; +import '../engine/models.dart'; +import '../shared/undo_snackbar.dart'; +import '../state/providers.dart'; + +class CharacterLibraryScreen extends ConsumerWidget { + const CharacterLibraryScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final entries = + ref.watch(characterLibraryProvider).valueOrNull ?? const []; + return Scaffold( + appBar: AppBar(title: const Text('Character library')), + body: ListView( + children: [ + if (entries.isEmpty) + const Padding( + padding: EdgeInsets.all(24), + child: Text('No saved characters yet. Copy one in from a ' + 'campaign below, or use "Save to library" on a roster ' + 'character.'), + ), + for (final c in entries) + ListTile( + key: Key('library-char-${c.id}'), + title: Text(c.name), + subtitle: c.note.isEmpty + ? null + : Text(c.note, maxLines: 1, overflow: TextOverflow.ellipsis), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + key: Key('library-rename-${c.id}'), + icon: const Icon(Icons.edit_outlined), + tooltip: 'Rename', + onPressed: () => _rename(context, ref, c), + ), + IconButton( + key: Key('library-delete-${c.id}'), + icon: const Icon(Icons.delete_outline), + tooltip: 'Delete', + onPressed: () => _delete(context, ref, c, entries), + ), + ], + ), + ), + const Divider(), + ListTile( + key: const Key('library-copy-from-campaign'), + leading: const Icon(Icons.download_outlined), + title: const Text('Copy from campaign'), + onTap: () => _copyFromCampaign(context, ref), + ), + ], + ), + ); + } + + void _delete(BuildContext context, WidgetRef ref, Character c, + List entries) { + final idx = entries.indexWhere((x) => x.id == c.id); + ref.read(characterLibraryProvider.notifier).remove(c.id); + showUndoSnackbar( + context, + '${c.name} deleted', + () => ref + .read(characterLibraryProvider.notifier) + .insertAt(idx < 0 ? 0 : idx, c)); + } + + Future _rename( + BuildContext context, WidgetRef ref, Character c) async { + final ctrl = TextEditingController(text: c.name); + final name = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Rename'), + content: TextField(controller: ctrl, autofocus: true), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel')), + FilledButton( + onPressed: () => Navigator.pop(context, ctrl.text.trim()), + child: const Text('Save')), + ], + ), + ); + ctrl.dispose(); + if (name == null || name.isEmpty) return; + await ref.read(characterLibraryProvider.notifier).rename(c.id, name); + } + + Future _copyFromCampaign(BuildContext context, WidgetRef ref) async { + final sessions = await ref.read(sessionsProvider.future); + final prefs = await ref.read(prefsProvider.future); + if (!context.mounted) return; + // Step 1: pick a campaign. + final sessionId = await showDialog( + context: context, + builder: (context) => SimpleDialog( + title: const Text('Copy from campaign'), + children: [ + for (final s in sessions.sessions) + SimpleDialogOption( + key: Key('library-src-${s.id}'), + onPressed: () => Navigator.pop(context, s.id), + child: Text(s.name), + ), + ], + ), + ); + if (sessionId == null || !context.mounted) return; + // Step 2: pick a character from that campaign's roster. + final roster = sessionCharactersFromPrefs(prefs, sessionId); + final picked = await showDialog( + context: context, + builder: (context) => SimpleDialog( + title: const Text('Pick a character'), + children: [ + if (roster.isEmpty) + const Padding( + padding: EdgeInsets.all(16), + child: Text('No characters in that campaign.'), + ), + for (final c in roster) + SimpleDialogOption( + key: Key('library-src-char-${c.id}'), + onPressed: () => Navigator.pop(context, c), + child: Text(c.name), + ), + ], + ), + ); + if (picked == null) return; + await ref + .read(characterLibraryProvider.notifier) + .add(libraryCopy(picked, DateTime.now().microsecondsSinceEpoch.toString())); + } +} +``` + +- [ ] **Step 4: Add the launcher entry** + +In `lib/features/launcher_screen.dart`, non-pristine branch, directly after the `launcher-import` ListTile (~line 347; NOT in the pristine branch — first-run stays minimal). Add the import `import 'character_library_screen.dart';` at the top. + +```dart + ListTile( + key: const Key('launcher-library'), + leading: const Icon(Icons.people_outline), + title: const Text('Character library'), + subtitle: const Text('Reusable heroes, shared across ' + 'campaigns'), + onTap: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => const CharacterLibraryScreen())), + ), +``` + +- [ ] **Step 5: Run tests** + +Run: `flutter test test/character_library_screen_test.dart test/launcher_welcome_test.dart test/launcher_first_run_test.dart test/backup_nudge_test.dart` +Expected: all PASS (new screen tests + no launcher regressions). + +- [ ] **Step 6: Format + commit** + +```bash +dart format lib/features/character_library_screen.dart lib/features/launcher_screen.dart +git add lib/features/character_library_screen.dart lib/features/launcher_screen.dart test/character_library_screen_test.dart +git commit -m "feat(library): launcher-level character library screen" +``` + +--- + +### Task 5: Roster hooks (From library / Save to library) + +**Files:** +- Modify: `lib/features/tracker_screen.dart` (new-character dialog `options` list ~line 624 + choice dispatch ~line 798; `lead-more` menu ~line 1298; compact card trailing ~line 1382) +- Test: `test/roster_library_hooks_test.dart` + +**Interfaces:** +- Consumes: `characterLibraryProvider`, `libraryCopy`, `CharacterNotifier.addFromLibrary` (Tasks 1–3). Imports to add in tracker_screen.dart: `import '../engine/character_library.dart';`. +- Produces: keys `new-from-library`, `library-pick-`, menu values `'save-library'` (lead card) and compact menu `compact-more-` with Save to library + Delete-with-undo. + +- [ ] **Step 1: Write the failing test** + +Model the setup on an existing roster widget test — find one with `grep -rln "new-generic\|generate-npc" test/ | head` and copy its pump/override scaffolding (roster tests pump the tracker/sheet pane with mock prefs; do NOT pump HomeShell). Then: + +```dart +// test/roster_library_hooks_test.dart — assertions to hit (scaffolding from +// the existing roster test): + +// 1. Library non-empty → New-character dialog shows 'new-from-library'; +// tapping it lists 'library-pick-'; picking adds to roster with role +// pc, no star, fresh id. +// 2. Library empty → 'new-from-library' absent from the dialog. +// 3. lead-more menu shows 'Save to library'; selecting it adds a library +// entry (assert prefs 'loreseer.charlibrary.v1' contains the name and NOT +// the roster id — fresh id). +// 4. compact-more- menu: 'Save to library' works the same; 'Delete' +// removes with an Undo snackbar that restores. +``` + +Write real tests for all four (mock prefs: `'loreseer.charlibrary.v1': '[{"id":"L1","name":"Brakka"}]'` for 1/3/4, `{}` for 2). + +- [ ] **Step 2: Run to verify they fail** + +Run: `flutter test test/roster_library_hooks_test.dart` +Expected: FAIL — keys not found. + +- [ ] **Step 3: Implement the hooks** + +(a) New-character dialog: in the `options` list builder (~line 624), the "From library" row is NOT a sheet-type option — add it as a separate ListTile above the sheet-type loop inside the dialog Column (before `for (final o in options)`), gated on the library being non-empty: + +```dart + Builder(builder: (context) { + final lib = ref.watch(characterLibraryProvider).valueOrNull ?? + const []; + if (lib.isEmpty) return const SizedBox.shrink(); + return ListTile( + key: const Key('new-from-library'), + title: const Text('From library'), + subtitle: const Text('Copy a saved character into this ' + 'campaign.'), + onTap: () => Navigator.pop(context, 'from-library'), + ); + }), +``` + +In the choice dispatch (after `if (choice == 'generic')` chain start), add: + +```dart + } else if (choice == 'from-library') { + await _addFromLibrary(context); +``` + +And the handler beside `_newIronsworn`: + +```dart + Future _addFromLibrary(BuildContext context) async { + final lib = ref.read(characterLibraryProvider).valueOrNull ?? + const []; + final picked = await showDialog( + context: context, + builder: (context) => SimpleDialog( + title: const Text('From library'), + children: [ + for (final c in lib) + SimpleDialogOption( + key: Key('library-pick-${c.id}'), + onPressed: () => Navigator.pop(context, c), + child: Text(c.name), + ), + ], + ), + ); + if (picked == null) return; + final id = + await ref.read(charactersProvider.notifier).addFromLibrary(picked); + if (mounted) setState(() => _editingId = id); + } +``` + +(b) `lead-more` menu (~line 1298): add case + item: + +```dart + case 'save-library': + ref.read(characterLibraryProvider.notifier).add( + libraryCopy(c, + DateTime.now().microsecondsSinceEpoch.toString())); + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text('${c.name} saved to library'))); +``` + +```dart + const PopupMenuItem( + value: 'save-library', + child: Text('Save to library'), + ), +``` + +(c) Compact card (~line 1382): replace the bare delete IconButton with a `PopupMenuButton` keyed `Key('compact-more-${c.id}')` carrying 'Save to library' (same handler as (b)) and 'Delete' — the delete now goes through `showUndoSnackbar` + `restoreAt` exactly like the lead card's delete case (capture `list`/`idx` from `charactersProvider` before `remove`, mirror lines 1308–1318). + +- [ ] **Step 4: Run tests** + +Run: `flutter test test/roster_library_hooks_test.dart` +Expected: PASS. Then the tracker's own suite: `flutter test test/ -x integration --name ""` is too broad — run the roster-touching files: `flutter test $(grep -rln "tracker_screen" test/ | tr '\n' ' ')` +Expected: all PASS. + +- [ ] **Step 5: Format + commit** + +```bash +dart format lib/features/tracker_screen.dart +git add lib/features/tracker_screen.dart test/roster_library_hooks_test.dart +git commit -m "feat(library): roster From-library import + Save-to-library" +``` + +--- + +### Task 6: Full verify + docs + +**Files:** +- Modify: `CLAUDE.md` (project notes — one bullet), spec status line. + +- [ ] **Step 1: Analyze + full suite** + +Run: `flutter analyze && flutter test` +Expected: no analyzer issues; suite green. If a failure appears, use the final "Failing tests:" block to attribute (NEVER the `+P -F:` progress lines), and treat it as caused by this work until a main-branch baseline proves otherwise. + +- [ ] **Step 2: Add CLAUDE.md project note** + +Append a bullet under Project notes: + +```markdown +- **Character library (2026-08-12)** — app-global library of character COPIES + (`characterLibraryProvider`, `loreseer.charlibrary.v1`, NOT session-scoped/ + exported — bestiary posture). Pure copy helpers in + `lib/engine/character_library.dart`: `libraryCopy` (fresh id, `polarityId` + dropped), `campaignCopy` (also role→pc, star cleared). Launcher + `launcher-library` → `CharacterLibraryScreen` (rename/delete-undo + + two-step `library-copy-from-campaign` picker via + `sessionCharactersFromPrefs`); roster `new-from-library` picker → + `CharacterNotifier.addFromLibrary`; `save-library` on the lead-more + + `compact-more-` menus (compact delete gained undo). See + `docs/superpowers/specs/2026-08-12-streamline-library-exclusive-capabilities-design.md`. +``` + +- [ ] **Step 3: Commit** + +```bash +git add CLAUDE.md +git commit -m "docs: character library project note" +``` diff --git a/docs/superpowers/specs/2026-08-12-streamline-library-exclusive-capabilities-design.md b/docs/superpowers/specs/2026-08-12-streamline-library-exclusive-capabilities-design.md new file mode 100644 index 0000000..609085f --- /dev/null +++ b/docs/superpowers/specs/2026-08-12-streamline-library-exclusive-capabilities-design.md @@ -0,0 +1,185 @@ +# Streamline: cross-campaign character library + single-select capabilities + +**Date:** 2026-08-12 +**Status:** Approved (design), pending implementation +**Decisions made with user:** library-of-copies model; launcher-level library +screen; wizard-picks-one editable later; all four overlap groups in scope; +tables resolved by MERGING into one catalog (not a preference); per-row +"Save to library" on the roster confirmed. + +## Goals + +1. A character roster that lives OUTSIDE any campaign so heroes are reusable + across campaigns. +2. Where multiple enabled tools do the same job (except oracles — explicitly + out of scope), the player picks ONE; the UI never stacks overlapping + control sets. + +## Non-goals + +- Live shared characters (damage in campaign A visible in campaign B). The + library is a library of COPIES; play state diverges per campaign. +- Oracle consolidation. Multiple oracles side-by-side is a feature. +- Back-compat migrations beyond tolerant reads (pre-release posture). + +--- + +## Part 1 — Character library (PR 1) + +### Model & persistence + +- `characterLibraryProvider` / `CharacterLibraryNotifier` in + `lib/state/providers.dart`. Key `loreseer.charlibrary.v1` — **app-global**: + NOT in `sessionScopedKeys`, NOT exported. Same posture as + `bestiaryProvider` / `customTablesProvider`. +- Entries are full `Character` JSON (identity + sheet + play state as + captured). No new model type; reuse `Character.fromJson/toJson` with the + tolerant `decodePersistedList` rail. +- Operations: `add(Character)` (fresh library id), `remove(id)`, + `rename(id, name)`. + +### Copy semantics (both directions) + +- **Save to library** (campaign → library): copy character JSON, mint fresh + id, **drop `polarityId`** (Practical Magic link is campaign-local — the + magic record lives in that campaign's `loreseer.magic.v1`). +- **Add from library** (library → campaign): copy JSON, mint fresh id, drop + `polarityId`, reset `role` to `pc`, clear `starred`. Conditions/HP come + along as captured (user manages). +- Fresh ids on every copy: no dangling journal `char:ID` mentions, no spine + or encounter cross-links, no id collisions. + +### UI + +- **Launcher** (`launcher_screen.dart`): a "Characters" entry opens the + library screen (`lib/features/character_library_screen.dart`): list rows + (name, system/sheet badge, role), per-row rename + delete (delete gets the + standard undo snackbar), and **"Copy from campaign"** — a two-step picker + (campaign from the sessions registry → character from that campaign's + `loreseer.characters.v1.` read via SharedPreferences, tolerant + decode). +- **Roster** (Sheet verb, `tracker_screen.dart` roster): Add menu gains + **"From library"** (`new-from-library`) → picker → copy in; each row's + menu gains **"Save to library"** (`save-to-library-`), confirmed by + snackbar. + +### Testing + +- Notifier round-trip (add/remove/rename, persistence key, tolerant decode). +- Copy semantics unit tests: fresh id, polarityId dropped, role reset on + import, original untouched. +- Widget: library screen list/delete/undo; roster "From library" adds a + character; "Save to library" adds a library entry. + +--- + +## Part 2 — Single-select capabilities (PR 2) + +### Mechanism A: exclusive groups over the existing `systems` set + +- Pure `kExclusiveGroups` in `lib/engine/campaign_surfaces.dart` (or + models.dart beside `kSystemCategory`): + `{'hex-flavor': ['verdant', 'hexcrawl']}` — one group for now; the dungeon + and party cases use the mechanisms below. Structure is a + `Map>` so future overlap groups drop in. +- **Wizard** (`NewCampaignDialog` step 1) and **`_EditSystemsDialog`**: any + system belonging to an exclusive group renders inside a labeled ChoiceChip + row (options + "None") instead of loose FilterChips. Selecting one removes + its siblings from the working set. Legacy campaigns with both enabled keep + working (gates are unchanged); the edit dialog normalizes to one on next + save (keeps the first, drops the rest — deterministic by group order). + +### Dungeon generator exclusivity + +- When `classic-dungeon` is enabled, the Dungeon pane runs classic mode + ONLY: base-mode room generation controls hidden (today both stack). + `classic-dungeon` off → base mode only, unchanged. UI gate in + `map_screen.dart`; no engine change. Existing base-mode rooms in a + classic campaign still render (data untouched, only the generation + controls are gated). + +### Party paradigm + +- The three party surfaces (Party Emulator / Sidekick / NPC Behavior, all + under the `party` flag in `party_tools_pane.dart`) become single-select: + new `SessionMeta.partyTool` (`String`, `'emulator' | 'sidekick' | + 'behavior'`, default `'emulator'`; JSON key `partyTool`, omitted at + default; tolerant parse). `SessionsNotifier.setPartyTool`. +- The party subtab renders ONLY the chosen pane; the SegmentedButton goes + away. Switcher lives in `_EditSystemsDialog` (a small ChoiceChip row shown + when `party` is enabled) and in the wizard step 1 under the party addon. +- Persisted state of the unchosen panes is untouched — switching back + restores it (panes already keep their own state). + +### Testing + +- Pure: exclusive-group normalization (one survivor, deterministic). +- Widget: wizard renders ChoiceChip row for verdant/hexcrawl and result set + never contains both; edit dialog same; party subtab renders exactly one + pane per `partyTool`; dungeon pane hides base generation controls when + classic-dungeon on. + +--- + +## Part 3 — Unified inspiration catalog (PR 3, the big one) + +One browsable catalog replaces three parallel surfaces (24 flavor +generators / built-in table sets + starter pack / My Tables). + +### Engine + +- `lib/engine/inspiration_catalog.dart` (pure): + `CatalogEntry {id, name, CatalogKind kind (generator|table), category, + genre, source, editable}` + `buildCatalog(List generators, + List builtins, List userTables)` returning + category-grouped entries. Reuses the existing table taxonomy + (`kTableCategories`, `groupTablesByCategory`, `matchesTableQuery`); + generators map to categories via their `GenSection`. +- Built-in table sets ship as data through the existing starter rail: + `starter_tables.json` entries appear IN the catalog directly as read-only + built-ins; the one-tap "import starter pack" button dies (no more + copy-into-My-Tables step). `build_starter_tables.py` unchanged as the + source of truth. + +### UI + +- **Ask → Tables** (`tables_screen.dart`) becomes the catalog: one + searchable, category-grouped tree of ALL entries. Generator rows roll via + their existing `Oracle` functions; table rows via `rollCustomTable` / + `rollNotation`. User entries keep edit affordances (`showCustomTableDialog`); + built-ins read-only. Search spans name/genre/category/source across kinds. +- **GenerateSheet** (`generate_sheet.dart`) renders the SAME catalog in its + category sections (Visual & Stateful section for the three bespoke + generators is unchanged — those need their custom renderers). +- All rolls keep the `addResult` pipeline and existing `sourceTool` + provenance tags (`gen-*`, `'custom-table'`) so journal history and Inspire + keep working unchanged. +- My Tables authoring (editor, packs import/export) unchanged — user tables + are simply entries in the same catalog. + +### Testing + +- Pure: `buildCatalog` merges three sources, category grouping, search + matching across kinds, built-ins flagged read-only. +- Widget: Tables tab shows generators + built-ins + user tables in one tree; + rolling each kind logs a journal entry with the right sourceTool; edit + reachable only on user entries; GenerateSheet renders from the catalog. + +--- + +## Rollout + +Three PRs in order: (1) character library, (2) exclusivity + partyTool, +(3) catalog merge. Each PR: tests above + `flutter analyze` + full suite + +device verify (macOS) per repo habit. CLAUDE.md project-notes update rides +each PR. + +## Risks / notes + +- Library "Copy from campaign" reads another session's SharedPreferences + key directly; uses the tolerant decode rail so a corrupt campaign can't + brick the picker. +- Catalog merge touches the Inspire seed path only via provenance tags — + no seam changes; `inspireGenResult`/`inspireEntry` contracts untouched. +- Exclusive groups deliberately do NOT hard-migrate stored `systems` sets; + normalization happens on next edit-dialog save. Gates tolerate both-on. diff --git a/lib/engine/character_library.dart b/lib/engine/character_library.dart new file mode 100644 index 0000000..8d44067 --- /dev/null +++ b/lib/engine/character_library.dart @@ -0,0 +1,61 @@ +// Pure copy helpers for the app-global character library. Copies go through +// JSON so every sheet type rides along without a per-field list. The library +// is a library of COPIES — play state diverges per campaign after the copy. +import 'models.dart'; + +/// Copy for saving INTO the library: fresh [newId]; the Practical-Magic link +/// is dropped because the linked magic record lives in the source campaign's +/// storage and would dangle anywhere else. +Character libraryCopy(Character c, String newId) { + final j = c.toJson() + ..['id'] = newId + ..remove('polarityId'); + return Character.fromJson(j); +} + +/// Copy for importing INTO a campaign roster: everything [libraryCopy] does, +/// plus role reset to pc and star cleared (both are campaign-local flags). +Character campaignCopy(Character c, String newId) { + final j = c.toJson() + ..['id'] = newId + ..remove('polarityId') + ..remove('role') + ..remove('starred'); + return Character.fromJson(j); +} + +/// Human sheet-system label for library rows/pickers, by non-null sheet +/// field. Sundered Isles shares [Character.starforged], so it reads plain +/// 'Starforged' here too. 'Generic' when no sheet field is set. +String sheetLabel(Character c) { + if (c.ironsworn != null) return 'Ironsworn'; + if (c.starforged != null) return 'Starforged'; + if (c.dnd != null) return 'D&D 5e'; + if (c.shadowdark != null) return 'Shadowdark'; + if (c.nimble != null) return 'Nimble'; + if (c.drawSteel != null) return 'Draw Steel'; + if (c.argosa != null) return 'Tales of Argosa'; + if (c.cairn != null) return 'Cairn'; + if (c.knave != null) return 'Knave'; + if (c.embark != null) return 'Embark'; + if (c.ose != null) return 'OSE'; + if (c.kalArath != null) return 'Kal-Arath'; + if (c.custom != null) return 'Custom'; + if (c.dcc != null) return 'DCC'; + if (c.funnel != null) return '0-Level Funnel'; + return 'Generic'; +} + +String _roleLabel(CharacterRole r) => switch (r) { + CharacterRole.pc => 'PC', + CharacterRole.companion => 'Companion', + CharacterRole.npc => 'NPC', + }; + +/// Row/picker badge text: [sheetLabel] plus the role, omitted for the +/// default `pc` (e.g. "D&D 5e" or "Cairn · Companion"). +String sheetRoleBadge(Character c) { + final label = sheetLabel(c); + if (c.role == CharacterRole.pc) return label; + return '$label · ${_roleLabel(c.role)}'; +} diff --git a/lib/features/character_library_screen.dart b/lib/features/character_library_screen.dart new file mode 100644 index 0000000..96a104e --- /dev/null +++ b/lib/features/character_library_screen.dart @@ -0,0 +1,170 @@ +// App-global character library manager, opened from the launcher. A library +// of COPIES: nothing here references campaign state, and copying in/out +// always mints fresh ids (see lib/engine/character_library.dart). +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../engine/character_library.dart'; +import '../engine/models.dart'; +import '../shared/undo_snackbar.dart'; +import '../state/providers.dart'; + +class CharacterLibraryScreen extends ConsumerWidget { + const CharacterLibraryScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final entries = + ref.watch(characterLibraryProvider).valueOrNull ?? const []; + return Scaffold( + appBar: AppBar(title: const Text('Character library')), + body: ListView( + children: [ + if (entries.isEmpty) + const Padding( + padding: EdgeInsets.all(24), + child: Text('No saved characters yet. Copy one in from a ' + 'campaign below, or use "Save to library" on a roster ' + 'character.'), + ), + for (final c in entries) + ListTile( + key: Key('library-char-${c.id}'), + title: Text(c.name), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(sheetRoleBadge(c)), + if (c.note.isNotEmpty) + Text(c.note, maxLines: 1, overflow: TextOverflow.ellipsis), + ], + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + key: Key('library-rename-${c.id}'), + icon: const Icon(Icons.edit_outlined), + tooltip: 'Rename', + onPressed: () => _rename(context, ref, c), + ), + IconButton( + key: Key('library-delete-${c.id}'), + icon: const Icon(Icons.delete_outline), + tooltip: 'Delete', + onPressed: () => _delete(context, ref, c, entries), + ), + ], + ), + ), + const Divider(), + ListTile( + key: const Key('library-copy-from-campaign'), + leading: const Icon(Icons.download_outlined), + title: const Text('Copy from campaign'), + onTap: () => _copyFromCampaign(context, ref), + ), + ], + ), + ); + } + + void _delete(BuildContext context, WidgetRef ref, Character c, + List entries) { + final idx = entries.indexWhere((x) => x.id == c.id); + // Captured before the snackbar shows: the snackbar's undo callback fires + // later, and a popped/rebuilt ConsumerWidget's `ref` may already be dead + // by then. + final notifier = ref.read(characterLibraryProvider.notifier); + notifier.remove(c.id); + showUndoSnackbar(context, '${c.name} deleted', + () => notifier.insertAt(idx < 0 ? 0 : idx, c)); + } + + Future _rename(BuildContext context, WidgetRef ref, Character c) async { + final ctrl = TextEditingController(text: c.name); + final name = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Rename'), + content: TextField(controller: ctrl, autofocus: true), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel')), + FilledButton( + onPressed: () => Navigator.pop(context, ctrl.text.trim()), + child: const Text('Save')), + ], + ), + ); + ctrl.dispose(); + if (name == null || name.isEmpty) return; + await ref.read(characterLibraryProvider.notifier).rename(c.id, name); + } + + Future _copyFromCampaign(BuildContext context, WidgetRef ref) async { + final sessions = await ref.read(sessionsProvider.future); + final prefs = await ref.read(prefsProvider.future); + if (!context.mounted) return; + // Step 1: pick a campaign. + final sessionId = await showDialog( + context: context, + builder: (context) => SimpleDialog( + title: const Text('Copy from campaign'), + children: [ + for (final s in sessions.sessions) + SimpleDialogOption( + key: Key('library-src-${s.id}'), + onPressed: () => Navigator.pop(context, s.id), + child: Text(s.name), + ), + SimpleDialogOption( + key: const Key('library-src-cancel'), + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ], + ), + ); + if (sessionId == null || !context.mounted) return; + // Step 2: pick a character from that campaign's roster. + final roster = sessionCharactersFromPrefs(prefs, sessionId); + final picked = await showDialog( + context: context, + builder: (context) => SimpleDialog( + title: const Text('Pick a character'), + children: [ + if (roster.isEmpty) + const Padding( + padding: EdgeInsets.all(16), + child: Text('No characters in that campaign.'), + ), + for (final c in roster) + SimpleDialogOption( + key: Key('library-src-char-${c.id}'), + onPressed: () => Navigator.pop(context, c), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(c.name), + Text(sheetRoleBadge(c), + style: Theme.of(context).textTheme.bodySmall), + ], + ), + ), + SimpleDialogOption( + key: const Key('library-src-char-cancel'), + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ], + ), + ); + if (picked == null) return; + await ref.read(characterLibraryProvider.notifier).add( + libraryCopy(picked, DateTime.now().microsecondsSinceEpoch.toString())); + } +} diff --git a/lib/features/launcher_screen.dart b/lib/features/launcher_screen.dart index 8781560..8563836 100644 --- a/lib/features/launcher_screen.dart +++ b/lib/features/launcher_screen.dart @@ -19,6 +19,7 @@ import '../shared/shell_route.dart'; import '../state/play_context.dart'; import '../state/providers.dart'; import 'ai_offer_dialog.dart'; +import 'character_library_screen.dart'; import 'enter_campaign.dart'; /// Startup campaign menu: Continue / switch / New / Import. Shown while @@ -345,6 +346,15 @@ class LauncherScreen extends ConsumerWidget { title: const Text('Import from file'), onTap: () => _import(context, ref), ), + ListTile( + key: const Key('launcher-library'), + leading: const Icon(Icons.people_outline), + title: const Text('Character library'), + subtitle: const Text('Reusable heroes, shared across ' + 'campaigns'), + onTap: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => const CharacterLibraryScreen())), + ), ], ], ), diff --git a/lib/features/tracker_screen.dart b/lib/features/tracker_screen.dart index 075e885..5346dff 100644 --- a/lib/features/tracker_screen.dart +++ b/lib/features/tracker_screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../engine/character_library.dart'; import '../engine/dice.dart'; import '../engine/mention_parser.dart'; import '../engine/models.dart'; @@ -602,7 +603,18 @@ class CharactersPaneState extends ConsumerState { final systems = ref.read(sessionsProvider).valueOrNull?.activeMeta.enabledSystems ?? kAllSystems; - if (!systems.contains('ironsworn') && + // Read once, before any early return or dialog opens: a `ref.watch` + // inside the dialog's own Builder wouldn't rebuild it (the dialog route + // sits outside this widget's element subtree, so a provider update only + // marks THIS state dirty, not the already-mounted dialog) — a snapshot is + // correct here since the library can't change while the picker is open. + // Hoisted above the guard below so a non-empty library still opens the + // picker even with no sheet-type system enabled (From-library must stay + // reachable in e.g. a ruleset-none campaign). + final lib = await ref.read(characterLibraryProvider.future); + if (!context.mounted) return; + if (lib.isEmpty && + !systems.contains('ironsworn') && !systems.contains('dnd') && !systems.contains('shadowdark') && !systems.contains('nimble') && @@ -756,6 +768,14 @@ class CharactersPaneState extends ConsumerState { child: Text('Choose a sheet type.'), ), const SizedBox(height: 4), + if (lib.isNotEmpty) + ListTile( + key: const Key('new-from-library'), + title: const Text('From library'), + subtitle: const Text( + 'Copy a saved character into this campaign.'), + onTap: () => Navigator.pop(context, 'from-library'), + ), for (final o in options) ListTile( key: Key(o.key), @@ -797,6 +817,8 @@ class CharactersPaneState extends ConsumerState { if (!context.mounted) return; if (choice == 'generic') { await _addCharacter(context); + } else if (choice == 'from-library') { + await _addFromLibrary(context); } else if (choice == 'ironsworn') { await _newIronsworn(); } else if (choice == 'starforged') { @@ -832,6 +854,42 @@ class CharactersPaneState extends ConsumerState { } } + Future _addFromLibrary(BuildContext context) async { + final lib = + ref.read(characterLibraryProvider).valueOrNull ?? const []; + final picked = await showDialog( + context: context, + builder: (context) => SimpleDialog( + title: const Text('From library'), + children: [ + for (final c in lib) + SimpleDialogOption( + key: Key('library-pick-${c.id}'), + onPressed: () => Navigator.pop(context, c), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(c.name), + Text(sheetRoleBadge(c), + style: Theme.of(context).textTheme.bodySmall), + ], + ), + ), + SimpleDialogOption( + key: const Key('library-pick-cancel'), + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ], + ), + ); + if (picked == null) return; + final id = + await ref.read(charactersProvider.notifier).addFromLibrary(picked); + if (mounted) setState(() => _editingId = id); + } + Future _newIronsworn() async { // Ensure a base Ironsworn ruleset is active so the asset picker has data. final rs = ref.read(rulesetsProvider).valueOrNull ?? const {}; @@ -1049,6 +1107,18 @@ class CharactersPaneState extends ConsumerState { ); } + /// Saves a copy of [c] into the app-global character library (fresh id, + /// magic link dropped — see [libraryCopy]). Shared by the lead-more and + /// compact-more menus. + Future _saveToLibrary(BuildContext context, Character c) async { + await ref + .read(characterLibraryProvider.notifier) + .add(libraryCopy(c, DateTime.now().microsecondsSinceEpoch.toString())); + if (!context.mounted) return; + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('${c.name} saved to library'))); + } + /// The role re-tag menu, shared by both variants. Key `role-` must stay /// findable. Widget _roleMenu(Character c) => PopupMenuButton( @@ -1305,6 +1375,8 @@ class CharactersPaneState extends ConsumerState { ref .read(charactersProvider.notifier) .toggleStarred(c.id); + case 'save-library': + _saveToLibrary(context, c); case 'delete': final list = ref.read(charactersProvider).valueOrNull ?? const []; @@ -1323,6 +1395,10 @@ class CharactersPaneState extends ConsumerState { value: 'star', child: Text(c.starred ? 'Unstar' : 'Star'), ), + const PopupMenuItem( + value: 'save-library', + child: Text('Save to library'), + ), const PopupMenuItem( value: 'delete', child: Text('Delete'), @@ -1383,10 +1459,37 @@ class CharactersPaneState extends ConsumerState { children: [ _roleMenu(c), _starButton(c), - IconButton( - icon: const Icon(Icons.delete_outline), - onPressed: () => - ref.read(charactersProvider.notifier).remove(c.id), + PopupMenuButton( + key: Key('compact-more-${c.id}'), + tooltip: 'More', + icon: const Icon(Icons.more_vert), + onSelected: (v) { + switch (v) { + case 'save-library': + _saveToLibrary(context, c); + case 'delete': + final list = ref.read(charactersProvider).valueOrNull ?? + const []; + final idx = list.indexWhere((x) => x.id == c.id); + ref.read(charactersProvider.notifier).remove(c.id); + showUndoSnackbar( + context, + '${c.name} deleted', + () => ref + .read(charactersProvider.notifier) + .restoreAt(idx < 0 ? 0 : idx, c)); + } + }, + itemBuilder: (_) => const [ + PopupMenuItem( + value: 'save-library', + child: Text('Save to library'), + ), + PopupMenuItem( + value: 'delete', + child: Text('Delete'), + ), + ], ), ], ), diff --git a/lib/state/providers.dart b/lib/state/providers.dart index 3e3014a..7491b73 100644 --- a/lib/state/providers.dart +++ b/lib/state/providers.dart @@ -34,6 +34,7 @@ import '../engine/oracle_data.dart'; import '../engine/custom_sheet.dart'; import '../engine/constructed_oracle.dart'; import '../engine/custom_table.dart'; +import '../engine/character_library.dart'; import '../engine/system_primer.dart'; import '../engine/quick_ref.dart'; import '../engine/spell.dart'; @@ -114,6 +115,16 @@ List decodePersistedList( } } +/// Tolerant read of ANY session's roster straight from prefs — the character +/// library's "Copy from campaign" picker needs rosters of campaigns that are +/// not active (the active one comes from [charactersProvider]). +List sessionCharactersFromPrefs( + SharedPreferences prefs, String sessionId) { + final raw = prefs.getString('loreseer.characters.v1.$sessionId'); + if (raw == null || raw.isEmpty) return const []; + return decodePersistedList(raw, Character.fromJson); +} + /// App-global boolean flag behind one SharedPreferences key. /// /// Deliberately NOT session-scoped and NOT exported: these are per-device @@ -515,6 +526,14 @@ class CharacterNotifier extends _PersistedList { return id; } + /// Copies a library entry into this campaign's roster (fresh id, role reset + /// to pc, star + magic link cleared) and returns the new character's id. + Future addFromLibrary(Character libraryEntry) async { + final id = _newId(); + await _persist([campaignCopy(libraryEntry, id), ...await _ready]); + return id; + } + /// Spawns a hero Character built by [buildHero] (top of roster) and marks /// peasant [index] of [funnelChar] graduated — in one persist. Returns the /// hero's id. @@ -2110,6 +2129,54 @@ final bestiaryProvider = AsyncNotifierProvider>( BestiaryNotifier.new); +/// App-global character library — a library of COPIES so heroes are reusable +/// across campaigns. Like [bestiaryProvider]: NOT session-scoped, NOT +/// exported. Copies in/out go through the pure helpers in +/// `lib/engine/character_library.dart` (fresh id, magic link dropped). +class CharacterLibraryNotifier extends AsyncNotifier> { + static const _key = 'loreseer.charlibrary.v1'; + + @override + Future> build() async { + final raw = (await ref.read(prefsProvider.future)).getString(_key); + if (raw == null || raw.isEmpty) return const []; + return decodePersistedList(raw, Character.fromJson); + } + + Future> get _ready async => state.valueOrNull ?? await future; + + Future _save(List list) async { + await (await ref.read(prefsProvider.future)) + .setString(_key, jsonEncode(list.map((c) => c.toJson()).toList())); + state = AsyncData(list); + } + + Future add(Character c) async { + await _save([...await _ready, c]); + } + + Future remove(String id) async { + await _save((await _ready).where((c) => c.id != id).toList()); + } + + Future rename(String id, String name) async { + await _save([ + for (final c in await _ready) c.id == id ? c.copyWith(name: name) : c, + ]); + } + + /// Re-inserts [c] at [index] (clamped) — the delete-undo restore. + Future insertAt(int index, Character c) async { + final list = [...await _ready]; + list.insert(index.clamp(0, list.length), c); + await _save(list); + } +} + +final characterLibraryProvider = + AsyncNotifierProvider>( + CharacterLibraryNotifier.new); + /// App-global store of user-authored random tables. Like [bestiaryProvider], /// this is NOT session-scoped and NOT exported — tables are reusable across /// campaigns and live per-device. diff --git a/test/character_library_copy_test.dart b/test/character_library_copy_test.dart new file mode 100644 index 0000000..68b483f --- /dev/null +++ b/test/character_library_copy_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/engine/character_library.dart'; +import 'package:loreseer/engine/models.dart'; + +void main() { + final src = Character( + id: 'orig', + name: 'Brakka', + note: 'scarred', + stats: const [CharStat(label: 'STR', value: '14')], + starred: true, + role: CharacterRole.companion, + conditions: const ['poisoned'], + coins: 7, + polarityId: 'pg-1', + dnd: DndSheet.premade(), + ); + + test('libraryCopy: fresh id, polarityId dropped, rest preserved', () { + final copy = libraryCopy(src, 'lib-1'); + expect(copy.id, 'lib-1'); + expect(copy.polarityId, isNull); + expect(copy.name, 'Brakka'); + expect(copy.note, 'scarred'); + expect(copy.stats.single.label, 'STR'); + expect(copy.dnd, isNotNull); + expect(copy.starred, isTrue); // library keeps flags as captured + expect(copy.role, CharacterRole.companion); + expect(copy.conditions, ['poisoned']); + expect(copy.coins, 7); + // Source untouched. + expect(src.id, 'orig'); + expect(src.polarityId, 'pg-1'); + }); + + test('campaignCopy: also resets role to pc and clears starred', () { + final copy = campaignCopy(src, 'camp-1'); + expect(copy.id, 'camp-1'); + expect(copy.polarityId, isNull); + expect(copy.role, CharacterRole.pc); + expect(copy.starred, isFalse); + expect(copy.conditions, ['poisoned']); // play state comes along + expect(copy.dnd, isNotNull); + }); +} diff --git a/test/character_library_import_test.dart b/test/character_library_import_test.dart new file mode 100644 index 0000000..930862b --- /dev/null +++ b/test/character_library_import_test.dart @@ -0,0 +1,42 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/engine/models.dart'; +import 'package:loreseer/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('addFromLibrary copies with fresh id, pc role, no star/magic link', + () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + const entry = Character( + id: 'lib-1', + name: 'Brakka', + starred: true, + role: CharacterRole.npc, + polarityId: 'pg-9'); + final id = + await container.read(charactersProvider.notifier).addFromLibrary(entry); + final roster = await container.read(charactersProvider.future); + final added = roster.firstWhere((c) => c.id == id); + expect(id, isNot('lib-1')); + expect(added.name, 'Brakka'); + expect(added.role, CharacterRole.pc); + expect(added.starred, isFalse); + expect(added.polarityId, isNull); + }); + + test('sessionCharactersFromPrefs reads another session tolerantly', () async { + SharedPreferences.setMockInitialValues({ + 'loreseer.characters.v1.other': + '[{"id":"x","name":"Xa"},{"corrupt":true}]', + }); + final prefs = await SharedPreferences.getInstance(); + final list = sessionCharactersFromPrefs(prefs, 'other'); + expect(list.single.name, 'Xa'); + expect(sessionCharactersFromPrefs(prefs, 'missing'), isEmpty); + }); +} diff --git a/test/character_library_labels_test.dart b/test/character_library_labels_test.dart new file mode 100644 index 0000000..89b7445 --- /dev/null +++ b/test/character_library_labels_test.dart @@ -0,0 +1,42 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/engine/character_library.dart'; +import 'package:loreseer/engine/models.dart'; + +void main() { + Character bare({ + DndSheet? dnd, + IronswornSheet? ironsworn, + StarforgedSheet? starforged, + FunnelSheet? funnel, + }) => + Character( + id: 'x', + name: 'X', + dnd: dnd, + ironsworn: ironsworn, + starforged: starforged, + funnel: funnel, + ); + + test('sheetLabel: generic when no sheet field is set', () { + expect(sheetLabel(bare()), 'Generic'); + }); + + test('sheetLabel: dnd', () { + expect(sheetLabel(bare(dnd: DndSheet.premade())), 'D&D 5e'); + }); + + test('sheetLabel: ironsworn', () { + expect(sheetLabel(bare(ironsworn: IronswornSheet.premade())), 'Ironsworn'); + }); + + test('sheetLabel: starforged (also backs Sundered Isles)', () { + expect( + sheetLabel(bare(starforged: StarforgedSheet.premade())), 'Starforged'); + }); + + test('sheetLabel: 0-level funnel', () { + expect(sheetLabel(bare(funnel: const FunnelSheet(peasants: []))), + '0-Level Funnel'); + }); +} diff --git a/test/character_library_provider_test.dart b/test/character_library_provider_test.dart new file mode 100644 index 0000000..ebbaa26 --- /dev/null +++ b/test/character_library_provider_test.dart @@ -0,0 +1,54 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/engine/models.dart'; +import 'package:loreseer/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('add/remove/rename round-trip and persist app-globally', () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final notifier = container.read(characterLibraryProvider.notifier); + + await notifier.add(const Character(id: 'a', name: 'Brakka')); + await notifier.add(const Character(id: 'b', name: 'Yeva')); + expect((await container.read(characterLibraryProvider.future)).length, 2); + + await notifier.rename('a', 'Brakka the Bold'); + var list = await container.read(characterLibraryProvider.future); + expect(list.firstWhere((c) => c.id == 'a').name, 'Brakka the Bold'); + + await notifier.remove('b'); + list = await container.read(characterLibraryProvider.future); + expect(list.single.id, 'a'); + + // Key is app-global: NOT suffixed with a session id. + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getString('loreseer.charlibrary.v1'), isNotNull); + }); + + test('corrupt storage degrades to empty, corrupt row skipped', () async { + SharedPreferences.setMockInitialValues( + {'loreseer.charlibrary.v1': '[{"id":"ok","name":"Ok"},{"bad":1}]'}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final list = await container.read(characterLibraryProvider.future); + expect(list.single.id, 'ok'); + }); + + test('insertAt restores a deleted row for undo', () async { + SharedPreferences.setMockInitialValues({}); + final container = ProviderContainer(); + addTearDown(container.dispose); + final notifier = container.read(characterLibraryProvider.notifier); + await notifier.add(const Character(id: 'a', name: 'A')); + await notifier.add(const Character(id: 'b', name: 'B')); + await notifier.remove('a'); + await notifier.insertAt(0, const Character(id: 'a', name: 'A')); + final list = await container.read(characterLibraryProvider.future); + expect(list.map((c) => c.id).toList(), ['a', 'b']); + }); +} diff --git a/test/character_library_screen_test.dart b/test/character_library_screen_test.dart new file mode 100644 index 0000000..156f9bc --- /dev/null +++ b/test/character_library_screen_test.dart @@ -0,0 +1,54 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/features/character_library_screen.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Future pumpLibrary(WidgetTester tester) async { + await tester.pumpWidget( + const ProviderScope(child: MaterialApp(home: CharacterLibraryScreen()))); + await tester.pumpAndSettle(); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('lists entries; delete has undo', (tester) async { + SharedPreferences.setMockInitialValues({ + 'loreseer.charlibrary.v1': '[{"id":"a","name":"Brakka"}]', + }); + await pumpLibrary(tester); + expect(find.text('Brakka'), findsOneWidget); + + await tester.tap(find.byKey(const Key('library-delete-a'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('library-char-a')), findsNothing); + + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('library-char-a')), findsOneWidget); + }); + + testWidgets('copy from campaign imports a copy (magic link dropped)', + (tester) async { + SharedPreferences.setMockInitialValues({ + 'loreseer.sessions.v1': + '{"active":"s1","sessions":[{"id":"s1","name":"Alpha"}]}', + 'loreseer.characters.v1.s1': + '[{"id":"c1","name":"Yeva","polarityId":"pg-1"}]', + }); + await pumpLibrary(tester); + await tester.tap(find.byKey(const Key('library-copy-from-campaign'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('library-src-s1'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('library-src-char-c1'))); + await tester.pumpAndSettle(); + expect(find.text('Yeva'), findsOneWidget); + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString('loreseer.charlibrary.v1')!; + expect(raw, contains('"Yeva"')); + expect(raw, isNot(contains('polarityId'))); + expect(raw, isNot(contains('"id":"c1"'))); // fresh id + }); +} diff --git a/test/roster_library_hooks_test.dart b/test/roster_library_hooks_test.dart new file mode 100644 index 0000000..07537e0 --- /dev/null +++ b/test/roster_library_hooks_test.dart @@ -0,0 +1,148 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:loreseer/engine/models.dart'; +import 'package:loreseer/features/tracker_screen.dart'; +import 'package:loreseer/shared/theme.dart'; +import 'package:loreseer/state/providers.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + const libOne = '[{"id":"L1","name":"Brakka"}]'; + + Future pump( + WidgetTester tester, { + String library = '[]', + String chars = '[]', + String? activeCharacterId, + }) async { + SharedPreferences.setMockInitialValues({ + 'loreseer.sessions.v1': + '{"active":"default","sessions":[{"id":"default","name":"C1"}]}', + 'loreseer.characters.v1.default': chars, + 'loreseer.charlibrary.v1': library, + if (activeCharacterId != null) + 'loreseer.context.v1.default': + '{"activeCharacterId":"$activeCharacterId"}', + }); + await tester.pumpWidget(ProviderScope( + child: MaterialApp( + theme: AppTheme.light(), + home: const Scaffold(body: CharactersPane())))); + await tester.pumpAndSettle(); + return ProviderScope.containerOf( + tester.element(find.byType(CharactersPane))); + } + + testWidgets( + 'From library appears when library is non-empty; picking adds a fresh-id pc', + (tester) async { + final container = await pump(tester, library: libOne); + await tester.tap(find.byKey(const Key('add-character'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('new-from-library')), findsOneWidget); + await tester.tap(find.byKey(const Key('new-from-library'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('library-pick-L1')), findsOneWidget); + await tester.tap(find.byKey(const Key('library-pick-L1'))); + await tester.pumpAndSettle(); + final chars = await container.read(charactersProvider.future); + expect(chars, hasLength(1)); + final added = chars.single; + expect(added.name, 'Brakka'); + expect(added.id, isNot('L1')); + expect(added.role, CharacterRole.pc); + expect(added.starred, isFalse); + }); + + testWidgets('From library is absent when the library is empty', + (tester) async { + await pump(tester, library: '[]'); + await tester.tap(find.byKey(const Key('add-character'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('new-from-library')), findsNothing); + }); + + testWidgets( + 'no sheet-type system enabled + non-empty library: Add still opens the ' + 'picker dialog with From-library reachable', (tester) async { + SharedPreferences.setMockInitialValues({ + 'loreseer.sessions.v1': '{"active":"default","sessions":[' + '{"id":"default","name":"C1","systems":[]}]}', + 'loreseer.characters.v1.default': '[]', + 'loreseer.charlibrary.v1': libOne, + }); + await tester.pumpWidget(ProviderScope( + child: MaterialApp( + theme: AppTheme.light(), + home: const Scaffold(body: CharactersPane())))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('add-character'))); + await tester.pumpAndSettle(); + // The old early-return would have skipped straight to the generic + // creator dialog, never showing this picker at all. + expect(find.text('New character'), findsOneWidget); + expect(find.byKey(const Key('new-from-library')), findsOneWidget); + }); + + testWidgets( + 'lead-more Save to library adds a fresh-id library entry (roster id not reused)', + (tester) async { + await pump(tester, + activeCharacterId: 'c1', + chars: '[{"id":"c1","name":"Ash","note":"","stats":[],"tracks":[],' + '"tags":[]}]'); + // c1 is set as the active PC, so it renders the lead card. + expect(find.byKey(const Key('lead-more')), findsOneWidget); + await tester.tap(find.byKey(const Key('lead-more'))); + await tester.pumpAndSettle(); + expect(find.text('Save to library'), findsOneWidget); + await tester.tap(find.text('Save to library')); + await tester.pumpAndSettle(); + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString('loreseer.charlibrary.v1')!; + final list = jsonDecode(raw) as List; + expect(list, hasLength(1)); + final saved = list.single as Map; + expect(saved['name'], 'Ash'); + expect(saved['id'], isNot('c1')); + }); + + testWidgets( + 'compact-more menu: Save to library works, Delete removes with Undo restore', + (tester) async { + // Two companions so both render as compact rows (no lead PC context set). + final container = await pump(tester, + chars: '[{"id":"c1","name":"Ash","note":"","stats":[],"tracks":[],' + '"tags":[],"role":"companion"},' + '{"id":"c2","name":"Bran","note":"","stats":[],"tracks":[],' + '"tags":[],"role":"companion"}]'); + expect(find.byKey(const Key('compact-more-c1')), findsOneWidget); + + // Save to library. + await tester.tap(find.byKey(const Key('compact-more-c1'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Save to library')); + await tester.pumpAndSettle(); + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString('loreseer.charlibrary.v1')!; + final list = jsonDecode(raw) as List; + expect(list, hasLength(1)); + expect((list.single as Map)['name'], 'Ash'); + + // Delete with undo. + await tester.tap(find.byKey(const Key('compact-more-c1'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Delete')); + await tester.pumpAndSettle(); + var chars = await container.read(charactersProvider.future); + expect(chars.map((c) => c.id), isNot(contains('c1'))); + expect(find.text('Undo'), findsOneWidget); + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + chars = await container.read(charactersProvider.future); + expect(chars.map((c) => c.id), contains('c1')); + }); +}