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 data) : id = data['id'], title = data['title'], description = data['description'] ?? '', coverAsset = data['coverAsset'], paperAsset = data['paperAsset'], defaultLanguage = (data['defaultLanguage'] as String? ?? 'en') .replaceAll('_', '-') .toLowerCase(), campaignAsset = data['campaignAsset'], notebookAsset = data['notebookAsset'], scriptsAsset = data['scriptsAsset'], tracksAsset = data['tracksAsset'], atmosphereAsset = data['atmosphereAsset'], 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, paperAsset, scriptsAsset, tracksAsset, atmosphereAsset; final int? continueAt; final int initiallyAccessible; final Map 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 stories; final AssetBundle bundle; final TranslationCatalog copy; static Future 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> _books = {}; Future 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); }), ); } }