Add browser playtest and improve library, media and input

Bundle web bootstrap, icons, local font fallbacks and hosting instructions.
Add optimized WebP/MP3 packaging, asset checks and a browser narration
regression tool. Support browser audio handoff and ad-free explained hints.

Refresh the responsive bookshelf and reduce unnecessary app, narration and
paper repaint work. Preserve deliberate page swipes while tolerating small
mouse movements during cell and navigation clicks.

Validation: all 77 Flutter tests pass; shell, JavaScript and Python scripts
parse; locale and web manifests are valid JSON; git diff --check passes.
This commit is contained in:
Hadrian Burkhardt
2026-11-06 03:33:26 +01:00
parent 7855aafade
commit 7e6b203a02
34 changed files with 1370 additions and 269 deletions
+9
View File
@@ -59,6 +59,15 @@ The normal application ID remains `com.lumen.daily`; version 2.0.2 uses build nu
The development release build currently uses the Android debug signing key so it can update the installed prototype. **Configure your private upload key before publishing.** No production signing material is included.
## Browser playtest
An additional ad-free browser version includes the story library, recorded
voices and the same puzzle game. Voices start after three seconds (with a Play
fallback if the browser blocks audio), explained hints are free, and each browser saves its own progress. Build a deployable ZIP with
`bash scripts/build_web.sh` and host its contents on your static web server.
Use `--base-href /lumen/` when hosting below that path.
See [browser hosting and tester instructions](docs/BROWSER_PLAYTEST.md).
## Verification
```sh
+1
View File
@@ -5,3 +5,4 @@ analyzer:
- build/**
- android/**
- ios/**
- web/**
+155
View File
@@ -0,0 +1,155 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Noto
Upstream-Contact: https://github.com/googlei18n/noto-fonts/issues
http://groups.google.com/group/noto-font
Source: https://github.com/googlei18n/noto-fonts
Files: *
Copyright:
2010,2012-2020, Google Inc.
2015-2020, Google LLC.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
Files:
debian/*
Copyright:
2013-2020, Jonas Smedegaard <dr@jones.dk>
2020, Purism, SPC
2013, Vasudev Kamath <kamathvasudev@gmail.com>
License-Grant:
This program is free software;
you can redistribute it and/or modify it
under the terms of the GNU General Public License
as published by the Free Software Foundation;
either version 3, or (at your option) any later version.
License: GPL-3+
Files:
debian/NotoMono/NotoMono-Regular.ttf
Copyright:
2007, Google Inc.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
License: OFL-1.1
PREAMBLE
.
The goals of the Open Font License (OFL) are to stimulate
worldwide development of collaborative font projects,
to support the font creation efforts
of academic and linguistic communities,
and to provide a free and open framework
in which fonts may be shared and improved
in partnership with others.
.
The OFL allows the licensed fonts to be used, studied,
modified and redistributed freely
as long as they are not sold by themselves.
The fonts, including any derivative works,
can be bundled, embedded,
redistributed and/or sold with any software
provided that any reserved names are not used
by derivative works.
The fonts and derivatives, however,
cannot be released under any other type of license.
The requirement for fonts to remain under this license
does not apply to any document
created using the fonts or their derivatives.
.
DEFINITIONS
.
"Font Software" refers to the set of files
released by the Copyright Holder(s) under this license
and clearly marked as such.
This may include source files, build scripts and documentation.
.
"Reserved Font Name" refers to any names specified as such
after the copyright statement(s).
.
"Original Version" refers to the collection
of Font Software components
as distributed by the Copyright Holder(s).
.
"Modified Version" refers to any derivative
made by adding to, deleting, or substituting --
in part or in whole --
any of the components of the Original Version,
by changing formats
or by porting the Font Software to a new environment.
.
"Author" refers to any designer, engineer, programmer,
technical writer or other person
who contributed to the Font Software.
.
PERMISSION & CONDITIONS
.
Permission is hereby granted, free of charge,
to any person obtaining a copy of the Font Software,
to use, study, copy, merge, embed, modify, redistribute,
and sell modified and unmodified copies of the Font Software,
subject to the following conditions:
.
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions,
may be sold by itself.
.
2) Original or Modified Versions of the Font Software
may be bundled, redistributed and/or sold with any software,
provided that each copy contains the above copyright notice
and this license.
These can be included either as stand-alone text files,
human-readable headers or in the appropriate
machine-readable metadata fields within text or binary files
as long as those fields can be easily viewed by the user.
.
3) No Modified Version of the Font Software may use
the Reserved Font Name(s)
unless explicit written permission is granted
by the corresponding Copyright Holder.
This restriction only applies to the primary font name
as presented to the users.
.
4) The name(s) of the Copyright Holder(s)
or the Author(s) of the Font Software
shall not be used to promote,
endorse or advertise any Modified Version,
except to acknowledge the contribution(s)
of the Copyright Holder(s) and the Author(s)
or with their explicit written permission.
.
5) The Font Software,
modified or unmodified, in part or in whole,
must be distributed entirely under this license,
and must not be distributed under any other license.
The requirement for fonts to remain under this license
does not apply to any document
created using the Font Software.
.
TERMINATION
.
This license becomes null and void
if any of the above conditions are not met.
.
DISCLAIMER
.
THE FONT SOFTWARE IS PROVIDED "AS IS",
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO
ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT.
IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF THE USE OR INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
License: GPL-3+
License-Reference: /usr/share/common-licenses/GPL-3
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+8 -1
View File
@@ -183,5 +183,12 @@
"{0}, fixed clue": "{0}, feste Vorgabe",
"{0}Follow device language": "{0}Gerätesprache verwenden",
"← Previous chapter": "← Vorheriges Kapitel",
"← Previous leaf": "← Vorherige Seite"
"← Previous leaf": "← Vorherige Seite",
"Tap Play this reading to hear the voices": "Tippe auf „Diese Lesung abspielen“, um die Stimmen zu hören",
"Tap Play again to allow audio in your browser.": "Tippe erneut auf Abspielen, um Ton in deinem Browser zu erlauben.",
"Hint": "Hinweis",
"Reveal one cell with an explanation?": "Ein Feld mit einer Erklärung aufdecken?",
"Show hint": "Hinweis zeigen",
"Hints are free in this browser playtest. Each hint reveals one cell and explains the deduction. Streaks count consecutive daily completions in this browser.": "Hinweise sind in dieser Browser-Testversion kostenlos. Jeder Hinweis deckt ein Feld auf und erklärt die Schlussfolgerung. Eine Serie zählt aufeinanderfolgende tägliche Abschlüsse in diesem Browser.",
"This browser playtest has no advertising. Progress, puzzle marks, bookmarks and settings are saved only in this browser. Clearing site data removes them. Progress does not sync between devices. Your web host may keep normal access logs.": "Diese Browser-Testversion enthält keine Werbung. Fortschritt, Rätselmarkierungen, Lesezeichen und Einstellungen werden nur in diesem Browser gespeichert. Beim Löschen der Websitedaten gehen sie verloren. Der Fortschritt wird nicht zwischen Geräten synchronisiert. Dein Webhost kann normale Zugriffsprotokolle führen."
}
+8 -1
View File
@@ -183,5 +183,12 @@
"{0}, fixed clue": "{0}, fixed clue",
"{0}Follow device language": "{0}Follow device language",
"← Previous chapter": "← Previous chapter",
"← Previous leaf": "← Previous leaf"
"← Previous leaf": "← Previous leaf",
"Tap Play this reading to hear the voices": "Tap Play this reading to hear the voices",
"Tap Play again to allow audio in your browser.": "Tap Play again to allow audio in your browser.",
"Hint": "Hint",
"Reveal one cell with an explanation?": "Reveal one cell with an explanation?",
"Show hint": "Show hint",
"Hints are free in this browser playtest. Each hint reveals one cell and explains the deduction. Streaks count consecutive daily completions in this browser.": "Hints are free in this browser playtest. Each hint reveals one cell and explains the deduction. Streaks count consecutive daily completions in this browser.",
"This browser playtest has no advertising. Progress, puzzle marks, bookmarks and settings are saved only in this browser. Clearing site data removes them. Progress does not sync between devices. Your web host may keep normal access logs.": "This browser playtest has no advertising. Progress, puzzle marks, bookmarks and settings are saved only in this browser. Clearing site data removes them. Progress does not sync between devices. Your web host may keep normal access logs."
}
+101
View File
@@ -0,0 +1,101 @@
# Lumen browser playtest
This is the same Flutter game and bundled story content as the mobile app:
Mara’s notebook, The paper boat (English/German), and The Midnight Invitation.
The browser version has no advertising. Explained hints are free.
Large desktop windows keep a centered game surface up to 1280 × 800 CSS pixels
to avoid expensive full-monitor canvas rendering. Smaller and portrait viewports
keep their responsive layout. Narration
starts three seconds after opening a narrated page; browsers that block audio
may require one tap on Play.
## Hosting the ZIP
Unzip `lumen-browser-playtest.zip` into a directory on your web server and send
friends its HTTPS URL. The directory must contain `index.html`, `main.dart.js`,
`flutter_bootstrap.js`, `canvaskit/`, and `assets/` together. Do not open
`index.html` directly from the filesystem. No application backend, database,
Node.js server or Apple account is needed.
The default build is for the root of a website, for example
`https://play.example.com/`. If you want a subdirectory such as
`https://example.com/lumen/`, rebuild with:
```sh
bash scripts/build_web.sh --base-href /lumen/
```
The leading and trailing slashes matter. The packaged `index.html` base href
can also be changed to `/lumen/` before hosting an existing ZIP there.
Serve `.wasm` as `application/wasm`, `.js` as `application/javascript`, `.json`
as `application/json`, and `.mp3` as `audio/mpeg`. Enable byte-range requests
for audio (standard static-file hosting in nginx/Apache provides this).
For background-thread rendering in supported browsers, serve the game with
`Cross-Origin-Opener-Policy: same-origin` and
`Cross-Origin-Embedder-Policy: require-corp`. It also works without isolation,
using a single rendering thread. Missing files should return 404, not an HTML
fallback page. Keep the directory
layout intact. Everything needed at runtime, including Flutter’s renderer,
fonts and recordings, is included; there is no dependency on a font/renderer CDN.
For updates, replace the whole build together. Serve `index.html`,
`flutter_bootstrap.js`, `flutter.js`, and `main.dart.js` with
`Cache-Control: no-cache`. Use revalidation for assets too unless you version
their URLs. This build does not install an offline service worker. Testers need
a connection to load new pages, pictures and recordings.
## Tell your testers
- Open the link in Safari on iPhone/iPad or Chrome on Android/computer.
- Choose a book from the shelf. Tap **Play this reading** on a narrated page to
hear the recorded voices if your browser blocks the automatic three-second
start. Pause, replay and speed controls remain available. Atmosphere depends on the browser permitting audio.
- Tap puzzle cells to cycle empty → light → crossed out. **Hint** offers a
confirmed, explained deduction without an advertisement.
- Bookmarks, puzzle marks, reading position and settings stay in that browser.
They do not sync between devices; private browsing or clearing site data can
remove them. Use a private window to start a fresh playtest.
- Report the book, page heading, device/browser and what happened when giving
feedback. Web testing covers stories, voices and gameplay; native ads and
store installation still need mobile builds.
## Build and verify
With the project’s supported Flutter SDK, Python Pillow and ffmpeg installed:
```sh
flutter pub get
bash scripts/build_web.sh
flutter test --no-pub
```
The helper builds WebAssembly with a JavaScript fallback, resolves dependencies,
emits web-only WebP artwork and MP3 audio,
verifies referenced assets,
and produces `artifacts/lumen-browser-playtest.zip`. Override `FLUTTER_BIN` to
use another SDK path. The unpacked output is `build/web/`.
For a local preview:
```sh
python3 -m http.server 8080 --directory build/web
```
Open `http://localhost:8080/`. Your production server should support HTTPS and
audio range requests, as described above. iPhone Safari testing on a real phone
is recommended before inviting a larger group.
### Narration handoff regression
With a dedicated Chrome instance exposing `--remote-debugging-port=9224`, run
this Node 22+ test against the built game preview:
```sh
node scripts/check_browser_narration.mjs http://localhost:8080/
```
For the Astro-hosted game, pass its `/lumen/play/` URL instead. Override
`CHROME_DEBUG_URL` if the debugger uses another port. The test creates its own
fresh browser context and checks the actual playing media URL after Next,
Previous and rapid page turns, without touching existing tabs or saved games.
+130 -141
View File
@@ -1,3 +1,5 @@
import 'services/browser_assets.dart';
import 'dart:async';
import 'dart:math' as math;
@@ -22,6 +24,7 @@ import 'services/ambience.dart';
import 'services/narrator.dart';
import 'services/progress.dart';
import 'ui/board.dart';
import 'ui/library.dart';
import 'ui/discovery.dart';
import 'ui/paper.dart';
@@ -34,6 +37,14 @@ Future<void> main() async {
'Dancing Script',
], await rootBundle.loadString('assets/fonts/OFL.txt'));
});
LicenseRegistry.addLicense(() async* {
yield LicenseEntryWithLineBreaks([
'Noto Sans',
'Noto Sans Symbols',
'Noto Sans Symbols 2',
'Noto Sans Math',
], await rootBundle.loadString('assets/fonts/NOTO-LICENSE.txt'));
});
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: cream,
@@ -59,14 +70,58 @@ Future<void> main() async {
runApp(LumenApp(game: game));
}
class LumenApp extends StatelessWidget {
class LumenApp extends StatefulWidget {
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, _) {
State<LumenApp> createState() => _LumenAppState();
}
class _LumenAppState extends State<LumenApp> {
Game get game => widget.game;
late Book _book;
late String _language;
@override
void initState() {
super.initState();
_book = game.book;
_language = game.requestedLanguage;
game.addListener(_configurationChanged);
}
void _configurationChanged() {
// Puzzle marks and navigation are already handled by Notebook. Rebuilding
// MaterialApp and its theme for each cell press needlessly rebuilds the app.
if (identical(_book, game.book) && _language == game.requestedLanguage) {
return;
}
setState(() {
_book = game.book;
_language = game.requestedLanguage;
});
}
@override
void didUpdateWidget(LumenApp oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.game != game) {
oldWidget.game.removeListener(_configurationChanged);
game.addListener(_configurationChanged);
}
_book = game.book;
_language = game.requestedLanguage;
}
@override
void dispose() {
game.removeListener(_configurationChanged);
super.dispose();
}
@override
Widget build(BuildContext context) {
final catalog = game.library?.copy ?? TranslationCatalog.english;
final language = game.requestedLanguage.replaceAll('_', '-');
final locale = localeFromTag(language);
@@ -101,6 +156,9 @@ class LumenApp extends StatelessWidget {
child: child!,
),
theme: ThemeData(
fontFamilyFallback: kIsWeb
? const ['LumenText', 'LumenSymbols', 'LumenSymbols2', 'LumenMath']
: null,
colorScheme: ColorScheme.fromSeed(seedColor: blue, surface: cream),
scaffoldBackgroundColor: cream,
fontFamily: latin ? 'MaraHand' : null,
@@ -117,11 +175,10 @@ class LumenApp extends StatelessWidget {
),
),
),
home: Notebook(game: game, adsEnabled: adsEnabled),
);
},
home: Notebook(game: game, adsEnabled: widget.adsEnabled),
);
}
}
class Notebook extends StatefulWidget {
const Notebook({
@@ -441,8 +498,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
@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.
// Reading pages follow the selected book; the library draws its own surface.
asset: g.screen == Screen.library ? null : g.book.paperAsset,
child: PopScope(
canPop:
@@ -524,27 +580,10 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
]),
);
}
return Leaf(
return LibraryShelf(
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>>(
onSettings: settings,
builder: (context, width) => FutureBuilder<List<Book>>(
future: shelfBooks(catalogue),
builder: (context, snapshot) {
if (snapshot.hasError) {
@@ -567,48 +606,30 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
if (books == null) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 40),
child: Center(
child: CircularProgressIndicator(color: blue),
),
child: Center(child: CircularProgressIndicator(color: blue)),
);
}
if (books.isEmpty) {
return writing(
'No stories are installed.',
size: 22,
color: muted,
);
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;
final columns = width >= 900 ? 3 : (width >= 560 ? 2 : 1);
const spacing = 28.0;
final cardWidth = (width - spacing * (columns - 1)) / columns;
return Wrap(
spacing: 14,
runSpacing: 2,
spacing: spacing,
runSpacing: 36,
children: [
for (final card in cards)
SizedBox(width: cardWidth, child: card),
for (final story in books)
SizedBox(width: cardWidth, child: bookCard(story)),
],
);
},
),
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}) {
/// Selection still restores the saved leaf independently for each story.
Widget bookCard(Book story) {
final catalogue = g.library;
if (catalogue == null) return const SizedBox.shrink();
final store = g.store.forStory(story.id);
@@ -617,81 +638,18 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
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
return LibraryBookCard(
story: story,
restored: restored,
resuming: saved != Screen.home.name && saved != Screen.library.name,
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,
),
]),
),
],
),
),
),
),
.toList(),
onOpen: () => unawaited(openStory(story.id)),
);
}
@@ -772,7 +730,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
),
if (g.book.isMara)
Image.asset(
'assets/artwork/home-harbour-v2.png',
artworkAsset('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.',
@@ -790,7 +748,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
InkWell(
onTap: g.openNotebook,
child: Image.asset(
asset,
artworkAsset(asset),
height: 220,
semanticLabel: g.book.title,
),
@@ -964,7 +922,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
if (p.speaker.isNotEmpty) writing(p.speaker, size: 17, color: muted),
if (p.illustrationAsset case final asset?)
Image.asset(
asset,
artworkAsset(asset),
height: 155,
fit: BoxFit.contain,
semanticLabel: p.caption.isEmpty ? p.title : p.caption,
@@ -1041,11 +999,10 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
? 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);
Widget reading(String text, {double? size}) => ValueListenableBuilder<String>(
valueListenable: narrator.highlightedPassage,
builder: (context, passage, _) {
final index = passage.isEmpty ? -1 : text.indexOf(passage);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text.rich(
@@ -1353,13 +1310,15 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
Widget board({double maxWidth = 350}) {
final p = g.puzzle;
if (p == null) return const SizedBox.shrink();
return Board(
return RepaintBoundary(
child: Board(
puzzle: p,
cells: g.cells,
onMark: g.mark,
selectedArea: g.selectedArea,
won: g.won,
maxWidth: maxWidth,
),
);
}
@@ -1373,7 +1332,8 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
size: 18,
color: muted,
),
if (!g.won) InkButton('Hint · rewarded ad', hint, size: 22),
if (!g.won)
InkButton(kIsWeb ? 'Hint' : 'Hint · rewarded ad', hint, size: 22),
];
/// The board stays in the viewport while supporting text scrolls separately.
@@ -1572,6 +1532,18 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
}
}
// Browser playtests have no mobile ad SDK or reward requirement.
if (kIsWeb) {
if (await confirm(
'A little nudge?',
'Reveal one cell with an explanation?',
'Show hint',
no: 'Keep thinking',
)) {
give();
}
return;
}
if (!await confirm(
'A little nudge?',
'Watch a rewarded ad for one explained hint.',
@@ -1615,7 +1587,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
label: level.object,
height: height,
artwork: Image.asset(
asset,
artworkAsset(asset),
height: height,
width: double.infinity,
fit: BoxFit.contain,
@@ -1702,12 +1674,29 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
);
}
void rules() => message(
'Find the light',
void rules() {
final text = CopyScope.text(
context,
'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.',
);
message(
'Find the light',
kIsWeb
? '${text.substring(0, text.lastIndexOf('\n\n'))}\n\n${CopyScope.text(context, 'Hints are free in this browser playtest. Each hint reveals one cell and explains the deduction. Streaks count consecutive daily completions in this browser.')}'
: text,
close: 'Got it',
);
}
Future<void> privacy() async {
if (kIsWeb) {
await message(
'Privacy & advertising',
'This browser playtest has no advertising. Progress, puzzle marks, bookmarks and settings are saved only in this browser. Clearing site data removes them. Progress does not sync between devices. Your web host may keep normal access logs.',
close: 'Close',
);
return;
}
if (!await ads.privacy()) {
await message(
'Privacy & advertising',
+8
View File
@@ -1,3 +1,5 @@
import 'browser_assets.dart';
import 'dart:async';
import 'package:audio_session/audio_session.dart';
@@ -29,14 +31,20 @@ class _AudioOutput implements AmbienceOutput {
@override
Future<void> load(Soundscape scene) async {
if (!kIsWeb) {
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
if (!await session.setActive(true)) {
throw StateError('Audio focus unavailable');
}
}
await _player.setLoopMode(LoopMode.one);
if (kIsWeb) {
await _player.setUrl(browserAudioUrl(scene.asset));
} else {
await _player.setAsset(scene.asset);
}
}
@override
Future<void> volume(double value) => _player.setVolume(value);
+16
View File
@@ -0,0 +1,16 @@
import 'package:flutter/foundation.dart';
/// The web packager emits lighter copies; native builds retain original media.
const optimizedBrowserMedia =
kIsWeb && bool.fromEnvironment('WEB_OPTIMIZED_MEDIA');
String artworkAsset(String asset) =>
optimizedBrowserMedia && asset.endsWith('.png')
? '${asset.substring(0, asset.length - 4)}.webp'
: asset;
String browserAudioUrl(String asset) => Uri.base
.resolve(
'assets/${optimizedBrowserMedia ? asset.replaceFirst(RegExp(r'\.wav$'), '.mp3') : asset}',
)
.toString();
+57 -7
View File
@@ -1,3 +1,5 @@
import 'browser_assets.dart';
import 'dart:async';
import 'package:flutter/foundation.dart';
@@ -9,8 +11,23 @@ class Narrator extends ChangeNotifier {
_subscriptions.add(
_player.playerStateStream.listen((_) => notifyListeners()),
);
_subscriptions.add(_player.positionStream.listen((_) => notifyListeners()));
_subscriptions.add(
_player.positionStream.listen((position) {
final state = (position.inSeconds, passage, speaker);
if (state == _positionState) return;
_positionState = state;
notifyListeners();
}),
);
}
(int, String, String)? _positionState;
final ValueNotifier<String> highlightedPassage = ValueNotifier('');
@override
void notifyListeners() {
highlightedPassage.value = passage;
super.notifyListeners();
}
Map<String, dynamic> tracks;
void replaceTracks(Map<String, dynamic> value) {
unawaited(stop());
@@ -29,7 +46,9 @@ class Narrator extends ChangeNotifier {
bool get finished => _player.processingState == ProcessingState.completed;
bool get paused => page.isNotEmpty && !playing && !finished && !loading;
Duration get position => _player.position;
String get label => loading
String get label => error.isNotEmpty
? 'Play this reading'
: loading
? 'Opening recording…'
: playing
? 'Pause recording'
@@ -96,20 +115,41 @@ class Narrator extends ChangeNotifier {
return;
}
final generation = ++_generation;
error = '';
try {
if (page != id) {
loading = true;
error = '';
notifyListeners();
if (!kIsWeb) {
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
}
if (generation != _generation) return;
page = id;
// PCM WAV avoids silent FLAC playback on the API 26 Huawei tablet.
await _player.setAsset(
final asset =
tracks[id]['asset'] as String? ??
'assets/audio/${tracks[id]['file']}',
);
'assets/audio/${tracks[id]['file']}';
if (kIsWeb) {
final url = browserAudioUrl(asset);
if (_player.audioSources.isEmpty) {
await _player.setUrl(url, initialPosition: Duration.zero);
} else {
// The web backend caches the root playlist by ID. Reusing setUrl
// on an active player can replay its cached first child. Mutate
// the playlist through its API so the browser receives the new
// source, while retaining the already-authorized media element.
await _player.pause();
await _player.clearAudioSources();
if (generation != _generation) return;
await _player.addAudioSource(AudioSource.uri(Uri.parse(url)));
if (generation != _generation) return;
await _player.seek(Duration.zero, index: 0);
}
} else {
// PCM WAV remains the tested format for the Android tablet.
await _player.setAsset(asset);
}
if (generation != _generation) return;
} else if (finished) {
await _player.seek(Duration.zero);
@@ -120,7 +160,9 @@ class Narrator extends ChangeNotifier {
notifyListeners();
unawaited(
_player.play().catchError((Object e) {
error = 'This recording could not be played. You can still read the entry.';
if (generation != _generation) return;
unawaited(_player.pause());
error = kIsWeb ? 'Tap Play again to allow audio in your browser.' : 'This recording could not be played. You can still read the entry.';
notifyListeners();
}),
);
@@ -147,8 +189,15 @@ class Narrator extends ChangeNotifier {
loading = false;
error = '';
notifyListeners();
if (kIsWeb) {
// Retain the browser media element and its audio permission between pages.
// stop() tears down the web decoder, making the next page start cold.
await _player.pause();
await _player.seek(Duration.zero);
} else {
await _player.stop();
}
}
@override
void dispose() {
@@ -157,6 +206,7 @@ class Narrator extends ChangeNotifier {
unawaited(s.cancel());
}
unawaited(_player.dispose());
highlightedPassage.dispose();
super.dispose();
}
}
+8 -3
View File
@@ -187,10 +187,15 @@ class Board extends StatelessWidget {
children: [
if (value != 0)
Positioned.fill(
child: RepaintBoundary(
child: CustomPaint(
painter: PencilMark(
value: value,
variation: i,
painter:
PencilMark(
value:
value,
variation:
i,
),
),
),
),
+254
View File
@@ -0,0 +1,254 @@
import '../services/browser_assets.dart';
import 'package:flutter/material.dart';
import '../domain/book.dart';
import 'translation.dart';
const _shelfPaper = Color(0xfff6f1e7);
const _shelfInk = Color(0xff283e37);
const _shelfMuted = Color(0xff746f62);
TextStyle _type(double size, {Color color = _shelfInk, bool serif = false}) =>
TextStyle(
fontFamily: serif ? 'serif' : 'sans-serif',
fontSize: size,
height: serif ? 1.2 : 1.5,
color: color,
);
/// The collection has its own quiet surface, outside any one story's notebook.
class LibraryShelf extends StatelessWidget {
const LibraryShelf({
super.key,
required this.builder,
required this.onSettings,
});
final Widget Function(BuildContext context, double width) builder;
final VoidCallback onSettings;
@override
Widget build(BuildContext context) => ColoredBox(
color: _shelfPaper,
child: SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
final compact = constraints.maxWidth < 600;
final padding = compact ? 24.0 : 48.0;
return SingleChildScrollView(
key: const ValueKey('library-scroll'),
padding: EdgeInsets.fromLTRB(padding, 20, padding, 48),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 1120),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 24,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.auto_stories_outlined,
color: _shelfInk,
size: 22,
),
const SizedBox(width: 10),
Text('L U M E N', style: _type(13)),
],
),
TextButton.icon(
onPressed: onSettings,
icon: const Icon(Icons.tune_rounded, size: 18),
label: CopyText('Settings', style: _type(13)),
style: TextButton.styleFrom(
foregroundColor: _shelfInk,
minimumSize: const Size(48, 48),
),
),
],
),
const SizedBox(height: 20),
Divider(color: _shelfInk.withValues(alpha: .18)),
SizedBox(height: compact ? 28 : 44),
CopyText(
'Choose a book',
style: _type(compact ? 36 : 48, serif: true),
),
const SizedBox(height: 12),
CopyText(
'Open a book to continue where you left off.',
style: _type(15, color: _shelfMuted),
),
SizedBox(height: compact ? 30 : 40),
LayoutBuilder(
builder: (context, c) => builder(context, c.maxWidth),
),
],
),
),
),
);
},
),
),
);
}
class LibraryBookCard extends StatelessWidget {
const LibraryBookCard({
super.key,
required this.story,
required this.restored,
required this.resuming,
required this.languages,
required this.onOpen,
});
final Book story;
final int restored;
final bool resuming;
final List<String> languages;
final VoidCallback onOpen;
@override
Widget build(BuildContext context) {
final (cloth, light) = switch (story.id) {
'mara-island' => (const Color(0xff355751), const Color(0xffe0e5d6)),
'paper-boat' => (const Color(0xff526c85), const Color(0xffe1e9e8)),
_ => (const Color(0xff51445e), const Color(0xffe8dfd8)),
};
return Semantics(
button: true,
child: Material(
color: Colors.transparent,
child: InkWell(
key: ValueKey('library-book-${story.id}'),
onTap: onOpen,
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// A cloth-bound cover with a recessed illustrated panel. The
// artwork keeps its natural proportions inside each book.
Container(
height: 276,
padding: const EdgeInsets.fromLTRB(22, 20, 14, 20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [cloth, Color.lerp(cloth, Colors.black, .2)!],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
boxShadow: [
BoxShadow(
color: cloth.withValues(alpha: .22),
offset: const Offset(0, 10),
blurRadius: 16,
spreadRadius: -5,
),
],
border: Border(
left: BorderSide(
color: Color.lerp(cloth, Colors.black, .35)!,
width: 7,
),
right: BorderSide(color: light, width: 3),
),
),
child: Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
border: Border.all(color: light.withValues(alpha: .4)),
),
child: Column(
children: [
Icon(
Icons.auto_awesome_outlined,
size: 18,
color: light,
),
const SizedBox(height: 12),
Expanded(
child: story.coverAsset == null
? Icon(Icons.menu_book, size: 64, color: light)
: Image.asset(
artworkAsset(story.coverAsset!),
fit: BoxFit.contain,
excludeFromSemantics: true,
errorBuilder: (_, _, _) => Icon(
Icons.menu_book,
size: 64,
color: light,
),
),
),
const SizedBox(height: 12),
SizedBox(width: 38, child: Divider(color: light)),
],
),
),
),
const SizedBox(height: 24),
CopyText(story.title, style: _type(25, serif: true)),
const SizedBox(height: 10),
if (story.description.isNotEmpty)
CopyText(
story.description,
style: _type(14, color: _shelfMuted),
),
if (languages.length > 1) ...[
const SizedBox(height: 10),
Text(
languages.join(' · '),
style: _type(12, color: _shelfMuted),
),
],
const SizedBox(height: 20),
if (story.levels.isNotEmpty) ...[
ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: restored / story.levels.length,
minHeight: 3,
color: cloth,
backgroundColor: cloth.withValues(alpha: .13),
),
),
const SizedBox(height: 8),
CopyText(
'$restored / ${story.levels.length} memories restored',
style: _type(12, color: _shelfMuted),
),
],
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: CopyText(
resuming ? 'Continue reading' : 'Open this book ›',
style: _type(
14,
color: cloth,
).copyWith(fontWeight: FontWeight.w600),
),
),
Icon(Icons.arrow_forward_rounded, size: 18, color: cloth),
],
),
const SizedBox(height: 8),
],
),
),
),
),
);
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ extension _MaraStory on _NotebookState {
body.addAll([
if (p.illustrationAsset case final asset?)
Image.asset(
asset,
artworkAsset(asset),
height: 155,
fit: BoxFit.contain,
semanticLabel: 'Watercolour of Gran’s stone cottage, blue door and warm window.',
+79 -10
View File
@@ -1,6 +1,9 @@
import '../services/browser_assets.dart';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'translation.dart';
@@ -13,6 +16,9 @@ const ink = Color(0xff36413c),
amber = Color(0xffe0b568);
TextStyle hand(double size, {Color color = ink}) => TextStyle(
fontFamily: 'MaraHand',
fontFamilyFallback: kIsWeb
? const ['LumenText', 'LumenSymbols', 'LumenSymbols2', 'LumenMath']
: null,
fontSize: size,
height: 1.30,
color: color,
@@ -78,6 +84,65 @@ class PaperSkin extends InheritedWidget {
bool updateShouldNotify(PaperSkin oldWidget) => asset != oldWidget.asset;
}
/// Flutter's default mouse drag threshold is one pixel. That turns ordinary
/// click jitter into a swipe and cancels a child button's/cell's tap recognizer.
/// Use the normal tap tolerance for mouse drags too, retaining deliberate swipes.
class _PageHorizontalDrag extends HorizontalDragGestureRecognizer {
_PageHorizontalDrag({super.debugOwner});
@override
bool hasSufficientGlobalDistanceToAccept(
PointerDeviceKind pointerDeviceKind,
double? deviceTouchSlop,
) => pointerDeviceKind == PointerDeviceKind.mouse
? globalDistanceMoved.abs() > kTouchSlop
: super.hasSufficientGlobalDistanceToAccept(
pointerDeviceKind,
deviceTouchSlop,
);
}
class _PageDragDetector extends StatelessWidget {
const _PageDragDetector({
required this.child,
this.onHorizontalDragStart,
this.onHorizontalDragUpdate,
this.onHorizontalDragEnd,
this.onHorizontalDragCancel,
this.dragStartBehavior = DragStartBehavior.start,
});
final Widget child;
final GestureDragStartCallback? onHorizontalDragStart;
final GestureDragUpdateCallback? onHorizontalDragUpdate;
final GestureDragEndCallback? onHorizontalDragEnd;
final GestureDragCancelCallback? onHorizontalDragCancel;
final DragStartBehavior dragStartBehavior;
@override
Widget build(BuildContext context) => RawGestureDetector(
behavior: HitTestBehavior.opaque,
gestures: {
if (onHorizontalDragStart != null ||
onHorizontalDragUpdate != null ||
onHorizontalDragEnd != null ||
onHorizontalDragCancel != null)
_PageHorizontalDrag:
GestureRecognizerFactoryWithHandlers<_PageHorizontalDrag>(
() => _PageHorizontalDrag(debugOwner: this),
(recognizer) => recognizer
..gestureSettings = MediaQuery.maybeGestureSettingsOf(context)
..dragStartBehavior = dragStartBehavior
..onStart = onHorizontalDragStart
..onUpdate = onHorizontalDragUpdate
..onEnd = onHorizontalDragEnd
..onCancel = onHorizontalDragCancel,
),
},
child: child,
);
}
class _PaperState extends State<Paper> {
Offset _drag = Offset.zero;
Offset _origin = Offset.zero;
@@ -115,8 +180,7 @@ class _PaperState extends State<Paper> {
onPointerCancel: (_) {
_drag = Offset.zero;
},
child: GestureDetector(
behavior: HitTestBehavior.opaque,
child: _PageDragDetector(
dragStartBehavior: DragStartBehavior.down,
onHorizontalDragStart: widget.onTurn == null
? null
@@ -148,17 +212,23 @@ class _PaperState extends State<Paper> {
clipBehavior: Clip.hardEdge,
children: [
Positioned(
left: left,
top: top,
width: w,
height: h,
// Crop the source image while painting, rather than
// caching a tall off-screen paper layer on wide displays.
left: landscape ? 0 : left,
top: landscape ? 0 : top,
width: landscape ? c.maxWidth : w,
height: landscape ? c.maxHeight : h,
child: RepaintBoundary(
child: Image.asset(
artworkAsset(
PaperSkin.assetOf(context) ??
'assets/artwork/mara-single-page-v2.png',
fit: BoxFit.fill,
),
fit: landscape ? BoxFit.cover : BoxFit.fill,
excludeFromSemantics: true,
),
),
),
Positioned.fromRect(rect: content, child: widget.child),
],
),
@@ -176,8 +246,7 @@ class PageSwipeBlocker extends StatelessWidget {
const PageSwipeBlocker({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) => GestureDetector(
behavior: HitTestBehavior.opaque,
Widget build(BuildContext context) => _PageDragDetector(
onHorizontalDragStart: (_) {},
onHorizontalDragUpdate: (_) {},
onHorizontalDragEnd: (_) {},
@@ -251,7 +320,7 @@ class Cover extends StatelessWidget {
children: [
Positioned.fill(
child: Image.asset(
'assets/artwork/home-notebook-cover-v2.png',
artworkAsset('assets/artwork/home-notebook-cover-v2.png'),
fit: BoxFit.fill,
excludeFromSemantics: true,
),
+13
View File
@@ -33,6 +33,7 @@ flutter:
- assets/stories/paper-boat/
- assets/stories/paper-boat/locales/
- assets/fonts/OFL.txt
- assets/fonts/NOTO-LICENSE.txt
- assets/campaign.json
- assets/notebook.json
- assets/artwork/mara-single-page-v2.png
@@ -90,3 +91,15 @@ flutter:
- family: MaraHand
fonts:
- asset: assets/fonts/DancingScript.ttf
- family: LumenText
fonts:
- asset: assets/fonts/NotoSans-Regular.ttf
- family: LumenSymbols
fonts:
- asset: assets/fonts/NotoSansSymbols-Regular.ttf
- family: LumenSymbols2
fonts:
- asset: assets/fonts/NotoSansSymbols2-Regular.ttf
- family: LumenMath
fonts:
- asset: assets/fonts/NotoSansMath-Regular.ttf
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
# Override FLUTTER_BIN when Flutter is not on PATH.
flutter_bin="${FLUTTER_BIN:-flutter}"
pub_options=()
if [[ "${PUB_OFFLINE:-0}" == 1 ]]; then pub_options+=(--offline); fi
"$flutter_bin" pub get "${pub_options[@]}"
"$flutter_bin" build web --wasm --release --no-pub --no-web-resources-cdn --dart-define=WEB_OPTIMIZED_MEDIA=true "$@"
python3 scripts/optimize_web_media.py build/web
python3 scripts/check_web_assets.py build/web
mkdir -p artifacts
python3 - <<'PY'
from pathlib import Path
from zipfile import ZipFile, ZIP_DEFLATED
output = Path('artifacts/lumen-browser-playtest.zip')
with ZipFile(output, 'w', ZIP_DEFLATED) as archive:
for path in sorted(Path('build/web').rglob('*')):
if path.is_file():
archive.write(path, path.relative_to('build/web'))
archive.write('docs/BROWSER_PLAYTEST.md', 'HOSTING.md')
print(f'Browser playtest: {output.resolve()} ({output.stat().st_size / 1024**2:.1f} MiB)')
PY
+115
View File
@@ -0,0 +1,115 @@
// Node 22+, a local preview, and a dedicated Chrome with --remote-debugging-port=9224.
// Each run uses a fresh browser context; existing tabs and saved games are untouched.
import assert from 'node:assert/strict';
const appUrl = process.argv[2] || 'http://127.0.0.1:8080/';
const debuggerUrl = process.env.CHROME_DEBUG_URL || 'http://127.0.0.1:9224';
const browser = await (await fetch(`${debuggerUrl}/json/version`)).json();
const socket = new WebSocket(browser.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
socket.onopen = resolve;
socket.onerror = reject;
});
let serial = 0;
const pending = new Map();
socket.onmessage = ({ data }) => {
const response = JSON.parse(data);
if (!response.id) return;
const request = pending.get(response.id);
if (!request) return;
clearTimeout(request.timer);
pending.delete(response.id);
if (response.error) request.reject(new Error(JSON.stringify(response.error)));
else request.resolve(response.result);
};
function call(method, params = {}, sessionId) {
return new Promise((resolve, reject) => {
const id = ++serial;
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`Timed out: ${method}`));
}, 15000);
pending.set(id, { resolve, reject, timer });
socket.send(JSON.stringify({ id, method, params, sessionId }));
});
}
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const { browserContextId } = await call('Target.createBrowserContext');
try {
const { targetId } = await call('Target.createTarget', { url: 'about:blank', browserContextId });
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
const page = (method, params) => call(method, params, sessionId);
async function evaluate(expression) {
const result = await page('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true, userGesture: true });
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
return result.result.value;
}
const controls = async () => (await page('Accessibility.getFullAXTree')).nodes;
async function until(check, description, timeout = 15000) {
const deadline = Date.now() + timeout;
do {
if (await check()) return;
await wait(100);
} while (Date.now() < deadline);
throw new Error(`Timed out waiting for ${description}`);
}
async function click(prefix, role = 'button') {
let node;
await until(async () => {
node = (await controls()).find(n => n.role?.value === role && n.name?.value?.startsWith(prefix));
return !!node;
}, prefix);
const { object } = await page('DOM.resolveNode', { backendNodeId: node.backendDOMNodeId });
if (role === 'button') {
await page('Runtime.callFunctionOn', { objectId: object.objectId, functionDeclaration: 'function(){this.click()}', userGesture: true });
} else {
// Book cards currently merge their progress bar into their semantics.
const result = await page('Runtime.callFunctionOn', {
objectId: object.objectId, returnByValue: true,
functionDeclaration: 'function(){const r=this.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}}',
});
for (const type of ['mousePressed', 'mouseReleased']) {
await page('Input.dispatchMouseEvent', { type, ...result.result.value, button: 'left', clickCount: 1 });
}
}
await wait(150);
}
const audio = () => evaluate(`window.__narrationTestAudio.map(a=>({src:a.src,paused:a.paused,time:a.currentTime}))`);
async function expectRecording(filename) {
await until(async () => (await audio()).some(a => a.src.endsWith(filename) && !a.paused && a.time > .1), filename, 7000);
const voices = (await audio()).filter(a => /narration_|midnight_/.test(a.src) && !/ambience|atmosphere/.test(a.src));
assert(voices.filter(a => !a.paused).every(a => a.src.endsWith(filename)), 'An old recording is still playing');
console.log(`Playing correct file: ${filename}`);
}
await page('Page.enable');
await page('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await page('Page.addScriptToEvaluateOnNewDocument', { source: `
localStorage.setItem('language', JSON.stringify('en'));
window.__narrationTestAudio = [];
const play = HTMLMediaElement.prototype.play;
HTMLMediaElement.prototype.play = function(...args) {
if (!window.__narrationTestAudio.includes(this)) window.__narrationTestAudio.push(this);
return play.apply(this, args);
};
` });
await page('Page.navigate', { url: appUrl });
await until(() => evaluate(`!!document.querySelector('flt-semantics-placeholder')`), 'game startup', 30000);
await evaluate(`document.querySelector('flt-semantics-placeholder').click()`);
await click('Mara’s notebook', 'progressbar');
await click('Open Mara’s notebook');
await expectRecording('narration_cottage_dedication.mp3');
await click('Next leaf');
await expectRecording('narration_cottage_window.mp3');
await click('← Previous leaf');
await expectRecording('narration_cottage_dedication.mp3');
await click('Next leaf');
await click('Next leaf');
await wait(3500);
assert((await audio()).filter(a => a.src.includes('narration_cottage_')).every(a => a.paused), 'A skipped leaf started narrating');
await click('← Previous leaf');
await expectRecording('narration_cottage_window.mp3');
console.log('Next, previous and rapid page turns use the correct narration.');
} finally {
await call('Target.disposeBrowserContext', { browserContextId });
socket.close();
}
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Check all story/art/audio references in a deployable Flutter web bundle."""
import json
import sys
from pathlib import Path
root = Path(sys.argv[1] if len(sys.argv) > 1 else 'build/web')
missing = []
references = set()
def visit(value):
if isinstance(value, dict):
for item in value.values():
visit(item)
elif isinstance(value, list):
for item in value:
visit(item)
elif isinstance(value, str) and value.startswith('assets/'):
references.add(value)
path = root / 'assets' / value
if path.suffix in ('.png', '.wav'):
path = path.with_suffix('.webp' if path.suffix == '.png' else '.mp3')
if not path.is_file():
missing.append(value)
for name in ['index.html', 'flutter_bootstrap.js', 'main.dart.js',
'manifest.json', 'main.dart.wasm', 'main.dart.mjs', 'assets/AssetManifest.bin.json',
'assets/assets/fonts/DancingScript.ttf']:
if not (root / name).is_file():
missing.append(name)
font_manifest = root / 'assets/FontManifest.json'
if font_manifest.is_file():
visit(json.loads(font_manifest.read_text()))
for path in (root / 'assets/assets').rglob('*.json'):
data = json.loads(path.read_text())
visit(data)
# Mara's original manifest uses filenames instead of asset paths.
if path.name == 'narration_manifest.json':
for track in data.get('tracks', {}).values():
if 'file' in track and 'asset' not in track:
visit('assets/audio/' + track['file'])
if missing:
raise SystemExit('Missing bundled files:\n' + '\n'.join(sorted(set(missing))))
print(f'Web bundle verified: {len(references)} referenced assets present.')
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Emit web-only WebP/MP3 copies. Original game assets are never changed."""
import argparse
import json
import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from PIL import Image
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('build', type=Path, nargs='?', default=Path('build/web'))
args = parser.parse_args()
assets = args.build / 'assets/assets'
sources = sorted([*assets.rglob('*.png'), *assets.rglob('*.wav')])
before = sum(p.stat().st_size for p in sources)
def convert(path):
if path.suffix == '.png':
target = path.with_suffix('.webp')
with Image.open(path) as image:
# Keep full-size notebook textures; illustrations need fewer pixels.
max_size = (1536, 1536) if 'page' in path.name else (1024, 1024)
image.thumbnail(max_size, Image.Resampling.LANCZOS)
image.save(target, 'WEBP', quality=86, method=6)
else:
target = path.with_suffix('.mp3')
subprocess.run([
'ffmpeg', '-nostdin', '-v', 'error', '-y', '-i', str(path),
'-codec:a', 'libmp3lame', '-b:a', '64k', str(target),
], check=True)
size = target.stat().st_size
path.unlink()
return size
with ThreadPoolExecutor(max_workers=4) as pool:
after = sum(pool.map(convert, sources))
print(f'Web media: {before / 1024**2:.1f} → {after / 1024**2:.1f} MiB '
f'({100 * (1 - after / before):.0f}% smaller; {len(sources)} files).')
+37
View File
@@ -0,0 +1,37 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:lumen/ui/paper.dart';
void main() {
testWidgets('paper raster layer stays within the viewport on large screens', (
tester,
) async {
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
for (final viewport in [
const Size(1920, 1080),
const Size(3840, 2160),
const Size(390, 844),
]) {
tester.view.physicalSize = viewport;
await tester.pumpWidget(
const MaterialApp(home: Paper(child: SizedBox.expand())),
);
await tester.pumpAndSettle();
final image = find.image(
const AssetImage('assets/artwork/mara-single-page-v2.png'),
);
final bounds = tester.getRect(image);
expect(bounds.left, greaterThanOrEqualTo(0));
expect(bounds.top, greaterThanOrEqualTo(0));
expect(bounds.right, lessThanOrEqualTo(viewport.width));
expect(bounds.bottom, lessThanOrEqualTo(viewport.height));
if (viewport.width > viewport.height) {
expect(bounds.size, viewport);
expect(tester.widget<Image>(image).fit, BoxFit.cover);
} else {
expect(bounds.size, const Size(390, 585));
}
}
});
}
+72
View File
@@ -0,0 +1,72 @@
import 'dart:ui' show PointerDeviceKind;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:lumen/domain/book.dart';
import 'package:lumen/domain/game.dart';
import 'package:lumen/main.dart';
import 'package:lumen/services/progress.dart';
void main() {
testWidgets('rapid mouse clicks tolerate small movement and cycle to X', (
tester,
) async {
final book = (await tester.runAsync(Book.load))!;
final game = Game(book, Progress.memory())..showStory(2);
await tester.pumpWidget(LumenApp(game: game, adsEnabled: false));
await tester.pumpAndSettle();
final cell = List.generate(
game.cells.length,
(i) => i,
).firstWhere((i) => !game.puzzle!.given[i]);
final center = tester.getCenter(find.byKey(ValueKey('cell-$cell')));
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: center);
await mouse.down(center);
await mouse.up();
await tester.pump(const Duration(milliseconds: 30));
expect(game.cells[cell], 1);
await mouse.down(center);
await mouse.moveTo(center + const Offset(4, 1));
await mouse.up();
await tester.pump();
expect(
game.cells[cell],
2,
reason: 'Minor mouse drift must not become a swipe',
);
await mouse.down(center);
await mouse.moveTo(center + const Offset(80, 0));
await mouse.up();
await tester.pump();
expect(game.cells[cell], 2, reason: 'A deliberate grid drag must not mark');
expect(game.storyIndex, 2, reason: 'A grid drag must not turn the page');
await mouse.removePointer();
await tester.pumpWidget(const SizedBox());
});
testWidgets('next-leaf mouse click tolerates small movement', (tester) async {
final book = (await tester.runAsync(Book.load))!;
final game = Game(book, Progress.memory())..showStory(0);
await tester.pumpWidget(LumenApp(game: game, adsEnabled: false));
await tester.pumpAndSettle();
final next = find.text('Next leaf →');
await tester.ensureVisible(next);
await tester.pumpAndSettle();
final center = tester.getCenter(next);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: center);
await mouse.down(center);
await mouse.moveTo(center + const Offset(5, 1));
await mouse.up();
await tester.pump();
expect(game.storyIndex, 1);
await mouse.down(const Offset(30, 300));
await mouse.moveTo(const Offset(110, 300));
await mouse.up();
await tester.pump();
expect(game.storyIndex, 0, reason: 'A deliberate margin swipe still turns');
await mouse.removePointer();
await tester.pumpWidget(const SizedBox());
});
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 959 B

+18
View File
@@ -0,0 +1,18 @@
{{flutter_js}}
{{flutter_build_config}}
_flutter.loader.load({
onEntrypointLoaded: async function (engineInitializer) {
try {
const appRunner = await engineInitializer.initializeEngine({
hostElement: document.getElementById('lumen-player')
});
await appRunner.runApp();
document.getElementById('loading')?.remove();
} catch (error) {
document.getElementById('loading-message').textContent =
'The bookshelf could not open. Check your connection and reload the page.';
console.error(error);
}
}
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 108 108">
<path fill="#274956" opacity="1" d="M0,0h108v108h-108z"/>
<path fill="#E0B568" opacity="0.5" d="M58,34L7,19L7,49z"/>
<path fill="#F3E7CC" opacity="1" d="M53,45L68,45L76,87L45,87z"/>
<path fill="#A35C48" opacity="1" d="M49,65L72,65L73,73L48,73z"/>
<path fill="#E0B568" opacity="1" d="M51,31h19v12h-19z"/>
<path fill="#172F3A" opacity="1" d="M46,30L61,18L76,30z M47,43h27v5h-27z M57,77h8v10h-8z"/>
<path fill="#8A9F9B" opacity="1" d="M14,92h80v2h-80z M19,98h38v1h-38z M68,98h22v1h-22z"/>
</svg>

After

Width:  |  Height:  |  Size: 556 B

+40
View File
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="theme-color" content="#314345">
<meta name="description" content="Explore Lumen’s illustrated stories, recorded voices and picture puzzles.">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<link rel="icon" type="image/svg+xml" href="icons/lumen.svg?v=2">
<link rel="icon" type="image/png" sizes="48x48" href="favicon.png?v=2">
<link rel="apple-touch-icon" href="icons/lumen-180.png?v=2">
<link rel="manifest" href="manifest.json">
<title>Lumen — browser playtest</title>
<style>
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #314345; color: #314345; }
body { display: flex; align-items: center; justify-content: center; height: 100dvh; }
#lumen-player { flex: none; position: relative; width: 100%; height: 100%; overflow: hidden; contain: layout paint style; user-select: none; -webkit-user-select: none; }
@media (min-width: 1280px) and (min-aspect-ratio: 1/1) {
#lumen-player { width: min(100vw, 1280px); height: min(100dvh, 800px); }
}
@media (pointer: coarse) { #lumen-player { width: 100%; height: 100%; } }
#loading { position: fixed; inset: 0; z-index: 1; box-sizing: border-box; display: grid; place-content: center; padding: 28px; text-align: center; font: 18px/1.6 Georgia, serif; background: #f7f0df; }
h1 { font-size: 42px; font-weight: normal; margin: 0; }
p { max-width: 30em; }
a { color: inherit; }
</style>
</head>
<body>
<main id="lumen-player" aria-label="Lumen"></main>
<div id="loading" role="status" aria-live="polite">
<h1>Lumen</h1>
<p id="loading-message">Opening the bookshelf…</p>
<p>Stories, voices and picture puzzles.<br>Your place is saved in this browser.</p>
</div>
<noscript>Please enable JavaScript to open Lumen.</noscript>
<script src="flutter_bootstrap.js" async></script>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
{
"name": "Lumen — browser playtest",
"short_name": "Lumen",
"start_url": ".",
"scope": ".",
"display": "standalone",
"background_color": "#f7f0df",
"theme_color": "#314345",
"description": "Illustrated stories, recorded voices and picture puzzles.",
"icons": [{"src": "icons/lumen-192.png", "sizes": "192x192", "type": "image/png"}, {"src": "icons/lumen-512.png", "sizes": "512x512", "type": "image/png"}]
}