An AI skill that turns books into animated, narrated, interactive web experiences
JavaScript ai-agentsai-educationanimationclaudeclaude-codeclaude-skillsedtecheducationinteractive-textbookscormtext-to-video
Frontend review: shared contents engine, layout and interaction fixes
Claude2d5d0200ad6c
diff --git a/.claude/skills/papermorph/assets/templates/book.html b/.claude/skills/papermorph/assets/templates/book.htmlindex 9b34669..82a6e0d 100644--- a/.claude/skills/papermorph/assets/templates/book.html+++ b/.claude/skills/papermorph/assets/templates/book.html@@ -3,129 +3,19 @@<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">-<script>-// Observe aborted incoming transitions before the first rendering opportunity.-addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));-</script><title>BOOK TITLE</title><meta name="description" content="ONE SENTENCE ABOUT THE BOOK."><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='14' fill='%231d2b27'/%3E%3Ctext x='32' y='45' text-anchor='middle' font-size='48' fill='%23f0b45a'%3E∞%3C/text%3E%3C/svg%3E"><link rel="stylesheet" href="lib/units.css">+<link rel="stylesheet" href="lib/contents.css"><script src="lib/units.js"></script>+<script src="lib/contents.js"></script><script src="unit-art.js"></script><link rel="expect" href="#ch01" blocking="render">+<!-- The book's own look, if it differs from the chalkboard: override the tokens of lib/contents.css here, e.g.<style>-:root {- --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;- --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;- --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;- --book: "Iowan Old Style", Palatino, Georgia, serif;- --ease: cubic-bezier(.2, .8, .2, 1);- color-scheme: dark;-}-* { box-sizing: border-box; }-html { scroll-padding-top: 90px; }-body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }-/* Chalkboard: the same grain and vignette as the lesson stage. */-body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;- background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),- url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }-a { color: inherit; }-a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }-.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }--/* ---------- cover ---------- */-#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;- padding: 48px 16px 64px; text-align: center; overflow: hidden; }-.open #cover, body:not(.open) #contents { display: none; }-#cover > * { animation: rise .8s var(--ease) backwards; }-#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }-#cover .kicker { animation-delay: .9s; }-#cover h1 { animation-delay: 1s; }-#cover .lede { animation-delay: 1.12s; }-#cover .acts { animation-delay: 1.24s; }-#cover .meta { animation-delay: 1.36s; }-h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }-h1 i { color: var(--task); font-style: italic; }-.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }-.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }-.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;- transition: transform .25s var(--ease), background-color .25s, border-color .25s; }-.btn[hidden] { display: none; }-.btn:hover { transform: translateY(-2px); }-.btn.go { background: var(--chalk); color: var(--board); }-.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }-.btn.quiet:hover { border-color: var(--dim); }-.btn svg { width: 15px; height: 15px; fill: currentColor; }-.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }-/* Faint chalk notes around the edges of the board. */-.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }-.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;- animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }-@keyframes chalk { to { opacity: .075; } }-@keyframes drift { to { translate: 0 -10px; } }-@keyframes rise { from { opacity: 0; transform: translateY(16px); } }--/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */-.mascot { display: block; overflow: visible; }-.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }-.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }-.mascot .joy { display: none; }-#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }-#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }-.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }-.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }-@keyframes draw { from { stroke-dashoffset: 1; } }-@keyframes pop { from { opacity: 0; transform: scale(.6); } }-.draw .face { transform-box: view-box; transform-origin: 60px 44px; }-@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }-@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }--/* ---------- contents ---------- */-.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));- background: rgba(22, 33, 29, .86); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid #2a3b35; }-.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }-.home .mascot { view-transition-name: guide; }-.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }-.home strong i { color: var(--task); }-.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }-.prog b { color: var(--good); font-weight: 600; }-main#contents { padding-bottom: 80px; }-.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }-.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;- padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);- text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }-.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px rgba(0, 0, 0, .3); }-.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }-.ch span { font-size: 18px; line-height: 1.3; }-.ch small { color: var(--dim); font-size: 14px; }-.ch.done small::before { content: var(--done, "✓ Finished · "); color: var(--good); font-weight: 600; }-.ch.last small::after { content: var(--last, " · Last opened"); color: var(--quiz); }-.ch.here:focus-visible { outline-color: var(--c); }-.ch.here { animation: here 1.8s ease-out .3s; }-@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }-.stagger .top { animation: rise .6s var(--ease) backwards; }-.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }--/* ---------- page-to-page motion ---------- */-@view-transition { navigation: auto; }-/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the- contents still rise in. -moz-orient exists only in Firefox. */-@supports (-moz-orient: inline) { @view-transition { navigation: none; } }-::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }-::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }-::view-transition-old(lesson) { animation-duration: .18s; }-@media (max-width: 560px) {- .home strong { font-size: 18px; }- #contents .top { flex-wrap: wrap; gap: 8px 12px; }- .ch { min-height: 0; }- .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }-}-@media (prefers-reduced-motion: reduce) {- *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }- .chalk span { opacity: .075; }-}-</style>+:root { --board: #fcfaf3; --chalk: #26241f; --top-bg: rgba(252, 250, 243, .9); --top-line: #ddd5c3; color-scheme: light; }+</style> --></head><body><section id="cover">@@ -155,139 +45,14 @@ main#contents { padding-bottom: 80px; }</main><script>-'use strict';-// Interface text in the page's <html lang>, as in the lessons; missing keys fall back to English.-// A value is a string or plural forms { one, few, many, other } chosen by vars.n.-const TRANSLATIONS = {- en: {- open: 'Open the book', toCover: 'Back to the cover', resume: 'Continue · Chapter {n}', unit: 'Unit {n}', minutes: '{n} min',- meta: '{chapters} · {units} · with sound', metaChapters: { one: '{n} chapter', other: '{n} chapters' }, metaUnits: { one: '{n} unit', other: '{n} units' },- chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',- doneMark: '✓ Finished · ', lastMark: ' · Last opened',- },- ru: {- open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',- meta: '{chapters} · {units} · со звуком',- metaChapters: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' },- metaUnits: { one: '{n} раздел', few: '{n} раздела', many: '{n} разделов', other: '{n} раздела' },- chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',- doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',- },-};-const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];-function translate(key, vars = {}) {- const language = TRANSLATIONS[LANGUAGE]?.[key] !== undefined ? LANGUAGE : 'en';- let text = TRANSLATIONS[language][key] ?? key;- if (typeof text === 'object') {- let rules;- try { rules = new Intl.PluralRules(language); } catch { rules = new Intl.PluralRules('en'); }- text = text[rules.select(vars.n)] ?? text.other;- }- return text.replace(/\{(\w+)\}/g, (placeholder, name) => name in vars ? vars[name] : placeholder);-}-for (const element of document.querySelectorAll('[data-t]')) element.firstChild.nodeValue = translate(element.dataset.t);-for (const element of document.querySelectorAll('[data-t-label]')) element.setAttribute('aria-label', translate(element.dataset.tLabel));-document.documentElement.style.setProperty('--done', JSON.stringify(translate('doneMark')));-document.documentElement.style.setProperty('--last', JSON.stringify(translate('lastMark')));--// Units and chapters are numbered in order from START (a book whose scope starts mid-way keeps the original numbers).-// Add a chapter here when its lesson is ready.-const START = { unit: 1, chapter: 1 };-const UNITS = [ // [unit title, [[chapter title, minutes], ...]]- ['First unit', [['First chapter', 8]]],-];-const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];-const id = n => 'ch' + String(n).padStart(2, '0');-let P = {};-const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('.', location.href).pathname;-try {- const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');- if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;-} catch {}-const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);--// Contents.-let n = START.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order-const esc = s => s.replace(/&/g, '&').replace(/</g, '<');-document.getElementById('units').innerHTML = UNITS.map(([name, chs], u) => {- return `<section class="unit" style="--c:${HUES[u % HUES.length]};--i:${i++}">${Units.header(u, translate('unit', { n: u + START.unit }), name)}<div class="grid">` +- chs.map(([t, min]) => { n++; total++;- const cls = 'ch' + (done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');- return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${translate('minutes', { n: min })}</small></a>`;- }).join('') + '</div></section>';-}).join('');-// A unit's sketch draws itself the first time the unit scrolls into view.-Units.watch();-const finished = [...done].filter(k => k >= START.chapter && k <= n).length;-document.getElementById('prog').innerHTML = finished ? translate('finished', { done: `<b>${finished}</b>`, n: total }) : translate('chapterCount', { n: total });-document.getElementById('meta').textContent = translate('meta', {- chapters: translate('metaChapters', { n: total }), units: translate('metaUnits', { n: UNITS.length }) });-const last = Number.isInteger(P.last) && document.getElementById(id(P.last));-if (last) {- const r = document.getElementById('resume');- r.hidden = false;- r.href = last.getAttribute('href');- r.textContent = translate('resume', { n: P.last });-}--// The guide, drawn the same way as in the lessons.-function lemniscate(cx, cy, a, k) {- let d = '';- for (let i = 0; i <= 96; i++) {- const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;- d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);- }- return d + 'Z';-}-for (const svg of document.querySelectorAll('svg.mascot')) {- svg.setAttribute('viewBox', '0 0 120 84');- svg.setAttribute('aria-hidden', 'true');- const ln = 'fill="none" stroke="#ece8dc" stroke-linecap="round" stroke-linejoin="round"';- svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` +- [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="#ece8dc"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') +- `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;-}--// The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.-// Lessons link back with #chNN, so the reader lands on the chapter they just left.-const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;-function show(animate) {- const open = location.hash.length > 1 && location.hash !== '#book';- const apply = () => {- document.body.classList.toggle('open', open);- document.body.classList.toggle('stagger', animate && open);- const here = open ? document.getElementById(location.hash.slice(1)) : null;- document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));- if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }- else scrollTo(0, 0);- if (animate) {- const heading = document.querySelector(open ? '#contents .home' : '#cover h1');- heading?.setAttribute('tabindex', '-1');- heading?.focus({ preventScroll: true });- }- };- if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {- const transition = document.startViewTransition(apply);- // Navigation can interrupt either promise; the new view is already applied.- transition.ready.catch(() => {});- transition.finished.catch(() => {});- } else apply();-}-addEventListener('hashchange', () => show(true));-show(false);--// Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.-let named = null;-const name = el => {- if (named) named.style.viewTransitionName = '';- named = el;- if (el) el.style.viewTransitionName = 'lesson';-};-document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });-addEventListener('pagereveal', e => {- const target = (location.hash.length > 1 && document.getElementById(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);- name(e.viewTransition && target ? target : null);- e.viewTransition?.finished.then(() => name(null), () => name(null));+// Units and chapters are numbered in order from start (a book whose scope starts mid-way, e.g. at unit 3, chapter 9,+// keeps the original numbers). Add a chapter here when its lesson is ready.+Contents.book({+ start: { unit: 1, chapter: 1 },+ units: [ // [unit title, [[chapter title, minutes], ...]]+ ['First unit', [['First chapter', 8]]],+ ],+ hues: ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'], // one colour per unit, cycling});</script></body>diff --git a/.claude/skills/papermorph/references/site.md b/.claude/skills/papermorph/references/site.mdindex 5ab4959..d0df459 100644--- a/.claude/skills/papermorph/references/site.md+++ b/.claude/skills/papermorph/references/site.md@@ -35,8 +35,9 @@ A chapter returns to its book's index. Preserve cover → contents → chapter nOne page: no hash or `#book` shows the cover, `#contents` or `#chNN` the contents; a lesson's home button returns to `#chNN`, and the card grows into the lesson frame through a view transition.- Edit the title, kicker, lede, the faint chalk phrases on the cover (a few formulas or lines from the book), and the `<title>`.-- `UNITS`: `[unit title, [[chapter title, minutes], …]]`; chapters are numbered in order from `START` (`{ unit: 1, chapter: 1 }`; a book whose scope starts mid-way, e.g. at unit 3, chapter 9, keeps the original numbers). Add a chapter when its lesson is ready; also set the previous chapter's `CHAPTER.next = '../chNN/'`.-- `HUES`: one colour per unit, cycling.+- The page's script calls `Contents.book({ start, units, hues })` (from the engine's `lib/contents.js`; the shared styles are `lib/contents.css`). `units`: `[unit title, [[chapter title, minutes], …]]`; chapters are numbered in order from `start` (`{ unit: 1, chapter: 1 }`; a book whose scope starts mid-way, e.g. at unit 3, chapter 9, keeps the original numbers). Add a chapter when its lesson is ready; also set the previous chapter's `CHAPTER.next = '../chNN/'`. An optional third entry `{ unit, chapter, sample: true }` renumbers a unit and marks it as a sample, left out of the chapter count.+- `hues`: one colour per unit, cycling.+- A book with its own look overrides the tokens of `lib/contents.css` (`--board`, `--chalk`, `--top-bg`, …) in a `<style>` after it, as the template's comment shows; don't copy the stylesheet into the page.## Unit sketches (`unit-art.js`)diff --git a/engine/check_i18n.py b/engine/check_i18n.pyindex 346030e..f65dcf0 100644--- a/engine/check_i18n.py+++ b/engine/check_i18n.py@@ -39,8 +39,18 @@ def at_base_ref(path):return result.stdout.decode("utf-8") if result.returncode == 0 else None-ENGINE_FILES = ("engine.js", "engine.css", "volume.js", "volume.css", "book.css")-BASE_FILES = {"book": at_base_ref(TEMPLATES / "book.html"), **{name: at_base_ref(ENGINE_DIR / name) for name in ENGINE_FILES}}+ENGINE_FILES = ("engine.js", "engine.css", "volume.js", "volume.css", "book.css", "units.js", "units.css", "contents.js", "contents.css")+++def engine_at_base_ref(name):+ """An engine file at BASE_REF; one added since then is taken from the working tree (the base template does not load it)."""+ if not BASE_REF:+ return None+ path = ENGINE_DIR / name+ return at_base_ref(path) or (path.read_text(encoding="utf-8") if path.exists() else "")+++BASE_FILES = {"book": at_base_ref(TEMPLATES / "book.html"), **{name: engine_at_base_ref(name) for name in ENGINE_FILES}}def with_language(html, language):@@ -103,6 +113,7 @@ async def lesson_snapshot(page):shots.append(await page.evaluate("document.getElementById('ui').innerHTML"))await page.locator(".box").fill("6")await page.locator(".box").press("Enter")+ await page.wait_for_timeout(200) # the band card refits to the feedback on the next frameshots.append(await page.evaluate("document.getElementById('ui').innerHTML"))await page.evaluate("seek(BEATS.length - 1, false)")await page.wait_for_timeout(600)@@ -111,7 +122,7 @@ async def lesson_snapshot(page):async def check_english_unchanged(browser, errors):- if not all(BASE_FILES.values()):+ if BASE_FILES["book"] is None or None in BASE_FILES.values():print(f"SKIP English identity: engine or book template not found at BASE_REF={BASE_REF!r}")returnbefore = await open_lesson(browser, "base", errors)diff --git a/engine/contents.css b/engine/contents.cssnew file mode 100644index 0000000..3f59f10--- /dev/null+++ b/engine/contents.css@@ -0,0 +1,115 @@+/* The book's cover and contents (index.html): the chalkboard look, the cover, the guide, the chapter grid and the+ page-to-page motion. A book's own <style> after this file sets its theme: the colour and font tokens below, and the+ few rules a theme redraws (e.g. body::before for the paper). */+:root {+ --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;+ --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;+ --book: "Iowan Old Style", Palatino, Georgia, serif;+ --ease: cubic-bezier(.2, .8, .2, 1);+ --top-bg: rgba(22, 33, 29, .86); --top-line: #2a3b35; /* the sticky contents header */+ --lift: rgba(0, 0, 0, .3); /* a card's shadow on hover */+ color-scheme: dark;+}+* { box-sizing: border-box; }+html { scroll-padding-top: 90px; }+body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }+/* Chalkboard: the same grain and vignette as the lesson stage. */+body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;+ background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }+a { color: inherit; }+a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }+.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }++/* ---------- cover ---------- */+#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;+ padding: 48px 16px 64px; text-align: center; overflow: hidden; }+.open #cover, body:not(.open) #contents { display: none; }+#cover > * { animation: rise .8s var(--ease) backwards; }+#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }+#cover .kicker { animation-delay: .9s; }+#cover h1 { animation-delay: 1s; }+#cover .lede { animation-delay: 1.12s; }+#cover .acts { animation-delay: 1.24s; }+#cover .meta { animation-delay: 1.36s; }+h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }+h1 i { color: var(--task); font-style: italic; }+.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }+.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }+.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;+ transition: transform .25s var(--ease), background-color .25s, border-color .25s; }+.btn[hidden] { display: none; }+.btn:hover { transform: translateY(-2px); }+.btn.go { background: var(--chalk); color: var(--board); }+.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }+.btn.quiet:hover { border-color: var(--dim); }+.btn svg { width: 15px; height: 15px; fill: currentColor; }+.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }+/* Faint chalk notes around the edges of the board. */+.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }+.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;+ animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }+@keyframes chalk { to { opacity: .075; } }+@keyframes drift { to { translate: 0 -10px; } }+@keyframes rise { from { opacity: 0; transform: translateY(16px); } }++/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */+.mascot { display: block; overflow: visible; }+.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }+.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }+.mascot .joy { display: none; }+#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }+#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }+.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }+.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }+@keyframes draw { from { stroke-dashoffset: 1; } }+@keyframes pop { from { opacity: 0; transform: scale(.6); } }+.draw .face { transform-box: view-box; transform-origin: 60px 44px; }+@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }+@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }++/* ---------- contents ---------- */+.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));+ background: var(--top-bg); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid var(--top-line); }+.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }+.home .mascot { view-transition-name: guide; }+.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }+.home strong i { color: var(--task); }+.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }+.prog b { color: var(--good); font-weight: 600; }+main#contents { padding-bottom: 80px; }+.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }+.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;+ padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);+ text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }+.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px var(--lift); }+.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }+.ch span { font-size: 18px; line-height: 1.3; }+.ch small { color: var(--dim); font-size: 14px; }+.ch.done small::before { content: var(--done, "✓ Finished · "); color: var(--good); font-weight: 600; }+.ch.last small::after { content: var(--last, " · Last opened"); color: var(--quiz); }+.ch.here:focus-visible { outline-color: var(--c); }+.ch.here { animation: here 1.8s ease-out .3s; }+@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }+.stagger .top { animation: rise .6s var(--ease) backwards; }+.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }++/* ---------- page-to-page motion ---------- */+@view-transition { navigation: auto; }+/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the+ contents still rise in. -moz-orient exists only in Firefox. */+@supports (-moz-orient: inline) { @view-transition { navigation: none; } }+::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }+::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }+::view-transition-old(lesson) { animation-duration: .18s; }+@media (max-width: 560px) {+ .home strong { font-size: 18px; }+ #contents .top { flex-wrap: wrap; gap: 8px 12px; }+ .ch { min-height: 0; }+ .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }+}+@media (prefers-reduced-motion: reduce) {+ *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }+ .chalk span { opacity: .075; }+}diff --git a/engine/contents.js b/engine/contents.jsnew file mode 100644index 0000000..fdc7de6--- /dev/null+++ b/engine/contents.js@@ -0,0 +1,169 @@+/* The book's cover and contents (index.html): interface text, the chapter list with reading progress, the guide,+ and the cover ↔ contents ↔ lesson motion. Load it in <head>; after the markup, the page calls+ Contents.book({ units, start, hues }) with its chapter list. */+'use strict';+// Observe aborted incoming transitions before the first rendering opportunity.+addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));++const Contents = (() => {+ // Interface text in the page's <html lang>, as in the lessons; missing keys fall back to English.+ // A value is a string or plural forms { one, few, many, other } chosen by vars.n.+ const TRANSLATIONS = {+ en: {+ open: 'Open the book', toCover: 'Back to the cover', resume: 'Continue · Chapter {n}', unit: 'Unit {n}', minutes: '{n} min',+ meta: '{chapters}{samples} · {units} · with sound', metaChapters: { one: '{n} chapter', other: '{n} chapters' },+ metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: ' + {n} sample',+ chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',+ doneMark: '✓ Finished · ', lastMark: ' · Last opened',+ },+ ru: {+ open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',+ meta: '{chapters}{samples} · {units} · со звуком',+ metaChapters: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' },+ metaUnits: { one: '{n} раздел', few: '{n} раздела', many: '{n} разделов', other: '{n} раздела' },+ metaSamples: { one: ' + {n} пробная', few: ' + {n} пробные', many: ' + {n} пробных', other: ' + {n} пробной' },+ chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',+ doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',+ },+ };+ const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];+ function translate(key, vars = {}) {+ const language = TRANSLATIONS[LANGUAGE]?.[key] !== undefined ? LANGUAGE : 'en';+ let text = TRANSLATIONS[language][key] ?? key;+ if (typeof text === 'object') {+ let rules;+ try { rules = new Intl.PluralRules(language); } catch { rules = new Intl.PluralRules('en'); }+ text = text[rules.select(vars.n)] ?? text.other;+ }+ return text.replace(/\{(\w+)\}/g, (placeholder, name) => name in vars ? vars[name] : placeholder);+ }+ const $ = id => document.getElementById(id);+ const id = n => 'ch' + String(n).padStart(2, '0');+ const esc = s => s.replace(/&/g, '&').replace(/</g, '<');+ const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];++ // Fixed interface text: data-t replaces an element's first text, data-t-label its aria-label.+ function translatePage() {+ for (const element of document.querySelectorAll('[data-t]')) element.firstChild.nodeValue = translate(element.dataset.t);+ for (const element of document.querySelectorAll('[data-t-label]')) element.setAttribute('aria-label', translate(element.dataset.tLabel));+ document.documentElement.style.setProperty('--done', JSON.stringify(translate('doneMark')));+ document.documentElement.style.setProperty('--last', JSON.stringify(translate('lastMark')));+ }++ // Reading progress { done: [chapter numbers], last }, written by the lessons. The engine and this page derive the+ // same key from the book's folder; a book that predates that passes its own key.+ function progress(key) {+ let P = {};+ try {+ const saved = JSON.parse(localStorage.getItem(key) || '{}');+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;+ } catch {}+ return { last: P.last, done: new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []) };+ }++ // The chapter cards, unit by unit, with progress, the header count, the cover's meta line and its resume button.+ // A unit's optional third entry { unit, chapter, sample } numbers it from elsewhere in the book; a sample chapter,+ // made to show another look, is not counted with the book's chapters.+ function contents(units, start, hues, P) {+ let n = start.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order+ const samples = new Set();+ $('units').innerHTML = units.map(([name, chs, o = {}], u) => {+ if (o.chapter) n = o.chapter - 1;+ return `<section class="unit" style="--c:${hues[u % hues.length]};--i:${i++}">${Units.header(u, translate('unit', { n: o.unit ?? u + start.unit }), name)}<div class="grid">` ++ chs.map(([t, min]) => { n++; if (o.sample) samples.add(n); else total++;+ const cls = 'ch' + (P.done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');+ return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${translate('minutes', { n: min })}</small></a>`;+ }).join('') + '</div></section>';+ }).join('');+ // A unit's sketch draws itself the first time the unit scrolls into view.+ Units.watch();+ const finished = [...P.done].filter(k => k >= start.chapter && k <= n && !samples.has(k)).length;+ $('prog').innerHTML = finished ? translate('finished', { done: `<b>${finished}</b>`, n: total }) : translate('chapterCount', { n: total });+ $('meta').textContent = translate('meta', {+ chapters: translate('metaChapters', { n: total }),+ samples: samples.size ? translate('metaSamples', { n: samples.size }) : '',+ units: translate('metaUnits', { n: units.filter(x => !x[2]?.sample).length }) });+ const last = Number.isInteger(P.last) && $(id(P.last));+ if (last) {+ const r = $('resume');+ r.hidden = false;+ r.href = last.getAttribute('href');+ r.textContent = translate('resume', { n: P.last });+ }+ }++ // The guide, drawn the same way as in the lessons, in the page's chalk (ink) colour.+ function lemniscate(cx, cy, a, k) {+ let d = '';+ for (let i = 0; i <= 96; i++) {+ const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;+ d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);+ }+ return d + 'Z';+ }+ function guides(ink) {+ for (const svg of document.querySelectorAll('svg.mascot')) {+ svg.setAttribute('viewBox', '0 0 120 84');+ svg.setAttribute('aria-hidden', 'true');+ const ln = `fill="none" stroke="${ink}" stroke-linecap="round" stroke-linejoin="round"`;+ svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` ++ [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="${ink}"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') ++ `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;+ }+ }++ // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.+ // Lessons link back with #chNN, so the reader lands on the chapter they just left.+ function views() {+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;+ function show(animate) {+ const open = location.hash.length > 1 && location.hash !== '#book';+ const apply = () => {+ document.body.classList.toggle('open', open);+ document.body.classList.toggle('stagger', animate && open);+ const here = open ? $(location.hash.slice(1)) : null;+ document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));+ if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }+ else scrollTo(0, 0);+ if (animate) {+ const heading = document.querySelector(open ? '#contents .home' : '#cover h1');+ heading?.setAttribute('tabindex', '-1');+ heading?.focus({ preventScroll: true });+ }+ };+ if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {+ const transition = document.startViewTransition(apply);+ // Navigation can interrupt either promise; the new view is already applied.+ transition.ready.catch(() => {});+ transition.finished.catch(() => {});+ } else apply();+ }+ addEventListener('hashchange', () => show(true));+ show(false);++ // Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.+ let named = null;+ const name = el => {+ if (named) named.style.viewTransitionName = '';+ named = el;+ if (el) el.style.viewTransitionName = 'lesson';+ };+ document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });+ addEventListener('pagereveal', e => {+ const target = (location.hash.length > 1 && $(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);+ name(e.viewTransition && target ? target : null);+ e.viewTransition?.finished.then(() => name(null), () => name(null));+ });+ }++ // units: [[unit title, [[chapter title, minutes], ...], { unit, chapter, sample }?], ...]. Chapters are numbered in+ // order from start (a book whose scope starts mid-way keeps the original numbers). hues: one colour per unit, cycling.+ function book({ units, start = { unit: 1, chapter: 1 }, hues = HUES, progressKey, ink } = {}) {+ translatePage();+ contents(units, start, hues, progress(progressKey ?? 'animebook:progress:' + new URL('.', location.href).pathname));+ guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');+ views();+ }++ return { book, translate };+})();diff --git a/engine/engine.css b/engine/engine.cssindex 0c532ab..9b9be00 100644--- a/engine/engine.css+++ b/engine/engine.css@@ -93,7 +93,7 @@ button[hidden] { display: none; }.hit:hover .ring, .hit:focus .ring { stroke-opacity: .7; }.hit.bad .ring { stroke: var(--bad); stroke-opacity: 1; }.hit.good .ring { stroke: var(--good); stroke-opacity: 1; stroke-width: 4; }-.tok { cursor: grab; }+.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page *//* Controls strip, part of the frame. */#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }diff --git a/engine/engine.js b/engine/engine.jsindex 2f6ba36..331ec10 100644--- a/engine/engine.js+++ b/engine/engine.js@@ -1323,32 +1323,28 @@ const choice = (opts, right, yes, no, onRight) => (body, api) => {key(e) { const b = bs[+e.key - 1]; if (!b || b.disabled) return false; b.click(); return true; },};};-// Tap a point on the stage number line.-const tap = (values, right, yes, no, onRight) => (body, api) => {- const L = qlayer(), hits = {};- let locked = false;- for (const v of values) {- const g = G(L, { x: X(v), y: Y0 });+// The shared body of the stage tap questions: each target ring is a focusable button that answers on click or Enter,+// and ← / → move the focus between them. targets: [{ g, label, ok, wrong }], wrong() shakes and returns the explanation.+const stageTap = (api, targets, show, yes, onRight, hint) => {+ let locked = false, cur = -1;+ const gs = targets.map(({ g, label, ok, wrong }) => {g.classList.add('hit');g.setAttribute('tabindex', 0);g.setAttribute('role', 'button');- g.setAttribute('aria-label', translate('pointLabel', { v: num(v) }));- mk('circle', { r: 30, class: 'ring' }, g);+ g.setAttribute('aria-label', label);const act = () => {if (locked) return;- if (v === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(S.dots[v]); api.grade(false, no(v)); }+ if (ok) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }+ else { g.classList.add('bad'); api.grade(false, wrong()); }};g.addEventListener('click', act);keyAct(g, act);- hits[v] = g;- }- const gs = values.map(v => hits[v]);- let cur = -1;+ return g;+ });return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },+ reveal() { gs[show].classList.add('good'); onRight?.(); return yes; },lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')],+ hint,key(e) {const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;if (!d || locked) return false;@@ -1358,71 +1354,38 @@ const tap = (values, right, yes, no, onRight) => (body, api) => {},};};+// Tap a point on the stage number line.+const tap = (values, right, yes, no, onRight) => (body, api) => {+ const L = qlayer();+ const targets = values.map(v => {+ const g = G(L, { x: X(v), y: Y0 });+ mk('circle', { r: 30, class: 'ring' }, g);+ return { g, label: translate('pointLabel', { v: num(v) }), ok: v === right, wrong: () => { shakeFx(S.dots[v]); return no(v); } };+ });+ return stageTap(api, targets, values.lastIndexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')]);+};// Tap one token of a stage token row, e.g. the operation to do first. idx: tappable token indexes.const tapEls = (row, idx, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = idx.map(i => {+ const targets = idx.map(i => {const e = row[i], w = e._w + 18, g = G(L, { x: e._px, y: row.y });- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', e.textContent.trim());mk('rect', { class: 'ring', x: -w / 2, y: -row.size * .95, width: w, height: row.size * 1.3, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(e); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: e.textContent.trim(), ok: i === right, wrong: () => { shakeFx(e); return no(i); } };});- return {- reveal() { hits[idx.indexOf(right)].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, idx.indexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')]);};// Click one of several stage objects (table cells, bars, small graphs). items: [{ el, box: [x, y, w, h], label }].const pickEls = (items, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = items.map((it, i) => {+ const targets = items.map((it, i) => {const [x, y, w, hh] = it.box, g = G(L);- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', it.label);mk('rect', { class: 'ring', x, y, width: w, height: hh, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(it.el); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: it.label, ok: i === right, wrong: () => { shakeFx(it.el); return no(i); } };});- return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, right, yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')]);};// Rows of toggles. items: { parts, ans: [keys], why }. parts are math parts (strings, F, R) unless text: true,// where they are rich text (strings and $m(...)). cols: [[key, label, colour?, shortcut?]]. multi: several per row.@@ -1647,6 +1610,13 @@ const sorter = (items, trayXY) => (body, api) => {drag = null;if (moved) place(c, st(c).x, st(c).y); else select(c);});+ // A cancelled drag (a system gesture, a lost capture) drops the chip where it is instead of leaving it stuck to no pointer.+ c.addEventListener('lostpointercapture', () => {+ if (!drag) return;+ const moved = drag.moved;+ drag = null;+ if (moved) place(c, st(c).x, st(c).y);+ });keyAct(c, () => { if (!locked) select(c); });return c;});@@ -1857,11 +1827,16 @@ function buildSegs() {return s.firstChild;});}+// ui() runs on every frame, paused or not: it writes only what changed, so an idle lesson does no layout work.+let stepText = '';+const setWidth = (f, w) => { if (f._w !== w) { f._w = w; f.style.width = w + '%'; } };function ui() {- segs.forEach((f, k) => { f.style.width = (k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)) + '%'; });- $('frame').classList.toggle('is-playing', P.playing && !P.done && !P.waiting);- $('frame').classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);- $('stepName').textContent = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ segs.forEach((f, k) => setWidth(f, k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)));+ const fr = $('frame');+ fr.classList.toggle('is-playing', P.playing && !P.done && !P.waiting);+ fr.classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);+ const step = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ if (step !== stepText) { stepText = step; $('stepName').textContent = step; }const b = BEATS[P.i];let text = '';if (captions && P.started && !b.ask && !P.done) {diff --git a/site/elementary-algebra/index.html b/site/elementary-algebra/index.htmlindex 5f04a01..c67ed51 100644--- a/site/elementary-algebra/index.html+++ b/site/elementary-algebra/index.html@@ -3,136 +3,16 @@<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">-<script>-// Observe aborted incoming transitions before the first rendering opportunity.-addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));-</script><title>Elementary Algebra — Papermorph</title><meta name="description" content="Animated pre-algebra and algebra, with narrated lessons, interactive quick checks, and chapter practice."><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='14' fill='%231d2b27'/%3E%3Ctext x='32' y='45' text-anchor='middle' font-size='48' fill='%23f0b45a'%3E∞%3C/text%3E%3C/svg%3E"><link rel="stylesheet" href="lib/units.css">+<link rel="stylesheet" href="lib/contents.css">+<link rel="stylesheet" href="../lib/books.css"><script src="lib/units.js"></script>+<script src="lib/contents.js"></script><script src="lib/unit-art.js"></script><link rel="expect" href="#ch01" blocking="render">-<style>-:root {- --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;- --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;- --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;- --book: "Iowan Old Style", Palatino, Georgia, serif;- --ease: cubic-bezier(.2, .8, .2, 1);- color-scheme: dark;-}-* { box-sizing: border-box; }-html { scroll-padding-top: 90px; }-body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }-/* Chalkboard: the same grain and vignette as the lesson stage. */-body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;- background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),- url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }-a { color: inherit; }-a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }-.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }--/* ---------- cover ---------- */-#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;- padding: 48px 16px 64px; text-align: center; overflow: hidden; }-.open #cover, body:not(.open) #contents { display: none; }-#cover > * { animation: rise .8s var(--ease) backwards; }-#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }-#cover .kicker { animation-delay: .9s; }-#cover h1 { animation-delay: 1s; }-#cover .lede { animation-delay: 1.12s; }-#cover .acts { animation-delay: 1.24s; }-#cover .meta { animation-delay: 1.36s; }-h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }-h1 i { color: var(--task); font-style: italic; }-.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }-.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }-.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;- transition: transform .25s var(--ease), background-color .25s, border-color .25s; }-.btn[hidden] { display: none; }-.btn:hover { transform: translateY(-2px); }-.btn.go { background: var(--chalk); color: var(--board); }-.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }-.btn.quiet:hover { border-color: var(--dim); }-.btn svg { width: 15px; height: 15px; fill: currentColor; }-.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }-.inspiration { max-width: 48em; margin: 22px 0 0; color: var(--dim); font-size: 14px; line-height: 1.6; text-wrap: balance; }-.inspiration a { text-decoration-color: var(--faint); text-underline-offset: 3px; }-.inspiration a:hover { color: var(--chalk); text-decoration-color: currentColor; }-/* Faint chalk notes around the edges of the board. */-.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }-.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;- animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }-@keyframes chalk { to { opacity: .075; } }-@keyframes drift { to { translate: 0 -10px; } }-@keyframes rise { from { opacity: 0; transform: translateY(16px); } }--/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */-.mascot { display: block; overflow: visible; }-.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }-.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }-.mascot .joy { display: none; }-#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }-#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }-.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }-.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }-@keyframes draw { from { stroke-dashoffset: 1; } }-@keyframes pop { from { opacity: 0; transform: scale(.6); } }-.draw .face { transform-box: view-box; transform-origin: 60px 44px; }-@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }-@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }--/* ---------- contents ---------- */-.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));- background: rgba(22, 33, 29, .86); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid #2a3b35; }-.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }-.home .mascot { view-transition-name: guide; }-.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }-.home strong i { color: var(--task); }-.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }-.prog b { color: var(--good); font-weight: 600; }-main#contents { padding-bottom: 80px; }-.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }-.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;- padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);- text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }-.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px rgba(0, 0, 0, .3); }-.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }-.ch span { font-size: 18px; line-height: 1.3; }-.ch small { color: var(--dim); font-size: 14px; }-.ch.done small::before { content: "✓ Finished · "; color: var(--good); font-weight: 600; }-.ch.last small::after { content: " · Last opened"; color: var(--quiz); }-.ch.here:focus-visible { outline-color: var(--c); }-.ch.here { animation: here 1.8s ease-out .3s; }-@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }-.stagger .top { animation: rise .6s var(--ease) backwards; }-.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }--.back-shelf { color: var(--dim); font: 13px var(--ui); text-decoration: none; white-space: nowrap; }-.back-shelf:hover { color: var(--chalk); }-.cover-back { position: absolute; top: 24px; left: 24px; }-.contents-back { margin-left: 16px; }--/* ---------- page-to-page motion ---------- */-@view-transition { navigation: auto; }-/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the- contents still rise in. -moz-orient exists only in Firefox. */-@supports (-moz-orient: inline) { @view-transition { navigation: none; } }-::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }-::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }-::view-transition-old(lesson) { animation-duration: .18s; }-@media (max-width: 560px) {- .home strong { font-size: 18px; }- .ch { min-height: 0; }- .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }-}-@media (prefers-reduced-motion: reduce) {- *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }- .chalk span { opacity: .075; }-}-</style></head><body><section id="cover">@@ -150,7 +30,7 @@ main#contents { padding-bottom: 80px; }<h1>Elementary <i>Algebra</i></h1><p class="lede">Lessons drawn and narrated step by step, quick checks inside the picture, and practice at the end of every chapter.</p><div class="acts">- <a class="btn go" href="#contents">Open the book<svg viewBox="0 0 16 16"><path d="M6 2.5 11.5 8 6 13.5 4.6 12.1 8.7 8 4.6 3.9z"/></svg></a>+ <a class="btn go" href="#contents" data-t="open">Open the book<svg viewBox="0 0 16 16"><path d="M6 2.5 11.5 8 6 13.5 4.6 12.1 8.7 8 4.6 3.9z"/></svg></a><a class="btn quiet" id="resume" hidden></a></div><p class="meta" id="meta"></p>@@ -160,7 +40,7 @@ main#contents { padding-bottom: 80px; }<main id="contents"><header class="top">- <a class="home" href="#book" aria-label="Back to the cover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>Elementary <i>Algebra</i></strong></a>+ <a class="home" href="#book" aria-label="Back to the cover" data-t-label="toCover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>Elementary <i>Algebra</i></strong></a><span class="prog" id="prog"></span><a class="back-shelf contents-back" href="../">← Bookshelf</a></header>@@ -168,120 +48,31 @@ main#contents { padding-bottom: 80px; }</main><script>-'use strict';-// Chapters are numbered in order through the units. Add a chapter here when its lesson is ready.-const UNITS = [- ['Arithmetic properties', [['Types of numbers', 8], ['Algebraic properties', 9], ['Order of operations', 7]]],- ['The number system', [['Adding positive and negative numbers', 7], ['Subtracting positive and negative numbers', 6],- ['Multiplying and dividing positive and negative numbers', 6], ['Multiplying and dividing fractions', 7], ['Adding and subtracting fractions', 7],- ['Adding and subtracting decimals', 7], ['Multiplying and dividing decimals', 7]]],- ['Ratios, proportions, and percents', [['Ratio', 6], ['Unit rate', 5], ['Proportion', 6], ['Percent', 7], ['Percent applications', 7],- ['Simple interest', 6], ['Percent rate of change', 5], ['Tables and ratios', 5]]],- ['Exponents and algebraic expressions', [['Exponents', 6], ['Scientific notation', 6], ['Expressions', 6], ['Evaluating algebraic expressions', 6],- ['Combining like terms', 6]]],- ['Linear equations and inequalities', [['Introduction to equations', 6], ['Solving one-variable equations', 7], ['Solving one-variable inequalities', 7],- ['Solving compound inequalities', 7], ['Rewriting formulas', 5], ['Solving systems by substitution', 7], ['Solving systems by elimination', 6]]],- ['Graphing linear equations and inequalities', [['Points and lines', 5], ['Graphing a line from a table', 5], ['Slope', 5], ['Slope-intercept form', 6],- ['Point-slope form', 7], ['Solving systems by graphing', 6], ['Graphing linear inequalities', 6], ['Systems of inequalities by graphing', 6]]],- ['Statistics and probability', [['Introduction to statistics', 6], ['Measures of center and variation', 8], ['Displaying data', 10], ['Probability', 10], ['Compound events', 8], ['Permutations and combinations', 9]]],- ['Functions', [['Relations and functions', 8], ['Function notation', 8], ['Application of functions', 9]]],- ['Polynomial operations', [['Adding and subtracting polynomials', 9], ['Multiplying and dividing powers', 8], ['Multiplying and dividing monomials', 9], ['Multiplying and dividing polynomials', 10]]],- ['Factoring polynomials', [['Factoring with the GCF', 10], ['Factoring by grouping', 8], ['Factoring trinomials when a = 1', 9], ['Factoring trinomials when a ≠ 1', 9], ['Special factoring patterns', 10]]],- ['Radicals', [['Square roots and cube roots', 9], ['Simplifying radicals', 9], ['Adding and subtracting radicals', 8], ['Multiplying and dividing radicals', 9]]],- ['Quadratic equations', [['Introduction to quadratic equations', 9], ['Solving by factoring', 10], ['Solving by taking square roots', 9], ['Completing the square', 10], ['The quadratic formula', 10], ['The discriminant', 8]]],- ['Quadratic functions', [['Graphing quadratic functions', 11], ['Solving by graphing', 9]]],-];-const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];-const id = n => 'ch' + String(n).padStart(2, '0');-let P = {};-try {- const saved = JSON.parse(localStorage.getItem('progress') || '{}');- if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;-} catch {}-const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);--// Contents.-let n = 0, total = 0, i = 0; // i staggers the entrance, in reading order-const esc = s => s.replace(/&/g, '&').replace(/</g, '<');-document.getElementById('units').innerHTML = UNITS.map(([name, chs], u) => {- return `<section class="unit" style="--c:${HUES[u % HUES.length]};--i:${i++}">${Units.header(u, `Unit ${u + 1}`, name)}<div class="grid">` +- chs.map(([t, min]) => { n++;- const cls = 'ch' + (done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');- return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${min} min</small></a>`;- }).join('') + '</div></section>';-}).join('');-total = n;-// A unit's sketch draws itself the first time the unit scrolls into view.-Units.watch();-const finished = [...done].filter(k => k <= total).length;-document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapters`;-document.getElementById('meta').textContent = `${total} chapters · ${UNITS.length} units · with sound`;-const last = Number.isInteger(P.last) && document.getElementById(id(P.last));-if (last) {- const r = document.getElementById('resume');- r.hidden = false;- r.href = last.getAttribute('href');- r.textContent = `Continue · Chapter ${P.last}`;-}--// The guide, drawn the same way as in the lessons.-function lemniscate(cx, cy, a, k) {- let d = '';- for (let i = 0; i <= 96; i++) {- const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;- d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);- }- return d + 'Z';-}-for (const svg of document.querySelectorAll('svg.mascot')) {- svg.setAttribute('viewBox', '0 0 120 84');- svg.setAttribute('aria-hidden', 'true');- const ln = 'fill="none" stroke="#ece8dc" stroke-linecap="round" stroke-linejoin="round"';- svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` +- [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="#ece8dc"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') +- `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;-}--// The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.-// Lessons link back with #chNN, so the reader lands on the chapter they just left.-const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;-function show(animate) {- const open = location.hash.length > 1 && location.hash !== '#book';- const apply = () => {- document.body.classList.toggle('open', open);- document.body.classList.toggle('stagger', animate && open);- const here = open ? document.getElementById(location.hash.slice(1)) : null;- document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));- if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }- else scrollTo(0, 0);- if (animate) {- const heading = document.querySelector(open ? '#contents .home' : '#cover h1');- heading?.setAttribute('tabindex', '-1');- heading?.focus({ preventScroll: true });- }- };- if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {- const transition = document.startViewTransition(apply);- // Navigation can interrupt either promise; the new view is already applied.- transition.ready.catch(() => {});- transition.finished.catch(() => {});- } else apply();-}-addEventListener('hashchange', () => show(true));-show(false);--// Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.-let named = null;-const name = el => {- if (named) named.style.viewTransitionName = '';- named = el;- if (el) el.style.viewTransitionName = 'lesson';-};-document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });-addEventListener('pagereveal', e => {- const target = (location.hash.length > 1 && document.getElementById(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);- name(e.viewTransition && target ? target : null);- e.viewTransition?.finished.then(() => name(null), () => name(null));+// Add a chapter here when its lesson is ready; chapters are numbered in order from start.+Contents.book({+ progressKey: 'progress', // this book's progress predates the per-book key+ units: [ // [unit title, [[chapter title, minutes], ...], { unit, chapter, sample }?]+ ['Arithmetic properties', [['Types of numbers', 8], ['Algebraic properties', 9], ['Order of operations', 7]]],+ ['The number system', [['Adding positive and negative numbers', 7], ['Subtracting positive and negative numbers', 6],+ ['Multiplying and dividing positive and negative numbers', 6], ['Multiplying and dividing fractions', 7], ['Adding and subtracting fractions', 7],+ ['Adding and subtracting decimals', 7], ['Multiplying and dividing decimals', 7]]],+ ['Ratios, proportions, and percents', [['Ratio', 6], ['Unit rate', 5], ['Proportion', 6], ['Percent', 7], ['Percent applications', 7],+ ['Simple interest', 6], ['Percent rate of change', 5], ['Tables and ratios', 5]]],+ ['Exponents and algebraic expressions', [['Exponents', 6], ['Scientific notation', 6], ['Expressions', 6], ['Evaluating algebraic expressions', 6],+ ['Combining like terms', 6]]],+ ['Linear equations and inequalities', [['Introduction to equations', 6], ['Solving one-variable equations', 7], ['Solving one-variable inequalities', 7],+ ['Solving compound inequalities', 7], ['Rewriting formulas', 5], ['Solving systems by substitution', 7], ['Solving systems by elimination', 6]]],+ ['Graphing linear equations and inequalities', [['Points and lines', 5], ['Graphing a line from a table', 5], ['Slope', 5], ['Slope-intercept form', 6],+ ['Point-slope form', 7], ['Solving systems by graphing', 6], ['Graphing linear inequalities', 6], ['Systems of inequalities by graphing', 6]]],+ ['Statistics and probability', [['Introduction to statistics', 6], ['Measures of center and variation', 8], ['Displaying data', 10], ['Probability', 10], ['Compound events', 8], ['Permutations and combinations', 9]]],+ ['Functions', [['Relations and functions', 8], ['Function notation', 8], ['Application of functions', 9]]],+ ['Polynomial operations', [['Adding and subtracting polynomials', 9], ['Multiplying and dividing powers', 8], ['Multiplying and dividing monomials', 9], ['Multiplying and dividing polynomials', 10]]],+ ['Factoring polynomials', [['Factoring with the GCF', 10], ['Factoring by grouping', 8], ['Factoring trinomials when a = 1', 9], ['Factoring trinomials when a ≠ 1', 9], ['Special factoring patterns', 10]]],+ ['Radicals', [['Square roots and cube roots', 9], ['Simplifying radicals', 9], ['Adding and subtracting radicals', 8], ['Multiplying and dividing radicals', 9]]],+ ['Quadratic equations', [['Introduction to quadratic equations', 9], ['Solving by factoring', 10], ['Solving by taking square roots', 9], ['Completing the square', 10], ['The quadratic formula', 10], ['The discriminant', 8]]],+ ['Quadratic functions', [['Graphing quadratic functions', 11], ['Solving by graphing', 9]]],+ ],+ hues: ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'],});</script></body>diff --git a/site/elementary-algebra/lib/contents.css b/site/elementary-algebra/lib/contents.cssnew file mode 100644index 0000000..3f59f10--- /dev/null+++ b/site/elementary-algebra/lib/contents.css@@ -0,0 +1,115 @@+/* The book's cover and contents (index.html): the chalkboard look, the cover, the guide, the chapter grid and the+ page-to-page motion. A book's own <style> after this file sets its theme: the colour and font tokens below, and the+ few rules a theme redraws (e.g. body::before for the paper). */+:root {+ --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;+ --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;+ --book: "Iowan Old Style", Palatino, Georgia, serif;+ --ease: cubic-bezier(.2, .8, .2, 1);+ --top-bg: rgba(22, 33, 29, .86); --top-line: #2a3b35; /* the sticky contents header */+ --lift: rgba(0, 0, 0, .3); /* a card's shadow on hover */+ color-scheme: dark;+}+* { box-sizing: border-box; }+html { scroll-padding-top: 90px; }+body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }+/* Chalkboard: the same grain and vignette as the lesson stage. */+body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;+ background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }+a { color: inherit; }+a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }+.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }++/* ---------- cover ---------- */+#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;+ padding: 48px 16px 64px; text-align: center; overflow: hidden; }+.open #cover, body:not(.open) #contents { display: none; }+#cover > * { animation: rise .8s var(--ease) backwards; }+#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }+#cover .kicker { animation-delay: .9s; }+#cover h1 { animation-delay: 1s; }+#cover .lede { animation-delay: 1.12s; }+#cover .acts { animation-delay: 1.24s; }+#cover .meta { animation-delay: 1.36s; }+h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }+h1 i { color: var(--task); font-style: italic; }+.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }+.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }+.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;+ transition: transform .25s var(--ease), background-color .25s, border-color .25s; }+.btn[hidden] { display: none; }+.btn:hover { transform: translateY(-2px); }+.btn.go { background: var(--chalk); color: var(--board); }+.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }+.btn.quiet:hover { border-color: var(--dim); }+.btn svg { width: 15px; height: 15px; fill: currentColor; }+.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }+/* Faint chalk notes around the edges of the board. */+.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }+.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;+ animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }+@keyframes chalk { to { opacity: .075; } }+@keyframes drift { to { translate: 0 -10px; } }+@keyframes rise { from { opacity: 0; transform: translateY(16px); } }++/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */+.mascot { display: block; overflow: visible; }+.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }+.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }+.mascot .joy { display: none; }+#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }+#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }+.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }+.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }+@keyframes draw { from { stroke-dashoffset: 1; } }+@keyframes pop { from { opacity: 0; transform: scale(.6); } }+.draw .face { transform-box: view-box; transform-origin: 60px 44px; }+@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }+@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }++/* ---------- contents ---------- */+.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));+ background: var(--top-bg); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid var(--top-line); }+.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }+.home .mascot { view-transition-name: guide; }+.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }+.home strong i { color: var(--task); }+.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }+.prog b { color: var(--good); font-weight: 600; }+main#contents { padding-bottom: 80px; }+.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }+.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;+ padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);+ text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }+.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px var(--lift); }+.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }+.ch span { font-size: 18px; line-height: 1.3; }+.ch small { color: var(--dim); font-size: 14px; }+.ch.done small::before { content: var(--done, "✓ Finished · "); color: var(--good); font-weight: 600; }+.ch.last small::after { content: var(--last, " · Last opened"); color: var(--quiz); }+.ch.here:focus-visible { outline-color: var(--c); }+.ch.here { animation: here 1.8s ease-out .3s; }+@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }+.stagger .top { animation: rise .6s var(--ease) backwards; }+.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }++/* ---------- page-to-page motion ---------- */+@view-transition { navigation: auto; }+/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the+ contents still rise in. -moz-orient exists only in Firefox. */+@supports (-moz-orient: inline) { @view-transition { navigation: none; } }+::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }+::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }+::view-transition-old(lesson) { animation-duration: .18s; }+@media (max-width: 560px) {+ .home strong { font-size: 18px; }+ #contents .top { flex-wrap: wrap; gap: 8px 12px; }+ .ch { min-height: 0; }+ .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }+}+@media (prefers-reduced-motion: reduce) {+ *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }+ .chalk span { opacity: .075; }+}diff --git a/site/elementary-algebra/lib/contents.js b/site/elementary-algebra/lib/contents.jsnew file mode 100644index 0000000..fdc7de6--- /dev/null+++ b/site/elementary-algebra/lib/contents.js@@ -0,0 +1,169 @@+/* The book's cover and contents (index.html): interface text, the chapter list with reading progress, the guide,+ and the cover ↔ contents ↔ lesson motion. Load it in <head>; after the markup, the page calls+ Contents.book({ units, start, hues }) with its chapter list. */+'use strict';+// Observe aborted incoming transitions before the first rendering opportunity.+addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));++const Contents = (() => {+ // Interface text in the page's <html lang>, as in the lessons; missing keys fall back to English.+ // A value is a string or plural forms { one, few, many, other } chosen by vars.n.+ const TRANSLATIONS = {+ en: {+ open: 'Open the book', toCover: 'Back to the cover', resume: 'Continue · Chapter {n}', unit: 'Unit {n}', minutes: '{n} min',+ meta: '{chapters}{samples} · {units} · with sound', metaChapters: { one: '{n} chapter', other: '{n} chapters' },+ metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: ' + {n} sample',+ chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',+ doneMark: '✓ Finished · ', lastMark: ' · Last opened',+ },+ ru: {+ open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',+ meta: '{chapters}{samples} · {units} · со звуком',+ metaChapters: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' },+ metaUnits: { one: '{n} раздел', few: '{n} раздела', many: '{n} разделов', other: '{n} раздела' },+ metaSamples: { one: ' + {n} пробная', few: ' + {n} пробные', many: ' + {n} пробных', other: ' + {n} пробной' },+ chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',+ doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',+ },+ };+ const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];+ function translate(key, vars = {}) {+ const language = TRANSLATIONS[LANGUAGE]?.[key] !== undefined ? LANGUAGE : 'en';+ let text = TRANSLATIONS[language][key] ?? key;+ if (typeof text === 'object') {+ let rules;+ try { rules = new Intl.PluralRules(language); } catch { rules = new Intl.PluralRules('en'); }+ text = text[rules.select(vars.n)] ?? text.other;+ }+ return text.replace(/\{(\w+)\}/g, (placeholder, name) => name in vars ? vars[name] : placeholder);+ }+ const $ = id => document.getElementById(id);+ const id = n => 'ch' + String(n).padStart(2, '0');+ const esc = s => s.replace(/&/g, '&').replace(/</g, '<');+ const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];++ // Fixed interface text: data-t replaces an element's first text, data-t-label its aria-label.+ function translatePage() {+ for (const element of document.querySelectorAll('[data-t]')) element.firstChild.nodeValue = translate(element.dataset.t);+ for (const element of document.querySelectorAll('[data-t-label]')) element.setAttribute('aria-label', translate(element.dataset.tLabel));+ document.documentElement.style.setProperty('--done', JSON.stringify(translate('doneMark')));+ document.documentElement.style.setProperty('--last', JSON.stringify(translate('lastMark')));+ }++ // Reading progress { done: [chapter numbers], last }, written by the lessons. The engine and this page derive the+ // same key from the book's folder; a book that predates that passes its own key.+ function progress(key) {+ let P = {};+ try {+ const saved = JSON.parse(localStorage.getItem(key) || '{}');+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;+ } catch {}+ return { last: P.last, done: new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []) };+ }++ // The chapter cards, unit by unit, with progress, the header count, the cover's meta line and its resume button.+ // A unit's optional third entry { unit, chapter, sample } numbers it from elsewhere in the book; a sample chapter,+ // made to show another look, is not counted with the book's chapters.+ function contents(units, start, hues, P) {+ let n = start.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order+ const samples = new Set();+ $('units').innerHTML = units.map(([name, chs, o = {}], u) => {+ if (o.chapter) n = o.chapter - 1;+ return `<section class="unit" style="--c:${hues[u % hues.length]};--i:${i++}">${Units.header(u, translate('unit', { n: o.unit ?? u + start.unit }), name)}<div class="grid">` ++ chs.map(([t, min]) => { n++; if (o.sample) samples.add(n); else total++;+ const cls = 'ch' + (P.done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');+ return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${translate('minutes', { n: min })}</small></a>`;+ }).join('') + '</div></section>';+ }).join('');+ // A unit's sketch draws itself the first time the unit scrolls into view.+ Units.watch();+ const finished = [...P.done].filter(k => k >= start.chapter && k <= n && !samples.has(k)).length;+ $('prog').innerHTML = finished ? translate('finished', { done: `<b>${finished}</b>`, n: total }) : translate('chapterCount', { n: total });+ $('meta').textContent = translate('meta', {+ chapters: translate('metaChapters', { n: total }),+ samples: samples.size ? translate('metaSamples', { n: samples.size }) : '',+ units: translate('metaUnits', { n: units.filter(x => !x[2]?.sample).length }) });+ const last = Number.isInteger(P.last) && $(id(P.last));+ if (last) {+ const r = $('resume');+ r.hidden = false;+ r.href = last.getAttribute('href');+ r.textContent = translate('resume', { n: P.last });+ }+ }++ // The guide, drawn the same way as in the lessons, in the page's chalk (ink) colour.+ function lemniscate(cx, cy, a, k) {+ let d = '';+ for (let i = 0; i <= 96; i++) {+ const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;+ d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);+ }+ return d + 'Z';+ }+ function guides(ink) {+ for (const svg of document.querySelectorAll('svg.mascot')) {+ svg.setAttribute('viewBox', '0 0 120 84');+ svg.setAttribute('aria-hidden', 'true');+ const ln = `fill="none" stroke="${ink}" stroke-linecap="round" stroke-linejoin="round"`;+ svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` ++ [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="${ink}"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') ++ `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;+ }+ }++ // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.+ // Lessons link back with #chNN, so the reader lands on the chapter they just left.+ function views() {+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;+ function show(animate) {+ const open = location.hash.length > 1 && location.hash !== '#book';+ const apply = () => {+ document.body.classList.toggle('open', open);+ document.body.classList.toggle('stagger', animate && open);+ const here = open ? $(location.hash.slice(1)) : null;+ document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));+ if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }+ else scrollTo(0, 0);+ if (animate) {+ const heading = document.querySelector(open ? '#contents .home' : '#cover h1');+ heading?.setAttribute('tabindex', '-1');+ heading?.focus({ preventScroll: true });+ }+ };+ if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {+ const transition = document.startViewTransition(apply);+ // Navigation can interrupt either promise; the new view is already applied.+ transition.ready.catch(() => {});+ transition.finished.catch(() => {});+ } else apply();+ }+ addEventListener('hashchange', () => show(true));+ show(false);++ // Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.+ let named = null;+ const name = el => {+ if (named) named.style.viewTransitionName = '';+ named = el;+ if (el) el.style.viewTransitionName = 'lesson';+ };+ document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });+ addEventListener('pagereveal', e => {+ const target = (location.hash.length > 1 && $(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);+ name(e.viewTransition && target ? target : null);+ e.viewTransition?.finished.then(() => name(null), () => name(null));+ });+ }++ // units: [[unit title, [[chapter title, minutes], ...], { unit, chapter, sample }?], ...]. Chapters are numbered in+ // order from start (a book whose scope starts mid-way keeps the original numbers). hues: one colour per unit, cycling.+ function book({ units, start = { unit: 1, chapter: 1 }, hues = HUES, progressKey, ink } = {}) {+ translatePage();+ contents(units, start, hues, progress(progressKey ?? 'animebook:progress:' + new URL('.', location.href).pathname));+ guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');+ views();+ }++ return { book, translate };+})();diff --git a/site/elementary-algebra/lib/engine.css b/site/elementary-algebra/lib/engine.cssindex 0c532ab..9b9be00 100644--- a/site/elementary-algebra/lib/engine.css+++ b/site/elementary-algebra/lib/engine.css@@ -93,7 +93,7 @@ button[hidden] { display: none; }.hit:hover .ring, .hit:focus .ring { stroke-opacity: .7; }.hit.bad .ring { stroke: var(--bad); stroke-opacity: 1; }.hit.good .ring { stroke: var(--good); stroke-opacity: 1; stroke-width: 4; }-.tok { cursor: grab; }+.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page *//* Controls strip, part of the frame. */#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }diff --git a/site/elementary-algebra/lib/engine.js b/site/elementary-algebra/lib/engine.jsindex 2f6ba36..331ec10 100644--- a/site/elementary-algebra/lib/engine.js+++ b/site/elementary-algebra/lib/engine.js@@ -1323,32 +1323,28 @@ const choice = (opts, right, yes, no, onRight) => (body, api) => {key(e) { const b = bs[+e.key - 1]; if (!b || b.disabled) return false; b.click(); return true; },};};-// Tap a point on the stage number line.-const tap = (values, right, yes, no, onRight) => (body, api) => {- const L = qlayer(), hits = {};- let locked = false;- for (const v of values) {- const g = G(L, { x: X(v), y: Y0 });+// The shared body of the stage tap questions: each target ring is a focusable button that answers on click or Enter,+// and ← / → move the focus between them. targets: [{ g, label, ok, wrong }], wrong() shakes and returns the explanation.+const stageTap = (api, targets, show, yes, onRight, hint) => {+ let locked = false, cur = -1;+ const gs = targets.map(({ g, label, ok, wrong }) => {g.classList.add('hit');g.setAttribute('tabindex', 0);g.setAttribute('role', 'button');- g.setAttribute('aria-label', translate('pointLabel', { v: num(v) }));- mk('circle', { r: 30, class: 'ring' }, g);+ g.setAttribute('aria-label', label);const act = () => {if (locked) return;- if (v === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(S.dots[v]); api.grade(false, no(v)); }+ if (ok) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }+ else { g.classList.add('bad'); api.grade(false, wrong()); }};g.addEventListener('click', act);keyAct(g, act);- hits[v] = g;- }- const gs = values.map(v => hits[v]);- let cur = -1;+ return g;+ });return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },+ reveal() { gs[show].classList.add('good'); onRight?.(); return yes; },lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')],+ hint,key(e) {const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;if (!d || locked) return false;@@ -1358,71 +1354,38 @@ const tap = (values, right, yes, no, onRight) => (body, api) => {},};};+// Tap a point on the stage number line.+const tap = (values, right, yes, no, onRight) => (body, api) => {+ const L = qlayer();+ const targets = values.map(v => {+ const g = G(L, { x: X(v), y: Y0 });+ mk('circle', { r: 30, class: 'ring' }, g);+ return { g, label: translate('pointLabel', { v: num(v) }), ok: v === right, wrong: () => { shakeFx(S.dots[v]); return no(v); } };+ });+ return stageTap(api, targets, values.lastIndexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')]);+};// Tap one token of a stage token row, e.g. the operation to do first. idx: tappable token indexes.const tapEls = (row, idx, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = idx.map(i => {+ const targets = idx.map(i => {const e = row[i], w = e._w + 18, g = G(L, { x: e._px, y: row.y });- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', e.textContent.trim());mk('rect', { class: 'ring', x: -w / 2, y: -row.size * .95, width: w, height: row.size * 1.3, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(e); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: e.textContent.trim(), ok: i === right, wrong: () => { shakeFx(e); return no(i); } };});- return {- reveal() { hits[idx.indexOf(right)].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, idx.indexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')]);};// Click one of several stage objects (table cells, bars, small graphs). items: [{ el, box: [x, y, w, h], label }].const pickEls = (items, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = items.map((it, i) => {+ const targets = items.map((it, i) => {const [x, y, w, hh] = it.box, g = G(L);- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', it.label);mk('rect', { class: 'ring', x, y, width: w, height: hh, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(it.el); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: it.label, ok: i === right, wrong: () => { shakeFx(it.el); return no(i); } };});- return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, right, yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')]);};// Rows of toggles. items: { parts, ans: [keys], why }. parts are math parts (strings, F, R) unless text: true,// where they are rich text (strings and $m(...)). cols: [[key, label, colour?, shortcut?]]. multi: several per row.@@ -1647,6 +1610,13 @@ const sorter = (items, trayXY) => (body, api) => {drag = null;if (moved) place(c, st(c).x, st(c).y); else select(c);});+ // A cancelled drag (a system gesture, a lost capture) drops the chip where it is instead of leaving it stuck to no pointer.+ c.addEventListener('lostpointercapture', () => {+ if (!drag) return;+ const moved = drag.moved;+ drag = null;+ if (moved) place(c, st(c).x, st(c).y);+ });keyAct(c, () => { if (!locked) select(c); });return c;});@@ -1857,11 +1827,16 @@ function buildSegs() {return s.firstChild;});}+// ui() runs on every frame, paused or not: it writes only what changed, so an idle lesson does no layout work.+let stepText = '';+const setWidth = (f, w) => { if (f._w !== w) { f._w = w; f.style.width = w + '%'; } };function ui() {- segs.forEach((f, k) => { f.style.width = (k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)) + '%'; });- $('frame').classList.toggle('is-playing', P.playing && !P.done && !P.waiting);- $('frame').classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);- $('stepName').textContent = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ segs.forEach((f, k) => setWidth(f, k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)));+ const fr = $('frame');+ fr.classList.toggle('is-playing', P.playing && !P.done && !P.waiting);+ fr.classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);+ const step = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ if (step !== stepText) { stepText = step; $('stepName').textContent = step; }const b = BEATS[P.i];let text = '';if (captions && P.started && !b.ask && !P.done) {diff --git a/site/lib/books.css b/site/lib/books.cssnew file mode 100644index 0000000..cc96421--- /dev/null+++ b/site/lib/books.css@@ -0,0 +1,12 @@+/* Website-only additions to the books' cover and contents (not part of the Papermorph template):+ the links back to the bookshelf and the "Inspired by" line. Loaded after lib/contents.css. */+.back-shelf { color: var(--dim); font: 13px var(--ui); text-decoration: none; white-space: nowrap; }+.back-shelf:hover { color: var(--chalk); }+.cover-back { position: absolute; top: 24px; left: 24px; }+.contents-back { margin-left: 16px; }+.inspiration { max-width: 48em; margin: 22px 0 0; color: var(--dim); font-size: 14px; line-height: 1.6; text-wrap: balance; }+.inspiration a { text-decoration-color: var(--faint); text-underline-offset: 3px; }+.inspiration a:hover { color: var(--chalk); text-decoration-color: currentColor; }+@media (max-width: 560px) {+ .contents-back { margin-left: 0; font-size: 11px; }+}diff --git a/site/lib/bookshelf.js b/site/lib/bookshelf.jsindex 77bbdcc..2e5ea80 100644--- a/site/lib/bookshelf.js+++ b/site/lib/bookshelf.js@@ -17,9 +17,9 @@const books = [{ id: 'elementary-algebra', key: 'progress', chapterBase: 'elementary-algebra/', chapters: 68 },{ id: 'math-notebook', key: 'animebook:progress:' + new URL('math-notebook/', location.href).pathname,- chapterBase: 'math-notebook/', chapters: 22 },+ chapterBase: 'math-notebook/', chapters: 23 },{ id: 'science', key: 'animebook:progress:' + new URL('science/', location.href).pathname,- chapterBase: 'science/', chapters: 11 },+ chapterBase: 'science/', chapters: 19 },];for (const book of books) {const cover = document.querySelector(`[data-book="${book.id}"]`);diff --git a/site/math-notebook/index.html b/site/math-notebook/index.htmlindex ad6af8d..74c9bbc 100644--- a/site/math-notebook/index.html+++ b/site/math-notebook/index.html@@ -3,138 +3,16 @@<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">-<script>-// Observe aborted incoming transitions before the first rendering opportunity.-addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));-</script><title>Elementary Mathematics — Papermorph</title><meta name="description" content="Animated middle-school mathematics, with narrated lessons, interactive quick checks, and chapter practice."><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='14' fill='%231d2b27'/%3E%3Ctext x='32' y='45' text-anchor='middle' font-size='48' fill='%23f0b45a'%3E∞%3C/text%3E%3C/svg%3E"><link rel="stylesheet" href="lib/units.css">+<link rel="stylesheet" href="lib/contents.css">+<link rel="stylesheet" href="../lib/books.css"><script src="lib/units.js"></script>+<script src="lib/contents.js"></script><script src="unit-art.js"></script><link rel="expect" href="#ch01" blocking="render">-<style>-:root {- --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;- --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;- --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;- --book: "Iowan Old Style", Palatino, Georgia, serif;- --ease: cubic-bezier(.2, .8, .2, 1);- color-scheme: dark;-}-* { box-sizing: border-box; }-html { scroll-padding-top: 90px; }-body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }-/* Chalkboard: the same grain and vignette as the lesson stage. */-body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;- background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),- url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }-a { color: inherit; }-a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }-.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }--/* ---------- cover ---------- */-#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;- padding: 48px 16px 64px; text-align: center; overflow: hidden; }-.open #cover, body:not(.open) #contents { display: none; }-#cover > * { animation: rise .8s var(--ease) backwards; }-#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }-#cover .kicker { animation-delay: .9s; }-#cover h1 { animation-delay: 1s; }-#cover .lede { animation-delay: 1.12s; }-#cover .acts { animation-delay: 1.24s; }-#cover .meta { animation-delay: 1.36s; }-h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }-h1 i { color: var(--task); font-style: italic; }-.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }-.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }-.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;- transition: transform .25s var(--ease), background-color .25s, border-color .25s; }-.btn[hidden] { display: none; }-.btn:hover { transform: translateY(-2px); }-.btn.go { background: var(--chalk); color: var(--board); }-.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }-.btn.quiet:hover { border-color: var(--dim); }-.btn svg { width: 15px; height: 15px; fill: currentColor; }-.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }-.inspiration { max-width: 48em; margin: 22px 0 0; color: var(--dim); font-size: 14px; line-height: 1.6; text-wrap: balance; }-.inspiration a { text-decoration-color: var(--faint); text-underline-offset: 3px; }-.inspiration a:hover { color: var(--chalk); text-decoration-color: currentColor; }-/* Faint chalk notes around the edges of the board. */-.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }-.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;- animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }-@keyframes chalk { to { opacity: .075; } }-@keyframes drift { to { translate: 0 -10px; } }-@keyframes rise { from { opacity: 0; transform: translateY(16px); } }--/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */-.mascot { display: block; overflow: visible; }-.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }-.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }-.mascot .joy { display: none; }-#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }-#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }-.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }-.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }-@keyframes draw { from { stroke-dashoffset: 1; } }-@keyframes pop { from { opacity: 0; transform: scale(.6); } }-.draw .face { transform-box: view-box; transform-origin: 60px 44px; }-@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }-@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }--/* ---------- contents ---------- */-.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));- background: rgba(22, 33, 29, .86); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid #2a3b35; }-.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }-.home .mascot { view-transition-name: guide; }-.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }-.home strong i { color: var(--task); }-.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }-.prog b { color: var(--good); font-weight: 600; }-main#contents { padding-bottom: 80px; }-.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }-.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;- padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);- text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }-.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px rgba(0, 0, 0, .3); }-.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }-.ch span { font-size: 18px; line-height: 1.3; }-.ch small { color: var(--dim); font-size: 14px; }-.ch.done small::before { content: "✓ Finished · "; color: var(--good); font-weight: 600; }-.ch.last small::after { content: " · Last opened"; color: var(--quiz); }-.ch.here:focus-visible { outline-color: var(--c); }-.ch.here { animation: here 1.8s ease-out .3s; }-@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }-.stagger .top { animation: rise .6s var(--ease) backwards; }-.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }--.back-shelf { color: var(--dim); font: 13px var(--ui); text-decoration: none; white-space: nowrap; }-.back-shelf:hover { color: var(--chalk); }-.cover-back { position: absolute; top: 24px; left: 24px; }-.contents-back { margin-left: 16px; }--/* ---------- page-to-page motion ---------- */-@view-transition { navigation: auto; }-/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the- contents still rise in. -moz-orient exists only in Firefox. */-@supports (-moz-orient: inline) { @view-transition { navigation: none; } }-::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }-::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }-::view-transition-old(lesson) { animation-duration: .18s; }-@media (max-width: 560px) {- .home strong { font-size: 18px; }- .contents-back { margin-left: 0; font-size: 11px; }- #contents .top { flex-wrap: wrap; gap: 8px 12px; }- .ch { min-height: 0; }- .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }-}-@media (prefers-reduced-motion: reduce) {- *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }- .chalk span { opacity: .075; }-}-</style></head><body><section id="cover">@@ -149,7 +27,7 @@ main#contents { padding-bottom: 80px; }<h1>Elementary <i>Mathematics</i></h1><p class="lede">Middle-school math you can watch and try: numbers sort themselves into families, slide along the number line, and wait for you to place the next one.</p><div class="acts">- <a class="btn go" href="#contents">Open the book<svg viewBox="0 0 16 16"><path d="M6 2.5 11.5 8 6 13.5 4.6 12.1 8.7 8 4.6 3.9z"/></svg></a>+ <a class="btn go" href="#contents" data-t="open">Open the book<svg viewBox="0 0 16 16"><path d="M6 2.5 11.5 8 6 13.5 4.6 12.1 8.7 8 4.6 3.9z"/></svg></a><a class="btn quiet" id="resume" hidden></a></div><p class="meta" id="meta"></p>@@ -159,7 +37,7 @@ main#contents { padding-bottom: 80px; }<main id="contents"><header class="top">- <a class="home" href="#book" aria-label="Back to the cover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>Elementary <i>Mathematics</i></strong></a>+ <a class="home" href="#book" aria-label="Back to the cover" data-t-label="toCover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>Elementary <i>Mathematics</i></strong></a><span class="prog" id="prog"></span><a class="back-shelf contents-back" href="../">← Bookshelf</a></header>@@ -167,105 +45,13 @@ main#contents { padding-bottom: 80px; }</main><script>-'use strict';-// Chapters are numbered in order through the units. Add a chapter here when its lesson is ready.-const UNITS = [ // [unit title, [[chapter title, minutes], ...]]; chapters are numbered in order. Add a chapter when its lesson is ready.- ['The Number System', [['Types of Numbers and the Number Line', 9], ['Positive and Negative Numbers', 8], ['Absolute Value', 9], ['Factors and Greatest Common Factor', 11], ['Multiples and Least Common Multiple', 10], ['Fraction Basics: Types of Fractions and Adding and Subtracting Fractions', 13], ['Multiplying and Dividing Fractions', 12], ['Adding and Subtracting Decimals', 11], ['Multiplying Decimals', 12], ['Dividing Decimals', 10], ['Adding Positive and Negative Numbers', 12], ['Subtracting Positive and Negative Numbers', 13], ['Multiplying and Dividing Positive and Negative Numbers', 14], ['Inequalities', 10]]],- ['Ratios, Proportions, and Percents', [['Ratios', 9], ['Unit Rate and Unit Price', 10], ['Proportions', 12], ['Converting Measurements', 13], ['Percent', 13], ['Percent Word Problems', 13], ['Taxes and Fees', 9], ['Discounts and Markups', 11], ['Gratuity and Commission', 7]]],-];-const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];-const id = n => 'ch' + String(n).padStart(2, '0');-let P = {};-const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('.', location.href).pathname;-try {- const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');- if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;-} catch {}-const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);--// Contents.-let n = 0, total = 0, i = 0; // i staggers the entrance, in reading order-const esc = s => s.replace(/&/g, '&').replace(/</g, '<');-document.getElementById('units').innerHTML = UNITS.map(([name, chs], u) => {- return `<section class="unit" style="--c:${HUES[u % HUES.length]};--i:${i++}">${Units.header(u, `Unit ${u + 1}`, name)}<div class="grid">` +- chs.map(([t, min]) => { n++;- const cls = 'ch' + (done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');- return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${min} min</small></a>`;- }).join('') + '</div></section>';-}).join('');-total = n;-// A unit's sketch draws itself the first time the unit scrolls into view.-Units.watch();-const finished = [...done].filter(k => k <= total).length;-document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapter${total === 1 ? '' : 's'}`;-const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;-document.getElementById('meta').textContent = `${plural(total, 'chapter')} · ${plural(UNITS.length, 'unit')} · with sound`;-const last = Number.isInteger(P.last) && document.getElementById(id(P.last));-if (last) {- const r = document.getElementById('resume');- r.hidden = false;- r.href = last.getAttribute('href');- r.textContent = `Continue · Chapter ${P.last}`;-}--// The guide, drawn the same way as in the lessons.-function lemniscate(cx, cy, a, k) {- let d = '';- for (let i = 0; i <= 96; i++) {- const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;- d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);- }- return d + 'Z';-}-for (const svg of document.querySelectorAll('svg.mascot')) {- svg.setAttribute('viewBox', '0 0 120 84');- svg.setAttribute('aria-hidden', 'true');- const ln = 'fill="none" stroke="#ece8dc" stroke-linecap="round" stroke-linejoin="round"';- svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` +- [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="#ece8dc"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') +- `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;-}--// The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.-// Lessons link back with #chNN, so the reader lands on the chapter they just left.-const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;-function show(animate) {- const open = location.hash.length > 1 && location.hash !== '#book';- const apply = () => {- document.body.classList.toggle('open', open);- document.body.classList.toggle('stagger', animate && open);- const here = open ? document.getElementById(location.hash.slice(1)) : null;- document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));- if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }- else scrollTo(0, 0);- if (animate) {- const heading = document.querySelector(open ? '#contents .home' : '#cover h1');- heading?.setAttribute('tabindex', '-1');- heading?.focus({ preventScroll: true });- }- };- if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {- const transition = document.startViewTransition(apply);- // Navigation can interrupt either promise; the new view is already applied.- transition.ready.catch(() => {});- transition.finished.catch(() => {});- } else apply();-}-addEventListener('hashchange', () => show(true));-show(false);--// Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.-let named = null;-const name = el => {- if (named) named.style.viewTransitionName = '';- named = el;- if (el) el.style.viewTransitionName = 'lesson';-};-document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });-addEventListener('pagereveal', e => {- const target = (location.hash.length > 1 && document.getElementById(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);- name(e.viewTransition && target ? target : null);- e.viewTransition?.finished.then(() => name(null), () => name(null));+// Add a chapter here when its lesson is ready; chapters are numbered in order from start.+Contents.book({+ units: [ // [unit title, [[chapter title, minutes], ...], { unit, chapter, sample }?]+ ['The Number System', [['Types of Numbers and the Number Line', 9], ['Positive and Negative Numbers', 8], ['Absolute Value', 9], ['Factors and Greatest Common Factor', 11], ['Multiples and Least Common Multiple', 10], ['Fraction Basics: Types of Fractions and Adding and Subtracting Fractions', 13], ['Multiplying and Dividing Fractions', 12], ['Adding and Subtracting Decimals', 11], ['Multiplying Decimals', 12], ['Dividing Decimals', 10], ['Adding Positive and Negative Numbers', 12], ['Subtracting Positive and Negative Numbers', 13], ['Multiplying and Dividing Positive and Negative Numbers', 14], ['Inequalities', 10]]],+ ['Ratios, Proportions, and Percents', [['Ratios', 9], ['Unit Rate and Unit Price', 10], ['Proportions', 12], ['Converting Measurements', 13], ['Percent', 13], ['Percent Word Problems', 13], ['Taxes and Fees', 9], ['Discounts and Markups', 11], ['Gratuity and Commission', 7]]],+ ],+ hues: ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'],});</script></body>diff --git a/site/math-notebook/lib/contents.css b/site/math-notebook/lib/contents.cssnew file mode 100644index 0000000..3f59f10--- /dev/null+++ b/site/math-notebook/lib/contents.css@@ -0,0 +1,115 @@+/* The book's cover and contents (index.html): the chalkboard look, the cover, the guide, the chapter grid and the+ page-to-page motion. A book's own <style> after this file sets its theme: the colour and font tokens below, and the+ few rules a theme redraws (e.g. body::before for the paper). */+:root {+ --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;+ --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;+ --book: "Iowan Old Style", Palatino, Georgia, serif;+ --ease: cubic-bezier(.2, .8, .2, 1);+ --top-bg: rgba(22, 33, 29, .86); --top-line: #2a3b35; /* the sticky contents header */+ --lift: rgba(0, 0, 0, .3); /* a card's shadow on hover */+ color-scheme: dark;+}+* { box-sizing: border-box; }+html { scroll-padding-top: 90px; }+body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }+/* Chalkboard: the same grain and vignette as the lesson stage. */+body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;+ background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }+a { color: inherit; }+a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }+.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }++/* ---------- cover ---------- */+#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;+ padding: 48px 16px 64px; text-align: center; overflow: hidden; }+.open #cover, body:not(.open) #contents { display: none; }+#cover > * { animation: rise .8s var(--ease) backwards; }+#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }+#cover .kicker { animation-delay: .9s; }+#cover h1 { animation-delay: 1s; }+#cover .lede { animation-delay: 1.12s; }+#cover .acts { animation-delay: 1.24s; }+#cover .meta { animation-delay: 1.36s; }+h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }+h1 i { color: var(--task); font-style: italic; }+.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }+.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }+.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;+ transition: transform .25s var(--ease), background-color .25s, border-color .25s; }+.btn[hidden] { display: none; }+.btn:hover { transform: translateY(-2px); }+.btn.go { background: var(--chalk); color: var(--board); }+.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }+.btn.quiet:hover { border-color: var(--dim); }+.btn svg { width: 15px; height: 15px; fill: currentColor; }+.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }+/* Faint chalk notes around the edges of the board. */+.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }+.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;+ animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }+@keyframes chalk { to { opacity: .075; } }+@keyframes drift { to { translate: 0 -10px; } }+@keyframes rise { from { opacity: 0; transform: translateY(16px); } }++/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */+.mascot { display: block; overflow: visible; }+.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }+.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }+.mascot .joy { display: none; }+#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }+#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }+.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }+.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }+@keyframes draw { from { stroke-dashoffset: 1; } }+@keyframes pop { from { opacity: 0; transform: scale(.6); } }+.draw .face { transform-box: view-box; transform-origin: 60px 44px; }+@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }+@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }++/* ---------- contents ---------- */+.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));+ background: var(--top-bg); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid var(--top-line); }+.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }+.home .mascot { view-transition-name: guide; }+.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }+.home strong i { color: var(--task); }+.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }+.prog b { color: var(--good); font-weight: 600; }+main#contents { padding-bottom: 80px; }+.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }+.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;+ padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);+ text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }+.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px var(--lift); }+.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }+.ch span { font-size: 18px; line-height: 1.3; }+.ch small { color: var(--dim); font-size: 14px; }+.ch.done small::before { content: var(--done, "✓ Finished · "); color: var(--good); font-weight: 600; }+.ch.last small::after { content: var(--last, " · Last opened"); color: var(--quiz); }+.ch.here:focus-visible { outline-color: var(--c); }+.ch.here { animation: here 1.8s ease-out .3s; }+@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }+.stagger .top { animation: rise .6s var(--ease) backwards; }+.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }++/* ---------- page-to-page motion ---------- */+@view-transition { navigation: auto; }+/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the+ contents still rise in. -moz-orient exists only in Firefox. */+@supports (-moz-orient: inline) { @view-transition { navigation: none; } }+::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }+::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }+::view-transition-old(lesson) { animation-duration: .18s; }+@media (max-width: 560px) {+ .home strong { font-size: 18px; }+ #contents .top { flex-wrap: wrap; gap: 8px 12px; }+ .ch { min-height: 0; }+ .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }+}+@media (prefers-reduced-motion: reduce) {+ *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }+ .chalk span { opacity: .075; }+}diff --git a/site/math-notebook/lib/contents.js b/site/math-notebook/lib/contents.jsnew file mode 100644index 0000000..fdc7de6--- /dev/null+++ b/site/math-notebook/lib/contents.js@@ -0,0 +1,169 @@+/* The book's cover and contents (index.html): interface text, the chapter list with reading progress, the guide,+ and the cover ↔ contents ↔ lesson motion. Load it in <head>; after the markup, the page calls+ Contents.book({ units, start, hues }) with its chapter list. */+'use strict';+// Observe aborted incoming transitions before the first rendering opportunity.+addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));++const Contents = (() => {+ // Interface text in the page's <html lang>, as in the lessons; missing keys fall back to English.+ // A value is a string or plural forms { one, few, many, other } chosen by vars.n.+ const TRANSLATIONS = {+ en: {+ open: 'Open the book', toCover: 'Back to the cover', resume: 'Continue · Chapter {n}', unit: 'Unit {n}', minutes: '{n} min',+ meta: '{chapters}{samples} · {units} · with sound', metaChapters: { one: '{n} chapter', other: '{n} chapters' },+ metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: ' + {n} sample',+ chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',+ doneMark: '✓ Finished · ', lastMark: ' · Last opened',+ },+ ru: {+ open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',+ meta: '{chapters}{samples} · {units} · со звуком',+ metaChapters: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' },+ metaUnits: { one: '{n} раздел', few: '{n} раздела', many: '{n} разделов', other: '{n} раздела' },+ metaSamples: { one: ' + {n} пробная', few: ' + {n} пробные', many: ' + {n} пробных', other: ' + {n} пробной' },+ chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',+ doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',+ },+ };+ const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];+ function translate(key, vars = {}) {+ const language = TRANSLATIONS[LANGUAGE]?.[key] !== undefined ? LANGUAGE : 'en';+ let text = TRANSLATIONS[language][key] ?? key;+ if (typeof text === 'object') {+ let rules;+ try { rules = new Intl.PluralRules(language); } catch { rules = new Intl.PluralRules('en'); }+ text = text[rules.select(vars.n)] ?? text.other;+ }+ return text.replace(/\{(\w+)\}/g, (placeholder, name) => name in vars ? vars[name] : placeholder);+ }+ const $ = id => document.getElementById(id);+ const id = n => 'ch' + String(n).padStart(2, '0');+ const esc = s => s.replace(/&/g, '&').replace(/</g, '<');+ const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];++ // Fixed interface text: data-t replaces an element's first text, data-t-label its aria-label.+ function translatePage() {+ for (const element of document.querySelectorAll('[data-t]')) element.firstChild.nodeValue = translate(element.dataset.t);+ for (const element of document.querySelectorAll('[data-t-label]')) element.setAttribute('aria-label', translate(element.dataset.tLabel));+ document.documentElement.style.setProperty('--done', JSON.stringify(translate('doneMark')));+ document.documentElement.style.setProperty('--last', JSON.stringify(translate('lastMark')));+ }++ // Reading progress { done: [chapter numbers], last }, written by the lessons. The engine and this page derive the+ // same key from the book's folder; a book that predates that passes its own key.+ function progress(key) {+ let P = {};+ try {+ const saved = JSON.parse(localStorage.getItem(key) || '{}');+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;+ } catch {}+ return { last: P.last, done: new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []) };+ }++ // The chapter cards, unit by unit, with progress, the header count, the cover's meta line and its resume button.+ // A unit's optional third entry { unit, chapter, sample } numbers it from elsewhere in the book; a sample chapter,+ // made to show another look, is not counted with the book's chapters.+ function contents(units, start, hues, P) {+ let n = start.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order+ const samples = new Set();+ $('units').innerHTML = units.map(([name, chs, o = {}], u) => {+ if (o.chapter) n = o.chapter - 1;+ return `<section class="unit" style="--c:${hues[u % hues.length]};--i:${i++}">${Units.header(u, translate('unit', { n: o.unit ?? u + start.unit }), name)}<div class="grid">` ++ chs.map(([t, min]) => { n++; if (o.sample) samples.add(n); else total++;+ const cls = 'ch' + (P.done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');+ return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${translate('minutes', { n: min })}</small></a>`;+ }).join('') + '</div></section>';+ }).join('');+ // A unit's sketch draws itself the first time the unit scrolls into view.+ Units.watch();+ const finished = [...P.done].filter(k => k >= start.chapter && k <= n && !samples.has(k)).length;+ $('prog').innerHTML = finished ? translate('finished', { done: `<b>${finished}</b>`, n: total }) : translate('chapterCount', { n: total });+ $('meta').textContent = translate('meta', {+ chapters: translate('metaChapters', { n: total }),+ samples: samples.size ? translate('metaSamples', { n: samples.size }) : '',+ units: translate('metaUnits', { n: units.filter(x => !x[2]?.sample).length }) });+ const last = Number.isInteger(P.last) && $(id(P.last));+ if (last) {+ const r = $('resume');+ r.hidden = false;+ r.href = last.getAttribute('href');+ r.textContent = translate('resume', { n: P.last });+ }+ }++ // The guide, drawn the same way as in the lessons, in the page's chalk (ink) colour.+ function lemniscate(cx, cy, a, k) {+ let d = '';+ for (let i = 0; i <= 96; i++) {+ const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;+ d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);+ }+ return d + 'Z';+ }+ function guides(ink) {+ for (const svg of document.querySelectorAll('svg.mascot')) {+ svg.setAttribute('viewBox', '0 0 120 84');+ svg.setAttribute('aria-hidden', 'true');+ const ln = `fill="none" stroke="${ink}" stroke-linecap="round" stroke-linejoin="round"`;+ svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` ++ [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="${ink}"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') ++ `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;+ }+ }++ // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.+ // Lessons link back with #chNN, so the reader lands on the chapter they just left.+ function views() {+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;+ function show(animate) {+ const open = location.hash.length > 1 && location.hash !== '#book';+ const apply = () => {+ document.body.classList.toggle('open', open);+ document.body.classList.toggle('stagger', animate && open);+ const here = open ? $(location.hash.slice(1)) : null;+ document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));+ if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }+ else scrollTo(0, 0);+ if (animate) {+ const heading = document.querySelector(open ? '#contents .home' : '#cover h1');+ heading?.setAttribute('tabindex', '-1');+ heading?.focus({ preventScroll: true });+ }+ };+ if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {+ const transition = document.startViewTransition(apply);+ // Navigation can interrupt either promise; the new view is already applied.+ transition.ready.catch(() => {});+ transition.finished.catch(() => {});+ } else apply();+ }+ addEventListener('hashchange', () => show(true));+ show(false);++ // Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.+ let named = null;+ const name = el => {+ if (named) named.style.viewTransitionName = '';+ named = el;+ if (el) el.style.viewTransitionName = 'lesson';+ };+ document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });+ addEventListener('pagereveal', e => {+ const target = (location.hash.length > 1 && $(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);+ name(e.viewTransition && target ? target : null);+ e.viewTransition?.finished.then(() => name(null), () => name(null));+ });+ }++ // units: [[unit title, [[chapter title, minutes], ...], { unit, chapter, sample }?], ...]. Chapters are numbered in+ // order from start (a book whose scope starts mid-way keeps the original numbers). hues: one colour per unit, cycling.+ function book({ units, start = { unit: 1, chapter: 1 }, hues = HUES, progressKey, ink } = {}) {+ translatePage();+ contents(units, start, hues, progress(progressKey ?? 'animebook:progress:' + new URL('.', location.href).pathname));+ guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');+ views();+ }++ return { book, translate };+})();diff --git a/site/math-notebook/lib/engine.css b/site/math-notebook/lib/engine.cssindex 0c532ab..9b9be00 100644--- a/site/math-notebook/lib/engine.css+++ b/site/math-notebook/lib/engine.css@@ -93,7 +93,7 @@ button[hidden] { display: none; }.hit:hover .ring, .hit:focus .ring { stroke-opacity: .7; }.hit.bad .ring { stroke: var(--bad); stroke-opacity: 1; }.hit.good .ring { stroke: var(--good); stroke-opacity: 1; stroke-width: 4; }-.tok { cursor: grab; }+.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page *//* Controls strip, part of the frame. */#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }diff --git a/site/math-notebook/lib/engine.js b/site/math-notebook/lib/engine.jsindex 2f6ba36..331ec10 100644--- a/site/math-notebook/lib/engine.js+++ b/site/math-notebook/lib/engine.js@@ -1323,32 +1323,28 @@ const choice = (opts, right, yes, no, onRight) => (body, api) => {key(e) { const b = bs[+e.key - 1]; if (!b || b.disabled) return false; b.click(); return true; },};};-// Tap a point on the stage number line.-const tap = (values, right, yes, no, onRight) => (body, api) => {- const L = qlayer(), hits = {};- let locked = false;- for (const v of values) {- const g = G(L, { x: X(v), y: Y0 });+// The shared body of the stage tap questions: each target ring is a focusable button that answers on click or Enter,+// and ← / → move the focus between them. targets: [{ g, label, ok, wrong }], wrong() shakes and returns the explanation.+const stageTap = (api, targets, show, yes, onRight, hint) => {+ let locked = false, cur = -1;+ const gs = targets.map(({ g, label, ok, wrong }) => {g.classList.add('hit');g.setAttribute('tabindex', 0);g.setAttribute('role', 'button');- g.setAttribute('aria-label', translate('pointLabel', { v: num(v) }));- mk('circle', { r: 30, class: 'ring' }, g);+ g.setAttribute('aria-label', label);const act = () => {if (locked) return;- if (v === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(S.dots[v]); api.grade(false, no(v)); }+ if (ok) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }+ else { g.classList.add('bad'); api.grade(false, wrong()); }};g.addEventListener('click', act);keyAct(g, act);- hits[v] = g;- }- const gs = values.map(v => hits[v]);- let cur = -1;+ return g;+ });return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },+ reveal() { gs[show].classList.add('good'); onRight?.(); return yes; },lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')],+ hint,key(e) {const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;if (!d || locked) return false;@@ -1358,71 +1354,38 @@ const tap = (values, right, yes, no, onRight) => (body, api) => {},};};+// Tap a point on the stage number line.+const tap = (values, right, yes, no, onRight) => (body, api) => {+ const L = qlayer();+ const targets = values.map(v => {+ const g = G(L, { x: X(v), y: Y0 });+ mk('circle', { r: 30, class: 'ring' }, g);+ return { g, label: translate('pointLabel', { v: num(v) }), ok: v === right, wrong: () => { shakeFx(S.dots[v]); return no(v); } };+ });+ return stageTap(api, targets, values.lastIndexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')]);+};// Tap one token of a stage token row, e.g. the operation to do first. idx: tappable token indexes.const tapEls = (row, idx, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = idx.map(i => {+ const targets = idx.map(i => {const e = row[i], w = e._w + 18, g = G(L, { x: e._px, y: row.y });- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', e.textContent.trim());mk('rect', { class: 'ring', x: -w / 2, y: -row.size * .95, width: w, height: row.size * 1.3, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(e); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: e.textContent.trim(), ok: i === right, wrong: () => { shakeFx(e); return no(i); } };});- return {- reveal() { hits[idx.indexOf(right)].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, idx.indexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')]);};// Click one of several stage objects (table cells, bars, small graphs). items: [{ el, box: [x, y, w, h], label }].const pickEls = (items, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = items.map((it, i) => {+ const targets = items.map((it, i) => {const [x, y, w, hh] = it.box, g = G(L);- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', it.label);mk('rect', { class: 'ring', x, y, width: w, height: hh, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(it.el); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: it.label, ok: i === right, wrong: () => { shakeFx(it.el); return no(i); } };});- return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, right, yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')]);};// Rows of toggles. items: { parts, ans: [keys], why }. parts are math parts (strings, F, R) unless text: true,// where they are rich text (strings and $m(...)). cols: [[key, label, colour?, shortcut?]]. multi: several per row.@@ -1647,6 +1610,13 @@ const sorter = (items, trayXY) => (body, api) => {drag = null;if (moved) place(c, st(c).x, st(c).y); else select(c);});+ // A cancelled drag (a system gesture, a lost capture) drops the chip where it is instead of leaving it stuck to no pointer.+ c.addEventListener('lostpointercapture', () => {+ if (!drag) return;+ const moved = drag.moved;+ drag = null;+ if (moved) place(c, st(c).x, st(c).y);+ });keyAct(c, () => { if (!locked) select(c); });return c;});@@ -1857,11 +1827,16 @@ function buildSegs() {return s.firstChild;});}+// ui() runs on every frame, paused or not: it writes only what changed, so an idle lesson does no layout work.+let stepText = '';+const setWidth = (f, w) => { if (f._w !== w) { f._w = w; f.style.width = w + '%'; } };function ui() {- segs.forEach((f, k) => { f.style.width = (k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)) + '%'; });- $('frame').classList.toggle('is-playing', P.playing && !P.done && !P.waiting);- $('frame').classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);- $('stepName').textContent = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ segs.forEach((f, k) => setWidth(f, k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)));+ const fr = $('frame');+ fr.classList.toggle('is-playing', P.playing && !P.done && !P.waiting);+ fr.classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);+ const step = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ if (step !== stepText) { stepText = step; $('stepName').textContent = step; }const b = BEATS[P.i];let text = '';if (captions && P.started && !b.ask && !P.done) {diff --git a/site/physics-notebook/index.html b/site/physics-notebook/index.htmlindex 66f2997..7f029a7 100644--- a/site/physics-notebook/index.html+++ b/site/physics-notebook/index.html@@ -3,137 +3,32 @@<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">-<script>-// Observe aborted incoming transitions before the first rendering opportunity.-addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));-</script><title>Energy & Change</title><meta name="description" content="An animated notebook about energy: Blip, a little bundle of energy, changes form but never disappears."><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='14' fill='%231d2b27'/%3E%3Ctext x='32' y='45' text-anchor='middle' font-size='48' fill='%23f0b45a'%3E∞%3C/text%3E%3C/svg%3E"><link rel="stylesheet" href="lib/units.css">+<link rel="stylesheet" href="lib/contents.css">+<link rel="stylesheet" href="../lib/books.css"><script src="lib/units.js"></script>+<script src="lib/contents.js"></script><script src="unit-art.js"></script><link rel="expect" href="#ch13" blocking="render"><style>+/* The notebook look of the lessons (lib/book.css): ink on lined paper, hand fonts. */:root {- /* the notebook look of the lessons (lib/book.css): ink on lined paper, hand fonts */--page: #d9d3c4; --board: #fcfaf3; --panel: #fffdf8; --edge: #d4ccb8;--chalk: #26241f; --dim: #6c665a; --faint: #a39b8a; --task: #e5398a; --quiz: #2d8fd0; --good: #2f9a5c;--ui: "Patrick Hand", "Avenir Next", "Segoe UI", sans-serif;--book: "Luckiest Guy", "Patrick Hand", sans-serif;- --ease: cubic-bezier(.2, .8, .2, 1);+ --top-bg: rgba(252, 250, 243, .9); --top-line: #ddd5c3; --lift: rgba(60, 50, 30, .18);color-scheme: light;}@font-face { font-family: "Patrick Hand"; src: url(lib/fonts/PatrickHand-Regular.ttf) format("truetype"); font-display: swap; }@font-face { font-family: "Luckiest Guy"; src: url(lib/fonts/LuckiestGuy-Regular.ttf) format("truetype"); font-display: swap; }-* { box-sizing: border-box; }-html { scroll-padding-top: 90px; }-body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }/* Notebook paper: blue rules and a red margin, like the lesson stage. */-body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;- background: linear-gradient(90deg, transparent 56px, #f2a7b5 56px 58px, transparent 58px),+body::before { background: linear-gradient(90deg, transparent 56px, #f2a7b5 56px 58px, transparent 58px),repeating-linear-gradient(180deg, transparent 0 34px, #bfe0ef 34px 35px); }-a { color: inherit; }-a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }-.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }--/* ---------- cover ---------- */-#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;- padding: 48px 16px 64px; text-align: center; overflow: hidden; }-.open #cover, body:not(.open) #contents { display: none; }-#cover > * { animation: rise .8s var(--ease) backwards; }-#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }-#cover .kicker { animation-delay: .9s; }-#cover h1 { animation-delay: 1s; }-#cover .lede { animation-delay: 1.12s; }-#cover .acts { animation-delay: 1.24s; }-#cover .meta { animation-delay: 1.36s; }-h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }-h1 i { color: var(--task); font-style: normal; }-.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }-.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }-.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;- transition: transform .25s var(--ease), background-color .25s, border-color .25s; }-.btn[hidden] { display: none; }-.btn:hover { transform: translateY(-2px); }-.btn.go { background: var(--chalk); color: var(--board); }-.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }-.btn.quiet:hover { border-color: var(--dim); }-.btn svg { width: 15px; height: 15px; fill: currentColor; }-.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }-/* Faint chalk notes around the edges of the board. */-.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }-.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;- animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }-@keyframes chalk { to { opacity: .075; } }-@keyframes drift { to { translate: 0 -10px; } }-@keyframes rise { from { opacity: 0; transform: translateY(16px); } }--/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */-.mascot { display: block; overflow: visible; }-.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }-.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }-.mascot .joy { display: none; }-#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }-#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }-.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }-.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }-@keyframes draw { from { stroke-dashoffset: 1; } }-@keyframes pop { from { opacity: 0; transform: scale(.6); } }-.draw .face { transform-box: view-box; transform-origin: 60px 44px; }-@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }-@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }--/* ---------- contents ---------- */-.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));- background: rgba(252, 250, 243, .9); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid #ddd5c3; }-.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }-.home .mascot { view-transition-name: guide; }-.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }-.home strong i { color: var(--task); }-.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }-.prog b { color: var(--good); font-weight: 600; }-main#contents { padding-bottom: 80px; }-.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }-.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;- padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);- text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }-.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px rgba(60, 50, 30, .18); }-.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }-.ch span { font-size: 18px; line-height: 1.3; }-.ch small { color: var(--dim); font-size: 14px; }-.ch.done small::before { content: "✓ Finished · "; color: var(--good); font-weight: 600; }-.ch.last small::after { content: " · Last opened"; color: var(--quiz); }-.ch.here:focus-visible { outline-color: var(--c); }-.ch.here { animation: here 1.8s ease-out .3s; }-@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }-.stagger .top { animation: rise .6s var(--ease) backwards; }-.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }--/* Links back to the project bookshelf (not part of the Skill's template). */-.back-shelf { color: var(--dim); font: 13px var(--ui); text-decoration: none; white-space: nowrap; }-.back-shelf:hover { color: var(--chalk); }-.cover-back { position: absolute; top: 24px; left: 24px; }-.contents-back { margin-left: 16px; }--/* ---------- page-to-page motion ---------- */-@view-transition { navigation: auto; }-/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the- contents still rise in. -moz-orient exists only in Firefox. */-@supports (-moz-orient: inline) { @view-transition { navigation: none; } }-::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }-::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }-::view-transition-old(lesson) { animation-duration: .18s; }-@media (max-width: 560px) {- .home strong { font-size: 18px; }- #contents .top { flex-wrap: wrap; gap: 8px 12px; }- .ch { min-height: 0; }- .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }-}-@media (prefers-reduced-motion: reduce) {- *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }- .chalk span { opacity: .075; }-}+h1 i { font-style: normal; }</style></head><body>@@ -149,7 +44,7 @@ main#contents { padding-bottom: 80px; }<h1>Energy <i>&</i> Change</h1><p class="lede">Follow Blip, a little bundle of energy, from sunlight to salad to a sprint. Watch balls roll, pens drop and bumper cars collide, and see why energy never disappears.</p><div class="acts">- <a class="btn go" href="#contents">Open the book<svg viewBox="0 0 16 16"><path d="M6 2.5 11.5 8 6 13.5 4.6 12.1 8.7 8 4.6 3.9z"/></svg></a>+ <a class="btn go" href="#contents" data-t="open">Open the book<svg viewBox="0 0 16 16"><path d="M6 2.5 11.5 8 6 13.5 4.6 12.1 8.7 8 4.6 3.9z"/></svg></a><a class="btn quiet" id="resume" hidden></a></div><p class="meta" id="meta"></p>@@ -158,7 +53,7 @@ main#contents { padding-bottom: 80px; }<main id="contents"><header class="top">- <a class="home" href="#book" aria-label="Back to the cover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>Energy <i>&</i> Change</strong></a>+ <a class="home" href="#book" aria-label="Back to the cover" data-t-label="toCover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>Energy <i>&</i> Change</strong></a><span class="prog" id="prog"></span><a class="back-shelf contents-back" href="../">← Bookshelf</a></header>@@ -166,105 +61,13 @@ main#contents { padding-bottom: 80px; }</main><script>-'use strict';-// Units and chapters are numbered in order from START (a book whose scope starts mid-way keeps the original numbers).-// Add a chapter here when its lesson is ready.-const START = { unit: 4, chapter: 13 };-const UNITS = [ // [unit title, [[chapter title, minutes], ...]]- ['Energy', [['Forms of Energy', 9]]],-];-const HUES = ['#e5398a', '#2d8fd0', '#e89a00', '#2f9a5c', '#7b55c9']; // marker colours that read on paper-const id = n => 'ch' + String(n).padStart(2, '0');-let P = {};-const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('.', location.href).pathname;-try {- const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');- if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;-} catch {}-const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);--// Contents.-let n = START.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order-const esc = s => s.replace(/&/g, '&').replace(/</g, '<');-document.getElementById('units').innerHTML = UNITS.map(([name, chs], u) => {- return `<section class="unit" style="--c:${HUES[u % HUES.length]};--i:${i++}">${Units.header(u, `Unit ${u + START.unit}`, name)}<div class="grid">` +- chs.map(([t, min]) => { n++; total++;- const cls = 'ch' + (done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');- return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${min} min</small></a>`;- }).join('') + '</div></section>';-}).join('');-// A unit's sketch draws itself the first time the unit scrolls into view.-Units.watch();-const finished = [...done].filter(k => k >= START.chapter && k <= n).length;-document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapter${total === 1 ? '' : 's'}`;-const pl = (k, w) => `${k} ${w}${k === 1 ? '' : 's'}`;-document.getElementById('meta').textContent = `${pl(total, 'chapter')} · ${pl(UNITS.length, 'unit')} · with sound`;-const last = Number.isInteger(P.last) && document.getElementById(id(P.last));-if (last) {- const r = document.getElementById('resume');- r.hidden = false;- r.href = last.getAttribute('href');- r.textContent = `Continue · Chapter ${P.last}`;-}--// The guide, drawn the same way as in the lessons.-function lemniscate(cx, cy, a, k) {- let d = '';- for (let i = 0; i <= 96; i++) {- const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;- d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);- }- return d + 'Z';-}-for (const svg of document.querySelectorAll('svg.mascot')) {- svg.setAttribute('viewBox', '0 0 120 84');- svg.setAttribute('aria-hidden', 'true');- const ln = 'fill="none" stroke="#26241f" stroke-linecap="round" stroke-linejoin="round"';- svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` +- [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="#26241f"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') +- `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;-}--// The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.-// Lessons link back with #chNN, so the reader lands on the chapter they just left.-const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;-function show(animate) {- const open = location.hash.length > 1 && location.hash !== '#book';- const apply = () => {- document.body.classList.toggle('open', open);- document.body.classList.toggle('stagger', animate && open);- const here = open ? document.getElementById(location.hash.slice(1)) : null;- document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));- if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }- else scrollTo(0, 0);- if (animate) {- const heading = document.querySelector(open ? '#contents .home' : '#cover h1');- heading?.setAttribute('tabindex', '-1');- heading?.focus({ preventScroll: true });- }- };- if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {- const transition = document.startViewTransition(apply);- // Navigation can interrupt either promise; the new view is already applied.- transition.ready.catch(() => {});- transition.finished.catch(() => {});- } else apply();-}-addEventListener('hashchange', () => show(true));-show(false);--// Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.-let named = null;-const name = el => {- if (named) named.style.viewTransitionName = '';- named = el;- if (el) el.style.viewTransitionName = 'lesson';-};-document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });-addEventListener('pagereveal', e => {- const target = (location.hash.length > 1 && document.getElementById(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);- name(e.viewTransition && target ? target : null);- e.viewTransition?.finished.then(() => name(null), () => name(null));+// Add a chapter here when its lesson is ready; chapters are numbered in order from start.+Contents.book({+ start: { unit: 4, chapter: 13 },+ units: [ // [unit title, [[chapter title, minutes], ...], { unit, chapter, sample }?]+ ['Energy', [['Forms of Energy', 9]]],+ ],+ hues: ['#e5398a', '#2d8fd0', '#e89a00', '#2f9a5c', '#7b55c9'], // marker colours that read on paper});</script></body>diff --git a/site/physics-notebook/lib/contents.css b/site/physics-notebook/lib/contents.cssnew file mode 100644index 0000000..3f59f10--- /dev/null+++ b/site/physics-notebook/lib/contents.css@@ -0,0 +1,115 @@+/* The book's cover and contents (index.html): the chalkboard look, the cover, the guide, the chapter grid and the+ page-to-page motion. A book's own <style> after this file sets its theme: the colour and font tokens below, and the+ few rules a theme redraws (e.g. body::before for the paper). */+:root {+ --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;+ --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;+ --book: "Iowan Old Style", Palatino, Georgia, serif;+ --ease: cubic-bezier(.2, .8, .2, 1);+ --top-bg: rgba(22, 33, 29, .86); --top-line: #2a3b35; /* the sticky contents header */+ --lift: rgba(0, 0, 0, .3); /* a card's shadow on hover */+ color-scheme: dark;+}+* { box-sizing: border-box; }+html { scroll-padding-top: 90px; }+body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }+/* Chalkboard: the same grain and vignette as the lesson stage. */+body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;+ background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }+a { color: inherit; }+a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }+.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }++/* ---------- cover ---------- */+#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;+ padding: 48px 16px 64px; text-align: center; overflow: hidden; }+.open #cover, body:not(.open) #contents { display: none; }+#cover > * { animation: rise .8s var(--ease) backwards; }+#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }+#cover .kicker { animation-delay: .9s; }+#cover h1 { animation-delay: 1s; }+#cover .lede { animation-delay: 1.12s; }+#cover .acts { animation-delay: 1.24s; }+#cover .meta { animation-delay: 1.36s; }+h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }+h1 i { color: var(--task); font-style: italic; }+.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }+.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }+.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;+ transition: transform .25s var(--ease), background-color .25s, border-color .25s; }+.btn[hidden] { display: none; }+.btn:hover { transform: translateY(-2px); }+.btn.go { background: var(--chalk); color: var(--board); }+.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }+.btn.quiet:hover { border-color: var(--dim); }+.btn svg { width: 15px; height: 15px; fill: currentColor; }+.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }+/* Faint chalk notes around the edges of the board. */+.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }+.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;+ animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }+@keyframes chalk { to { opacity: .075; } }+@keyframes drift { to { translate: 0 -10px; } }+@keyframes rise { from { opacity: 0; transform: translateY(16px); } }++/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */+.mascot { display: block; overflow: visible; }+.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }+.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }+.mascot .joy { display: none; }+#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }+#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }+.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }+.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }+@keyframes draw { from { stroke-dashoffset: 1; } }+@keyframes pop { from { opacity: 0; transform: scale(.6); } }+.draw .face { transform-box: view-box; transform-origin: 60px 44px; }+@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }+@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }++/* ---------- contents ---------- */+.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));+ background: var(--top-bg); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid var(--top-line); }+.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }+.home .mascot { view-transition-name: guide; }+.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }+.home strong i { color: var(--task); }+.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }+.prog b { color: var(--good); font-weight: 600; }+main#contents { padding-bottom: 80px; }+.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }+.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;+ padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);+ text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }+.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px var(--lift); }+.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }+.ch span { font-size: 18px; line-height: 1.3; }+.ch small { color: var(--dim); font-size: 14px; }+.ch.done small::before { content: var(--done, "✓ Finished · "); color: var(--good); font-weight: 600; }+.ch.last small::after { content: var(--last, " · Last opened"); color: var(--quiz); }+.ch.here:focus-visible { outline-color: var(--c); }+.ch.here { animation: here 1.8s ease-out .3s; }+@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }+.stagger .top { animation: rise .6s var(--ease) backwards; }+.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }++/* ---------- page-to-page motion ---------- */+@view-transition { navigation: auto; }+/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the+ contents still rise in. -moz-orient exists only in Firefox. */+@supports (-moz-orient: inline) { @view-transition { navigation: none; } }+::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }+::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }+::view-transition-old(lesson) { animation-duration: .18s; }+@media (max-width: 560px) {+ .home strong { font-size: 18px; }+ #contents .top { flex-wrap: wrap; gap: 8px 12px; }+ .ch { min-height: 0; }+ .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }+}+@media (prefers-reduced-motion: reduce) {+ *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }+ .chalk span { opacity: .075; }+}diff --git a/site/physics-notebook/lib/contents.js b/site/physics-notebook/lib/contents.jsnew file mode 100644index 0000000..fdc7de6--- /dev/null+++ b/site/physics-notebook/lib/contents.js@@ -0,0 +1,169 @@+/* The book's cover and contents (index.html): interface text, the chapter list with reading progress, the guide,+ and the cover ↔ contents ↔ lesson motion. Load it in <head>; after the markup, the page calls+ Contents.book({ units, start, hues }) with its chapter list. */+'use strict';+// Observe aborted incoming transitions before the first rendering opportunity.+addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));++const Contents = (() => {+ // Interface text in the page's <html lang>, as in the lessons; missing keys fall back to English.+ // A value is a string or plural forms { one, few, many, other } chosen by vars.n.+ const TRANSLATIONS = {+ en: {+ open: 'Open the book', toCover: 'Back to the cover', resume: 'Continue · Chapter {n}', unit: 'Unit {n}', minutes: '{n} min',+ meta: '{chapters}{samples} · {units} · with sound', metaChapters: { one: '{n} chapter', other: '{n} chapters' },+ metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: ' + {n} sample',+ chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',+ doneMark: '✓ Finished · ', lastMark: ' · Last opened',+ },+ ru: {+ open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',+ meta: '{chapters}{samples} · {units} · со звуком',+ metaChapters: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' },+ metaUnits: { one: '{n} раздел', few: '{n} раздела', many: '{n} разделов', other: '{n} раздела' },+ metaSamples: { one: ' + {n} пробная', few: ' + {n} пробные', many: ' + {n} пробных', other: ' + {n} пробной' },+ chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',+ doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',+ },+ };+ const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];+ function translate(key, vars = {}) {+ const language = TRANSLATIONS[LANGUAGE]?.[key] !== undefined ? LANGUAGE : 'en';+ let text = TRANSLATIONS[language][key] ?? key;+ if (typeof text === 'object') {+ let rules;+ try { rules = new Intl.PluralRules(language); } catch { rules = new Intl.PluralRules('en'); }+ text = text[rules.select(vars.n)] ?? text.other;+ }+ return text.replace(/\{(\w+)\}/g, (placeholder, name) => name in vars ? vars[name] : placeholder);+ }+ const $ = id => document.getElementById(id);+ const id = n => 'ch' + String(n).padStart(2, '0');+ const esc = s => s.replace(/&/g, '&').replace(/</g, '<');+ const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];++ // Fixed interface text: data-t replaces an element's first text, data-t-label its aria-label.+ function translatePage() {+ for (const element of document.querySelectorAll('[data-t]')) element.firstChild.nodeValue = translate(element.dataset.t);+ for (const element of document.querySelectorAll('[data-t-label]')) element.setAttribute('aria-label', translate(element.dataset.tLabel));+ document.documentElement.style.setProperty('--done', JSON.stringify(translate('doneMark')));+ document.documentElement.style.setProperty('--last', JSON.stringify(translate('lastMark')));+ }++ // Reading progress { done: [chapter numbers], last }, written by the lessons. The engine and this page derive the+ // same key from the book's folder; a book that predates that passes its own key.+ function progress(key) {+ let P = {};+ try {+ const saved = JSON.parse(localStorage.getItem(key) || '{}');+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;+ } catch {}+ return { last: P.last, done: new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []) };+ }++ // The chapter cards, unit by unit, with progress, the header count, the cover's meta line and its resume button.+ // A unit's optional third entry { unit, chapter, sample } numbers it from elsewhere in the book; a sample chapter,+ // made to show another look, is not counted with the book's chapters.+ function contents(units, start, hues, P) {+ let n = start.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order+ const samples = new Set();+ $('units').innerHTML = units.map(([name, chs, o = {}], u) => {+ if (o.chapter) n = o.chapter - 1;+ return `<section class="unit" style="--c:${hues[u % hues.length]};--i:${i++}">${Units.header(u, translate('unit', { n: o.unit ?? u + start.unit }), name)}<div class="grid">` ++ chs.map(([t, min]) => { n++; if (o.sample) samples.add(n); else total++;+ const cls = 'ch' + (P.done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');+ return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${translate('minutes', { n: min })}</small></a>`;+ }).join('') + '</div></section>';+ }).join('');+ // A unit's sketch draws itself the first time the unit scrolls into view.+ Units.watch();+ const finished = [...P.done].filter(k => k >= start.chapter && k <= n && !samples.has(k)).length;+ $('prog').innerHTML = finished ? translate('finished', { done: `<b>${finished}</b>`, n: total }) : translate('chapterCount', { n: total });+ $('meta').textContent = translate('meta', {+ chapters: translate('metaChapters', { n: total }),+ samples: samples.size ? translate('metaSamples', { n: samples.size }) : '',+ units: translate('metaUnits', { n: units.filter(x => !x[2]?.sample).length }) });+ const last = Number.isInteger(P.last) && $(id(P.last));+ if (last) {+ const r = $('resume');+ r.hidden = false;+ r.href = last.getAttribute('href');+ r.textContent = translate('resume', { n: P.last });+ }+ }++ // The guide, drawn the same way as in the lessons, in the page's chalk (ink) colour.+ function lemniscate(cx, cy, a, k) {+ let d = '';+ for (let i = 0; i <= 96; i++) {+ const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;+ d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);+ }+ return d + 'Z';+ }+ function guides(ink) {+ for (const svg of document.querySelectorAll('svg.mascot')) {+ svg.setAttribute('viewBox', '0 0 120 84');+ svg.setAttribute('aria-hidden', 'true');+ const ln = `fill="none" stroke="${ink}" stroke-linecap="round" stroke-linejoin="round"`;+ svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` ++ [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="${ink}"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') ++ `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;+ }+ }++ // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.+ // Lessons link back with #chNN, so the reader lands on the chapter they just left.+ function views() {+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;+ function show(animate) {+ const open = location.hash.length > 1 && location.hash !== '#book';+ const apply = () => {+ document.body.classList.toggle('open', open);+ document.body.classList.toggle('stagger', animate && open);+ const here = open ? $(location.hash.slice(1)) : null;+ document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));+ if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }+ else scrollTo(0, 0);+ if (animate) {+ const heading = document.querySelector(open ? '#contents .home' : '#cover h1');+ heading?.setAttribute('tabindex', '-1');+ heading?.focus({ preventScroll: true });+ }+ };+ if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {+ const transition = document.startViewTransition(apply);+ // Navigation can interrupt either promise; the new view is already applied.+ transition.ready.catch(() => {});+ transition.finished.catch(() => {});+ } else apply();+ }+ addEventListener('hashchange', () => show(true));+ show(false);++ // Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.+ let named = null;+ const name = el => {+ if (named) named.style.viewTransitionName = '';+ named = el;+ if (el) el.style.viewTransitionName = 'lesson';+ };+ document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });+ addEventListener('pagereveal', e => {+ const target = (location.hash.length > 1 && $(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);+ name(e.viewTransition && target ? target : null);+ e.viewTransition?.finished.then(() => name(null), () => name(null));+ });+ }++ // units: [[unit title, [[chapter title, minutes], ...], { unit, chapter, sample }?], ...]. Chapters are numbered in+ // order from start (a book whose scope starts mid-way keeps the original numbers). hues: one colour per unit, cycling.+ function book({ units, start = { unit: 1, chapter: 1 }, hues = HUES, progressKey, ink } = {}) {+ translatePage();+ contents(units, start, hues, progress(progressKey ?? 'animebook:progress:' + new URL('.', location.href).pathname));+ guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');+ views();+ }++ return { book, translate };+})();diff --git a/site/physics-notebook/lib/engine.css b/site/physics-notebook/lib/engine.cssindex 0c532ab..9b9be00 100644--- a/site/physics-notebook/lib/engine.css+++ b/site/physics-notebook/lib/engine.css@@ -93,7 +93,7 @@ button[hidden] { display: none; }.hit:hover .ring, .hit:focus .ring { stroke-opacity: .7; }.hit.bad .ring { stroke: var(--bad); stroke-opacity: 1; }.hit.good .ring { stroke: var(--good); stroke-opacity: 1; stroke-width: 4; }-.tok { cursor: grab; }+.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page *//* Controls strip, part of the frame. */#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }diff --git a/site/physics-notebook/lib/engine.js b/site/physics-notebook/lib/engine.jsindex 2f6ba36..331ec10 100644--- a/site/physics-notebook/lib/engine.js+++ b/site/physics-notebook/lib/engine.js@@ -1323,32 +1323,28 @@ const choice = (opts, right, yes, no, onRight) => (body, api) => {key(e) { const b = bs[+e.key - 1]; if (!b || b.disabled) return false; b.click(); return true; },};};-// Tap a point on the stage number line.-const tap = (values, right, yes, no, onRight) => (body, api) => {- const L = qlayer(), hits = {};- let locked = false;- for (const v of values) {- const g = G(L, { x: X(v), y: Y0 });+// The shared body of the stage tap questions: each target ring is a focusable button that answers on click or Enter,+// and ← / → move the focus between them. targets: [{ g, label, ok, wrong }], wrong() shakes and returns the explanation.+const stageTap = (api, targets, show, yes, onRight, hint) => {+ let locked = false, cur = -1;+ const gs = targets.map(({ g, label, ok, wrong }) => {g.classList.add('hit');g.setAttribute('tabindex', 0);g.setAttribute('role', 'button');- g.setAttribute('aria-label', translate('pointLabel', { v: num(v) }));- mk('circle', { r: 30, class: 'ring' }, g);+ g.setAttribute('aria-label', label);const act = () => {if (locked) return;- if (v === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(S.dots[v]); api.grade(false, no(v)); }+ if (ok) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }+ else { g.classList.add('bad'); api.grade(false, wrong()); }};g.addEventListener('click', act);keyAct(g, act);- hits[v] = g;- }- const gs = values.map(v => hits[v]);- let cur = -1;+ return g;+ });return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },+ reveal() { gs[show].classList.add('good'); onRight?.(); return yes; },lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')],+ hint,key(e) {const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;if (!d || locked) return false;@@ -1358,71 +1354,38 @@ const tap = (values, right, yes, no, onRight) => (body, api) => {},};};+// Tap a point on the stage number line.+const tap = (values, right, yes, no, onRight) => (body, api) => {+ const L = qlayer();+ const targets = values.map(v => {+ const g = G(L, { x: X(v), y: Y0 });+ mk('circle', { r: 30, class: 'ring' }, g);+ return { g, label: translate('pointLabel', { v: num(v) }), ok: v === right, wrong: () => { shakeFx(S.dots[v]); return no(v); } };+ });+ return stageTap(api, targets, values.lastIndexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')]);+};// Tap one token of a stage token row, e.g. the operation to do first. idx: tappable token indexes.const tapEls = (row, idx, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = idx.map(i => {+ const targets = idx.map(i => {const e = row[i], w = e._w + 18, g = G(L, { x: e._px, y: row.y });- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', e.textContent.trim());mk('rect', { class: 'ring', x: -w / 2, y: -row.size * .95, width: w, height: row.size * 1.3, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(e); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: e.textContent.trim(), ok: i === right, wrong: () => { shakeFx(e); return no(i); } };});- return {- reveal() { hits[idx.indexOf(right)].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, idx.indexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')]);};// Click one of several stage objects (table cells, bars, small graphs). items: [{ el, box: [x, y, w, h], label }].const pickEls = (items, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = items.map((it, i) => {+ const targets = items.map((it, i) => {const [x, y, w, hh] = it.box, g = G(L);- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', it.label);mk('rect', { class: 'ring', x, y, width: w, height: hh, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(it.el); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: it.label, ok: i === right, wrong: () => { shakeFx(it.el); return no(i); } };});- return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, right, yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')]);};// Rows of toggles. items: { parts, ans: [keys], why }. parts are math parts (strings, F, R) unless text: true,// where they are rich text (strings and $m(...)). cols: [[key, label, colour?, shortcut?]]. multi: several per row.@@ -1647,6 +1610,13 @@ const sorter = (items, trayXY) => (body, api) => {drag = null;if (moved) place(c, st(c).x, st(c).y); else select(c);});+ // A cancelled drag (a system gesture, a lost capture) drops the chip where it is instead of leaving it stuck to no pointer.+ c.addEventListener('lostpointercapture', () => {+ if (!drag) return;+ const moved = drag.moved;+ drag = null;+ if (moved) place(c, st(c).x, st(c).y);+ });keyAct(c, () => { if (!locked) select(c); });return c;});@@ -1857,11 +1827,16 @@ function buildSegs() {return s.firstChild;});}+// ui() runs on every frame, paused or not: it writes only what changed, so an idle lesson does no layout work.+let stepText = '';+const setWidth = (f, w) => { if (f._w !== w) { f._w = w; f.style.width = w + '%'; } };function ui() {- segs.forEach((f, k) => { f.style.width = (k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)) + '%'; });- $('frame').classList.toggle('is-playing', P.playing && !P.done && !P.waiting);- $('frame').classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);- $('stepName').textContent = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ segs.forEach((f, k) => setWidth(f, k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)));+ const fr = $('frame');+ fr.classList.toggle('is-playing', P.playing && !P.done && !P.waiting);+ fr.classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);+ const step = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ if (step !== stepText) { stepText = step; $('stepName').textContent = step; }const b = BEATS[P.i];let text = '';if (captions && P.started && !b.ask && !P.done) {diff --git a/site/science/index.html b/site/science/index.htmlindex 59ff964..7829768 100644--- a/site/science/index.html+++ b/site/science/index.html@@ -3,135 +3,16 @@<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">-<script>-// Observe aborted incoming transitions before the first rendering opportunity.-addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));-</script><title>Ace Science · Physics</title>-<meta name="description" content="ONE SENTENCE ABOUT THE BOOK.">+<meta name="description" content="The physics chapters of a middle-school science notebook — motion, forces, gravity and machines — as narrated animations with quick checks."><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='14' fill='%231d2b27'/%3E%3Ctext x='32' y='45' text-anchor='middle' font-size='48' fill='%23f0b45a'%3E∞%3C/text%3E%3C/svg%3E"><link rel="stylesheet" href="lib/units.css">+<link rel="stylesheet" href="lib/contents.css">+<link rel="stylesheet" href="../lib/books.css"><script src="lib/units.js"></script>+<script src="lib/contents.js"></script><script src="unit-art.js"></script>-<link rel="expect" href="#ch01" blocking="render">-<style>-:root {- --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;- --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;- --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;- --book: "Iowan Old Style", Palatino, Georgia, serif;- --ease: cubic-bezier(.2, .8, .2, 1);- color-scheme: dark;-}-* { box-sizing: border-box; }-html { scroll-padding-top: 90px; }-body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }-/* Chalkboard: the same grain and vignette as the lesson stage. */-body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;- background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),- url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }-a { color: inherit; }-a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }-.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }--/* ---------- cover ---------- */-#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;- padding: 48px 16px 64px; text-align: center; overflow: hidden; }-.open #cover, body:not(.open) #contents { display: none; }-#cover > * { animation: rise .8s var(--ease) backwards; }-#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }-#cover .kicker { animation-delay: .9s; }-#cover h1 { animation-delay: 1s; }-#cover .lede { animation-delay: 1.12s; }-#cover .acts { animation-delay: 1.24s; }-#cover .meta { animation-delay: 1.36s; }-h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }-h1 i { color: var(--task); font-style: italic; }-.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }-.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }-.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;- transition: transform .25s var(--ease), background-color .25s, border-color .25s; }-.btn[hidden] { display: none; }-.btn:hover { transform: translateY(-2px); }-.btn.go { background: var(--chalk); color: var(--board); }-.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }-.btn.quiet:hover { border-color: var(--dim); }-.btn svg { width: 15px; height: 15px; fill: currentColor; }-.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }-/* Faint chalk notes around the edges of the board. */-.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }-.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;- animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }-@keyframes chalk { to { opacity: .075; } }-@keyframes drift { to { translate: 0 -10px; } }-@keyframes rise { from { opacity: 0; transform: translateY(16px); } }--/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */-.mascot { display: block; overflow: visible; }-.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }-.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }-.mascot .joy { display: none; }-#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }-#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }-.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }-.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }-@keyframes draw { from { stroke-dashoffset: 1; } }-@keyframes pop { from { opacity: 0; transform: scale(.6); } }-.draw .face { transform-box: view-box; transform-origin: 60px 44px; }-@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }-@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }--/* ---------- contents ---------- */-.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));- background: rgba(22, 33, 29, .86); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid #2a3b35; }-.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }-.home .mascot { view-transition-name: guide; }-.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }-.home strong i { color: var(--task); }-.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }-.prog b { color: var(--good); font-weight: 600; }-main#contents { padding-bottom: 80px; }-.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }-.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;- padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);- text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }-.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px rgba(0, 0, 0, .3); }-.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }-.ch span { font-size: 18px; line-height: 1.3; }-.ch small { color: var(--dim); font-size: 14px; }-.ch.done small::before { content: "✓ Finished · "; color: var(--good); font-weight: 600; }-.ch.last small::after { content: " · Last opened"; color: var(--quiz); }-.ch.here:focus-visible { outline-color: var(--c); }-.ch.here { animation: here 1.8s ease-out .3s; }-@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }-.stagger .top { animation: rise .6s var(--ease) backwards; }-.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }--.back-shelf { color: var(--dim); font: 13px var(--ui); text-decoration: none; white-space: nowrap; }-.back-shelf:hover { color: var(--chalk); }-.cover-back { position: absolute; top: 24px; left: 24px; }-.contents-back { margin-left: 16px; }--/* ---------- page-to-page motion ---------- */-@view-transition { navigation: auto; }-/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the- contents still rise in. -moz-orient exists only in Firefox. */-@supports (-moz-orient: inline) { @view-transition { navigation: none; } }-::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }-::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }-::view-transition-old(lesson) { animation-duration: .18s; }-@media (max-width: 560px) {- .home strong { font-size: 18px; }- .contents-back { margin-left: 0; font-size: 11px; }- #contents .top { flex-wrap: wrap; gap: 8px 12px; }- .ch { min-height: 0; }- .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }-}-@media (prefers-reduced-motion: reduce) {- *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }- .chalk span { opacity: .075; }-}-</style>+<link rel="expect" href="#ch09" blocking="render"></head><body><section id="cover">@@ -144,9 +25,9 @@ main#contents { padding-bottom: 80px; }<svg class="mascot draw" id="guide" width="210" height="147"></svg><p class="kicker">An animated science book · physics</p><h1>Motion <i>&</i> Forces</h1>- <p class="lede">The physics chapters of a middle-school science notebook, as short narrated animations with quick checks. Chapters 9 to 11 are ready.</p>+ <p class="lede">The physics chapters of a middle-school science notebook, as short narrated animations with quick checks. Chapters 9 to 12 are ready.</p><div class="acts">- <a class="btn go" href="#contents">Open the book<svg viewBox="0 0 16 16"><path d="M6 2.5 11.5 8 6 13.5 4.6 12.1 8.7 8 4.6 3.9z"/></svg></a>+ <a class="btn go" href="#contents" data-t="open">Open the book<svg viewBox="0 0 16 16"><path d="M6 2.5 11.5 8 6 13.5 4.6 12.1 8.7 8 4.6 3.9z"/></svg></a><a class="btn quiet" id="resume" hidden></a></div><p class="meta" id="meta"></p>@@ -155,7 +36,7 @@ main#contents { padding-bottom: 80px; }<main id="contents"><header class="top">- <a class="home" href="#book" aria-label="Back to the cover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>Motion <i>&</i> Forces</strong></a>+ <a class="home" href="#book" aria-label="Back to the cover" data-t-label="toCover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>Motion <i>&</i> Forces</strong></a><span class="prog" id="prog"></span><a class="back-shelf contents-back" href="../">← Bookshelf</a></header>@@ -163,110 +44,14 @@ main#contents { padding-bottom: 80px; }</main><script>-'use strict';-// Physics only: the book's chapters 9–17 (units 3–4) keep their original numbers. START gives the first unit and-// chapter numbers; chapters are numbered in order from there. Add a chapter here when its lesson is ready.-// A unit's optional third entry { unit, chapter, sample } numbers it from elsewhere in the book; a sample chapter, made-// to show another look, is not counted with the book's chapters.-const START = { unit: 3, chapter: 9 };-const UNITS = [ // [unit title, [[chapter title, minutes], ...]]- ['Motion, Forces, and Work', [['Motion', 18], ['Force and Newton’s Laws of Motion', 13], ['Gravity, Friction, and More Forces in Everyday Life', 15], ['Work and Machines', 14]]],- ['Outer Space: the Sun, Earth and Moon', [['The Sun-Earth-Moon System', 14]], { unit: 5, chapter: 19, sample: true }],-];-const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];-const id = n => 'ch' + String(n).padStart(2, '0');-let P = {};-const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('.', location.href).pathname;-try {- const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');- if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;-} catch {}-const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);--// Contents.-let n = START.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order-const esc = s => s.replace(/&/g, '&').replace(/</g, '<');-const samples = new Set();-document.getElementById('units').innerHTML = UNITS.map(([name, chs, o = {}], u) => {- if (o.chapter) n = o.chapter - 1;- return `<section class="unit" style="--c:${HUES[u % HUES.length]};--i:${i++}">${Units.header(u, `Unit ${o.unit ?? u + START.unit}`, name)}<div class="grid">` +- chs.map(([t, min]) => { n++; if (o.sample) samples.add(n); else total++;- const cls = 'ch' + (done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');- return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${min} min</small></a>`;- }).join('') + '</div></section>';-}).join('');-// A unit's sketch draws itself the first time the unit scrolls into view.-Units.watch();-const finished = [...done].filter(k => k >= START.chapter && k <= n && !samples.has(k)).length;-document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapter${total === 1 ? '' : 's'}`;-const pl = (k, w) => `${k} ${w}${k === 1 ? '' : 's'}`;-document.getElementById('meta').textContent = `${pl(total, 'chapter')}${samples.size ? ` + ${samples.size} sample` : ''} · ${pl(UNITS.filter(x => !x[2]?.sample).length, 'unit')} · with sound`;-const last = Number.isInteger(P.last) && document.getElementById(id(P.last));-if (last) {- const r = document.getElementById('resume');- r.hidden = false;- r.href = last.getAttribute('href');- r.textContent = `Continue · Chapter ${P.last}`;-}--// The guide, drawn the same way as in the lessons.-function lemniscate(cx, cy, a, k) {- let d = '';- for (let i = 0; i <= 96; i++) {- const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;- d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);- }- return d + 'Z';-}-for (const svg of document.querySelectorAll('svg.mascot')) {- svg.setAttribute('viewBox', '0 0 120 84');- svg.setAttribute('aria-hidden', 'true');- const ln = 'fill="none" stroke="#ece8dc" stroke-linecap="round" stroke-linejoin="round"';- svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` +- [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="#ece8dc"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') +- `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;-}--// The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.-// Lessons link back with #chNN, so the reader lands on the chapter they just left.-const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;-function show(animate) {- const open = location.hash.length > 1 && location.hash !== '#book';- const apply = () => {- document.body.classList.toggle('open', open);- document.body.classList.toggle('stagger', animate && open);- const here = open ? document.getElementById(location.hash.slice(1)) : null;- document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));- if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }- else scrollTo(0, 0);- if (animate) {- const heading = document.querySelector(open ? '#contents .home' : '#cover h1');- heading?.setAttribute('tabindex', '-1');- heading?.focus({ preventScroll: true });- }- };- if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {- const transition = document.startViewTransition(apply);- // Navigation can interrupt either promise; the new view is already applied.- transition.ready.catch(() => {});- transition.finished.catch(() => {});- } else apply();-}-addEventListener('hashchange', () => show(true));-show(false);--// Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.-let named = null;-const name = el => {- if (named) named.style.viewTransitionName = '';- named = el;- if (el) el.style.viewTransitionName = 'lesson';-};-document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });-addEventListener('pagereveal', e => {- const target = (location.hash.length > 1 && document.getElementById(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);- name(e.viewTransition && target ? target : null);- e.viewTransition?.finished.then(() => name(null), () => name(null));+// Add a chapter here when its lesson is ready; chapters are numbered in order from start.+Contents.book({+ start: { unit: 3, chapter: 9 },+ units: [ // [unit title, [[chapter title, minutes], ...], { unit, chapter, sample }?]+ ['Motion, Forces, and Work', [['Motion', 18], ['Force and Newton’s Laws of Motion', 13], ['Gravity, Friction, and More Forces in Everyday Life', 15], ['Work and Machines', 14]]],+ ['Outer Space: the Sun, Earth and Moon', [['The Sun-Earth-Moon System', 14]], { unit: 5, chapter: 19, sample: true }],+ ],+ hues: ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'],});</script></body>diff --git a/site/science/lib/contents.css b/site/science/lib/contents.cssnew file mode 100644index 0000000..3f59f10--- /dev/null+++ b/site/science/lib/contents.css@@ -0,0 +1,115 @@+/* The book's cover and contents (index.html): the chalkboard look, the cover, the guide, the chapter grid and the+ page-to-page motion. A book's own <style> after this file sets its theme: the colour and font tokens below, and the+ few rules a theme redraws (e.g. body::before for the paper). */+:root {+ --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;+ --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;+ --book: "Iowan Old Style", Palatino, Georgia, serif;+ --ease: cubic-bezier(.2, .8, .2, 1);+ --top-bg: rgba(22, 33, 29, .86); --top-line: #2a3b35; /* the sticky contents header */+ --lift: rgba(0, 0, 0, .3); /* a card's shadow on hover */+ color-scheme: dark;+}+* { box-sizing: border-box; }+html { scroll-padding-top: 90px; }+body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }+/* Chalkboard: the same grain and vignette as the lesson stage. */+body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;+ background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }+a { color: inherit; }+a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }+.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }++/* ---------- cover ---------- */+#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;+ padding: 48px 16px 64px; text-align: center; overflow: hidden; }+.open #cover, body:not(.open) #contents { display: none; }+#cover > * { animation: rise .8s var(--ease) backwards; }+#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }+#cover .kicker { animation-delay: .9s; }+#cover h1 { animation-delay: 1s; }+#cover .lede { animation-delay: 1.12s; }+#cover .acts { animation-delay: 1.24s; }+#cover .meta { animation-delay: 1.36s; }+h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }+h1 i { color: var(--task); font-style: italic; }+.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }+.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }+.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;+ transition: transform .25s var(--ease), background-color .25s, border-color .25s; }+.btn[hidden] { display: none; }+.btn:hover { transform: translateY(-2px); }+.btn.go { background: var(--chalk); color: var(--board); }+.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }+.btn.quiet:hover { border-color: var(--dim); }+.btn svg { width: 15px; height: 15px; fill: currentColor; }+.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }+/* Faint chalk notes around the edges of the board. */+.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }+.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;+ animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }+@keyframes chalk { to { opacity: .075; } }+@keyframes drift { to { translate: 0 -10px; } }+@keyframes rise { from { opacity: 0; transform: translateY(16px); } }++/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */+.mascot { display: block; overflow: visible; }+.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }+.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }+.mascot .joy { display: none; }+#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }+#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }+.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }+.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }+@keyframes draw { from { stroke-dashoffset: 1; } }+@keyframes pop { from { opacity: 0; transform: scale(.6); } }+.draw .face { transform-box: view-box; transform-origin: 60px 44px; }+@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }+@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }++/* ---------- contents ---------- */+.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));+ background: var(--top-bg); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid var(--top-line); }+.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }+.home .mascot { view-transition-name: guide; }+.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }+.home strong i { color: var(--task); }+.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }+.prog b { color: var(--good); font-weight: 600; }+main#contents { padding-bottom: 80px; }+.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }+.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;+ padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);+ text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }+.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px var(--lift); }+.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }+.ch span { font-size: 18px; line-height: 1.3; }+.ch small { color: var(--dim); font-size: 14px; }+.ch.done small::before { content: var(--done, "✓ Finished · "); color: var(--good); font-weight: 600; }+.ch.last small::after { content: var(--last, " · Last opened"); color: var(--quiz); }+.ch.here:focus-visible { outline-color: var(--c); }+.ch.here { animation: here 1.8s ease-out .3s; }+@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }+.stagger .top { animation: rise .6s var(--ease) backwards; }+.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }++/* ---------- page-to-page motion ---------- */+@view-transition { navigation: auto; }+/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the+ contents still rise in. -moz-orient exists only in Firefox. */+@supports (-moz-orient: inline) { @view-transition { navigation: none; } }+::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }+::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }+::view-transition-old(lesson) { animation-duration: .18s; }+@media (max-width: 560px) {+ .home strong { font-size: 18px; }+ #contents .top { flex-wrap: wrap; gap: 8px 12px; }+ .ch { min-height: 0; }+ .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }+}+@media (prefers-reduced-motion: reduce) {+ *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }+ .chalk span { opacity: .075; }+}diff --git a/site/science/lib/contents.js b/site/science/lib/contents.jsnew file mode 100644index 0000000..fdc7de6--- /dev/null+++ b/site/science/lib/contents.js@@ -0,0 +1,169 @@+/* The book's cover and contents (index.html): interface text, the chapter list with reading progress, the guide,+ and the cover ↔ contents ↔ lesson motion. Load it in <head>; after the markup, the page calls+ Contents.book({ units, start, hues }) with its chapter list. */+'use strict';+// Observe aborted incoming transitions before the first rendering opportunity.+addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));++const Contents = (() => {+ // Interface text in the page's <html lang>, as in the lessons; missing keys fall back to English.+ // A value is a string or plural forms { one, few, many, other } chosen by vars.n.+ const TRANSLATIONS = {+ en: {+ open: 'Open the book', toCover: 'Back to the cover', resume: 'Continue · Chapter {n}', unit: 'Unit {n}', minutes: '{n} min',+ meta: '{chapters}{samples} · {units} · with sound', metaChapters: { one: '{n} chapter', other: '{n} chapters' },+ metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: ' + {n} sample',+ chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',+ doneMark: '✓ Finished · ', lastMark: ' · Last opened',+ },+ ru: {+ open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',+ meta: '{chapters}{samples} · {units} · со звуком',+ metaChapters: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' },+ metaUnits: { one: '{n} раздел', few: '{n} раздела', many: '{n} разделов', other: '{n} раздела' },+ metaSamples: { one: ' + {n} пробная', few: ' + {n} пробные', many: ' + {n} пробных', other: ' + {n} пробной' },+ chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',+ doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',+ },+ };+ const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];+ function translate(key, vars = {}) {+ const language = TRANSLATIONS[LANGUAGE]?.[key] !== undefined ? LANGUAGE : 'en';+ let text = TRANSLATIONS[language][key] ?? key;+ if (typeof text === 'object') {+ let rules;+ try { rules = new Intl.PluralRules(language); } catch { rules = new Intl.PluralRules('en'); }+ text = text[rules.select(vars.n)] ?? text.other;+ }+ return text.replace(/\{(\w+)\}/g, (placeholder, name) => name in vars ? vars[name] : placeholder);+ }+ const $ = id => document.getElementById(id);+ const id = n => 'ch' + String(n).padStart(2, '0');+ const esc = s => s.replace(/&/g, '&').replace(/</g, '<');+ const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];++ // Fixed interface text: data-t replaces an element's first text, data-t-label its aria-label.+ function translatePage() {+ for (const element of document.querySelectorAll('[data-t]')) element.firstChild.nodeValue = translate(element.dataset.t);+ for (const element of document.querySelectorAll('[data-t-label]')) element.setAttribute('aria-label', translate(element.dataset.tLabel));+ document.documentElement.style.setProperty('--done', JSON.stringify(translate('doneMark')));+ document.documentElement.style.setProperty('--last', JSON.stringify(translate('lastMark')));+ }++ // Reading progress { done: [chapter numbers], last }, written by the lessons. The engine and this page derive the+ // same key from the book's folder; a book that predates that passes its own key.+ function progress(key) {+ let P = {};+ try {+ const saved = JSON.parse(localStorage.getItem(key) || '{}');+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;+ } catch {}+ return { last: P.last, done: new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []) };+ }++ // The chapter cards, unit by unit, with progress, the header count, the cover's meta line and its resume button.+ // A unit's optional third entry { unit, chapter, sample } numbers it from elsewhere in the book; a sample chapter,+ // made to show another look, is not counted with the book's chapters.+ function contents(units, start, hues, P) {+ let n = start.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order+ const samples = new Set();+ $('units').innerHTML = units.map(([name, chs, o = {}], u) => {+ if (o.chapter) n = o.chapter - 1;+ return `<section class="unit" style="--c:${hues[u % hues.length]};--i:${i++}">${Units.header(u, translate('unit', { n: o.unit ?? u + start.unit }), name)}<div class="grid">` ++ chs.map(([t, min]) => { n++; if (o.sample) samples.add(n); else total++;+ const cls = 'ch' + (P.done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');+ return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${translate('minutes', { n: min })}</small></a>`;+ }).join('') + '</div></section>';+ }).join('');+ // A unit's sketch draws itself the first time the unit scrolls into view.+ Units.watch();+ const finished = [...P.done].filter(k => k >= start.chapter && k <= n && !samples.has(k)).length;+ $('prog').innerHTML = finished ? translate('finished', { done: `<b>${finished}</b>`, n: total }) : translate('chapterCount', { n: total });+ $('meta').textContent = translate('meta', {+ chapters: translate('metaChapters', { n: total }),+ samples: samples.size ? translate('metaSamples', { n: samples.size }) : '',+ units: translate('metaUnits', { n: units.filter(x => !x[2]?.sample).length }) });+ const last = Number.isInteger(P.last) && $(id(P.last));+ if (last) {+ const r = $('resume');+ r.hidden = false;+ r.href = last.getAttribute('href');+ r.textContent = translate('resume', { n: P.last });+ }+ }++ // The guide, drawn the same way as in the lessons, in the page's chalk (ink) colour.+ function lemniscate(cx, cy, a, k) {+ let d = '';+ for (let i = 0; i <= 96; i++) {+ const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;+ d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);+ }+ return d + 'Z';+ }+ function guides(ink) {+ for (const svg of document.querySelectorAll('svg.mascot')) {+ svg.setAttribute('viewBox', '0 0 120 84');+ svg.setAttribute('aria-hidden', 'true');+ const ln = `fill="none" stroke="${ink}" stroke-linecap="round" stroke-linejoin="round"`;+ svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` ++ [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="${ink}"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') ++ `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;+ }+ }++ // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.+ // Lessons link back with #chNN, so the reader lands on the chapter they just left.+ function views() {+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;+ function show(animate) {+ const open = location.hash.length > 1 && location.hash !== '#book';+ const apply = () => {+ document.body.classList.toggle('open', open);+ document.body.classList.toggle('stagger', animate && open);+ const here = open ? $(location.hash.slice(1)) : null;+ document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));+ if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }+ else scrollTo(0, 0);+ if (animate) {+ const heading = document.querySelector(open ? '#contents .home' : '#cover h1');+ heading?.setAttribute('tabindex', '-1');+ heading?.focus({ preventScroll: true });+ }+ };+ if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {+ const transition = document.startViewTransition(apply);+ // Navigation can interrupt either promise; the new view is already applied.+ transition.ready.catch(() => {});+ transition.finished.catch(() => {});+ } else apply();+ }+ addEventListener('hashchange', () => show(true));+ show(false);++ // Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.+ let named = null;+ const name = el => {+ if (named) named.style.viewTransitionName = '';+ named = el;+ if (el) el.style.viewTransitionName = 'lesson';+ };+ document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });+ addEventListener('pagereveal', e => {+ const target = (location.hash.length > 1 && $(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);+ name(e.viewTransition && target ? target : null);+ e.viewTransition?.finished.then(() => name(null), () => name(null));+ });+ }++ // units: [[unit title, [[chapter title, minutes], ...], { unit, chapter, sample }?], ...]. Chapters are numbered in+ // order from start (a book whose scope starts mid-way keeps the original numbers). hues: one colour per unit, cycling.+ function book({ units, start = { unit: 1, chapter: 1 }, hues = HUES, progressKey, ink } = {}) {+ translatePage();+ contents(units, start, hues, progress(progressKey ?? 'animebook:progress:' + new URL('.', location.href).pathname));+ guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');+ views();+ }++ return { book, translate };+})();diff --git a/site/science/lib/engine.css b/site/science/lib/engine.cssindex 0c532ab..9b9be00 100644--- a/site/science/lib/engine.css+++ b/site/science/lib/engine.css@@ -93,7 +93,7 @@ button[hidden] { display: none; }.hit:hover .ring, .hit:focus .ring { stroke-opacity: .7; }.hit.bad .ring { stroke: var(--bad); stroke-opacity: 1; }.hit.good .ring { stroke: var(--good); stroke-opacity: 1; stroke-width: 4; }-.tok { cursor: grab; }+.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page *//* Controls strip, part of the frame. */#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }diff --git a/site/science/lib/engine.js b/site/science/lib/engine.jsindex 2f6ba36..331ec10 100644--- a/site/science/lib/engine.js+++ b/site/science/lib/engine.js@@ -1323,32 +1323,28 @@ const choice = (opts, right, yes, no, onRight) => (body, api) => {key(e) { const b = bs[+e.key - 1]; if (!b || b.disabled) return false; b.click(); return true; },};};-// Tap a point on the stage number line.-const tap = (values, right, yes, no, onRight) => (body, api) => {- const L = qlayer(), hits = {};- let locked = false;- for (const v of values) {- const g = G(L, { x: X(v), y: Y0 });+// The shared body of the stage tap questions: each target ring is a focusable button that answers on click or Enter,+// and ← / → move the focus between them. targets: [{ g, label, ok, wrong }], wrong() shakes and returns the explanation.+const stageTap = (api, targets, show, yes, onRight, hint) => {+ let locked = false, cur = -1;+ const gs = targets.map(({ g, label, ok, wrong }) => {g.classList.add('hit');g.setAttribute('tabindex', 0);g.setAttribute('role', 'button');- g.setAttribute('aria-label', translate('pointLabel', { v: num(v) }));- mk('circle', { r: 30, class: 'ring' }, g);+ g.setAttribute('aria-label', label);const act = () => {if (locked) return;- if (v === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(S.dots[v]); api.grade(false, no(v)); }+ if (ok) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }+ else { g.classList.add('bad'); api.grade(false, wrong()); }};g.addEventListener('click', act);keyAct(g, act);- hits[v] = g;- }- const gs = values.map(v => hits[v]);- let cur = -1;+ return g;+ });return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },+ reveal() { gs[show].classList.add('good'); onRight?.(); return yes; },lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')],+ hint,key(e) {const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;if (!d || locked) return false;@@ -1358,71 +1354,38 @@ const tap = (values, right, yes, no, onRight) => (body, api) => {},};};+// Tap a point on the stage number line.+const tap = (values, right, yes, no, onRight) => (body, api) => {+ const L = qlayer();+ const targets = values.map(v => {+ const g = G(L, { x: X(v), y: Y0 });+ mk('circle', { r: 30, class: 'ring' }, g);+ return { g, label: translate('pointLabel', { v: num(v) }), ok: v === right, wrong: () => { shakeFx(S.dots[v]); return no(v); } };+ });+ return stageTap(api, targets, values.lastIndexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')]);+};// Tap one token of a stage token row, e.g. the operation to do first. idx: tappable token indexes.const tapEls = (row, idx, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = idx.map(i => {+ const targets = idx.map(i => {const e = row[i], w = e._w + 18, g = G(L, { x: e._px, y: row.y });- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', e.textContent.trim());mk('rect', { class: 'ring', x: -w / 2, y: -row.size * .95, width: w, height: row.size * 1.3, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(e); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: e.textContent.trim(), ok: i === right, wrong: () => { shakeFx(e); return no(i); } };});- return {- reveal() { hits[idx.indexOf(right)].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, idx.indexOf(right), yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')]);};// Click one of several stage objects (table cells, bars, small graphs). items: [{ el, box: [x, y, w, h], label }].const pickEls = (items, right, yes, no, onRight) => (body, api) => {const L = qlayer();- let locked = false, cur = -1;- const hits = items.map((it, i) => {+ const targets = items.map((it, i) => {const [x, y, w, hh] = it.box, g = G(L);- g.classList.add('hit');- g.setAttribute('tabindex', 0);- g.setAttribute('role', 'button');- g.setAttribute('aria-label', it.label);mk('rect', { class: 'ring', x, y, width: w, height: hh, rx: 12 }, g);- const act = () => {- if (locked) return;- if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }- else { g.classList.add('bad'); shakeFx(it.el); api.grade(false, no(i)); }- };- g.addEventListener('click', act);- keyAct(g, act);- return g;+ return { g, label: it.label, ok: i === right, wrong: () => { shakeFx(it.el); return no(i); } };});- return {- reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },- lock() { locked = true; },- hint: [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')],- key(e) {- const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;- if (!d || locked) return false;- cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;- hits[cur].focus();- return true;- },- };+ return stageTap(api, targets, right, yes, onRight,+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')]);};// Rows of toggles. items: { parts, ans: [keys], why }. parts are math parts (strings, F, R) unless text: true,// where they are rich text (strings and $m(...)). cols: [[key, label, colour?, shortcut?]]. multi: several per row.@@ -1647,6 +1610,13 @@ const sorter = (items, trayXY) => (body, api) => {drag = null;if (moved) place(c, st(c).x, st(c).y); else select(c);});+ // A cancelled drag (a system gesture, a lost capture) drops the chip where it is instead of leaving it stuck to no pointer.+ c.addEventListener('lostpointercapture', () => {+ if (!drag) return;+ const moved = drag.moved;+ drag = null;+ if (moved) place(c, st(c).x, st(c).y);+ });keyAct(c, () => { if (!locked) select(c); });return c;});@@ -1857,11 +1827,16 @@ function buildSegs() {return s.firstChild;});}+// ui() runs on every frame, paused or not: it writes only what changed, so an idle lesson does no layout work.+let stepText = '';+const setWidth = (f, w) => { if (f._w !== w) { f._w = w; f.style.width = w + '%'; } };function ui() {- segs.forEach((f, k) => { f.style.width = (k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)) + '%'; });- $('frame').classList.toggle('is-playing', P.playing && !P.done && !P.waiting);- $('frame').classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);- $('stepName').textContent = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ segs.forEach((f, k) => setWidth(f, k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)));+ const fr = $('frame');+ fr.classList.toggle('is-playing', P.playing && !P.done && !P.waiting);+ fr.classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);+ const step = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;+ if (step !== stepText) { stepText = step; $('stepName').textContent = step; }const b = BEATS[P.i];let text = '';if (captions && P.started && !b.ask && !P.done) {