Add modular story library and shared-progress translations
This commit is contained in:
+225
-57
@@ -3,10 +3,14 @@ import 'dart:convert';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'puzzle.dart';
|
||||
import 'library.dart';
|
||||
|
||||
class CampaignLevel {
|
||||
CampaignLevel(Map<String, dynamic> data)
|
||||
: chapter = data['chapter'],
|
||||
: id = data['id'] as String? ?? '',
|
||||
chapterId = data['chapterId'] as String? ?? data['chapter'],
|
||||
size = data['size'] as int? ?? 7,
|
||||
chapter = data['chapter'],
|
||||
title = data['title'],
|
||||
object = data['object'],
|
||||
before = data['before'],
|
||||
@@ -17,21 +21,30 @@ class CampaignLevel {
|
||||
picture = (data['picture'] as String).split('').map(int.parse).toList(),
|
||||
clues = data['clues'],
|
||||
areas = data['areas'];
|
||||
final String id, chapterId;
|
||||
final int size;
|
||||
final String chapter, title, object, before, after, clues, areas;
|
||||
final String beforeContinuation, afterContinuation;
|
||||
final String? illustrationAsset;
|
||||
final List<int> picture;
|
||||
Puzzle puzzle() {
|
||||
final p = Puzzle(7, picture);
|
||||
final p = Puzzle(size, picture);
|
||||
if (clues.isNotEmpty) {
|
||||
for (final c in clues.split(',')) {
|
||||
p.given[int.parse(c)] = true;
|
||||
final index = int.parse(c);
|
||||
if (index < 0 || index >= picture.length) {
|
||||
throw FormatException('Invalid fixed clue: $id: $index');
|
||||
}
|
||||
p.given[index] = true;
|
||||
}
|
||||
}
|
||||
if (areas.isNotEmpty) {
|
||||
var i = 0;
|
||||
for (final a in areas.split(';')) {
|
||||
final v = a.split(',').map(int.parse).toList();
|
||||
if (v.length != 4) {
|
||||
throw FormatException('Invalid region: $id');
|
||||
}
|
||||
p.regions.add(
|
||||
Region(String.fromCharCode(65 + i++), v[0], v[1], v[2], v[3]),
|
||||
);
|
||||
@@ -61,9 +74,10 @@ class StoryPage {
|
||||
this.speaker = '',
|
||||
this.illustrationAsset,
|
||||
this.continuation = '',
|
||||
this.caption = '',
|
||||
});
|
||||
final String id, title, text;
|
||||
final String continuation;
|
||||
final String continuation, caption;
|
||||
final StoryPageType type;
|
||||
final int? campaignIndex;
|
||||
final String speaker;
|
||||
@@ -71,68 +85,222 @@ class StoryPage {
|
||||
}
|
||||
|
||||
class Book {
|
||||
Book(this.premise, this.levels, this.pages, this.tracks);
|
||||
Book(
|
||||
this.premise,
|
||||
this.levels,
|
||||
this.pages,
|
||||
this.tracks, {
|
||||
this.id = 'mara-island',
|
||||
this.title = 'Mara’s notebook',
|
||||
this.description = '',
|
||||
this.language = 'en',
|
||||
this.defaultLanguage = 'en',
|
||||
this.presentation = 'mara',
|
||||
this.coverAsset = 'assets/artwork/home-notebook-cover-v2.png',
|
||||
this.continueAt = 4,
|
||||
this.initiallyAccessible = 3,
|
||||
this.fontFamily = 'MaraHand',
|
||||
this.copy = const {},
|
||||
});
|
||||
final String id, title, description, language, defaultLanguage, presentation;
|
||||
final String? coverAsset, fontFamily;
|
||||
final int? continueAt;
|
||||
final int initiallyAccessible;
|
||||
final Map<String, String> copy;
|
||||
final String premise;
|
||||
final List<CampaignLevel> levels;
|
||||
final List<StoryPage> pages;
|
||||
final Map<String, dynamic> tracks;
|
||||
bool get isMara => presentation == 'mara';
|
||||
List<String> get chapters => levels.map((l) => l.chapterId).toSet().toList();
|
||||
List<int> chapterLevels(int chapter) => [
|
||||
for (var i = 0; i < levels.length; i++)
|
||||
if (levels[i].chapterId == chapters[chapter]) i,
|
||||
];
|
||||
int chapterFor(int level) => chapters.indexOf(levels[level].chapterId);
|
||||
String puzzleKey(int index) => id == 'mara-island'
|
||||
? 'story_v1_$index'
|
||||
: 'story_${id}_${levels[index].id}';
|
||||
int pageFor(int campaignIndex, StoryPageType type) => pages.indexWhere(
|
||||
(p) => p.campaignIndex == campaignIndex && p.type == type,
|
||||
);
|
||||
static Future<Book> load() async {
|
||||
final campaign = jsonDecode(
|
||||
await rootBundle.loadString('assets/campaign.json'),
|
||||
) as Map<String, dynamic>;
|
||||
final scripts = jsonDecode(
|
||||
await rootBundle.loadString('assets/narration/scripts.json'),
|
||||
) as List;
|
||||
final tracks =
|
||||
jsonDecode(
|
||||
await rootBundle.loadString(
|
||||
'assets/audio/narration_manifest.json',
|
||||
),
|
||||
)['tracks']
|
||||
as Map<String, dynamic>;
|
||||
final levels = (campaign['levels'] as List)
|
||||
.map((e) => CampaignLevel(e))
|
||||
.toList();
|
||||
final notebook = jsonDecode(
|
||||
await rootBundle.loadString('assets/notebook.json'),
|
||||
) as Map<String, dynamic>;
|
||||
return Book(
|
||||
campaign['premise'],
|
||||
levels,
|
||||
(notebook['pages'] as List).map((record) {
|
||||
final index = record['campaignIndex'] as int?;
|
||||
final text = switch (record['textSource']) {
|
||||
'before' => levels[index!].before,
|
||||
'after' => levels[index!].after,
|
||||
'recording' =>
|
||||
scripts
|
||||
.where((s) => s['pageId'] == record['id'])
|
||||
.map((s) => (s['baseText'] ?? s['text']) as String)
|
||||
.firstOrNull ??
|
||||
'',
|
||||
_ => record['text'] as String? ?? '',
|
||||
};
|
||||
return StoryPage(
|
||||
record['id'],
|
||||
record['title'],
|
||||
text,
|
||||
type: StoryPageType.values.byName(record['type']),
|
||||
campaignIndex: index,
|
||||
speaker: record['speaker'] as String? ?? '',
|
||||
illustrationAsset: record['illustrationAsset'] as String?,
|
||||
continuation:
|
||||
record['continuation'] as String? ??
|
||||
switch (record['textSource']) {
|
||||
'before' => levels[index!].beforeContinuation,
|
||||
'after' => levels[index!].afterContinuation,
|
||||
_ => '',
|
||||
},
|
||||
static Future<Book> load() async =>
|
||||
(await StoryLibrary.load()).open('mara-island');
|
||||
|
||||
static Future<Book> loadDefinition(
|
||||
StoryDefinition definition, {
|
||||
String language = 'en',
|
||||
AssetBundle? bundle,
|
||||
}) async {
|
||||
final assets = bundle ?? rootBundle;
|
||||
Future<dynamic> read(String path) async =>
|
||||
jsonDecode(await assets.loadString(path));
|
||||
final campaign = Map<String, dynamic>.from(
|
||||
await read(definition.campaignAsset),
|
||||
);
|
||||
final notebook = await read(definition.notebookAsset);
|
||||
final scripts = definition.scriptsAsset == null
|
||||
? <dynamic>[]
|
||||
: await read(definition.scriptsAsset!) as List;
|
||||
final actualLanguage = definition.languageFor(language);
|
||||
final locale = definition.languages[actualLanguage] as Map;
|
||||
final translation = locale['asset'] == null
|
||||
? <String, dynamic>{}
|
||||
: Map<String, dynamic>.from(await read(locale['asset']));
|
||||
final translatedLevels = translation['levels'] as Map? ?? {};
|
||||
final translatedPages = translation['pages'] as Map? ?? {};
|
||||
// Translations may only replace presentation fields, never puzzle identity
|
||||
// or rules. A missing field falls back to the original text.
|
||||
const levelText = [
|
||||
'chapter',
|
||||
'title',
|
||||
'object',
|
||||
'before',
|
||||
'after',
|
||||
'beforeContinuation',
|
||||
'afterContinuation',
|
||||
'illustrationAsset',
|
||||
];
|
||||
const pageText = [
|
||||
'title',
|
||||
'text',
|
||||
'speaker',
|
||||
'continuation',
|
||||
'caption',
|
||||
'illustrationAsset',
|
||||
];
|
||||
Map<String, dynamic> overlay(
|
||||
Map<String, dynamic> base,
|
||||
Map? translated,
|
||||
List<String> fields,
|
||||
) => {
|
||||
...base,
|
||||
for (final field in fields)
|
||||
if (translated?[field] is String) field: translated![field],
|
||||
};
|
||||
final levels = (campaign['levels'] as List).map((record) {
|
||||
final base = Map<String, dynamic>.from(record);
|
||||
base['chapterId'] ??= base['chapter'];
|
||||
return CampaignLevel(
|
||||
overlay(base, translatedLevels[base['id']], levelText),
|
||||
);
|
||||
}).toList();
|
||||
final pages = (notebook['pages'] as List).map((record) {
|
||||
final index = record['campaignIndex'] as int?;
|
||||
if (index != null && (index < 0 || index >= levels.length)) {
|
||||
throw FormatException('Unknown puzzle on page ${record['id']}');
|
||||
}
|
||||
final text = switch (record['textSource']) {
|
||||
'before' => levels[index!].before,
|
||||
'after' => levels[index!].after,
|
||||
'recording' =>
|
||||
scripts
|
||||
.where((s) => s['pageId'] == record['id'])
|
||||
.map((s) => (s['baseText'] ?? s['text']) as String)
|
||||
.firstOrNull ??
|
||||
'',
|
||||
_ => record['text'] as String? ?? '',
|
||||
};
|
||||
final base = <String, dynamic>{
|
||||
...record,
|
||||
'text': text,
|
||||
'continuation':
|
||||
record['continuation'] ??
|
||||
switch (record['textSource']) {
|
||||
'before' => levels[index!].beforeContinuation,
|
||||
'after' => levels[index!].afterContinuation,
|
||||
_ => '',
|
||||
},
|
||||
};
|
||||
final page = overlay(base, translatedPages[record['id']], pageText);
|
||||
return StoryPage(
|
||||
page['id'],
|
||||
page['title'],
|
||||
page['text'],
|
||||
type: StoryPageType.values.byName(page['type']),
|
||||
campaignIndex: index,
|
||||
speaker: page['speaker'] as String? ?? '',
|
||||
illustrationAsset: page['illustrationAsset'] as String?,
|
||||
continuation: page['continuation'] as String? ?? '',
|
||||
caption: page['caption'] as String? ?? '',
|
||||
);
|
||||
}).toList();
|
||||
if (levels.isEmpty ||
|
||||
pages.isEmpty ||
|
||||
levels.any(
|
||||
(l) =>
|
||||
!RegExp(r'^[a-z0-9._-]+$').hasMatch(l.id) ||
|
||||
l.size < 2 ||
|
||||
l.size > 10 ||
|
||||
l.picture.length != l.size * l.size ||
|
||||
l.picture.any((v) => v != 0 && v != 1),
|
||||
) ||
|
||||
levels.map((l) => l.id).toSet().length != levels.length ||
|
||||
pages.map((p) => p.id).toSet().length != pages.length ||
|
||||
pages.any((p) => p.id.isEmpty) ||
|
||||
definition.continueAt != null &&
|
||||
(definition.continueAt! < 0 ||
|
||||
definition.continueAt! >= levels.length) ||
|
||||
pages.any(
|
||||
(p) =>
|
||||
[StoryPageType.puzzle, StoryPageType.memory].contains(p.type) &&
|
||||
p.campaignIndex == null,
|
||||
)) {
|
||||
throw FormatException('Invalid story content: ${definition.id}');
|
||||
}
|
||||
final seenChapters = <String>{};
|
||||
String? lastChapter;
|
||||
for (final level in levels) {
|
||||
if (level.chapterId != lastChapter &&
|
||||
!seenChapters.add(level.chapterId)) {
|
||||
throw FormatException(
|
||||
'Chapter levels must be contiguous: ${level.chapterId}',
|
||||
);
|
||||
}).toList(),
|
||||
}
|
||||
lastChapter = level.chapterId;
|
||||
final puzzle = level.puzzle();
|
||||
if (puzzle.regions.any(
|
||||
(r) =>
|
||||
r.top < 0 ||
|
||||
r.left < 0 ||
|
||||
r.width <= 0 ||
|
||||
r.height <= 0 ||
|
||||
r.top + r.height > puzzle.size ||
|
||||
r.left + r.width > puzzle.size,
|
||||
)) {
|
||||
throw FormatException('Invalid puzzle region: ${level.id}');
|
||||
}
|
||||
}
|
||||
// Never play original-language narration over translated text. A locale
|
||||
// supplies its own manifest, or remains readable without a recording.
|
||||
final trackPath =
|
||||
locale['tracksAsset'] as String? ??
|
||||
(actualLanguage == definition.defaultLanguage
|
||||
? definition.tracksAsset
|
||||
: null);
|
||||
final tracks = trackPath == null
|
||||
? <String, dynamic>{}
|
||||
: Map<String, dynamic>.from((await read(trackPath))['tracks']);
|
||||
return Book(
|
||||
translation['premise'] as String? ?? campaign['premise'],
|
||||
levels,
|
||||
pages,
|
||||
tracks,
|
||||
id: definition.id,
|
||||
title: translation['title'] as String? ?? definition.title,
|
||||
description:
|
||||
translation['description'] as String? ?? definition.description,
|
||||
language: actualLanguage,
|
||||
defaultLanguage: definition.defaultLanguage,
|
||||
presentation: definition.presentation,
|
||||
coverAsset: translation['coverAsset'] as String? ?? definition.coverAsset,
|
||||
continueAt: definition.continueAt,
|
||||
initiallyAccessible: definition.initiallyAccessible.clamp(
|
||||
0,
|
||||
levels.length - 1,
|
||||
),
|
||||
fontFamily: locale['fontFamily'] as String?,
|
||||
copy: Map<String, String>.from(translation['copy'] as Map? ?? {}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+94
-29
@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../services/progress.dart';
|
||||
import 'book.dart';
|
||||
import 'library.dart';
|
||||
import 'puzzle.dart';
|
||||
|
||||
enum Screen { home, story, contents, briefing, game, reveal }
|
||||
@@ -17,9 +18,52 @@ Puzzle generatePractice(Map<String, Object> args) => Puzzle.generate(
|
||||
);
|
||||
|
||||
class Game extends ChangeNotifier {
|
||||
Game(this.book, this.progress);
|
||||
final Book book;
|
||||
final Progress progress;
|
||||
Game(this.book, this.store, {this.library});
|
||||
Book book;
|
||||
final Progress store;
|
||||
final StoryLibrary? library;
|
||||
Progress get progress => store.forStory(book.id);
|
||||
String get languagePreference => store.text('language', 'system');
|
||||
String get requestedLanguage =>
|
||||
languagePreference == 'system' ? deviceLanguage : languagePreference;
|
||||
String deviceLanguage = 'en';
|
||||
int _bookRequest = 0;
|
||||
|
||||
Future<void> selectStory(String id) async {
|
||||
final catalogue = library;
|
||||
if (catalogue == null) return;
|
||||
final request = ++_bookRequest;
|
||||
final next = await catalogue.open(id, language: requestedLanguage);
|
||||
if (request != _bookRequest) return;
|
||||
_request++;
|
||||
book = next;
|
||||
puzzle = null;
|
||||
key = '';
|
||||
cells = [];
|
||||
_undo.clear();
|
||||
storyIndex = campaignIndex = contentsChapter = 0;
|
||||
busy = false;
|
||||
screen = Screen.home;
|
||||
unawaited(store.set('selected_story', book.id));
|
||||
await restore();
|
||||
if (request == _bookRequest) notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> selectLanguage(String preference) async {
|
||||
final catalogue = library;
|
||||
if (catalogue == null) return;
|
||||
final request = ++_bookRequest;
|
||||
final next = await catalogue.open(
|
||||
book.id,
|
||||
language: preference == 'system' ? deviceLanguage : preference,
|
||||
);
|
||||
if (request != _bookRequest) return;
|
||||
unawaited(store.set('language', preference));
|
||||
// Identity and puzzle data are unchanged: keep the live grid and undo stack.
|
||||
book = next;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Screen screen = Screen.home;
|
||||
Mode mode = Mode.classic;
|
||||
Difficulty get difficulty =>
|
||||
@@ -37,12 +81,18 @@ class Game extends ChangeNotifier {
|
||||
bool get won => progress.flag('done_$key');
|
||||
bool get canUndo => _undo.isNotEmpty && !won;
|
||||
int get solved => progress.number('solved');
|
||||
int get recoveredCount =>
|
||||
List.generate(12, (i) => recovered(i)).where((v) => v).length;
|
||||
int get unlocked => progress.number('campaignUnlocked').clamp(0, 11);
|
||||
int get recoveredCount => List.generate(
|
||||
book.levels.length,
|
||||
(i) => recovered(i),
|
||||
).where((v) => v).length;
|
||||
int get unlocked =>
|
||||
progress.number('campaignUnlocked').clamp(0, book.levels.length - 1);
|
||||
int get accessible => math.max(
|
||||
3,
|
||||
math.max(unlocked, progress.number('story_access_level').clamp(0, 11)),
|
||||
book.initiallyAccessible,
|
||||
math.max(
|
||||
unlocked,
|
||||
progress.number('story_access_level').clamp(0, book.levels.length - 1),
|
||||
),
|
||||
);
|
||||
int get practiceLevel => progress.number('level_${difficulty.stored}', 1);
|
||||
int get streak => visibleStreak(
|
||||
@@ -50,10 +100,12 @@ class Game extends ChangeNotifier {
|
||||
progress.number('streak'),
|
||||
epochDay(DateTime.now()),
|
||||
);
|
||||
bool recovered(int i) => progress.flag('done_story_v1_$i');
|
||||
bool recovered(int i) => progress.flag('done_${book.puzzleKey(i)}');
|
||||
Future<void> restore() async {
|
||||
final saved = progress.text('flutter_screen', 'home');
|
||||
campaignIndex = progress.number('flutter_campaign').clamp(0, 11);
|
||||
campaignIndex = progress
|
||||
.number('flutter_campaign')
|
||||
.clamp(0, book.levels.length - 1);
|
||||
if (saved == 'story') {
|
||||
showStory(
|
||||
book.pages
|
||||
@@ -116,9 +168,12 @@ class Game extends ChangeNotifier {
|
||||
storyIndex = i.clamp(0, book.pages.length - 1);
|
||||
mode = Mode.campaign;
|
||||
campaignIndex = storyPage.campaignIndex ?? 0;
|
||||
if (campaignIndex > accessible) {
|
||||
unawaited(progress.set('story_access_level', campaignIndex));
|
||||
}
|
||||
if (storyPage.type == StoryPageType.puzzle &&
|
||||
key != 'story_v1_$campaignIndex') {
|
||||
_read(book.levels[campaignIndex].puzzle(), 'story_v1_$campaignIndex');
|
||||
key != book.puzzleKey(campaignIndex)) {
|
||||
_read(book.levels[campaignIndex].puzzle(), book.puzzleKey(campaignIndex));
|
||||
}
|
||||
unawaited(progress.set('notebook_last_page', book.pages[storyIndex].id));
|
||||
unawaited(progress.set('viewed_${book.pages[storyIndex].id}', true));
|
||||
@@ -128,20 +183,29 @@ class Game extends ChangeNotifier {
|
||||
void contents([int? chapter]) {
|
||||
_request++;
|
||||
busy = false;
|
||||
contentsChapter = (chapter ?? campaignIndex ~/ 4).clamp(0, accessible ~/ 4);
|
||||
contentsChapter = (chapter ?? book.chapterFor(campaignIndex)).clamp(
|
||||
0,
|
||||
book.chapterFor(accessible),
|
||||
);
|
||||
unawaited(progress.set('notebook_contents_chapter', contentsChapter));
|
||||
_route(Screen.contents);
|
||||
}
|
||||
|
||||
void leaveCottage() {
|
||||
unawaited(progress.set('story_access_level', math.max(accessible, 4)));
|
||||
briefing(4);
|
||||
final next = book.continueAt;
|
||||
if (next == null) {
|
||||
contents();
|
||||
return;
|
||||
}
|
||||
unawaited(progress.set('story_access_level', math.max(accessible, next)));
|
||||
briefing(next);
|
||||
}
|
||||
|
||||
void briefing(int i) {
|
||||
campaignIndex = i.clamp(0, accessible);
|
||||
if (campaignIndex < 4) {
|
||||
showStory(book.pageFor(campaignIndex, StoryPageType.entry));
|
||||
final page = book.pageFor(campaignIndex, StoryPageType.entry);
|
||||
if (page >= 0) {
|
||||
showStory(page);
|
||||
return;
|
||||
}
|
||||
mode = Mode.campaign;
|
||||
@@ -154,8 +218,9 @@ class Game extends ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
campaignIndex = i;
|
||||
if (i < 4) {
|
||||
showStory(book.pageFor(i, StoryPageType.memory));
|
||||
final page = book.pageFor(i, StoryPageType.memory);
|
||||
if (page >= 0) {
|
||||
showStory(page);
|
||||
return;
|
||||
}
|
||||
mode = Mode.campaign;
|
||||
@@ -200,14 +265,15 @@ class Game extends ChangeNotifier {
|
||||
void startCampaign(int i) {
|
||||
_request++;
|
||||
busy = false;
|
||||
if (i > accessible) return;
|
||||
if (i < 0 || i >= book.levels.length || i > accessible) return;
|
||||
campaignIndex = i;
|
||||
mode = Mode.campaign;
|
||||
if (i < 4) {
|
||||
showStory(book.pageFor(i, StoryPageType.puzzle));
|
||||
final page = book.pageFor(i, StoryPageType.puzzle);
|
||||
if (page >= 0) {
|
||||
showStory(page);
|
||||
return;
|
||||
}
|
||||
_read(book.levels[i].puzzle(), 'story_v1_$i');
|
||||
_read(book.levels[i].puzzle(), book.puzzleKey(i));
|
||||
_route(Screen.game);
|
||||
}
|
||||
|
||||
@@ -304,14 +370,13 @@ class Game extends ChangeNotifier {
|
||||
unawaited(
|
||||
progress.set(
|
||||
'campaignUnlocked',
|
||||
math.max(unlocked, math.min(11, campaignIndex + 1)),
|
||||
math.max(
|
||||
unlocked,
|
||||
math.min(book.levels.length - 1, campaignIndex + 1),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (screen == Screen.story) {
|
||||
showStory(book.pageFor(campaignIndex, StoryPageType.memory));
|
||||
} else {
|
||||
reveal(campaignIndex);
|
||||
}
|
||||
reveal(campaignIndex);
|
||||
} else {
|
||||
unawaited(progress.set('level_${difficulty.stored}', playingLevel + 1));
|
||||
unawaited(
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'book.dart';
|
||||
import '../services/translation.dart';
|
||||
|
||||
/// A catalogue entry identifies a story independently of its translations.
|
||||
class StoryDefinition {
|
||||
StoryDefinition(Map<String, dynamic> data)
|
||||
: id = data['id'],
|
||||
title = data['title'],
|
||||
description = data['description'] ?? '',
|
||||
coverAsset = data['coverAsset'],
|
||||
defaultLanguage = (data['defaultLanguage'] as String? ?? 'en')
|
||||
.replaceAll('_', '-')
|
||||
.toLowerCase(),
|
||||
campaignAsset = data['campaignAsset'],
|
||||
notebookAsset = data['notebookAsset'],
|
||||
scriptsAsset = data['scriptsAsset'],
|
||||
tracksAsset = data['tracksAsset'],
|
||||
presentation = data['presentation'] ?? 'standard',
|
||||
continueAt = data['continueAt'],
|
||||
initiallyAccessible = data['initiallyAccessible'] ?? 0,
|
||||
languages = {
|
||||
for (final entry in (data['languages'] as Map).entries)
|
||||
(entry.key as String).replaceAll('_', '-').toLowerCase(): entry.value,
|
||||
};
|
||||
|
||||
final String id, title, description, defaultLanguage, presentation;
|
||||
final String campaignAsset, notebookAsset;
|
||||
final String? coverAsset, scriptsAsset, tracksAsset;
|
||||
final int? continueAt;
|
||||
final int initiallyAccessible;
|
||||
final Map<String, dynamic> languages;
|
||||
|
||||
String languageFor(String requested) {
|
||||
final tag = requested.replaceAll('_', '-').toLowerCase();
|
||||
if (languages.containsKey(tag)) return tag;
|
||||
final base = tag.split('-').first;
|
||||
return languages.containsKey(base) ? base : defaultLanguage;
|
||||
}
|
||||
}
|
||||
|
||||
class StoryLibrary {
|
||||
StoryLibrary(
|
||||
this.stories, {
|
||||
AssetBundle? bundle,
|
||||
this.copy = TranslationCatalog.english,
|
||||
}) : bundle = bundle ?? rootBundle {
|
||||
if (stories.isEmpty ||
|
||||
stories.map((s) => s.id).toSet().length != stories.length) {
|
||||
throw const FormatException('The library needs unique story IDs.');
|
||||
}
|
||||
for (final story in stories) {
|
||||
if (!RegExp(r'^[a-z0-9-]+$').hasMatch(story.id) ||
|
||||
!story.languages.containsKey(story.defaultLanguage)) {
|
||||
throw FormatException('Invalid story definition: ${story.id}');
|
||||
}
|
||||
}
|
||||
}
|
||||
final List<StoryDefinition> stories;
|
||||
final AssetBundle bundle;
|
||||
final TranslationCatalog copy;
|
||||
|
||||
static Future<StoryLibrary> load({AssetBundle? bundle}) async {
|
||||
final assets = bundle ?? rootBundle;
|
||||
final data = jsonDecode(await assets.loadString('assets/library.json'));
|
||||
return StoryLibrary(
|
||||
(data['stories'] as List).map((s) => StoryDefinition(s)).toList(),
|
||||
bundle: assets,
|
||||
copy: await TranslationCatalog.load(assets),
|
||||
);
|
||||
}
|
||||
|
||||
StoryDefinition definition(String id) =>
|
||||
stories.where((s) => s.id == id).firstOrNull ?? stories.first;
|
||||
|
||||
final Map<String, Future<Book>> _books = {};
|
||||
Future<Book> open(String id, {String language = 'en'}) {
|
||||
final story = definition(id);
|
||||
final key = '${story.id}:${story.languageFor(language)}';
|
||||
return _books.putIfAbsent(
|
||||
key,
|
||||
() => Book.loadDefinition(story, language: language, bundle: bundle)
|
||||
.catchError((Object error, StackTrace stack) {
|
||||
_books.remove(key);
|
||||
Error.throwWithStackTrace(error, stack);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user