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
+221 -232
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,68 +70,114 @@ 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, _) {
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,
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);
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(
fontFamilyFallback: kIsWeb
? const ['LumenText', 'LumenSymbols', 'LumenSymbols2', 'LumenMath']
: null,
colorScheme: ColorScheme.fromSeed(seedColor: blue, surface: cream),
scaffoldBackgroundColor: cream,
fontFamily: latin ? 'MaraHand' : null,
textTheme: ThemeData.light().textTheme.apply(
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,
),
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),
);
},
);
),
home: Notebook(game: game, adsEnabled: widget.adsEnabled),
);
}
}
class Notebook extends StatefulWidget {
@@ -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,91 +580,56 @@ 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>>(
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),
]),
),
onSettings: settings,
builder: (context, width) => 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 columns = width >= 900 ? 3 : (width >= 560 ? 2 : 1);
const spacing = 28.0;
final cardWidth = (width - spacing * (columns - 1)) / columns;
return Wrap(
spacing: spacing,
runSpacing: 36,
children: [
for (final story in books)
SizedBox(width: cardWidth, child: bookCard(story)),
],
);
},
),
);
}
/// 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
.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,
),
]),
),
],
),
),
),
),
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(),
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(
puzzle: p,
cells: g.cells,
onMark: g.mark,
selectedArea: g.selectedArea,
won: g.won,
maxWidth: maxWidth,
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',
'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',
);
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',
+13 -5
View File
@@ -1,3 +1,5 @@
import 'browser_assets.dart';
import 'dart:async';
import 'package:audio_session/audio_session.dart';
@@ -29,13 +31,19 @@ class _AudioOutput implements AmbienceOutput {
@override
Future<void> load(Soundscape scene) async {
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
if (!await session.setActive(true)) {
throw StateError('Audio focus unavailable');
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);
await _player.setAsset(scene.asset);
if (kIsWeb) {
await _player.setUrl(browserAudioUrl(scene.asset));
} else {
await _player.setAsset(scene.asset);
}
}
@override
+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();
+61 -11
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();
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
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(
tracks[id]['asset'] as String? ??
'assets/audio/${tracks[id]['file']}',
);
final asset =
tracks[id]['asset'] as String? ??
'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,7 +189,14 @@ class Narrator extends ChangeNotifier {
loading = false;
error = '';
notifyListeners();
await _player.stop();
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
@@ -157,6 +206,7 @@ class Narrator extends ChangeNotifier {
unawaited(s.cancel());
}
unawaited(_player.dispose());
highlightedPassage.dispose();
super.dispose();
}
}
+9 -4
View File
@@ -187,10 +187,15 @@ class Board extends StatelessWidget {
children: [
if (value != 0)
Positioned.fill(
child: CustomPaint(
painter: PencilMark(
value: value,
variation: i,
child: RepaintBoundary(
child: CustomPaint(
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.',
+83 -14
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,15 +212,21 @@ class _PaperState extends State<Paper> {
clipBehavior: Clip.hardEdge,
children: [
Positioned(
left: left,
top: top,
width: w,
height: h,
child: Image.asset(
PaperSkin.assetOf(context) ??
'assets/artwork/mara-single-page-v2.png',
fit: BoxFit.fill,
excludeFromSemantics: true,
// 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: 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,
),