Files
logic-puzzle/lib/main.dart
T
Hadrian Burkhardt 0718e3f252 Open Lumen on a responsive bookshelf and land pending story work
- Start the app on a shelf of every installed book instead of the last
  book's home. Cards show the cover, translated metadata, available
  languages, restored patterns and either "Continue reading" or a way in.
- Keep each book's saved route: the shelf is never written to
  flutter_screen, so choosing a book resumes its own leaf.
- Lay the shelf out responsively: dense single-column cards on phones,
  a two-column grid from 720 logical pixels, a centred 860 px column on
  tablets and a chevron that exists in the bundled handwriting font.
- Keep Settings reachable from the shelf and let the home page's story
  library button open the shelf instead of a dialog.
- Add tool/shelf_screenshots_test.dart, which renders the shelf at phone
  and tablet metrics, checks that every card and Settings stay reachable
  without overflow, and writes artifacts/library/shelf-*.png.
- Commit the pending Midnight Invitation package (campaign, notebook,
  narration and artwork), cast drama and ambience tooling, region
  selection, phone/tablet integration coverage and related docs.

flutter analyze is clean and all 74 widget/domain tests pass.
2026-11-05 14:29:50 +01:00

1720 lines
57 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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';
import 'domain/puzzle.dart';
import 'services/ads.dart';
import 'services/ambience.dart';
import 'services/narrator.dart';
import 'services/progress.dart';
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* {
yield LicenseEntryWithLineBreaks([
'Dancing Script',
], await rootBundle.loadString('assets/fonts/OFL.txt'));
});
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: cream,
statusBarIconBrightness: Brightness.dark,
systemNavigationBarColor: Color(0xff314345),
),
);
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();
// The shelf is the first window. `restore()` has already positioned each
// book's saved leaf, so choosing a book resumes exactly where it was left.
game.showLibrary();
runApp(LumenApp(game: game));
}
class LumenApp extends StatelessWidget {
const LumenApp({super.key, required this.game, this.adsEnabled = true});
final Game game;
final bool adsEnabled;
@override
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),
);
},
);
}
class Notebook extends StatefulWidget {
const Notebook({
super.key,
required this.game,
required this.adsEnabled,
this.narrator,
this.ambience,
this.ads,
});
final Game game;
final bool adsEnabled;
final Narrator? narrator;
final Ambience? ambience;
final Ads? ads;
@override
State<Notebook> createState() => _NotebookState();
}
class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
Game get g => widget.game;
Progress get prefs => g.progress;
late final Narrator narrator;
late final Ambience ambience;
late final Ads ads;
bool _foreground = true;
String _route = '';
Future<List<Book>>? _shelf;
String _shelfLanguage = '';
String get route =>
'${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 = widget.ambience ?? Ambience();
narrator.addListener(_syncAtmosphere);
ads = widget.ads ?? Ads(enabled: widget.adsEnabled);
g.addListener(_changed);
_route = route;
WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(ads.start());
_syncAtmosphere();
if (mounted) _scheduleAutoplay();
});
}
void _changed() {
if (!identical(narrator.tracks, g.book.tracks)) {
narrator.replaceTracks(g.book.tracks);
}
if (_route != route) {
_route = route;
unawaited(narrator.stop());
_scheduleAutoplay();
}
_syncAtmosphere();
if (mounted) setState(() {});
}
bool get atmosphereEnabled =>
!prefs.contains('ambience_enabled') || prefs.flag('ambience_enabled');
void _scheduleAutoplay() {
final recordedPage =
_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(
recordedPage ? recordingId : null,
prefs.decimal('recording_speed'),
);
}
void _syncAtmosphere() {
final inStory =
g.mode == Mode.campaign &&
[
Screen.story,
Screen.briefing,
Screen.game,
Screen.reveal,
].contains(g.screen);
ambience.update(
scene: !inStory
? null
: g.book.isMara
? soundscapeFor(g.campaignIndex)
: g.screen == Screen.story
? g.book.atmosphere[g.storyPage.id]
: null,
enabled: atmosphereEnabled,
foreground: _foreground,
narrating: narrator.playing || narrator.loading,
volume: prefs.decimal('ambience_volume', .7),
);
}
@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;
_syncAtmosphere();
if (state != AppLifecycleState.resumed) {
unawaited(narrator.stop());
unawaited(prefs.flushed);
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
g.removeListener(_changed);
narrator.removeListener(_syncAtmosphere);
ambience.dispose();
narrator.dispose();
ads.dispose();
super.dispose();
}
void toast(String text) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: CopyText(text, style: hand(20, color: cream)),
),
);
}
}
Future<bool> confirm(
String title,
String text,
String yes, {
String no = 'Keep reading',
}) async =>
await showDialog<bool>(
context: context,
builder: (c) => AlertDialog(
title: CopyText(title, style: hand(29)),
content: CopyText(text, style: hand(23)),
actions: [
TextButton(
onPressed: () => Navigator.pop(c, false),
child: CopyText(no),
),
TextButton(
onPressed: () => Navigator.pop(c, true),
child: CopyText(yes),
),
],
),
) ??
false;
Future<void> message(
String title,
String text, {
String close = 'Keep going',
}) async {
await showDialog<void>(
context: context,
builder: (c) => AlertDialog(
title: CopyText(title, style: hand(29)),
content: SingleChildScrollView(child: CopyText(text, style: hand(23))),
actions: [
TextButton(onPressed: () => Navigator.pop(c), child: CopyText(close)),
],
),
);
}
Future<void> turn(int direction) async {
if (direction > 0 && g.storyIndex == g.book.pages.length - 1) {
readingBreak(g.book.pages.length, crossToHarbour);
return;
}
final next = (g.storyIndex + direction).clamp(0, g.book.pages.length - 1);
if (next == g.storyIndex) return;
final pageId = g.storyPage.id;
if (g.storyPage.type == StoryPageType.puzzle && direction > 0 && !g.won) {
unawaited(narrator.stop());
if (!await confirm(
'Leave a ribbon here?',
'Your puzzle marks are saved. You can read the memory now and come back to solve the pattern whenever you like.',
'Read ahead',
no: 'Keep solving',
)) {
return;
}
await prefs.set('notebook_read_ahead', true);
}
if (mounted && g.storyPage.id == pageId) {
if (direction > 0) {
readingBreak(next, () => g.showStory(next));
} else {
g.showStory(next);
}
}
}
void readingBreak(int position, VoidCallback next) {
final book = g.book;
final legacyLevels = book.continueAt == null
? 0
: book.levels.length - book.continueAt!;
final total = book.pages.length + legacyLevels * 3;
if (g.claimBookAd(position, total)) {
unawaited(narrator.stop());
ads.between(() {
if (mounted && g.book == book) next();
});
} else {
next();
}
}
void crossToHarbour() {
g.leaveCottage();
}
Future<void> turnCampaign(int direction) async {
final index = g.campaignIndex;
switch (g.screen) {
case Screen.briefing:
if (direction > 0) {
g.startCampaign(index);
} else if (index > 0) {
if (index == g.book.continueAt) {
g.showStory(g.book.pages.length - 1);
} else {
g.reveal(index - 1, readAhead: true);
}
} else {
g.contents();
}
case Screen.game:
if (direction < 0) {
g.briefing(index);
return;
}
if (!g.won &&
!await confirm(
'Leave a ribbon here?',
'Your puzzle marks are saved. You can read the memory now and return to this pattern whenever you like.',
'Read ahead',
no: 'Keep solving',
)) {
return;
}
if (mounted) g.reveal(index, readAhead: true);
case Screen.reveal:
if (direction < 0) {
g.startCampaign(index);
} else {
nextCampaign();
}
default:
break;
}
}
void nextCampaign() {
final index = g.campaignIndex;
if (index == g.book.levels.length - 1) {
readingBreak(
g.book.pages.length + (index - (g.book.continueAt ?? 0) + 1) * 3,
g.contents,
);
return;
}
// Reading access is distinct from completed puzzles and their awards.
unawaited(
prefs.set('story_access_level', math.max(g.accessible, index + 1)),
);
void next() {
if (mounted) g.briefing(index + 1);
}
readingBreak(
g.book.pages.length + (index - (g.book.continueAt ?? 0) + 1) * 3,
next,
);
}
void back() {
if (g.busy) {
g.home();
return;
}
if (g.screen == Screen.library) return;
if (g.screen == Screen.home) {
// With a catalogue the shelf is the app's root; without one (widget tests
// and embedders) the book's home stays the first and last leaf.
if (g.library != null) g.showLibrary();
return;
}
g.home();
}
@override
Widget build(BuildContext context) => PaperSkin(
// The shelf is shared by every book, so it uses the default notebook page
// rather than the paper of whichever book was last open.
asset: g.screen == Screen.library ? null : g.book.paperAsset,
child: PopScope(
canPop:
(g.screen == Screen.library ||
(g.screen == Screen.home && g.library == null)) &&
!g.busy,
onPopInvokedWithResult: (didPop, result) {
if (!didPop) back();
},
child: Scaffold(
body: Stack(
children: [
switch (g.screen) {
Screen.library => libraryScreen(),
Screen.home => home(),
Screen.story => story(),
Screen.contents => contents(),
Screen.briefing => briefing(),
Screen.game => game(),
Screen.reveal => reveal(),
},
if (g.busy)
Positioned.fill(
child: ColoredBox(
color: cream.withValues(alpha: .9),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(color: blue),
writing('Finding a fresh pattern…'),
InkButton('Back to the notebook', g.home),
],
),
),
),
),
],
),
),
),
);
Widget column(List<Widget> children) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
);
Widget action(String title, VoidCallback run, {bool primary = false}) =>
Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: InkButton(title, run, primary: primary),
);
Widget gap([double n = 16]) => SizedBox(height: n);
Widget divider() => Padding(
padding: const EdgeInsets.symmetric(vertical: 18),
child: Row(
children: [
Expanded(child: Divider(color: muted.withValues(alpha: .3))),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: CopyText('❦', style: hand(27, color: muted)),
),
Expanded(child: Divider(color: muted.withValues(alpha: .3))),
],
),
);
Widget folio(String text) => writing(text, size: 15, color: blue);
/// The app's first window: every installed book on one shelf. Tapping a card
/// selects that story and lets `Game.restore()` reopen its saved leaf.
Widget libraryScreen() {
final catalogue = g.library;
if (catalogue == null) {
return Leaf(
key: const ValueKey('library'),
body: column([
folio('L U M E N / STORY LIBRARY'),
writing('No stories are installed.', size: 24, color: muted),
action('Back to the notebook', g.home),
]),
);
}
return Leaf(
key: const ValueKey('library'),
body: LayoutBuilder(
builder: (context, c) {
final compact = c.maxWidth < 480;
// Wide tablets get two columns of books; phones keep one dense column.
final width = math.min(c.maxWidth, 860.0);
final columns = width >= 720 ? 2 : 1;
return Center(
child: SizedBox(
width: width,
child: column([
folio('L U M E N / STORY LIBRARY'),
writing('Choose a book', size: compact ? 34 : 40),
writing(
'Open a book to continue where you left off.',
size: compact ? 19 : 23,
color: const Color(0xff70503b),
),
gap(compact ? 10 : 16),
FutureBuilder<List<Book>>(
future: shelfBooks(catalogue),
builder: (context, snapshot) {
if (snapshot.hasError) {
return column([
writing(
'This story could not be opened. Please try again.',
size: 21,
color: muted,
),
action(
'Try again',
() => setState(() {
_shelf = null;
_shelfLanguage = '';
}),
),
]);
}
final books = snapshot.data;
if (books == null) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 40),
child: Center(
child: CircularProgressIndicator(color: blue),
),
);
}
if (books.isEmpty) {
return writing(
'No stories are installed.',
size: 22,
color: muted,
);
}
final cards = [
for (final story in books)
bookCard(story, compact: compact),
];
if (columns == 1) return column(cards);
final cardWidth = (width - 14) / 2;
return Wrap(
spacing: 14,
runSpacing: 2,
children: [
for (final card in cards)
SizedBox(width: cardWidth, child: card),
],
);
},
),
gap(4),
action('Settings', settings),
]),
),
);
},
),
);
}
/// One book on the shelf: cover, translated metadata, progress and the way
/// back into the reader. A book with a saved leaf offers "Continue reading".
/// Phones get a denser card so several books fit the narrow notebook page.
Widget bookCard(Book story, {required bool compact}) {
final catalogue = g.library;
if (catalogue == null) return const SizedBox.shrink();
final store = g.store.forStory(story.id);
final restored = [
for (var i = 0; i < story.levels.length; i++)
store.flag('done_${story.puzzleKey(i)}'),
].where((done) => done).length;
final saved = store.text('flutter_screen', 'home');
final resuming = saved != Screen.home.name && saved != Screen.library.name;
final current = story.id == g.book.id;
final languages = catalogue
.definition(story.id)
.languages
.values
.map((entry) => entry['label'] as String? ?? '')
.where((label) => label.isNotEmpty)
.toList();
return Padding(
padding: EdgeInsets.symmetric(vertical: compact ? 5 : 7),
child: InkWell(
key: ValueKey('library-book-${story.id}'),
borderRadius: BorderRadius.circular(4),
onTap: () => unawaited(openStory(story.id)),
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
color: blue.withValues(alpha: current ? .55 : .18),
width: current ? 1.5 : 1,
),
borderRadius: BorderRadius.circular(4),
),
child: Padding(
padding: EdgeInsets.all(compact ? 9 : 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (story.coverAsset case final asset?)
Padding(
padding: EdgeInsets.only(right: compact ? 10 : 14),
child: SizedBox(
width: compact ? 54 : 78,
height: compact ? 74 : 104,
child: Image.asset(
asset,
fit: BoxFit.contain,
semanticLabel: story.title,
errorBuilder: (_, _, _) => const SizedBox.shrink(),
),
),
),
Expanded(
child: column([
writing(story.title, size: compact ? 23 : 29),
if (!compact && story.description.isNotEmpty)
writing(
story.description,
size: 20,
color: const Color(0xff70503b),
),
if (languages.length > 1)
writing(
languages.join(' · '),
size: compact ? 14 : 16,
color: muted,
),
if (story.levels.isNotEmpty)
writing(
'$restored / ${story.levels.length} memories restored',
size: compact ? 14 : 17,
color: muted,
),
writing(
resuming ? 'Continue reading' : 'Open this book ›',
size: compact ? 17 : 19,
color: blue,
),
]),
),
],
),
),
),
),
);
}
/// Loads the whole catalogue once per requested language. A broken package is
/// skipped so the rest of the shelf stays usable.
Future<List<Book>> shelfBooks(StoryLibrary catalogue) {
final language = g.requestedLanguage;
final cached = _shelf;
if (cached != null && _shelfLanguage == language) return cached;
_shelfLanguage = language;
return _shelf = () async {
final books = <Book>[];
for (final story in catalogue.stories) {
try {
books.add(await catalogue.open(story.id, language: language));
} catch (_) {
continue;
}
}
return books;
}();
}
/// Waits for the shelf before switching screens, so the home button never
/// flashes a loading state and its tap settles in one pump.
Future<void> openLibrary() async {
narrator.cancelAutoplay();
final catalogue = g.library;
if (catalogue == null) return;
await shelfBooks(catalogue);
if (mounted) g.showLibrary();
}
Future<void> openStory(String id) async {
narrator.cancelAutoplay();
try {
await g.selectStory(id);
} catch (_) {
if (mounted) toast('This story could not be opened. Please try again.');
}
}
Widget home() => ColoredBox(
key: ValueKey('home-${g.book.id}'),
color: cream,
child: SafeArea(
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(28, 34, 28, 8),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 650),
child: SizedBox(
width: double.infinity,
child: folio(
g.book.isMara
? 'L U M E N / AN ISLAND STORY'
: 'L U M E N / STORY LIBRARY',
),
),
),
),
),
Expanded(
child: SingleChildScrollView(
key: const ValueKey('home-scroll'),
padding: const EdgeInsets.fromLTRB(28, 0, 28, 36),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 650),
child: column([
writing(
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),
),
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 ${g.book.title} · ${g.recoveredCount} / ${g.book.levels.length}',
g.openNotebook,
primary: true,
),
action('Story library', () => unawaited(openLibrary())),
action('Settings', settings),
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: [
Expanded(
child: CopyText(
'${g.streak}\nDAY STREAK',
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',
Localizations.localeOf(context).languageCode,
).format(DateTime.now()),
size: 27,
),
action(
'Play today’s puzzle →',
() => g.startDaily(DateTime.now()),
),
gap(),
folio('BY THE COTTAGE WINDOW'),
writing(
'A few spare pages for practice. For overlapping-area puzzles, follow the notebook’s story.',
size: 22,
color: muted,
),
action(
'Difficulty · ${g.difficulty.label} ▾',
chooseDifficulty,
),
action(
'Practice · ${g.difficulty.label} · Level ${g.practiceLevel}',
() => unawaited(g.startPractice()),
),
action('How to play', rules),
action(
'Open-source licenses',
() => showLicensePage(
context: context,
applicationName: 'Lumen',
),
),
gap(),
writing(
'Leave a light in the window.',
size: 26,
color: const Color(0xff70503b),
),
]),
),
),
),
),
],
),
),
);
Future<void> settings() => showDialog<void>(
context: context,
builder: (c) => SimpleDialog(
title: const CopyText('Settings'),
children: [
for (final option in <(String, VoidCallback)>[
('Language', chooseLanguage),
('Sound & atmosphere', soundSettings),
('Recording speed', speed),
('Privacy & advertising', privacy),
])
SimpleDialogOption(
onPressed: () {
Navigator.pop(c);
option.$2();
},
child: CopyText(option.$1),
),
],
),
);
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),
fittedBody: p.type == StoryPageType.puzzle
? fittedPuzzle(
details: [
areaPicker(),
...puzzleNotes(),
...heading,
if (p.text.isNotEmpty) reading(p.text),
if (p.continuation.isNotEmpty) reading(p.continuation),
if (g.book.tracks.containsKey(p.id)) audio(),
],
)
: null,
wideBody: p.type == StoryPageType.puzzle
? splitPuzzle(
side: [
...heading,
if (p.text.isNotEmpty) reading(p.text, size: 18),
areaPicker(),
...puzzleNotes(),
],
)
: null,
footer: navigation(),
);
}
Widget navigation() {
final wide = MediaQuery.orientationOf(context) == Orientation.landscape;
final previous = InkButton(
'← Previous leaf',
g.storyIndex > 0 ? () => turn(-1) : null,
size: wide ? 19 : 21,
);
final next = InkButton(
g.storyIndex == g.book.pages.length - 1
? (g.book.isMara ? 'Across the tide →' : 'Back to contents')
: 'Next leaf →',
() => turn(1),
size: wide ? 19 : 21,
);
return Row(
children: [
Expanded(child: previous),
const SizedBox(width: 8),
Expanded(child: next),
],
);
}
String get recordingId => g.screen == Screen.story
? g.storyPage.id
: 'campaign.${g.campaignIndex}.${g.screen == Screen.briefing ? 'before' : 'after'}';
Widget reading(String text, {double? size}) => ListenableBuilder(
listenable: narrator,
builder: (context, _) {
final passage = narrator.passage,
index = passage.isEmpty ? -1 : text.indexOf(passage);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text.rich(
TextSpan(
style: hand(size ?? (g.storyIndex == 0 ? 22 : 21))
.copyWith(fontFamily: g.book.fontFamily ?? 'sans-serif'),
children: index < 0
? [TextSpan(text: text)]
: [
TextSpan(text: text.substring(0, index)),
TextSpan(
text: passage,
style: TextStyle(
backgroundColor: amber.withValues(alpha: .35),
),
),
TextSpan(text: text.substring(index + passage.length)),
],
),
),
);
},
);
Widget audio() => ListenableBuilder(
listenable: narrator,
builder: (context, _) => column([
writing(
(narrator.page == recordingId
? narrator.speaker
: g.book.tracks[recordingId]?['speaker']) ==
'Narrator'
? 'Narrator · recorded story'
: g.book.isMara
? 'Mara · diary reading'
: '${narrator.page == recordingId ? narrator.speaker : g.book.tracks[recordingId]?['speaker'] ?? g.storyPage.speaker} · recorded story',
size: 17,
color: muted,
),
Row(
children: [
Expanded(
flex: 3,
child: InkButton(
narrator.label,
narrator.loading
? null
: () => narrator.toggle(
recordingId,
prefs.decimal('recording_speed'),
),
size: 21,
),
),
const SizedBox(width: 5),
Expanded(child: InkButton('Stop', () => narrator.stop(), size: 21)),
const SizedBox(width: 5),
Expanded(child: InkButton('Speed', speed, size: 21)),
],
),
writing(narrator.status, size: 17, color: muted),
InkButton('Sound & atmosphere', soundSettings, size: 18),
]),
);
void refreshNotebook() => setState(() {});
Widget story() => g.book.isMara ? maraStory() : standardStory();
Future<void> speed() async {
await narrator.pause();
if (!mounted) return;
await showDialog<void>(
context: context,
builder: (c) => SimpleDialog(
title: CopyText('Recording speed', style: hand(29)),
children: [
for (final entry in [
(0.85, 'Unhurried · 0.85×'),
(1.0, 'Original reading · 1.0×'),
(1.15, 'A little faster · 1.15×'),
])
SimpleDialogOption(
onPressed: () {
unawaited(prefs.set('recording_speed', entry.$1));
Navigator.pop(c);
},
child: CopyText(entry.$2, style: hand(23)),
),
],
),
);
}
Future<void> soundSettings() {
narrator.cancelAutoplay();
return showDialog<void>(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (context, refresh) {
void save(String key, Object value) {
unawaited(prefs.set(key, value));
_syncAtmosphere();
if (mounted) setState(() {});
refresh(() {});
}
return AlertDialog(
title: CopyText('Sound & atmosphere', style: hand(29)),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: CopyText('Environmental sounds', style: hand(23)),
value: atmosphereEnabled,
onChanged: (value) => save('ambience_enabled', value),
),
writing(
'Water at the harbour and bridge, wind around the tower. The atmosphere grows quieter while the story is read.',
size: 20,
),
writing('Atmosphere volume', size: 20),
Slider(
label:
'${(prefs.decimal('ambience_volume', .7) * 100).round()}%',
value: prefs.decimal('ambience_volume', .7).clamp(0.0, 1.0),
divisions: 10,
onChanged: atmosphereEnabled
? (value) => save('ambience_volume', value)
: null,
),
writing(
'Readings start 3 seconds after opening a page. You can play, pause or stop them at any time. Your device volume controls the voice.',
size: 18,
color: muted,
),
if (ambience.error.isNotEmpty)
writing(ambience.error, size: 18),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const CopyText('Keep going'),
),
],
);
},
),
);
}
Widget contents() {
final chapter = g.contentsChapter;
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');
final ribbon = g.book.pages.where((p) => p.id == bookmarkId).firstOrNull;
return Leaf(
key: ValueKey('contents-$chapter'),
body: column([
folio('${g.book.title.toUpperCase()} · CONTENTS'),
writing(g.book.levels[first].chapter, size: 34),
if (!g.book.isMara) ...[
if (chapter == 0) 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),
),
action('Open the dedication', () => g.showStory(0)),
if (saved != null)
action('Continue reading · ${saved.title}', g.openNotebook),
if (ribbon != null)
action(
'Return to my ribbon bookmark',
() => g.showStory(g.book.pages.indexOf(ribbon)),
),
divider(),
],
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
? () {
if (g.recovered(i)) {
g.reveal(i);
} else {
g.briefing(i);
}
}
: null,
),
],
if (chapter == 0 && g.book.isMara) ...[
divider(),
action('The folded note', () => g.showStory(4)),
action('Gran’s repair note', () => g.showStory(5)),
action(
'Before you leave',
() => g.showStory(g.book.pages.length - 1),
),
],
writing(
'${g.recoveredCount} / ${g.book.levels.length} memories restored',
size: 20,
color: muted,
),
]),
footer: column([
Row(
children: [
Expanded(
child: InkButton(
'← Previous chapter',
chapter > 0 ? () => g.contents(chapter - 1) : null,
size: 19,
),
),
Expanded(
child: InkButton(
'Next chapter →',
chapter + 1 < g.book.chapters.length &&
g.book.chapterLevels(chapter + 1).first <= g.accessible
? () => g.contents(chapter + 1)
: null,
size: 19,
),
),
],
),
InkButton('Close the notebook', g.home, size: 19),
]),
);
}
Widget briefing() {
final l = g.book.levels[g.campaignIndex];
return Leaf(
key: ValueKey('briefing-${g.campaignIndex}'),
onTurn: (d) => turnCampaign(d),
body: column([
folio('${g.book.title.toUpperCase()} / LEAF ${g.campaignIndex + 1}'),
writing(l.chapter, size: 20, color: blue),
writing(l.title, size: 33),
gap(),
reading(l.before, size: 25),
if (l.beforeContinuation.isNotEmpty) reading(l.beforeContinuation),
if (g.book.tracks.containsKey(recordingId)) audio(),
divider(),
writing(
g.campaignIndex < 2
? 'Light the cells to match each row and column total. Cross out the cells that stay dark. The finished grid is a picture from the story.'
: 'A, B and C are outlined areas with their own light totals. Shared cells count in each area they belong to. Compare clues and subtract their shared parts to find new deductions.',
size: 22,
color: muted,
),
action(
g.recovered(g.campaignIndex)
? 'View the solved pattern →'
: prefs.contains('grid_${g.book.puzzleKey(g.campaignIndex)}')
? 'Continue this pattern →'
: 'Restore the pattern →',
() => g.startCampaign(g.campaignIndex),
primary: true,
),
action('Back to notebook', g.contents),
]),
);
}
Widget puzzleBody() => column([areaPicker(), board(), ...puzzleNotes()]);
Widget areaPicker() {
final p = g.puzzle;
if (p == null || p.regions.isEmpty) return const SizedBox.shrink();
return column([
Wrap(
spacing: 6,
children: [
for (var i = 0; i < p.regions.length; i++)
RegionButton(
key: ValueKey('area-$i'),
label:
'${p.regions[i].label} · ${List.generate(g.cells.length, (j) => j).where((j) => p.regions[i].contains(j, p.size) && g.cells[j] == 1).length} / ${p.regionTotal(p.regions[i])}',
onPressed: () => g.area(i),
selected: i == g.selectedArea,
),
],
),
writing('Tap A, B or C to highlight its area', size: 17, color: muted),
]);
}
Widget board({double maxWidth = 350}) {
final p = g.puzzle;
if (p == null) return const SizedBox.shrink();
return Board(
puzzle: p,
cells: g.cells,
onMark: g.mark,
selectedArea: g.selectedArea,
won: g.won,
maxWidth: maxWidth,
);
}
List<Widget> puzzleNotes() => [
if (g.mode == Mode.campaign)
InkButton('Sound & atmosphere', soundSettings, size: 18),
writing(
g.won
? 'Already restored. Turn the leaf to revisit the memory.'
: 'Tap: light → cross → clear. Mark every cell.',
size: 18,
color: muted,
),
if (!g.won) InkButton('Hint · rewarded ad', hint, size: 22),
];
/// The board stays in the viewport while supporting text scrolls separately.
Widget fittedPuzzle({required List<Widget> details}) => LayoutBuilder(
builder: (context, constraints) {
final grid = math.min(
math.min(constraints.maxWidth, 350.0),
constraints.maxHeight * .70,
);
return Column(
children: [
SizedBox(
height: grid,
child: board(maxWidth: grid),
),
Expanded(
child: SingleChildScrollView(
key: const ValueKey('puzzle-details-scroll'),
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
child: column(details),
),
),
],
);
},
);
/// Landscape puzzle leaf: the grid keeps the left column at its full height
/// while the heading, area clues and notes sit beside it, so nothing has to
/// be scrolled into view before the board can be played.
Widget splitPuzzle({required List<Widget> side}) => LayoutBuilder(
builder: (context, c) {
final width = math.min(c.maxWidth, 980.0),
height = c.maxHeight.isFinite ? c.maxHeight : c.maxWidth,
// Keep a readable column for the notes, then give the rest to the
// grid, which stays a square no taller than the page.
panel = math.min(
math.min(280.0, math.max(200.0, width * .40)),
width * .55,
),
grid = math.min(math.min(height, width - panel - 18), 520.0);
return Align(
alignment: Alignment.center,
child: SizedBox(
width: width,
height: height,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: grid,
child: Center(child: board(maxWidth: grid)),
),
const SizedBox(width: 18),
Expanded(
child: SingleChildScrollView(
key: const ValueKey('leaf-side-scroll'),
padding: const EdgeInsets.fromLTRB(2, 8, 2, 8),
child: column(side),
),
),
],
),
),
);
},
);
Widget game() {
List<Widget> heading({bool compact = false}) => [
folio(
g.mode == Mode.daily
? 'DAILY / ${DateFormat('d MMMM', Localizations.localeOf(context).languageCode).format(g.date)}'
: g.mode == Mode.campaign
? '${g.book.title.toUpperCase()} / ${g.campaignIndex + 1} OF ${g.book.levels.length}'
: 'CLASSIC / ${g.difficulty.label} / LEVEL ${g.playingLevel}',
),
writing(
g.mode == Mode.campaign
? g.book.levels[g.campaignIndex].title
: 'Find the light.',
size: compact ? 27 : 32,
),
writing(
g.puzzle?.regions.isEmpty ?? true
? 'Match the totals. Let the pattern emerge.'
: 'Compare rows, columns and overlapping areas.',
size: compact ? 18 : 21,
color: muted,
),
];
final actions = <({String label, VoidCallback run, bool primary})>[
if (g.won)
(
label: g.mode == Mode.daily
? 'Return to the notebook'
: g.mode == Mode.campaign
? 'Revisit the memory →'
: 'Next puzzle →',
run: g.mode == Mode.daily
? g.home
: g.mode == Mode.campaign
? () => g.reveal(g.campaignIndex)
: nextPractice,
primary: true,
),
(label: 'How to play', run: rules, primary: false),
(
label: 'Back to notebook',
run: g.mode == Mode.campaign ? g.contents : g.home,
primary: false,
),
];
final clarity = writing('A moment of clarity.', size: 29);
return Leaf(
key: ValueKey('game-${g.key}'),
onTurn: g.mode == Mode.campaign ? (d) => turnCampaign(d) : null,
body: column([
...heading(),
puzzleBody(),
if (g.won) clarity,
for (final a in actions) action(a.label, a.run, primary: a.primary),
]),
fittedBody: fittedPuzzle(
details: [
areaPicker(),
...puzzleNotes(),
...heading(compact: true),
if (g.won) clarity,
for (final a in actions) action(a.label, a.run, primary: a.primary),
],
),
// Landscape: the heading and notes sit beside the grid while the leaf's
// actions stay in a compact bar that does not take room from the board.
wideBody: Column(
children: [
Expanded(
child: splitPuzzle(
side: [
...heading(compact: true),
areaPicker(),
...puzzleNotes(),
if (g.won) writing('A moment of clarity.', size: 23),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 6, bottom: 4),
child: Row(
children: [
for (var i = 0; i < actions.length; i++) ...[
if (i > 0) const SizedBox(width: 8),
Expanded(
child: InkButton(
actions[i].label,
actions[i].run,
size: 20,
primary: actions[i].primary,
),
),
],
],
),
),
],
),
);
}
Future<void> hint() async {
final requested = g.key;
var granted = false;
void give() async {
if (granted ||
!mounted ||
g.key != requested ||
g.won ||
!(g.screen == Screen.game ||
g.screen == Screen.story &&
g.storyPage.type == StoryPageType.puzzle)) {
return;
}
granted = true;
final h = g.applyHint();
if (h == null) return;
await message(
'Row ${h.cell ~/ g.puzzle!.size + 1}, column ${h.cell % g.puzzle!.size + 1}',
'${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 &&
(g.screen == Screen.game ||
g.screen == Screen.story &&
g.storyPage.type == StoryPageType.puzzle)) {
g.check();
}
}
if (!await confirm(
'A little nudge?',
'Watch a rewarded ad for one explained hint.',
'Watch ad',
no: 'Keep thinking',
)) {
return;
}
if (!await ads.hint(give)) {
toast('No ad available. Please try again later.');
}
}
void nextPractice() {
final n = prefs.number('practiceCompleted');
if (n > 0 && n % 4 == 0) {
ads.between(() => unawaited(g.startPractice()));
} else {
unawaited(g.startPractice());
}
}
Widget discoveryArt(CampaignLevel level, {double height = 190}) {
// Discovery images belong only to the leaf after the puzzle, even when
// revisiting an earlier page with a completed save.
if (!(g.screen == Screen.reveal ||
g.screen == Screen.story && g.storyPage.type == StoryPageType.memory)) {
return const SizedBox.shrink();
}
if (!g.recovered(g.book.levels.indexOf(level))) {
return writing(
'The picture will appear once you restore the pattern.',
size: 19,
color: muted,
);
}
if (level.illustrationAsset case final asset?) {
return Discovery(
key: ValueKey('discovery-${g.campaignIndex}'),
picture: level.picture,
label: level.object,
height: height,
artwork: Image.asset(
asset,
height: height,
width: double.infinity,
fit: BoxFit.contain,
semanticLabel: 'Watercolour illustration: ${level.object}',
errorBuilder: (_, _, _) =>
PixelPicture(level.picture, label: level.object, height: height),
),
);
}
return PixelPicture(level.picture, label: level.object, height: height);
}
Widget reveal() {
final i = g.campaignIndex, l = g.book.levels[i];
return Leaf(
key: ValueKey('reveal-$i'),
onTurn: (d) => turnCampaign(d),
body: column([
folio('${g.book.title.toUpperCase()} / LEAF ${i + 1}'),
writing(
g.recovered(i)
? 'Something found. Something remembered.'
: 'A memory to read · your pattern can wait',
size: 23,
color: muted,
),
writing(l.object, size: 35),
discoveryArt(l),
reading(l.after, size: 25),
if (l.afterContinuation.isNotEmpty) reading(l.afterContinuation),
if (g.book.tracks.containsKey(recordingId)) audio(),
action(
g.recovered(i) ? 'View the solved pattern' : 'Return to this pattern',
() => g.startCampaign(i),
),
gap(),
writing(
g.recovered(i)
? 'Kept safe, between these pages. — M.'
: 'Your pattern is saved for another day.',
size: 23,
color: const Color(0xff70503b),
),
divider(),
if (i == g.book.levels.length - 1) ...[
folio(
g.recoveredCount == g.book.levels.length
? 'THE END · YOUR WATCH HAS BEGUN'
: 'THE LAST PAGE · COME BACK WHENEVER YOU LIKE',
),
writing(
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),
action('Today’s puzzle', () => g.startDaily(DateTime.now())),
] else
action('Turn the page →', nextCampaign, primary: true),
action('Back to notebook', g.contents),
]),
);
}
Future<void> chooseDifficulty() async {
await showDialog<void>(
context: context,
builder: (c) => SimpleDialog(
title: CopyText('Classic practice pace', style: hand(29)),
children: [
for (final d in Difficulty.values)
SimpleDialogOption(
onPressed: () {
g.selectDifficulty(d);
Navigator.pop(c);
},
child: CopyText(
'${CopyScope.text(context, d.label)} — ${CopyScope.text(context, d.description)}',
style: hand(23),
),
),
],
),
);
}
void rules() => message(
'Find the light',
'Light exactly as many cells as the number beside each row and above each column.\n\nTap to cycle: empty → light → crossed out → empty. Mark every cell to finish. Small dots mark fixed clues.\n\nA, B and C are overlapping areas with their own totals. Shared cells count in both areas. Compare clues and subtract their shared parts to find new deductions.\n\nEvery story grid reveals an object. Later pages require area comparisons; all are solvable without guessing. Classic practice grades the length of simpler row and column chains.\n\nWatch a rewarded ad for each explained hint. Hints are optional, and your puzzle remains available if no ad can be shown. Streaks count consecutive daily completions on this device.',
close: 'Got it',
);
Future<void> privacy() async {
if (!await ads.privacy()) {
await message(
'Privacy & advertising',
'Game progress stays on this device. No account or game backend is used. Google advertising services may process device and ad interaction data when ads are available.\n\nNo advertising privacy options are currently required or available for your region.',
close: 'Close',
);
}
}
}