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);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
+366
-237
@@ -2,9 +2,17 @@ import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'ui/translation.dart';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:intl/date_symbol_data_local.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
|
||||
import 'domain/library.dart';
|
||||
import 'services/translation.dart';
|
||||
|
||||
import 'domain/book.dart';
|
||||
import 'domain/game.dart';
|
||||
@@ -17,6 +25,8 @@ import 'ui/board.dart';
|
||||
import 'ui/discovery.dart';
|
||||
import 'ui/paper.dart';
|
||||
|
||||
part 'ui/mara_story.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
LicenseRegistry.addLicense(() async* {
|
||||
@@ -31,8 +41,17 @@ Future<void> main() async {
|
||||
systemNavigationBarColor: Color(0xff314345),
|
||||
),
|
||||
);
|
||||
final book = await Book.load(), progress = await Progress.load();
|
||||
final game = Game(book, progress);
|
||||
await initializeDateFormatting();
|
||||
final library = await StoryLibrary.load(), progress = await Progress.load();
|
||||
final deviceLanguage = WidgetsBinding.instance.platformDispatcher.locale
|
||||
.toLanguageTag();
|
||||
final preference = progress.text('language', 'system');
|
||||
final book = await library.open(
|
||||
progress.text('selected_story', 'mara-island'),
|
||||
language: preference == 'system' ? deviceLanguage : preference,
|
||||
);
|
||||
final game = Game(book, progress, library: library)
|
||||
..deviceLanguage = deviceLanguage;
|
||||
await game.restore();
|
||||
runApp(LumenApp(game: game));
|
||||
}
|
||||
@@ -42,24 +61,62 @@ class LumenApp extends StatelessWidget {
|
||||
final Game game;
|
||||
final bool adsEnabled;
|
||||
@override
|
||||
Widget build(BuildContext context) => MaterialApp(
|
||||
title: 'Lumen',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: blue, surface: cream),
|
||||
scaffoldBackgroundColor: cream,
|
||||
fontFamily: 'MaraHand',
|
||||
textTheme: ThemeData.light().textTheme.apply(
|
||||
fontFamily: 'MaraHand',
|
||||
bodyColor: ink,
|
||||
displayColor: ink,
|
||||
),
|
||||
dialogTheme: const DialogThemeData(backgroundColor: cream),
|
||||
textButtonTheme: TextButtonThemeData(
|
||||
style: TextButton.styleFrom(textStyle: hand(22), foregroundColor: blue),
|
||||
),
|
||||
),
|
||||
home: Notebook(game: game, adsEnabled: adsEnabled),
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: game,
|
||||
builder: (context, _) {
|
||||
final catalog = game.library?.copy ?? TranslationCatalog.english;
|
||||
final language = game.requestedLanguage.replaceAll('_', '-');
|
||||
final locale = localeFromTag(language);
|
||||
final parts = language.split('-');
|
||||
final languages = <String>{
|
||||
...catalog.languages.keys,
|
||||
...?game.library?.stories.expand((s) => s.languages.keys),
|
||||
};
|
||||
final latin = const [
|
||||
'en',
|
||||
'de',
|
||||
'fr',
|
||||
'es',
|
||||
'it',
|
||||
'pt',
|
||||
'nl',
|
||||
'da',
|
||||
'sv',
|
||||
'no',
|
||||
'fi',
|
||||
].contains(parts.first);
|
||||
return MaterialApp(
|
||||
title: 'Lumen',
|
||||
debugShowCheckedModeBanner: false,
|
||||
locale: locale,
|
||||
supportedLocales: languages.map(localeFromTag).toList(),
|
||||
localizationsDelegates: GlobalMaterialLocalizations.delegates,
|
||||
builder: (context, child) => CopyScope(
|
||||
catalog: catalog,
|
||||
language: language,
|
||||
overrides: game.book.copy,
|
||||
child: child!,
|
||||
),
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: blue, surface: cream),
|
||||
scaffoldBackgroundColor: cream,
|
||||
fontFamily: latin ? 'MaraHand' : null,
|
||||
textTheme: ThemeData.light().textTheme.apply(
|
||||
fontFamily: latin ? 'MaraHand' : null,
|
||||
bodyColor: ink,
|
||||
displayColor: ink,
|
||||
),
|
||||
dialogTheme: const DialogThemeData(backgroundColor: cream),
|
||||
textButtonTheme: TextButtonThemeData(
|
||||
style: TextButton.styleFrom(
|
||||
textStyle: hand(22),
|
||||
foregroundColor: blue,
|
||||
),
|
||||
),
|
||||
),
|
||||
home: Notebook(game: game, adsEnabled: adsEnabled),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -88,10 +145,11 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
bool _foreground = true;
|
||||
String _route = '';
|
||||
String get route =>
|
||||
'${g.screen.name}:${g.screen == Screen.story ? g.storyIndex : g.campaignIndex}';
|
||||
'${g.book.id}:${g.book.language}:${g.screen.name}:${g.screen == Screen.story ? g.storyIndex : g.campaignIndex}';
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
unawaited(initializeDateFormatting());
|
||||
narrator = widget.narrator ?? Narrator(g.book.tracks);
|
||||
ambience = Ambience();
|
||||
narrator.addListener(_syncAtmosphere);
|
||||
@@ -107,6 +165,9 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
}
|
||||
|
||||
void _changed() {
|
||||
if (!identical(narrator.tracks, g.book.tracks)) {
|
||||
narrator.replaceTracks(g.book.tracks);
|
||||
}
|
||||
if (_route != route) {
|
||||
_route = route;
|
||||
unawaited(narrator.stop());
|
||||
@@ -124,6 +185,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
_foreground &&
|
||||
[Screen.story, Screen.briefing, Screen.reveal].contains(g.screen) &&
|
||||
!(g.screen == Screen.story &&
|
||||
g.book.isMara &&
|
||||
g.storyPage.type == StoryPageType.note &&
|
||||
!prefs.flag('notebook_note_open'));
|
||||
narrator.scheduleAutoplay(
|
||||
@@ -142,7 +204,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
Screen.reveal,
|
||||
].contains(g.screen);
|
||||
ambience.update(
|
||||
scene: inStory ? soundscapeFor(g.campaignIndex) : null,
|
||||
scene: inStory && g.book.isMara ? soundscapeFor(g.campaignIndex) : null,
|
||||
enabled: atmosphereEnabled,
|
||||
foreground: _foreground,
|
||||
narrating: narrator.playing || narrator.loading,
|
||||
@@ -150,6 +212,20 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeLocales(List<Locale>? locales) {
|
||||
g.deviceLanguage = locales?.firstOrNull?.toLanguageTag() ?? 'en';
|
||||
if (g.languagePreference == 'system') {
|
||||
unawaited(
|
||||
g.selectLanguage('system').catchError((Object _) {
|
||||
if (mounted) {
|
||||
toast('This language could not be opened. Please try again.');
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
_foreground = state == AppLifecycleState.resumed;
|
||||
@@ -175,7 +251,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(text, style: hand(20, color: cream)),
|
||||
content: CopyText(text, style: hand(20, color: cream)),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -190,16 +266,16 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: Text(title, style: hand(29)),
|
||||
content: Text(text, style: hand(23)),
|
||||
title: CopyText(title, style: hand(29)),
|
||||
content: CopyText(text, style: hand(23)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(c, false),
|
||||
child: Text(no),
|
||||
child: CopyText(no),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(c, true),
|
||||
child: Text(yes),
|
||||
child: CopyText(yes),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -213,10 +289,10 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: Text(title, style: hand(29)),
|
||||
content: SingleChildScrollView(child: Text(text, style: hand(23))),
|
||||
title: CopyText(title, style: hand(29)),
|
||||
content: SingleChildScrollView(child: CopyText(text, style: hand(23))),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(c), child: Text(close)),
|
||||
TextButton(onPressed: () => Navigator.pop(c), child: CopyText(close)),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -256,7 +332,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
if (direction > 0) {
|
||||
g.startCampaign(index);
|
||||
} else if (index > 0) {
|
||||
if (index == 4) {
|
||||
if (index == g.book.continueAt) {
|
||||
g.showStory(g.book.pages.length - 1);
|
||||
} else {
|
||||
g.reveal(index - 1, readAhead: true);
|
||||
@@ -292,7 +368,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
|
||||
void nextCampaign() {
|
||||
final index = g.campaignIndex;
|
||||
if (index == 11) {
|
||||
if (index == g.book.levels.length - 1) {
|
||||
g.contents();
|
||||
return;
|
||||
}
|
||||
@@ -305,7 +381,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
}
|
||||
|
||||
if (g.recovered(index) &&
|
||||
(index + 1) % 4 == 0 &&
|
||||
g.book.chapterLevels(g.book.chapterFor(index)).last == index &&
|
||||
!prefs.flag('storyAd_$index')) {
|
||||
unawaited(prefs.set('storyAd_$index', true));
|
||||
ads.between(next);
|
||||
@@ -397,7 +473,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
Expanded(child: Divider(color: muted.withValues(alpha: .3))),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
child: Text('❦', style: hand(27, color: muted)),
|
||||
child: CopyText('❦', style: hand(27, color: muted)),
|
||||
),
|
||||
Expanded(child: Divider(color: muted.withValues(alpha: .3))),
|
||||
],
|
||||
@@ -416,7 +492,11 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
constraints: const BoxConstraints(maxWidth: 650),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: folio('L U M E N / AN ISLAND STORY'),
|
||||
child: folio(
|
||||
g.book.isMara
|
||||
? 'L U M E N / AN ISLAND STORY'
|
||||
: 'L U M E N / STORY LIBRARY',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -429,44 +509,81 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 650),
|
||||
child: column([
|
||||
writing('A light to come\nhome to.', size: 40),
|
||||
Image.asset(
|
||||
'assets/artwork/home-harbour-v2.png',
|
||||
height: 220,
|
||||
fit: BoxFit.contain,
|
||||
semanticLabel: 'Watercolour of the island at dusk, with the lighthouse and Gran’s cottage.',
|
||||
),
|
||||
writing(
|
||||
'Some things are worth keeping. — Gran',
|
||||
g.book.isMara
|
||||
? 'A light to come\nhome to.'
|
||||
: g.book.title,
|
||||
size: 40,
|
||||
),
|
||||
if (g.book.isMara)
|
||||
Image.asset(
|
||||
'assets/artwork/home-harbour-v2.png',
|
||||
height: 220,
|
||||
fit: BoxFit.contain,
|
||||
semanticLabel: 'Watercolour of the island at dusk, with the lighthouse and Gran’s cottage.',
|
||||
),
|
||||
writing(
|
||||
g.book.isMara
|
||||
? 'Some things are worth keeping. — Gran'
|
||||
: g.book.description,
|
||||
size: 25,
|
||||
color: const Color(0xff70503b),
|
||||
),
|
||||
Cover(onTap: g.openNotebook),
|
||||
if (g.book.isMara)
|
||||
Cover(onTap: g.openNotebook)
|
||||
else if (g.book.coverAsset case final asset?)
|
||||
InkWell(
|
||||
onTap: g.openNotebook,
|
||||
child: Image.asset(
|
||||
asset,
|
||||
height: 220,
|
||||
semanticLabel: g.book.title,
|
||||
),
|
||||
),
|
||||
action(
|
||||
'Open Mara’s notebook · ${g.recoveredCount} / 12',
|
||||
'Open ${g.book.title} · ${g.recoveredCount} / ${g.book.levels.length}',
|
||||
g.openNotebook,
|
||||
primary: true,
|
||||
),
|
||||
action('Story library', storyLibrary),
|
||||
action('Language', chooseLanguage),
|
||||
if (g.requestedLanguage
|
||||
.replaceAll('_', '-')
|
||||
.split('-')
|
||||
.first !=
|
||||
g.book.language.split('-').first)
|
||||
writing(
|
||||
'This story is shown in its original language.',
|
||||
size: 18,
|
||||
color: muted,
|
||||
),
|
||||
gap(),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
Text(
|
||||
'${g.streak}\nDAY STREAK',
|
||||
textAlign: TextAlign.center,
|
||||
style: hand(18, color: blue),
|
||||
Expanded(
|
||||
child: CopyText(
|
||||
'${g.streak}\nDAY STREAK',
|
||||
textAlign: TextAlign.center,
|
||||
style: hand(18, color: blue),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${g.solved}\nPATTERNS FOUND',
|
||||
textAlign: TextAlign.center,
|
||||
style: hand(18, color: blue),
|
||||
Expanded(
|
||||
child: CopyText(
|
||||
'${g.solved}\nPATTERNS FOUND',
|
||||
textAlign: TextAlign.center,
|
||||
style: hand(18, color: blue),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
divider(),
|
||||
folio('A SMALL DAILY RITUAL'),
|
||||
writing(
|
||||
DateFormat('EEEE, d MMMM').format(DateTime.now()),
|
||||
DateFormat(
|
||||
'EEEE, d MMMM',
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(DateTime.now()),
|
||||
size: 27,
|
||||
),
|
||||
action(
|
||||
@@ -513,6 +630,153 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
),
|
||||
),
|
||||
);
|
||||
Future<void> storyLibrary() async {
|
||||
narrator.cancelAutoplay();
|
||||
final catalogue = g.library;
|
||||
if (catalogue == null) return;
|
||||
List<Book> books;
|
||||
try {
|
||||
books = await Future.wait(
|
||||
catalogue.stories.map(
|
||||
(story) => catalogue.open(story.id, language: g.requestedLanguage),
|
||||
),
|
||||
);
|
||||
} catch (_) {
|
||||
if (mounted) toast('This story could not be opened. Please try again.');
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
final selected = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: const CopyText('Story library'),
|
||||
content: SizedBox(
|
||||
width: 520,
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
for (final story in books)
|
||||
ListTile(
|
||||
leading: story.coverAsset == null
|
||||
? null
|
||||
: Image.asset(story.coverAsset!, width: 56),
|
||||
title: Text(story.title),
|
||||
subtitle: Text(
|
||||
'${story.description}\n${catalogue.definition(story.id).languages.values.map((v) => v['label']).join(' · ')}',
|
||||
),
|
||||
isThreeLine: true,
|
||||
selected: story.id == g.book.id,
|
||||
onTap: () => Navigator.pop(c, story.id),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(c),
|
||||
child: const CopyText('Close'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (selected == null || !mounted) return;
|
||||
try {
|
||||
await g.selectStory(selected);
|
||||
} catch (_) {
|
||||
if (mounted) toast('This story could not be opened. Please try again.');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> chooseLanguage() async {
|
||||
narrator.cancelAutoplay();
|
||||
final catalogue = g.library;
|
||||
if (catalogue == null) return;
|
||||
final languages = <String, String>{...catalogue.copy.languages};
|
||||
for (final story in catalogue.stories) {
|
||||
for (final entry in story.languages.entries) {
|
||||
languages[entry.key] = entry.value['label'];
|
||||
}
|
||||
}
|
||||
final selected = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (c) => SimpleDialog(
|
||||
title: const CopyText('Language'),
|
||||
children: [
|
||||
SimpleDialogOption(
|
||||
onPressed: () => Navigator.pop(c, 'system'),
|
||||
child: CopyText(
|
||||
'${g.languagePreference == 'system' ? '✓ ' : ''}Follow device language',
|
||||
),
|
||||
),
|
||||
for (final entry in languages.entries)
|
||||
SimpleDialogOption(
|
||||
onPressed: () => Navigator.pop(c, entry.key),
|
||||
child: Text(
|
||||
'${g.languagePreference == entry.key ? '✓ ' : ''}${entry.value}',
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: CopyText(
|
||||
'Missing translations use the story’s original language. Your reading position and puzzle marks are shared across languages.',
|
||||
style: hand(18),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (selected == null || !mounted) return;
|
||||
try {
|
||||
await g.selectLanguage(selected);
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
toast('This language could not be opened. Please try again.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Widget standardStory() {
|
||||
final p = g.storyPage;
|
||||
final heading = <Widget>[
|
||||
folio('${g.book.title} / ${g.storyIndex + 1} OF ${g.book.pages.length}'),
|
||||
writing(p.title, size: 31),
|
||||
];
|
||||
final body = <Widget>[
|
||||
...heading,
|
||||
if (p.speaker.isNotEmpty) writing(p.speaker, size: 17, color: muted),
|
||||
if (p.illustrationAsset case final asset?)
|
||||
Image.asset(
|
||||
asset,
|
||||
height: 155,
|
||||
fit: BoxFit.contain,
|
||||
semanticLabel: p.caption.isEmpty ? p.title : p.caption,
|
||||
),
|
||||
if (p.caption.isNotEmpty) reading(p.caption, size: 18),
|
||||
if (p.type == StoryPageType.memory)
|
||||
discoveryArt(g.book.levels[p.campaignIndex!], height: 155),
|
||||
if (p.text.isNotEmpty) reading(p.text),
|
||||
if (p.continuation.isNotEmpty) reading(p.continuation),
|
||||
if (g.book.tracks.containsKey(p.id)) audio(),
|
||||
if (p.type == StoryPageType.puzzle) puzzleBody(),
|
||||
if (p.type == StoryPageType.memory)
|
||||
action(
|
||||
g.recovered(p.campaignIndex!)
|
||||
? 'View the solved pattern'
|
||||
: 'Return to this pattern',
|
||||
() => g.startCampaign(p.campaignIndex!),
|
||||
),
|
||||
];
|
||||
return Leaf(
|
||||
key: ValueKey('${g.book.id}-story-${p.id}'),
|
||||
onTurn: (d) => turn(d),
|
||||
body: column(body),
|
||||
wideBody: p.type == StoryPageType.puzzle
|
||||
? splitPuzzle(side: [...heading, areaPicker(), ...puzzleNotes()])
|
||||
: null,
|
||||
footer: navigation(),
|
||||
);
|
||||
}
|
||||
|
||||
void bookmark() {
|
||||
unawaited(
|
||||
prefs.set('notebook_manual_bookmark', g.book.pages[g.storyIndex].id),
|
||||
@@ -529,7 +793,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
);
|
||||
final next = InkButton(
|
||||
g.storyIndex == g.book.pages.length - 1
|
||||
? 'Across the tide →'
|
||||
? (g.book.isMara ? 'Across the tide →' : 'Back to contents')
|
||||
: 'Next leaf →',
|
||||
() => turn(1),
|
||||
size: wide ? 19 : 21,
|
||||
@@ -542,6 +806,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
Expanded(child: InkButton('Contents', g.contents, size: 19)),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(child: InkButton('Bookmark', bookmark, size: 19)),
|
||||
Expanded(child: InkButton('Language', chooseLanguage, size: 19)),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(child: InkButton('Close book', g.home, size: 19)),
|
||||
const SizedBox(width: 6),
|
||||
@@ -557,6 +822,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
Expanded(child: InkButton('Contents', g.contents, size: 20)),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(child: InkButton('Bookmark', bookmark, size: 20)),
|
||||
Expanded(child: InkButton('Language', chooseLanguage, size: 20)),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(child: InkButton('Close book', g.home, size: 20)),
|
||||
],
|
||||
@@ -584,7 +850,8 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
style: hand(size ?? (g.storyIndex == 0 ? 22 : 21)),
|
||||
style: hand(size ?? (g.storyIndex == 0 ? 22 : 21))
|
||||
.copyWith(fontFamily: g.book.fontFamily ?? 'sans-serif'),
|
||||
children: index < 0
|
||||
? [TextSpan(text: text)]
|
||||
: [
|
||||
@@ -611,7 +878,9 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
: g.book.tracks[recordingId]?['speaker']) ==
|
||||
'Narrator'
|
||||
? 'Narrator · recorded story'
|
||||
: 'Mara · diary reading',
|
||||
: g.book.isMara
|
||||
? 'Mara · diary reading'
|
||||
: '${g.book.tracks[recordingId]?['speaker'] ?? g.storyPage.speaker} · recorded story',
|
||||
size: 17,
|
||||
color: muted,
|
||||
),
|
||||
@@ -640,162 +909,8 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
InkButton('Sound & atmosphere', soundSettings, size: 18),
|
||||
]),
|
||||
);
|
||||
Widget story() {
|
||||
final p = g.book.pages[g.storyIndex];
|
||||
final heading = <Widget>[
|
||||
folio('THE COTTAGE / ${g.storyIndex + 1} OF ${g.book.pages.length}'),
|
||||
writing(p.title, size: 31),
|
||||
];
|
||||
final body = <Widget>[...heading];
|
||||
Widget? wideBody;
|
||||
switch (p.type) {
|
||||
case StoryPageType.dedication:
|
||||
body.addAll([
|
||||
writing('A few things worth keeping', size: 20, color: muted),
|
||||
divider(),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
]);
|
||||
case StoryPageType.entry:
|
||||
body.addAll([
|
||||
if (p.illustrationAsset case final asset?)
|
||||
Image.asset(
|
||||
asset,
|
||||
height: 155,
|
||||
fit: BoxFit.contain,
|
||||
semanticLabel: 'Watercolour of Gran’s stone cottage, blue door and warm window.',
|
||||
),
|
||||
writing(p.speaker, size: 17, color: muted),
|
||||
reading(p.text),
|
||||
if (p.continuation.isNotEmpty) reading(p.continuation),
|
||||
if (g.book.tracks.containsKey(p.id)) audio(),
|
||||
if (p.campaignIndex != 0)
|
||||
action('Turn to the pattern →', () => turn(1)),
|
||||
]);
|
||||
case StoryPageType.puzzle:
|
||||
final intro = writing(
|
||||
g.campaignIndex < 2
|
||||
? 'Restore a small light, or leave a bookmark and read on.'
|
||||
: 'Compare the shared areas. Each cell counts in every area it belongs to.',
|
||||
size: 21,
|
||||
color: muted,
|
||||
);
|
||||
body.addAll([intro, puzzleBody()]);
|
||||
wideBody = splitPuzzle(
|
||||
side: [...heading, intro, areaPicker(), ...puzzleNotes()],
|
||||
);
|
||||
case StoryPageType.memory:
|
||||
body.addAll([
|
||||
discoveryArt(g.book.levels[p.campaignIndex!], height: 155),
|
||||
writing(
|
||||
g.recovered(p.campaignIndex!)
|
||||
? 'A pattern restored · a memory kept'
|
||||
: 'A memory to read · your puzzle can wait',
|
||||
size: 17,
|
||||
color: muted,
|
||||
),
|
||||
reading(p.text),
|
||||
if (p.continuation.isNotEmpty) reading(p.continuation),
|
||||
if (g.book.tracks.containsKey(p.id)) audio(),
|
||||
action(
|
||||
g.recovered(p.campaignIndex!)
|
||||
? 'View the solved pattern'
|
||||
: 'Return to this pattern',
|
||||
() => g.showStory(
|
||||
g.book.pageFor(p.campaignIndex!, StoryPageType.puzzle),
|
||||
),
|
||||
),
|
||||
]);
|
||||
case StoryPageType.note:
|
||||
if (!prefs.flag('notebook_note_open')) {
|
||||
body.addAll([
|
||||
writing('A folded scrap, tucked between the leaves.'),
|
||||
GestureDetector(
|
||||
onTap: openLetter,
|
||||
child: const Sketch('envelope', height: 190),
|
||||
),
|
||||
action('Unfold Gran’s note', openLetter),
|
||||
writing(
|
||||
'You don’t have to solve anything to discover this.',
|
||||
size: 20,
|
||||
color: muted,
|
||||
),
|
||||
]);
|
||||
} else {
|
||||
body.addAll([
|
||||
writing(
|
||||
'For the crossing',
|
||||
size: 28,
|
||||
color: const Color(0xff70503b),
|
||||
),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
action('Fold the note again', () {
|
||||
unawaited(narrator.stop());
|
||||
unawaited(prefs.set('notebook_note_open', false));
|
||||
setState(() {});
|
||||
}),
|
||||
]);
|
||||
}
|
||||
case StoryPageType.inspection:
|
||||
body.addAll([
|
||||
writing(
|
||||
prefs.flag('notebook_handle_seen')
|
||||
? 'A repair made to keep small fingers safe.'
|
||||
: 'A repair note, tucked into the margin.',
|
||||
size: 20,
|
||||
color: muted,
|
||||
),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
action('Read Gran’s margin note', inspect),
|
||||
action('Follow the lantern into the next entry →', () => turn(1)),
|
||||
]);
|
||||
case StoryPageType.closing:
|
||||
body.addAll([
|
||||
reading(p.text),
|
||||
if (g.book.tracks.containsKey(p.id)) audio(),
|
||||
writing(
|
||||
'Four memories in the cottage · ${List.generate(4, (i) => g.recovered(i)).where((v) => v).length} patterns restored',
|
||||
size: 19,
|
||||
color: muted,
|
||||
),
|
||||
action(
|
||||
'Take the path to the harbour →',
|
||||
crossToHarbour,
|
||||
primary: true,
|
||||
),
|
||||
writing(
|
||||
'Your unfinished patterns will wait here for you.',
|
||||
size: 19,
|
||||
color: muted,
|
||||
),
|
||||
]);
|
||||
}
|
||||
return Leaf(
|
||||
key: ValueKey('story-${g.storyIndex}'),
|
||||
onTurn: (d) => turn(d),
|
||||
body: column(body),
|
||||
wideBody: wideBody,
|
||||
footer: navigation(),
|
||||
);
|
||||
}
|
||||
|
||||
void openLetter() {
|
||||
unawaited(prefs.set('notebook_note_open', true));
|
||||
_scheduleAutoplay();
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
Future<void> inspect() async {
|
||||
await prefs.set('notebook_handle_seen', true);
|
||||
await message(
|
||||
'A careful repair',
|
||||
'The wire is hidden under a strip of cloth. In the margin, Gran has written: “The light matters. So do the hands carrying it.”',
|
||||
close: 'Keep that thought',
|
||||
);
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
void refreshNotebook() => setState(() {});
|
||||
Widget story() => g.book.isMara ? maraStory() : standardStory();
|
||||
|
||||
Future<void> speed() async {
|
||||
await narrator.pause();
|
||||
@@ -803,7 +918,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (c) => SimpleDialog(
|
||||
title: Text('Recording speed', style: hand(29)),
|
||||
title: CopyText('Recording speed', style: hand(29)),
|
||||
children: [
|
||||
for (final entry in [
|
||||
(0.85, 'Unhurried · 0.85×'),
|
||||
@@ -815,7 +930,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
unawaited(prefs.set('recording_speed', entry.$1));
|
||||
Navigator.pop(c);
|
||||
},
|
||||
child: Text(entry.$2, style: hand(23)),
|
||||
child: CopyText(entry.$2, style: hand(23)),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -836,7 +951,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
}
|
||||
|
||||
return AlertDialog(
|
||||
title: Text('Sound & atmosphere', style: hand(29)),
|
||||
title: CopyText('Sound & atmosphere', style: hand(29)),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@@ -844,7 +959,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
children: [
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text('Environmental sounds', style: hand(23)),
|
||||
title: CopyText('Environmental sounds', style: hand(23)),
|
||||
value: atmosphereEnabled,
|
||||
onChanged: (value) => save('ambience_enabled', value),
|
||||
),
|
||||
@@ -875,7 +990,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext),
|
||||
child: const Text('Keep going'),
|
||||
child: const CopyText('Keep going'),
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -886,7 +1001,8 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
|
||||
Widget contents() {
|
||||
final chapter = g.contentsChapter;
|
||||
final first = chapter * 4;
|
||||
final indices = g.book.chapterLevels(chapter);
|
||||
final first = indices.first;
|
||||
final savedId = prefs.text('notebook_last_page');
|
||||
final saved = g.book.pages.where((p) => p.id == savedId).firstOrNull;
|
||||
final bookmarkId = prefs.text('notebook_manual_bookmark');
|
||||
@@ -894,9 +1010,18 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
return Leaf(
|
||||
key: ValueKey('contents-$chapter'),
|
||||
body: column([
|
||||
folio('MARA’S NOTEBOOK · CONTENTS'),
|
||||
folio('${g.book.title.toUpperCase()} · CONTENTS'),
|
||||
writing(g.book.levels[first].chapter, size: 34),
|
||||
if (chapter == 0) ...[
|
||||
if (chapter == 0 && !g.book.isMara) ...[
|
||||
reading(g.book.premise),
|
||||
action('Continue reading', g.openNotebook),
|
||||
if (ribbon != null)
|
||||
action(
|
||||
'Return to my ribbon bookmark',
|
||||
() => g.showStory(g.book.pages.indexOf(ribbon)),
|
||||
),
|
||||
],
|
||||
if (chapter == 0 && g.book.isMara) ...[
|
||||
writing(
|
||||
'For you, when you are ready. With all my love, Gran.',
|
||||
color: const Color(0xff70503b),
|
||||
@@ -911,7 +1036,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
),
|
||||
divider(),
|
||||
],
|
||||
for (var i = first; i < first + 4; i++) ...[
|
||||
for (final i in indices) ...[
|
||||
InkButton(
|
||||
'${i + 1} · ${g.book.levels[i].title}${g.recovered(i) ? ' ✓' : ''}${chapter == 0 && ribbon?.campaignIndex == i ? ' · ribbon' : ''}',
|
||||
i <= g.accessible
|
||||
@@ -925,7 +1050,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
: null,
|
||||
),
|
||||
],
|
||||
if (chapter == 0) ...[
|
||||
if (chapter == 0 && g.book.isMara) ...[
|
||||
divider(),
|
||||
action('The folded note', () => g.showStory(4)),
|
||||
action('Gran’s repair note', () => g.showStory(5)),
|
||||
@@ -935,7 +1060,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
),
|
||||
],
|
||||
writing(
|
||||
'${g.recoveredCount} / 12 memories restored',
|
||||
'${g.recoveredCount} / ${g.book.levels.length} memories restored',
|
||||
size: 20,
|
||||
color: muted,
|
||||
),
|
||||
@@ -953,7 +1078,8 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
Expanded(
|
||||
child: InkButton(
|
||||
'Next chapter →',
|
||||
chapter < 2 && (chapter + 1) * 4 <= g.accessible
|
||||
chapter + 1 < g.book.chapters.length &&
|
||||
g.book.chapterLevels(chapter + 1).first <= g.accessible
|
||||
? () => g.contents(chapter + 1)
|
||||
: null,
|
||||
size: 19,
|
||||
@@ -972,7 +1098,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
key: ValueKey('briefing-${g.campaignIndex}'),
|
||||
onTurn: (d) => turnCampaign(d),
|
||||
body: column([
|
||||
folio('MARA’S NOTEBOOK / LEAF ${g.campaignIndex + 1}'),
|
||||
folio('${g.book.title.toUpperCase()} / LEAF ${g.campaignIndex + 1}'),
|
||||
writing(l.chapter, size: 20, color: blue),
|
||||
writing(l.title, size: 33),
|
||||
gap(),
|
||||
@@ -990,7 +1116,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
action(
|
||||
g.recovered(g.campaignIndex)
|
||||
? 'View the solved pattern →'
|
||||
: prefs.contains('grid_story_v1_${g.campaignIndex}')
|
||||
: prefs.contains('grid_${g.book.puzzleKey(g.campaignIndex)}')
|
||||
? 'Continue this pattern →'
|
||||
: 'Restore the pattern →',
|
||||
() => g.startCampaign(g.campaignIndex),
|
||||
@@ -1107,9 +1233,9 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
List<Widget> heading({bool compact = false}) => [
|
||||
folio(
|
||||
g.mode == Mode.daily
|
||||
? 'DAILY / ${DateFormat('d MMMM').format(g.date)}'
|
||||
? 'DAILY / ${DateFormat('d MMMM', Localizations.localeOf(context).languageCode).format(g.date)}'
|
||||
: g.mode == Mode.campaign
|
||||
? 'THE LAST LIGHT / ${g.campaignIndex + 1} OF 12'
|
||||
? '${g.book.title.toUpperCase()} / ${g.campaignIndex + 1} OF ${g.book.levels.length}'
|
||||
: 'CLASSIC / ${g.difficulty.label} / LEVEL ${g.playingLevel}',
|
||||
),
|
||||
writing(
|
||||
@@ -1213,7 +1339,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
if (h == null) return;
|
||||
await message(
|
||||
'Row ${h.cell ~/ g.puzzle!.size + 1}, column ${h.cell % g.puzzle!.size + 1}',
|
||||
'${h.explanation}\n\n${h.value == 1 ? 'This cell is lit.' : 'This cell stays dark.'}',
|
||||
'${CopyScope.text(context, h.explanation)}\n\n${CopyScope.text(context, h.value == 1 ? 'This cell is lit.' : 'This cell stays dark.')}',
|
||||
);
|
||||
if (mounted &&
|
||||
g.key == requested &&
|
||||
@@ -1286,7 +1412,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
key: ValueKey('reveal-$i'),
|
||||
onTurn: (d) => turnCampaign(d),
|
||||
body: column([
|
||||
folio('MARA’S NOTEBOOK / LEAF ${i + 1}'),
|
||||
folio('${g.book.title.toUpperCase()} / LEAF ${i + 1}'),
|
||||
writing(
|
||||
g.recovered(i)
|
||||
? 'Something found. Something remembered.'
|
||||
@@ -1312,15 +1438,15 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
color: const Color(0xff70503b),
|
||||
),
|
||||
divider(),
|
||||
if (i == 11) ...[
|
||||
if (i == g.book.levels.length - 1) ...[
|
||||
folio(
|
||||
g.recoveredCount == 12
|
||||
g.recoveredCount == g.book.levels.length
|
||||
? 'THE END · YOUR WATCH HAS BEGUN'
|
||||
: 'THE LAST PAGE · COME BACK WHENEVER YOU LIKE',
|
||||
),
|
||||
writing(
|
||||
g.recoveredCount == 12
|
||||
? 'Twelve patterns. One light brought home. The daily puzzle will be here whenever you return.'
|
||||
g.recoveredCount == g.book.levels.length
|
||||
? 'Every pattern restored. The daily puzzle will be here whenever you return.'
|
||||
: 'A light kept in these pages. Your unfinished patterns will be here whenever you return.',
|
||||
),
|
||||
action('Return to the notebook', g.contents, primary: true),
|
||||
@@ -1336,7 +1462,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (c) => SimpleDialog(
|
||||
title: Text('Classic practice pace', style: hand(29)),
|
||||
title: CopyText('Classic practice pace', style: hand(29)),
|
||||
children: [
|
||||
for (final d in Difficulty.values)
|
||||
SimpleDialogOption(
|
||||
@@ -1344,7 +1470,10 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
|
||||
g.selectDifficulty(d);
|
||||
Navigator.pop(c);
|
||||
},
|
||||
child: Text('${d.label} — ${d.description}', style: hand(23)),
|
||||
child: CopyText(
|
||||
'${CopyScope.text(context, d.label)} — ${CopyScope.text(context, d.description)}',
|
||||
style: hand(23),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -11,7 +11,12 @@ class Narrator extends ChangeNotifier {
|
||||
);
|
||||
_subscriptions.add(_player.positionStream.listen((_) => notifyListeners()));
|
||||
}
|
||||
final Map<String, dynamic> tracks;
|
||||
Map<String, dynamic> tracks;
|
||||
void replaceTracks(Map<String, dynamic> value) {
|
||||
unawaited(stop());
|
||||
tracks = value;
|
||||
}
|
||||
|
||||
final _player = AudioPlayer();
|
||||
final List<StreamSubscription<dynamic>> _subscriptions = [];
|
||||
String page = '', error = '';
|
||||
@@ -101,7 +106,10 @@ class Narrator extends ChangeNotifier {
|
||||
if (generation != _generation) return;
|
||||
page = id;
|
||||
// PCM WAV avoids silent FLAC playback on the API 26 Huawei tablet.
|
||||
await _player.setAsset('assets/audio/${tracks[id]['file']}');
|
||||
await _player.setAsset(
|
||||
tracks[id]['asset'] as String? ??
|
||||
'assets/audio/${tracks[id]['file']}',
|
||||
);
|
||||
if (generation != _generation) return;
|
||||
} else if (finished) {
|
||||
await _player.seek(Duration.zero);
|
||||
|
||||
+36
-14
@@ -2,7 +2,27 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Flutter has its own store; the former Android `lumen.xml` is never imported.
|
||||
class Progress {
|
||||
Progress._(this._disk, this._values);
|
||||
Progress._(this._disk, this._values, [this._storyId, this._root]);
|
||||
final String? _storyId;
|
||||
final Progress? _root;
|
||||
|
||||
/// The original book retains its existing save keys. Other stories get a
|
||||
/// namespace; device settings, daily/practice records and totals stay global.
|
||||
Progress forStory(String id) => Progress._(_disk, _values, id, _root ?? this);
|
||||
String _key(String key) {
|
||||
if (_storyId == null || _storyId == 'mara-island') return key;
|
||||
final storyKey =
|
||||
key.startsWith('notebook_') ||
|
||||
key.startsWith('flutter_') ||
|
||||
key.startsWith('viewed_') ||
|
||||
key.startsWith('storyAd_') ||
|
||||
key.startsWith('grid_story_') ||
|
||||
key.startsWith('done_story_') ||
|
||||
key == 'campaignUnlocked' ||
|
||||
key == 'story_access_level';
|
||||
return storyKey ? 'story/$_storyId/$key' : key;
|
||||
}
|
||||
|
||||
final SharedPreferencesAsync? _disk;
|
||||
final Map<String, Object> _values;
|
||||
static Future<Progress> load() async {
|
||||
@@ -13,35 +33,37 @@ class Progress {
|
||||
factory Progress.memory([Map<String, Object> values = const {}]) =>
|
||||
Progress._(null, Map.of(values));
|
||||
int number(String key, [int fallback = 0]) =>
|
||||
(_values[key] as num?)?.toInt() ?? fallback;
|
||||
(_values[_key(key)] as num?)?.toInt() ?? fallback;
|
||||
double decimal(String key, [double fallback = 1]) =>
|
||||
(_values[key] as num?)?.toDouble() ?? fallback;
|
||||
bool flag(String key) => _values[key] == true;
|
||||
(_values[_key(key)] as num?)?.toDouble() ?? fallback;
|
||||
bool flag(String key) => _values[_key(key)] == true;
|
||||
String text(String key, [String fallback = '']) =>
|
||||
_values[key] as String? ?? fallback;
|
||||
bool contains(String key) => _values.containsKey(key);
|
||||
_values[_key(key)] as String? ?? fallback;
|
||||
bool contains(String key) => _values.containsKey(_key(key));
|
||||
Map<String, Object> get snapshot => Map.unmodifiable(_values);
|
||||
Future<void> _writes = Future.value();
|
||||
Future<void> set(String key, Object value) {
|
||||
_values[key] = value;
|
||||
_values[_key(key)] = value;
|
||||
final disk = _disk;
|
||||
if (disk == null) return Future.value();
|
||||
_writes = _writes.then((_) async {
|
||||
final writer = _root ?? this;
|
||||
final storedKey = _key(key);
|
||||
writer._writes = writer._writes.then((_) async {
|
||||
switch (value) {
|
||||
case bool v:
|
||||
await disk.setBool(key, v);
|
||||
await disk.setBool(storedKey, v);
|
||||
case int v:
|
||||
await disk.setInt(key, v);
|
||||
await disk.setInt(storedKey, v);
|
||||
case double v:
|
||||
await disk.setDouble(key, v);
|
||||
await disk.setDouble(storedKey, v);
|
||||
case String v:
|
||||
await disk.setString(key, v);
|
||||
await disk.setString(storedKey, v);
|
||||
default:
|
||||
throw ArgumentError('Unsupported preference');
|
||||
}
|
||||
});
|
||||
return _writes;
|
||||
return writer._writes;
|
||||
}
|
||||
|
||||
Future<void> get flushed => _writes;
|
||||
Future<void> get flushed => (_root ?? this)._writes;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// UI messages use their English source as catalogue keys. Numbered slots in
|
||||
/// dynamic messages are preserved by translators and can be reordered.
|
||||
class TranslationCatalog {
|
||||
const TranslationCatalog(this.languages, this.messages);
|
||||
static const english = TranslationCatalog({'en': 'English'}, {});
|
||||
final Map<String, String> languages;
|
||||
final Map<String, Map<String, String>> messages;
|
||||
|
||||
static Future<TranslationCatalog> load(AssetBundle bundle) async {
|
||||
final index = jsonDecode(
|
||||
await bundle.loadString('assets/locales/catalog.json'),
|
||||
) as Map;
|
||||
final messages = <String, Map<String, String>>{};
|
||||
final languages = <String, String>{};
|
||||
for (final entry in index.entries) {
|
||||
languages[entry.key] = entry.value['label'];
|
||||
messages[entry.key] = Map<String, String>.from(
|
||||
jsonDecode(await bundle.loadString(entry.value['asset'])),
|
||||
);
|
||||
for (final message in messages[entry.key]!.entries) {
|
||||
Set<String> slots(String text) =>
|
||||
RegExp(r'\{\d+\}').allMatches(text).map((m) => m[0]!).toSet();
|
||||
if (slots(message.key).difference(slots(message.value)).isNotEmpty ||
|
||||
slots(message.value).difference(slots(message.key)).isNotEmpty) {
|
||||
throw FormatException(
|
||||
'Translation placeholders differ: ${entry.key}: ${message.key}',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return TranslationCatalog(languages, messages);
|
||||
}
|
||||
|
||||
MessageTranslator translator(
|
||||
String locale, {
|
||||
Map<String, String> overrides = const {},
|
||||
}) {
|
||||
final tag = locale.replaceAll('_', '-').toLowerCase();
|
||||
return MessageTranslator({
|
||||
...?messages['en'],
|
||||
...?messages[tag.split('-').first],
|
||||
...?messages[tag],
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
String text(
|
||||
String source,
|
||||
String locale, {
|
||||
Map<String, String> overrides = const {},
|
||||
}) => translator(locale, overrides: overrides).text(source);
|
||||
}
|
||||
|
||||
class MessageTranslator {
|
||||
MessageTranslator(this.messages) {
|
||||
for (final entry in messages.entries) {
|
||||
if (entry.key == entry.value) continue;
|
||||
final slots = _slots.allMatches(entry.key).toList();
|
||||
if (slots.isEmpty) continue;
|
||||
var pattern = '^', end = 0;
|
||||
for (final slot in slots) {
|
||||
pattern += RegExp.escape(entry.key.substring(end, slot.start));
|
||||
pattern += r'([\s\S]*?)';
|
||||
end = slot.end;
|
||||
}
|
||||
pattern += '${RegExp.escape(entry.key.substring(end))}\$';
|
||||
_templates.add(
|
||||
_Template(
|
||||
RegExp(pattern),
|
||||
entry.value,
|
||||
slots.map((m) => m[1]!).toList(),
|
||||
entry.key.length - slots.fold(0, (n, m) => n + m[0]!.length),
|
||||
),
|
||||
);
|
||||
}
|
||||
// "Row {0}, column {1}" must match before the shorter "Row {0}".
|
||||
_templates.sort((a, b) => b.specificity.compareTo(a.specificity));
|
||||
}
|
||||
static final _slots = RegExp(r'\{(\d+)\}');
|
||||
final Map<String, String> messages;
|
||||
final List<_Template> _templates = [];
|
||||
|
||||
String text(String source) => _text(source, 0);
|
||||
String _text(String source, int depth) {
|
||||
final exact = messages[source];
|
||||
if (exact != null && exact != source) return exact;
|
||||
if (depth > 4) return source;
|
||||
for (final template in _templates) {
|
||||
final match = template.pattern.firstMatch(source);
|
||||
if (match == null) continue;
|
||||
final values = <String, String>{
|
||||
for (var i = 0; i < template.slots.length; i++)
|
||||
template.slots[i]: _text(match[i + 1]!, depth + 1),
|
||||
};
|
||||
return template.value.replaceAllMapped(
|
||||
_slots,
|
||||
(m) => values[m[1]] ?? m[0]!,
|
||||
);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
}
|
||||
|
||||
class _Template {
|
||||
const _Template(this.pattern, this.value, this.slots, this.specificity);
|
||||
final RegExp pattern;
|
||||
final String value;
|
||||
final List<String> slots;
|
||||
final int specificity;
|
||||
}
|
||||
+136
-128
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/puzzle.dart';
|
||||
import 'paper.dart';
|
||||
import 'translation.dart';
|
||||
|
||||
class Board extends StatelessWidget {
|
||||
const Board({
|
||||
@@ -25,149 +26,155 @@ class Board extends StatelessWidget {
|
||||
final double maxWidth;
|
||||
@override
|
||||
Widget build(BuildContext context) => PageSwipeBlocker(
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxWidth: maxWidth),
|
||||
child: AspectRatio(
|
||||
aspectRatio: 1,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, c) {
|
||||
final n = puzzle.size,
|
||||
u = c.maxWidth / (n + 1.3),
|
||||
r = puzzle.regions.isEmpty
|
||||
? null
|
||||
: puzzle.regions[selectedArea];
|
||||
Widget clue(String text, bool complete) => SizedBox(
|
||||
width: u,
|
||||
height: u,
|
||||
child: Center(
|
||||
child: Text(
|
||||
text,
|
||||
style: hand(
|
||||
(u * .42).clamp(16, 23),
|
||||
color: complete ? blue : muted,
|
||||
child: Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxWidth: maxWidth),
|
||||
child: AspectRatio(
|
||||
aspectRatio: 1,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, c) {
|
||||
final n = puzzle.size,
|
||||
u = c.maxWidth / (n + 1.3),
|
||||
r = puzzle.regions.isEmpty
|
||||
? null
|
||||
: puzzle.regions[selectedArea];
|
||||
Widget clue(String text, bool complete) => SizedBox(
|
||||
width: u,
|
||||
height: u,
|
||||
child: Center(
|
||||
child: Text(
|
||||
text,
|
||||
style: hand(
|
||||
(u * .42).clamp(16, 23),
|
||||
color: complete ? blue : muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
bool complete(Iterable<int> indices, int total) =>
|
||||
indices.where((i) => cells[i] == 1).length == total;
|
||||
return Align(
|
||||
alignment: Alignment.center,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
SizedBox(width: u, height: u),
|
||||
for (var col = 0; col < n; col++)
|
||||
clue(
|
||||
'${puzzle.cols[col]}',
|
||||
complete(
|
||||
List.generate(n, (i) => i * n + col),
|
||||
puzzle.cols[col],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
for (var row = 0; row < n; row++)
|
||||
);
|
||||
bool complete(Iterable<int> indices, int total) =>
|
||||
indices.where((i) => cells[i] == 1).length == total;
|
||||
return Align(
|
||||
alignment: Alignment.center,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
clue(
|
||||
'${puzzle.rows[row]}',
|
||||
complete(
|
||||
List.generate(n, (i) => row * n + i),
|
||||
puzzle.rows[row],
|
||||
),
|
||||
),
|
||||
SizedBox(width: u, height: u),
|
||||
for (var col = 0; col < n; col++)
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final i = row * n + col,
|
||||
value = cells[i],
|
||||
fixed = puzzle.given[i],
|
||||
inside = r?.contains(i, n) ?? false;
|
||||
final state = value == 0
|
||||
? 'empty'
|
||||
: value == 1
|
||||
? 'lit'
|
||||
: 'crossed out';
|
||||
return Semantics(
|
||||
label:
|
||||
clue(
|
||||
'${puzzle.cols[col]}',
|
||||
complete(
|
||||
List.generate(n, (i) => i * n + col),
|
||||
puzzle.cols[col],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
for (var row = 0; row < n; row++)
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
clue(
|
||||
'${puzzle.rows[row]}',
|
||||
complete(
|
||||
List.generate(n, (i) => row * n + i),
|
||||
puzzle.rows[row],
|
||||
),
|
||||
),
|
||||
for (var col = 0; col < n; col++)
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final i = row * n + col,
|
||||
value = cells[i],
|
||||
fixed = puzzle.given[i],
|
||||
inside = r?.contains(i, n) ?? false;
|
||||
final state = value == 0
|
||||
? 'empty'
|
||||
: value == 1
|
||||
? 'lit'
|
||||
: 'crossed out';
|
||||
return Semantics(
|
||||
label: CopyScope.text(
|
||||
context,
|
||||
'Row ${row + 1}, column ${col + 1}, $state${fixed ? ', fixed clue' : ''}',
|
||||
button: !fixed && !won,
|
||||
enabled: !fixed && !won,
|
||||
onTap: fixed || won ? null : () => onMark(i),
|
||||
excludeSemantics: true,
|
||||
child: GestureDetector(
|
||||
key: ValueKey('cell-$i'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
),
|
||||
button: !fixed && !won,
|
||||
enabled: !fixed && !won,
|
||||
onTap: fixed || won
|
||||
? null
|
||||
: () => onMark(i),
|
||||
child: SizedBox(
|
||||
width: u,
|
||||
height: u,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(2),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: inside
|
||||
? amber.withValues(alpha: .22)
|
||||
: Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(
|
||||
2,
|
||||
),
|
||||
border: Border.all(
|
||||
excludeSemantics: true,
|
||||
child: GestureDetector(
|
||||
key: ValueKey('cell-$i'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: fixed || won
|
||||
? null
|
||||
: () => onMark(i),
|
||||
child: SizedBox(
|
||||
width: u,
|
||||
height: u,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(2),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: inside
|
||||
? const Color(0xffaa5b2a)
|
||||
: muted.withValues(
|
||||
alpha: .48,
|
||||
),
|
||||
width: inside ? 1.4 : .65,
|
||||
? amber.withValues(alpha: .22)
|
||||
: Colors.transparent,
|
||||
borderRadius:
|
||||
BorderRadius.circular(2),
|
||||
border: Border.all(
|
||||
color: inside
|
||||
? const Color(0xffaa5b2a)
|
||||
: muted.withValues(
|
||||
alpha: .48,
|
||||
),
|
||||
width: inside ? 1.4 : .65,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Stack(
|
||||
children: [
|
||||
if (value != 0)
|
||||
Positioned.fill(
|
||||
child: CustomPaint(
|
||||
painter: PencilMark(
|
||||
value: value,
|
||||
variation: i,
|
||||
child: Stack(
|
||||
children: [
|
||||
if (value != 0)
|
||||
Positioned.fill(
|
||||
child: CustomPaint(
|
||||
painter: PencilMark(
|
||||
value: value,
|
||||
variation: i,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (fixed)
|
||||
Positioned(
|
||||
right: 3,
|
||||
bottom: 3,
|
||||
child: Container(
|
||||
width: 4,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: muted,
|
||||
shape: BoxShape.circle,
|
||||
if (fixed)
|
||||
Positioned(
|
||||
right: 3,
|
||||
bottom: 3,
|
||||
child: Container(
|
||||
width: 4,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: muted,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -265,7 +272,7 @@ class PixelPicture extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) => Semantics(
|
||||
image: true,
|
||||
label: 'Recovered pixel picture: $label',
|
||||
label: CopyScope.text(context, 'Recovered pixel picture: $label'),
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
width: height,
|
||||
@@ -307,7 +314,7 @@ class PatternStamp extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) => Semantics(
|
||||
image: true,
|
||||
label: 'Your restored seven by seven pattern: $label',
|
||||
label: CopyScope.text(context, 'Your restored pattern: $label'),
|
||||
child: SizedBox.square(
|
||||
dimension: height,
|
||||
child: CustomPaint(painter: _Pixels(picture)),
|
||||
@@ -320,10 +327,11 @@ class _Pixels extends CustomPainter {
|
||||
final List<int> picture;
|
||||
@override
|
||||
void paint(Canvas c, Size s) {
|
||||
final p = Paint()..color = blue, u = s.width / 7;
|
||||
for (var i = 0; i < 49; i++) {
|
||||
final n = math.sqrt(picture.length).round();
|
||||
final p = Paint()..color = blue, u = s.width / n;
|
||||
for (var i = 0; i < picture.length; i++) {
|
||||
if (picture[i] == 1) {
|
||||
c.drawRect(Rect.fromLTWH(i % 7 * u, i ~/ 7 * u, u + .3, u + .3), p);
|
||||
c.drawRect(Rect.fromLTWH(i % n * u, i ~/ n * u, u + .3, u + .3), p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'translation.dart';
|
||||
|
||||
import 'board.dart';
|
||||
import 'paper.dart';
|
||||
|
||||
@@ -90,7 +92,7 @@ class _DiscoveryState extends State<Discovery>
|
||||
PatternStamp(widget.picture, label: widget.label, height: 56),
|
||||
const SizedBox(width: 14),
|
||||
Flexible(
|
||||
child: Text(
|
||||
child: CopyText(
|
||||
'Your restored pattern\n${widget.label}',
|
||||
style: hand(18, color: muted),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
part of '../main.dart';
|
||||
|
||||
// The original story's folded note and repair inspection are optional book
|
||||
// presentation behavior. Standard story packages use the reusable page renderer.
|
||||
extension _MaraStory on _NotebookState {
|
||||
Widget maraStory() {
|
||||
final p = g.book.pages[g.storyIndex];
|
||||
final heading = <Widget>[
|
||||
folio('THE COTTAGE / ${g.storyIndex + 1} OF ${g.book.pages.length}'),
|
||||
writing(p.title, size: 31),
|
||||
];
|
||||
final body = <Widget>[...heading];
|
||||
Widget? wideBody;
|
||||
switch (p.type) {
|
||||
case StoryPageType.dedication:
|
||||
body.addAll([
|
||||
writing('A few things worth keeping', size: 20, color: muted),
|
||||
divider(),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
]);
|
||||
case StoryPageType.entry:
|
||||
body.addAll([
|
||||
if (p.illustrationAsset case final asset?)
|
||||
Image.asset(
|
||||
asset,
|
||||
height: 155,
|
||||
fit: BoxFit.contain,
|
||||
semanticLabel: 'Watercolour of Gran’s stone cottage, blue door and warm window.',
|
||||
),
|
||||
writing(p.speaker, size: 17, color: muted),
|
||||
reading(p.text),
|
||||
if (p.continuation.isNotEmpty) reading(p.continuation),
|
||||
if (g.book.tracks.containsKey(p.id)) audio(),
|
||||
if (p.campaignIndex != 0)
|
||||
action('Turn to the pattern →', () => turn(1)),
|
||||
]);
|
||||
case StoryPageType.puzzle:
|
||||
final intro = writing(
|
||||
g.campaignIndex < 2
|
||||
? 'Restore a small light, or leave a bookmark and read on.'
|
||||
: 'Compare the shared areas. Each cell counts in every area it belongs to.',
|
||||
size: 21,
|
||||
color: muted,
|
||||
);
|
||||
body.addAll([intro, puzzleBody()]);
|
||||
wideBody = splitPuzzle(
|
||||
side: [...heading, intro, areaPicker(), ...puzzleNotes()],
|
||||
);
|
||||
case StoryPageType.memory:
|
||||
body.addAll([
|
||||
discoveryArt(g.book.levels[p.campaignIndex!], height: 155),
|
||||
writing(
|
||||
g.recovered(p.campaignIndex!)
|
||||
? 'A pattern restored · a memory kept'
|
||||
: 'A memory to read · your puzzle can wait',
|
||||
size: 17,
|
||||
color: muted,
|
||||
),
|
||||
reading(p.text),
|
||||
if (p.continuation.isNotEmpty) reading(p.continuation),
|
||||
if (g.book.tracks.containsKey(p.id)) audio(),
|
||||
action(
|
||||
g.recovered(p.campaignIndex!)
|
||||
? 'View the solved pattern'
|
||||
: 'Return to this pattern',
|
||||
() => g.showStory(
|
||||
g.book.pageFor(p.campaignIndex!, StoryPageType.puzzle),
|
||||
),
|
||||
),
|
||||
]);
|
||||
case StoryPageType.note:
|
||||
if (!prefs.flag('notebook_note_open')) {
|
||||
body.addAll([
|
||||
writing('A folded scrap, tucked between the leaves.'),
|
||||
GestureDetector(
|
||||
onTap: openLetter,
|
||||
child: const Sketch('envelope', height: 190),
|
||||
),
|
||||
action('Unfold Gran’s note', openLetter),
|
||||
writing(
|
||||
'You don’t have to solve anything to discover this.',
|
||||
size: 20,
|
||||
color: muted,
|
||||
),
|
||||
]);
|
||||
} else {
|
||||
body.addAll([
|
||||
writing(
|
||||
'For the crossing',
|
||||
size: 28,
|
||||
color: const Color(0xff70503b),
|
||||
),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
action('Fold the note again', () {
|
||||
unawaited(narrator.stop());
|
||||
unawaited(prefs.set('notebook_note_open', false));
|
||||
refreshNotebook();
|
||||
}),
|
||||
]);
|
||||
}
|
||||
case StoryPageType.inspection:
|
||||
body.addAll([
|
||||
writing(
|
||||
prefs.flag('notebook_handle_seen')
|
||||
? 'A repair made to keep small fingers safe.'
|
||||
: 'A repair note, tucked into the margin.',
|
||||
size: 20,
|
||||
color: muted,
|
||||
),
|
||||
reading(p.text),
|
||||
audio(),
|
||||
action('Read Gran’s margin note', inspect),
|
||||
action('Follow the lantern into the next entry →', () => turn(1)),
|
||||
]);
|
||||
case StoryPageType.closing:
|
||||
body.addAll([
|
||||
reading(p.text),
|
||||
if (g.book.tracks.containsKey(p.id)) audio(),
|
||||
writing(
|
||||
'Four memories in the cottage · ${List.generate(4, (i) => g.recovered(i)).where((v) => v).length} patterns restored',
|
||||
size: 19,
|
||||
color: muted,
|
||||
),
|
||||
action(
|
||||
'Take the path to the harbour →',
|
||||
crossToHarbour,
|
||||
primary: true,
|
||||
),
|
||||
writing(
|
||||
'Your unfinished patterns will wait here for you.',
|
||||
size: 19,
|
||||
color: muted,
|
||||
),
|
||||
]);
|
||||
}
|
||||
return Leaf(
|
||||
key: ValueKey('story-${g.storyIndex}'),
|
||||
onTurn: (d) => turn(d),
|
||||
body: column(body),
|
||||
wideBody: wideBody,
|
||||
footer: navigation(),
|
||||
);
|
||||
}
|
||||
|
||||
void openLetter() {
|
||||
unawaited(prefs.set('notebook_note_open', true));
|
||||
_scheduleAutoplay();
|
||||
refreshNotebook();
|
||||
}
|
||||
|
||||
Future<void> inspect() async {
|
||||
await prefs.set('notebook_handle_seen', true);
|
||||
await message(
|
||||
'A careful repair',
|
||||
'The wire is hidden under a strip of cloth. In the margin, Gran has written: “The light matters. So do the hands carrying it.”',
|
||||
close: 'Keep that thought',
|
||||
);
|
||||
if (mounted) refreshNotebook();
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -1,6 +1,9 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'translation.dart';
|
||||
|
||||
import 'package:flutter/gestures.dart';
|
||||
|
||||
const ink = Color(0xff36413c),
|
||||
@@ -16,7 +19,7 @@ TextStyle hand(double size, {Color color = ink}) => TextStyle(
|
||||
);
|
||||
Widget writing(String value, {double size = 23, Color color = ink}) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 5),
|
||||
child: Text(value, style: hand(size, color: color)),
|
||||
child: CopyText(value, style: hand(size, color: color)),
|
||||
);
|
||||
|
||||
class InkButton extends StatelessWidget {
|
||||
@@ -49,7 +52,7 @@ class InkButton extends StatelessWidget {
|
||||
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 8),
|
||||
shape: const RoundedRectangleBorder(),
|
||||
),
|
||||
child: Text(label, textAlign: TextAlign.center),
|
||||
child: CopyText(label, textAlign: TextAlign.center),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -241,7 +244,7 @@ class Cover extends StatelessWidget {
|
||||
child: Center(
|
||||
child: Transform.rotate(
|
||||
angle: -.044,
|
||||
child: Text(
|
||||
child: CopyText(
|
||||
'Mara’s\nisland notebook',
|
||||
textAlign: TextAlign.center,
|
||||
style: hand(28),
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../services/translation.dart';
|
||||
|
||||
Locale localeFromTag(String tag) {
|
||||
final parts = tag.replaceAll('_', '-').split('-');
|
||||
final script = parts.skip(1).where((p) => p.length == 4).firstOrNull;
|
||||
final region = parts
|
||||
.skip(1)
|
||||
.where((p) => p.length == 2 || p.length == 3)
|
||||
.firstOrNull;
|
||||
return Locale.fromSubtags(
|
||||
languageCode: parts.first.toLowerCase(),
|
||||
scriptCode: script == null
|
||||
? null
|
||||
: '${script[0].toUpperCase()}${script.substring(1).toLowerCase()}',
|
||||
countryCode: region?.toUpperCase(),
|
||||
);
|
||||
}
|
||||
|
||||
class CopyScope extends InheritedWidget {
|
||||
CopyScope({
|
||||
super.key,
|
||||
required this.catalog,
|
||||
required this.language,
|
||||
this.overrides = const {},
|
||||
required super.child,
|
||||
}) : translator = catalog.translator(language, overrides: overrides);
|
||||
final TranslationCatalog catalog;
|
||||
final MessageTranslator translator;
|
||||
final String language;
|
||||
final Map<String, String> overrides;
|
||||
static String text(BuildContext context, String source) {
|
||||
final scope = context.dependOnInheritedWidgetOfExactType<CopyScope>();
|
||||
return scope?.translator.text(source) ?? source;
|
||||
}
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(CopyScope old) =>
|
||||
old.language != language ||
|
||||
old.catalog != catalog ||
|
||||
old.overrides != overrides;
|
||||
}
|
||||
|
||||
class CopyText extends StatelessWidget {
|
||||
const CopyText(this.data, {super.key, this.style, this.textAlign});
|
||||
final String data;
|
||||
final TextStyle? style;
|
||||
final TextAlign? textAlign;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final language = Localizations.maybeLocaleOf(context)?.languageCode ?? 'en';
|
||||
final latin = const [
|
||||
'en',
|
||||
'de',
|
||||
'fr',
|
||||
'es',
|
||||
'it',
|
||||
'pt',
|
||||
'nl',
|
||||
'da',
|
||||
'sv',
|
||||
'no',
|
||||
'fi',
|
||||
].contains(language);
|
||||
return Text(
|
||||
CopyScope.text(context, data),
|
||||
style: latin
|
||||
? style
|
||||
: (style ?? const TextStyle()).copyWith(fontFamily: 'sans-serif'),
|
||||
textAlign: textAlign,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user