Add modular story library and shared-progress translations

This commit is contained in:
Hadrian Burkhardt
2026-11-03 17:15:15 +01:00
parent 5b9a76fb53
commit d45cd0698a
30 changed files with 2694 additions and 495 deletions
+248
View File
@@ -0,0 +1,248 @@
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:lumen/domain/game.dart';
import 'package:lumen/domain/library.dart';
import 'package:lumen/services/progress.dart';
import 'support/story_fixtures.dart';
class DelayedTranslationBundle extends FixtureBundle {
DelayedTranslationBundle(super.data);
final waiting = Completer<void>();
final started = Completer<void>();
@override
Future<ByteData> load(String key) async {
if (key == 'fixture/de.json') {
if (!started.isCompleted) started.complete();
await waiting.future;
}
return super.load(key);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test(
'bundled library loads every language and keeps original Mara saves',
() async {
final library = await StoryLibrary.load();
expect(library.stories.map((s) => s.id), ['mara-island', 'paper-boat']);
for (final story in library.stories) {
for (final language in story.languages.keys) {
final book = await library.open(story.id, language: language);
expect(book.language, language);
expect(book.pages, isNotEmpty);
for (final level in book.levels) {
expect(level.puzzle().solution.length, level.size * level.size);
expect(
level.puzzle().countSolutions(),
1,
reason: '${story.id}: ${level.id}',
);
}
}
}
final mara = await library.open('mara-island', language: 'de-DE');
expect(mara.language, 'en');
expect(mara.tracks, isNotEmpty);
final g = Game(
mara,
Progress.memory({
'done_story_v1_0': true,
'campaignUnlocked': 3,
'notebook_manual_bookmark': 'cottage.folded.note',
'notebook_last_page': 'cottage.window',
'flutter_screen': 'story',
}),
);
await g.restore();
expect(g.recovered(0), true);
expect(g.storyPage.id, 'cottage.window');
expect(
g.progress.text('notebook_manual_bookmark'),
'cottage.folded.note',
);
},
);
test('translations preserve identity and rules, fall back by field, and use their own narration', () async {
final library = StoryLibrary([
definition('fixture'),
], bundle: FixtureBundle(fixture()));
final en = await library.open('fixture');
final de = await library.open('fixture', language: 'de-AT');
expect(de.language, 'de');
expect(de.title, 'Eine Testgeschichte');
expect(de.pages.first.id, en.pages.first.id);
expect(de.levels.first.id, 'puzzle-0');
expect(de.levels.first.picture, en.levels.first.picture);
expect(de.levels.first.chapterId, 'first');
expect(de.pages.first.text, 'Vorher');
expect(de.pages.first.title, 'Ein Anfang');
expect(de.pages[2].text, en.pages[2].text);
expect(en.tracks, isNotEmpty);
expect(de.tracks, isEmpty);
expect((await library.open('fixture', language: 'it')).language, 'en');
});
test('switching stories isolates marks, bookmarks and achievements; language keeps live undo', () async {
final library = StoryLibrary([
definition('first'),
definition('second'),
], bundle: FixtureBundle(fixture()));
final store = Progress.memory();
final g = Game(await library.open('first'), store, library: library);
g.startCampaign(0);
g.mark(0);
final firstMarks = List<int>.of(g.cells);
await g.progress.set('notebook_manual_bookmark', g.storyPage.id);
await g.selectLanguage('de');
expect(g.book.language, 'de');
expect(g.cells, firstMarks);
expect(g.canUndo, true);
expect(g.storyPage.id, 'puzzle-0');
expect(g.progress.text('notebook_manual_bookmark'), 'puzzle-0');
g.undo();
expect(g.cells.every((c) => c == 0), true);
g.mark(0);
await g.selectStory('second');
expect(g.book.language, 'de');
expect(g.progress.text('notebook_manual_bookmark'), isEmpty);
expect(g.recoveredCount, 0);
g.startCampaign(0);
expect(g.cells.every((c) => c == 0), true);
g.mark(1);
final secondMarks = List<int>.of(g.cells);
await g.selectStory('first');
expect(g.cells, firstMarks);
expect(g.progress.text('notebook_manual_bookmark'), 'puzzle-0');
await g.selectStory('second');
expect(g.cells, secondMarks);
final restarted = Game(
await library.open(
store.text('selected_story'),
language: store.text('language'),
),
Progress.memory(store.snapshot),
library: library,
);
await restarted.restore();
expect(restarted.book.id, 'second');
expect(restarted.book.language, 'de');
expect(restarted.cells, secondMarks);
});
test('variable chapters and completing a new story award once and restore by stable keys', () async {
final library = StoryLibrary([
definition('fixture'),
], bundle: FixtureBundle(fixture()));
final g = Game(
await library.open('fixture'),
Progress.memory(),
library: library,
);
expect(g.book.chapterLevels(0), [0, 1]);
expect(g.book.chapterLevels(1), [2]);
for (var i = 0; i < 3; i++) {
g.startCampaign(i);
expect(g.storyPage.id, 'puzzle-$i');
for (var c = 0; c < g.cells.length; c++) {
while (g.cells[c] != (g.puzzle!.solution[c] == 1 ? 1 : 2)) {
g.mark(c);
}
}
expect(g.storyPage.id, 'memory-$i');
expect(g.solved, i + 1);
g.check();
expect(g.solved, i + 1);
}
expect(g.recoveredCount, 3);
g.contents(1);
expect(g.contentsChapter, 1);
expect(g.book.puzzleKey(0), 'story_fixture_puzzle-0');
await g.selectLanguage('de');
expect(g.recoveredCount, 3);
g.leaveCottage(); // A standard book ends in its own contents.
expect(g.screen, Screen.contents);
});
test(
'UI translations preserve values and prioritize the most specific template',
() async {
final catalog = (await StoryLibrary.load()).copy;
final tr = catalog.translator('de-DE');
expect(tr.text('Next leaf →'), 'Nächste Seite →');
expect(
tr.text('Open The paper boat · 0 / 1'),
'The paper boat öffnen · 0 / 1',
);
expect(tr.text('Row 2, column 3'), 'Zeile 2, Spalte 3');
expect(tr.text('Difficulty · Easy ▾'), 'Schwierigkeit · Einfach ▾');
expect(tr.text('An unknown message'), 'An unknown message');
expect(catalog.text('Close', 'ar'), 'Close');
expect(
catalog.text('Close', 'de', overrides: {'Close': 'Fertig'}),
'Fertig',
);
},
);
test(
'reading into a new chapter unlocks reading access without achievements',
() async {
final library = StoryLibrary([
definition('fixture'),
], bundle: FixtureBundle(fixture()));
final g = Game(await library.open('fixture'), Progress.memory());
expect(g.accessible, 0);
g.showStory(6);
expect(g.accessible, 2);
expect(g.recoveredCount, 0);
expect(g.solved, 0);
g.contents();
expect(g.contentsChapter, 1);
},
);
test('a late language load cannot replace a newer story selection', () async {
final bundle = DelayedTranslationBundle(fixture());
final library = StoryLibrary([
definition('first'),
definition('second'),
], bundle: bundle);
final g = Game(
await library.open('first'),
Progress.memory(),
library: library,
);
final oldLanguage = g.selectLanguage('de');
await bundle.started.future;
await g.selectStory('second');
bundle.waiting.complete();
await oldLanguage;
expect(g.book.id, 'second');
expect(g.book.language, 'en');
expect(g.languagePreference, 'system');
});
test(
'invalid page references and duplicate IDs fail while loading a package',
() async {
final data = fixture();
(data['fixture/notebook.json'] as Map)['pages'] = [
{'id': 'bad', 'title': 'Bad', 'type': 'puzzle', 'campaignIndex': 99},
];
final library = StoryLibrary([
definition('fixture'),
], bundle: FixtureBundle(data));
await expectLater(library.open('fixture'), throwsFormatException);
expect(
() => StoryLibrary([definition('same'), definition('same')]),
throwsFormatException,
);
},
);
}
+168
View File
@@ -0,0 +1,168 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:lumen/domain/game.dart';
import 'package:lumen/domain/library.dart';
import 'package:lumen/main.dart';
import 'package:lumen/services/progress.dart';
import 'package:lumen/services/translation.dart';
import 'package:lumen/ui/translation.dart';
import 'support/story_fixtures.dart';
void main() {
testWidgets(
'library and language controls open a translated story and preserve live marks',
(tester) async {
tester.view.physicalSize = const Size(600, 960);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.runAsync(() async {
final font = FontLoader('MaraHand')
..addFont(rootBundle.load('assets/fonts/DancingScript.ttf'));
await font.load();
});
final library = (await tester.runAsync(StoryLibrary.load))!;
for (final story in library.stories) {
for (final language in story.languages.keys) {
await tester.runAsync(
() => library.open(story.id, language: language),
);
}
}
final book = (await tester.runAsync(() => library.open('mara-island')))!;
final g = Game(book, Progress.memory(), library: library);
await tester.pumpWidget(LumenApp(game: g, adsEnabled: false));
await tester.pumpAndSettle();
Future<void> tap(String text) async {
await tester.ensureVisible(find.text(text));
await tester.pumpAndSettle();
await tester.tap(find.text(text));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
);
await tester.pumpAndSettle();
}
await tap('Story library');
await tap('The paper boat');
expect(g.book.id, 'paper-boat');
await tap('Open The paper boat · 0 / 1');
expect(g.storyPage.id, 'boat.entry');
await tap('Next leaf →');
await tester.ensureVisible(find.byKey(const ValueKey('cell-0')));
await tester.tap(find.byKey(const ValueKey('cell-0')));
await tester.pumpAndSettle();
final marks = List<int>.of(g.cells);
await tap('Bookmark');
await tap('Language');
await tap('Deutsch');
expect(g.book.language, 'de');
expect(g.storyPage.id, 'boat.puzzle');
expect(g.cells, marks);
expect(g.canUndo, true);
expect(find.text('Eine kleine Überfahrt'), findsOneWidget);
expect(find.text('Nächste Seite →'), findsOneWidget);
expect(g.progress.text('notebook_manual_bookmark'), 'boat.puzzle');
await tap('Buch schließen');
await tap('Geschichtenbibliothek');
expect(
find.descendant(
of: find.byType(AlertDialog),
matching: find.text('Das Papierboot'),
),
findsOneWidget,
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
},
);
testWidgets(
'German story pages fit portrait and landscape with larger text',
(tester) async {
addTearDown(tester.view.reset);
tester.platformDispatcher.textScaleFactorTestValue = 1.5;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final library = (await tester.runAsync(StoryLibrary.load))!;
final book = (await tester.runAsync(
() => library.open('paper-boat', language: 'de'),
))!;
for (final size in [const Size(360, 640), const Size(960, 600)]) {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
final g = Game(
book,
Progress.memory({'language': 'de'}),
library: library,
);
await tester.pumpWidget(LumenApp(game: g, adsEnabled: false));
await tester.pumpAndSettle();
for (var i = 0; i < book.pages.length; i++) {
g.showStory(i);
await tester.pumpAndSettle();
expect(find.text('Sprache').hitTestable(), findsOneWidget);
expect(
find
.text(i == 2 ? 'Zum Inhaltsverzeichnis' : 'Nächste Seite →')
.hitTestable(),
findsOneWidget,
);
expect(tester.takeException(), isNull);
}
g.contents();
await tester.pumpAndSettle();
expect(find.text('Eine kleine Überfahrt'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
}
},
);
testWidgets('a right-to-left story uses RTL layout and a system font', (
tester,
) async {
final data = fixture();
data['fixture/ar.json'] = {
'title': 'قصة قصيرة',
'pages': {
'entry-0': {'title': 'البداية', 'text': 'تبدأ الرحلة هنا.'},
},
};
final original = definition('arabic');
original.languages['ar'] = {'label': 'العربية', 'asset': 'fixture/ar.json'};
final library = StoryLibrary(
[original],
bundle: FixtureBundle(data),
copy: const TranslationCatalog(
{'en': 'English', 'ar': 'العربية'},
{
'ar': {'Language': 'اللغة'},
},
),
);
final book = (await tester.runAsync(
() => library.open('arabic', language: 'ar'),
))!;
final g = Game(book, Progress.memory({'language': 'ar'}), library: library)
..showStory(0);
await tester.pumpWidget(LumenApp(game: g, adsEnabled: false));
await tester.pumpAndSettle();
final heading = find.text('البداية');
expect(Directionality.of(tester.element(heading)), TextDirection.rtl);
expect(tester.widget<Text>(heading).style?.fontFamily, 'sans-serif');
expect(find.text('اللغة'), findsOneWidget);
g.startCampaign(0);
await tester.pumpAndSettle();
expect(
tester.getCenter(find.byKey(const ValueKey('cell-0'))).dx,
lessThan(tester.getCenter(find.byKey(const ValueKey('cell-4'))).dx),
);
expect(tester.takeException(), isNull);
expect(tester.takeException(), isNull);
expect(localeFromTag('zh-Hant-TW').scriptCode, 'Hant');
expect(localeFromTag('zh-Hant-TW').countryCode, 'TW');
await tester.pumpWidget(const SizedBox());
});
}
+96
View File
@@ -0,0 +1,96 @@
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:lumen/domain/library.dart';
class FixtureBundle extends CachingAssetBundle {
FixtureBundle(this.data);
final Map<String, Object> data;
@override
Future<ByteData> load(String key) async {
final value = data[key];
if (value == null) return rootBundle.load(key);
return ByteData.sublistView(
Uint8List.fromList(utf8.encode(jsonEncode(value))),
);
}
}
StoryDefinition definition(String id) => StoryDefinition({
'id': id,
'title': 'A fixture story',
'defaultLanguage': 'en',
'campaignAsset': 'fixture/campaign.json',
'notebookAsset': 'fixture/notebook.json',
'tracksAsset': 'fixture/audio.json',
'languages': {
'en': {'label': 'English'},
'de': {'label': 'Deutsch', 'asset': 'fixture/de.json'},
},
});
Map<String, Object> fixture() => {
'fixture/campaign.json': {
'premise': 'A starting point.',
'levels': [
for (var i = 0; i < 3; i++)
{
'id': 'puzzle-$i',
'size': 5,
'chapterId': i < 2 ? 'first' : 'second',
'chapter': i < 2 ? 'First chapter' : 'Second chapter',
'title': 'Puzzle $i',
'object': 'Object $i',
'before': 'Before $i',
'after': 'After $i',
'picture': '1000001000001000001000001',
'clues': '',
'areas': '',
},
],
},
'fixture/notebook.json': {
'pages': [
for (var i = 0; i < 3; i++) ...[
{
'id': 'entry-$i',
'type': 'entry',
'title': 'Entry $i',
'campaignIndex': i,
'textSource': 'before',
},
{
'id': 'puzzle-$i',
'type': 'puzzle',
'title': 'Puzzle $i',
'campaignIndex': i,
},
{
'id': 'memory-$i',
'type': 'memory',
'title': 'Memory $i',
'campaignIndex': i,
'textSource': 'after',
},
],
],
},
'fixture/audio.json': {
'tracks': {
'entry-0': {'file': 'english.wav'},
},
},
'fixture/de.json': {
'title': 'Eine Testgeschichte',
'levels': {
'puzzle-0': {
'title': 'Ein Muster', 'before': 'Vorher',
// Translation records cannot replace the puzzle or its identity.
'id': 'tampered', 'picture': '0000', 'chapterId': 'tampered',
},
},
'pages': {
'entry-0': {'title': 'Ein Anfang', 'id': 'tampered'},
},
},
};