An AI skill that turns books into animated, narrated, interactive web experiences
JavaScript ai-agentsai-educationanimationclaudeclaude-codeclaude-skillsedtecheducationinteractive-textbookscormtext-to-video
feat(i18n): add Russian UI and narration support
Nikolai Ivakhnenko00b10bd3c4a3
diff --git a/.claude/skills/papermorph/SKILL.md b/.claude/skills/papermorph/SKILL.mdindex 2e4f163..95c95aa 100644--- a/.claude/skills/papermorph/SKILL.md+++ b/.claude/skills/papermorph/SKILL.md@@ -28,7 +28,7 @@ site/ static output; private sources stay outside<book>/chNN/audio/<lang>/ beat MP3s + timings.js```-`SKILL` means this skill's absolute folder; `<book>` is the book slug, `<lang>` its primary language code. Existing books keep their paths. Needs: `uv`, `ffmpeg`/`ffprobe`, Edge TTS network access and Playwright Chromium (`uv run --with playwright playwright install chromium`). Preview: `python3 -m http.server 8765 -d site`.+`SKILL` means this skill's absolute folder; `<book>` is the book slug, `<lang>` its primary language code, also set as each page's `<html lang>` for the interface text ([site.md](references/site.md#languages)). Existing books keep their paths. Needs: `uv`, `ffmpeg`/`ffprobe`, Edge TTS network access and Playwright Chromium (`uv run --with playwright playwright install chromium`). Preview: `python3 -m http.server 8765 -d site`.## Pipelinediff --git a/.claude/skills/papermorph/assets/engine/engine.js b/.claude/skills/papermorph/assets/engine/engine.jsindex c75969d..7082e13 100644--- a/.claude/skills/papermorph/assets/engine/engine.js+++ b/.claude/skills/papermorph/assets/engine/engine.js@@ -3,8 +3,106 @@'use strict';// A fast follow-up navigation can abort the incoming page transition.addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));++/* ---------- interface language ---------- */+// The page's <html lang> picks the interface text; CHAPTER.language picks the audio folder. Set both alike.+// A value is a string or plural forms { one, few, many, other } chosen by vars.n. Missing keys fall back to English.+const TRANSLATIONS = {+ en: {+ decimalSign: '.', stageLabel: 'Lesson animation', stageLabelTitled: 'Lesson animation: {title}',+ shortcuts: 'Keyboard shortcuts', lesson: 'Lesson', questions: 'Questions',+ helpPlay: 'Play or pause', helpStep: 'Previous or next step', helpStepInQuestion: 'Change step during a question', helpRestart: 'Start over',+ helpCaptions: 'Captions on or off', helpFullScreen: 'Full screen', helpList: 'Show this list',+ helpChoose: 'Choose an answer or a ring', helpTrueFalse: 'True or false', helpRows: 'Move between rows',+ helpNumberLine: 'Move along the number line, or pick a number to sort', helpEnter: 'Check, then continue',+ helpShowAnswer: 'Show the answer', helpLeaveBox: 'Leave an answer box', helpClose: 'Press {key} to close.',+ paused: 'Paused. Press space or click to continue.',+ soundFailed: 'Sound could not play. The lesson continues with the on-screen text.',+ startLesson: 'Start lesson', coverKeys: 'Press {space} to start, {help} for shortcuts.', spaceKey: 'Space',+ chapterNumber: 'Chapter {n}', aboutMinutes: 'About {n} minutes, with sound and quick checks.',+ allChapters: 'All chapters', playLabel: 'Play or pause (space)', backLabel: 'Previous step (left arrow)', restartLabel: 'Restart lesson',+ volumeLabel: 'Adjust volume', volumeTitle: 'Volume (0 = muted)', volumeSlider: 'Volume',+ helpLabel: 'Keyboard shortcuts (?)', captionsLabel: 'Captions (C)', fullScreenLabel: 'Full screen', goToStep: 'Go to step {n}: {title}',+ quickCheck: 'Quick check', countOf: '{k} of {n}', check: 'Check', showAnswer: 'Show answer', nextQuestion: 'Next question', continue: 'Continue',+ correct: 'Correct. ', notQuite: 'Not quite. ', answerPrefix: 'Answer: ', keysPrefix: 'Keys: ',+ hintMove: ' move, ', hintChoose: ' choose', hintChooseOrClickGrid: ' choose, or click the grid', hintMoveAlongLine: ' move along the line, ',+ hintChooseOrClick: ' choose, or click', hintRow: ' row, ', hintTypeFraction: 'type numbers like 3/4 or −2 1/4, ', hintTypeNumber: 'type the number, ',+ hintTypeDecimal: 'type the number, ', hintNextBox: ' next box, ', hintCheck: ' check, ', hintLeaveBox: ' leave the box',+ hintPickNumber: ' pick a number, ', hintPickRing: ' choose its ring',+ rowsRight: '{r} of {n} right. Fix the rows marked ✗ and check again.',+ choicesShown: 'the correct choices are now selected.', numbersShown: 'the correct numbers are filled in.',+ notPlacedYet: '{x} is not placed yet.',+ realRingIsEmpty: '{x}: every real number is rational or irrational, so that space has no numbers of its own.',+ ringsRight: '{r} of {n} in the right ring.', ringsShown: 'every number is now in its smallest ring.',+ chipPlaced: '{x}, placed in {ring}', chipNotPlaced: '{x}, not placed', pointLabel: 'The point {v}', answerBox: 'Answer',+ stepsLeftOfZero: '{n} steps left of 0',+ natural: 'Natural', whole: 'Whole', integers: 'Integers', rational: 'Rational', irrational: 'Irrational', real: 'Real', integerColumn: 'Integer',+ trueLabel: 'True', falseLabel: 'False',+ chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice',+ firstTryScore: '{name}: {r} of {t} right on the first try.', notAttempted: '{name}: not attempted.',+ watchAgain: 'Watch again', nextChapter: 'Next chapter',+ },+ ru: {+ decimalSign: ',', stageLabel: 'Анимация урока', stageLabelTitled: 'Анимация урока: {title}',+ shortcuts: 'Горячие клавиши', lesson: 'Урок', questions: 'Вопросы',+ helpPlay: 'Пуск или пауза', helpStep: 'Предыдущий или следующий шаг', helpStepInQuestion: 'Сменить шаг во время вопроса', helpRestart: 'Начать сначала',+ helpCaptions: 'Субтитры вкл. или выкл.', helpFullScreen: 'Полноэкранный режим', helpList: 'Показать этот список',+ helpChoose: 'Выбрать ответ или круг', helpTrueFalse: 'Верно или неверно', helpRows: 'Перейти между строками',+ helpNumberLine: 'Двигаться по числовой прямой или выбрать число для сортировки', helpEnter: 'Проверить, затем продолжить',+ helpShowAnswer: 'Показать ответ', helpLeaveBox: 'Выйти из поля ответа', helpClose: 'Нажмите {key}, чтобы закрыть.',+ paused: 'Пауза. Нажмите пробел или щёлкните, чтобы продолжить.',+ soundFailed: 'Звук не воспроизводится. Урок продолжится с текстом на экране.',+ startLesson: 'Начать урок', coverKeys: '{space} — начать, {help} — горячие клавиши.', spaceKey: 'Пробел',+ chapterNumber: 'Глава {n}',+ aboutMinutes: { one: 'Около {n} минуты, со звуком и проверками.', few: 'Около {n} минут, со звуком и проверками.',+ many: 'Около {n} минут, со звуком и проверками.', other: 'Около {n} минуты, со звуком и проверками.' },+ allChapters: 'Все главы', playLabel: 'Пуск или пауза (пробел)', backLabel: 'Предыдущий шаг (стрелка влево)', restartLabel: 'Начать урок заново',+ volumeLabel: 'Настроить громкость', volumeTitle: 'Громкость (0 — без звука)', volumeSlider: 'Громкость',+ helpLabel: 'Горячие клавиши (?)', captionsLabel: 'Субтитры (C)', fullScreenLabel: 'Полный экран', goToStep: 'Перейти к шагу {n}: {title}',+ quickCheck: 'Проверь себя', countOf: '{k} из {n}', check: 'Проверить', showAnswer: 'Показать ответ', nextQuestion: 'Следующий вопрос', continue: 'Продолжить',+ correct: 'Верно. ', notQuite: 'Не совсем. ', answerPrefix: 'Ответ: ', keysPrefix: 'Клавиши: ',+ hintMove: ' двигаться, ', hintChoose: ' выбрать', hintChooseOrClickGrid: ' выбрать или щёлкнуть по сетке', hintMoveAlongLine: ' двигаться по прямой, ',+ hintChooseOrClick: ' выбрать или щёлкнуть', hintRow: ' строка, ', hintTypeFraction: 'вводите числа вида 3/4 или −2 1/4, ', hintTypeNumber: 'введите число, ',+ hintTypeDecimal: 'вводите числа вида 0,75, ', hintNextBox: ' следующее поле, ', hintCheck: ' проверить, ', hintLeaveBox: ' выйти из поля',+ hintPickNumber: ' выбрать число, ', hintPickRing: ' выбрать его круг',+ rowsRight: 'Верно {r} из {n}. Исправьте строки с ✗ и проверьте снова.',+ choicesShown: 'правильные варианты отмечены.', numbersShown: 'правильные числа вписаны.',+ notPlacedYet: '{x}: ещё не размещено.',+ realRingIsEmpty: '{x}: каждое действительное число рационально или иррационально, поэтому своих чисел у этой области нет.',+ ringsRight: 'В нужном круге: {r} из {n}.', ringsShown: 'каждое число теперь в своём наименьшем круге.',+ chipPlaced: '{x}, в круге «{ring}»', chipNotPlaced: '{x}, не размещено', pointLabel: 'Точка {v}', answerBox: 'Ответ',+ stepsLeftOfZero: { one: '{n} шаг влево от 0', few: '{n} шага влево от 0', many: '{n} шагов влево от 0', other: '{n} шага влево от 0' },+ natural: 'Натуральные', whole: 'Целые неотрицательные', integers: 'Целые', rational: 'Рациональные', irrational: 'Иррациональные', real: 'Действительные', integerColumn: 'Целые',+ trueLabel: 'Верно', falseLabel: 'Неверно',+ chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе',+ firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',+ watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',+ },+};+const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];+const pluralRules = {};+// Interface text in LANGUAGE: translate('chapterNumber', { n: 3 }) → 'Chapter 3'. Chapters may use it too, e.g. for practice labels.+function translate(key, vars = {}) {+ const language = TRANSLATIONS[LANGUAGE]?.[key] !== undefined ? LANGUAGE : 'en';+ let text = TRANSLATIONS[language][key] ?? key;+ if (typeof text === 'object') {+ try {+ pluralRules[language] ??= new Intl.PluralRules(language);+ } catch {+ pluralRules[language] = new Intl.PluralRules('en');+ }+ text = text[pluralRules[language].select(vars.n)] ?? text.other;+ }+ return text.replace(/\{(\w+)\}/g, (placeholder, name) => name in vars ? vars[name] : placeholder);+}+const DECIMAL_SIGN = translate('decimalSign'); // shown by num() and accepted by answer boxes+const isLatinLetter = key => /^[a-z]$/i.test(key);+// A letter shortcut on any keyboard layout: the typed letter, or the same physical key when the layout types a non-Latin letter.+const isShortcut = (event, letter) => event.key.toLowerCase() === letter.toLowerCase()+ || (isLatinLetter(letter) && !isLatinLetter(event.key) && event.code === 'Key' + letter.toUpperCase());+document.body.insertAdjacentHTML('afterbegin', `<div id="frame">- <svg id="stage" viewBox="0 0 1600 900" role="img" aria-label="Lesson animation">+ <svg id="stage" viewBox="0 0 1600 900" role="img" aria-label="${translate('stageLabel')}"><defs><filter id="grain" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency=".85" numOctaves="2" seed="7" />@@ -21,69 +119,69 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame"><g id="scene"></g></svg><div id="ui"></div>- <div class="paused-mark"><div>Paused. Press space or click to continue.</div></div>+ <div class="paused-mark"><div>${translate('paused')}</div></div><div class="caption" id="caption" hidden></div>- <div class="help" id="help" hidden role="dialog" aria-label="Keyboard shortcuts">+ <div class="help" id="help" hidden role="dialog" aria-label="${translate('shortcuts')}"><div class="help-box">- <h2>Keyboard shortcuts</h2>+ <h2>${translate('shortcuts')}</h2><div class="help-cols">- <div><h3>Lesson</h3><dl>- <dt><kbd>Space</kbd></dt><dd>Play or pause</dd>- <dt><kbd>←</kbd><kbd>→</kbd></dt><dd>Previous or next step</dd>- <dt><kbd>Shift</kbd><kbd>←</kbd><kbd>→</kbd></dt><dd>Change step during a question</dd>- <dt><kbd>Home</kbd></dt><dd>Start over</dd>- <dt><kbd>C</kbd></dt><dd>Captions on or off</dd>- <dt><kbd>F</kbd></dt><dd>Full screen</dd>- <dt><kbd>?</kbd></dt><dd>Show this list</dd>+ <div><h3>${translate('lesson')}</h3><dl>+ <dt><kbd>${translate('spaceKey')}</kbd></dt><dd>${translate('helpPlay')}</dd>+ <dt><kbd>←</kbd><kbd>→</kbd></dt><dd>${translate('helpStep')}</dd>+ <dt><kbd>Shift</kbd><kbd>←</kbd><kbd>→</kbd></dt><dd>${translate('helpStepInQuestion')}</dd>+ <dt><kbd>Home</kbd></dt><dd>${translate('helpRestart')}</dd>+ <dt><kbd>C</kbd></dt><dd>${translate('helpCaptions')}</dd>+ <dt><kbd>F</kbd></dt><dd>${translate('helpFullScreen')}</dd>+ <dt><kbd>?</kbd></dt><dd>${translate('helpList')}</dd></dl></div>- <div><h3>Questions</h3><dl>- <dt><kbd>1</kbd>–<kbd>6</kbd></dt><dd>Choose an answer or a ring</dd>- <dt><kbd>T</kbd><kbd>F</kbd></dt><dd>True or false</dd>- <dt><kbd>↑</kbd><kbd>↓</kbd></dt><dd>Move between rows</dd>- <dt><kbd>←</kbd><kbd>→</kbd></dt><dd>Move along the number line, or pick a number to sort</dd>- <dt><kbd>Enter</kbd></dt><dd>Check, then continue</dd>- <dt><kbd>S</kbd></dt><dd>Show the answer</dd>- <dt><kbd>Esc</kbd></dt><dd>Leave an answer box</dd>+ <div><h3>${translate('questions')}</h3><dl>+ <dt><kbd>1</kbd>–<kbd>6</kbd></dt><dd>${translate('helpChoose')}</dd>+ <dt><kbd>T</kbd><kbd>F</kbd></dt><dd>${translate('helpTrueFalse')}</dd>+ <dt><kbd>↑</kbd><kbd>↓</kbd></dt><dd>${translate('helpRows')}</dd>+ <dt><kbd>←</kbd><kbd>→</kbd></dt><dd>${translate('helpNumberLine')}</dd>+ <dt><kbd>Enter</kbd></dt><dd>${translate('helpEnter')}</dd>+ <dt><kbd>S</kbd></dt><dd>${translate('helpShowAnswer')}</dd>+ <dt><kbd>Esc</kbd></dt><dd>${translate('helpLeaveBox')}</dd></dl></div></div>- <p class="help-close">Press <kbd>Esc</kbd> to close.</p>+ <p class="help-close">${translate('helpClose', { key: '<kbd>Esc</kbd>' })}</p></div></div>- <p class="sound-note" id="soundNote" hidden>Sound could not play. The lesson continues with the on-screen text.</p>+ <p class="sound-note" id="soundNote" hidden>${translate('soundFailed')}</p><button class="cover" id="cover"><div><p class="cover-k" id="coverK"></p><h1 class="cover-t" id="coverT"></h1>- <span class="go"><svg width="24" height="24" viewBox="0 0 18 18"><path d="M3 1.5v15l13-7.5z" fill="currentColor"/></svg>Start lesson</span>- <small><span id="coverMeta"></span> Press <kbd>Space</kbd> to start, <kbd>?</kbd> for shortcuts.</small>+ <span class="go"><svg width="24" height="24" viewBox="0 0 18 18"><path d="M3 1.5v15l13-7.5z" fill="currentColor"/></svg>${translate('startLesson')}</span>+ <small><span id="coverMeta"></span> ${translate('coverKeys', { space: `<kbd>${translate('spaceKey')}</kbd>`, help: '<kbd>?</kbd>' })}</small></div></button><div id="bar">- <a class="icon" id="bHome" href="../" aria-label="All chapters" title="All chapters">+ <a class="icon" id="bHome" href="../" aria-label="${translate('allChapters')}" title="${translate('allChapters')}"><svg viewBox="0 0 18 18"><path d="M2 2h6v6H2zM10 2h6v6h-6zM2 10h6v6H2zM10 10h6v6h-6z"/></svg></a>- <button class="icon" id="bPlay" aria-label="Play or pause (space)">+ <button class="icon" id="bPlay" aria-label="${translate('playLabel')}"><svg class="i-play" viewBox="0 0 18 18"><path d="M4 2v14l12-7z"/></svg><svg class="i-pause" viewBox="0 0 18 18"><path d="M3.5 2h4v14h-4zM10.5 2h4v14h-4z"/></svg></button>- <button class="icon" id="bBack" aria-label="Previous step (left arrow)">+ <button class="icon" id="bBack" aria-label="${translate('backLabel')}"><svg viewBox="0 0 18 18"><path d="M3 2h2.5v14H3zM16 2v14L6.5 9z"/></svg></button>- <button class="icon" id="bRestart" aria-label="Restart lesson">+ <button class="icon" id="bRestart" aria-label="${translate('restartLabel')}"><svg viewBox="0 0 18 18"><path d="M9 2.5a6.5 6.5 0 1 1-6.3 8.1l2-.5A4.5 4.5 0 1 0 9 4.5V7L4.5 3.5 9 0z"/></svg></button><div class="segs" id="segs"></div><div class="step" id="stepName"></div><div class="volume">- <button class="icon" id="bVolume" aria-label="Adjust volume" aria-controls="volume" title="Volume (0 = muted)">+ <button class="icon" id="bVolume" aria-label="${translate('volumeLabel')}" aria-controls="volume" title="${translate('volumeTitle')}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 9v6h4l5 4V5L7 9z" fill="currentColor"/><path d="M16 8a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg></button>- <input id="volume" type="range" min="0" max="1" step="0.05" value="1" aria-label="Volume">+ <input id="volume" type="range" min="0" max="1" step="0.05" value="1" aria-label="${translate('volumeSlider')}"></div>- <button class="icon txt" id="bHelp" aria-label="Keyboard shortcuts (?)" title="Keyboard shortcuts (?)">?</button>- <button class="icon cc" id="bCC" aria-pressed="false" aria-label="Captions (C)" title="Captions (C)">CC</button>- <button class="icon" id="bFull" aria-label="Full screen">+ <button class="icon txt" id="bHelp" aria-label="${translate('helpLabel')}" title="${translate('helpLabel')}">?</button>+ <button class="icon cc" id="bCC" aria-pressed="false" aria-label="${translate('captionsLabel')}" title="${translate('captionsLabel')}">CC</button>+ <button class="icon" id="bFull" aria-label="${translate('fullScreenLabel')}"><svg viewBox="0 0 18 18"><path d="M1 1h6v2H3v4H1zM11 1h6v6h-2V3h-4zM1 11h2v4h4v2H1zM15 11h2v6h-6v-2h4z"/></svg></button></div>@@ -95,7 +193,7 @@ const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8',chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';const MATH = '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';-const NAME = { nat: 'Natural', whole: 'Whole', int: 'Integers', rat: 'Rational', irr: 'Irrational', real: 'Real' };+const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };// Card positions inside the 1600×900 picture.const BAND = { x: 96, y: 686, w: 1408, cls: 'band' }; // below the number lineconst RIGHT = { x: 1258, y: 546, w: 330, cls: 'side', maxH: 346 }; // right of the number map@@ -694,7 +792,7 @@ const pickPoint = (P, ans, yes, no, onRight, test) => (body, api) => {return {reveal() { moveTo(...ans); P.dot(ans[0], ans[1], COL.good, 0, { run: fx, into: L }); onRight?.(); return typeof yes === 'function' ? yes(...ans) : yes; },lock() { locked = true; },- hint: [kbd('←'), kbd('↑'), kbd('↓'), kbd('→'), ' move, ', kbd('Enter'), ' choose, or click the grid'],+ hint: [kbd('←'), kbd('↑'), kbd('↓'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClickGrid')],key(e) {if (locked) return false;const d = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] }[e.key];@@ -841,7 +939,7 @@ const scene = document.getElementById('scene');const S = {};const AXIS = { o: 800, u: 120 }; // number line: x of 0, pixels per unit; a chapter may change itconst X = v => AXIS.o + AXIS.u * v, Y0 = 610;-const num = v => (v < 0 ? '−' : '') + Math.abs(v);+const num = v => (v < 0 ? '−' : '') + String(Math.abs(v)).replace('.', DECIMAL_SIGN);function reset() {scene.replaceChildren();for (const k in S) delete S[k];@@ -897,29 +995,29 @@ function hopsFx(n) {const a = X(1 - k), b = X(-k);fx(path(S.q, `M${a} ${Y0 - 12}Q${(a + b) / 2} ${Y0 - 84} ${b} ${Y0 - 12}`, { stroke: COL.int, 'stroke-width': 3 }, { d: 0 }), { d: 1 }, (k - 1) * .35, .35, lin);}- floatText(`${-n} steps left of 0`, X(n / 2), Y0 - 100, COL.int);+ floatText(translate('stepsLeftOfZero', { n: -n }), X(n / 2), Y0 - 100, COL.int);}/* ---------- shared answer columns ---------- */const FAMILIES = ['nat', 'whole', 'int', 'rat', 'irr', 'real'];-const FAM_COLS = FAMILIES.map(k => [k, k === 'int' ? 'Integer' : NAME[k], COL[k]]);-const TF = [['t', 'True', null, 'T'], ['f', 'False', null, 'F']];+const FAM_COLS = FAMILIES.map(k => [k, k === 'int' ? translate('integerColumn') : NAME[k], COL[k]]);+const TF = [['t', translate('trueLabel'), null, 'T'], ['f', translate('falseLabel'), null, 'F']];function finishCard() {const c = card(SCREEN, 'fin');const sum = pre => Object.entries(SCORE).filter(([k]) => k.startsWith(pre)).reduce((a, [, v]) => [a[0] + v.right, a[1] + v.total], [0, 0]);- const line = (name, [r, t]) => h('p', 'fb', t ? `${name}: ${r} of ${t} right on the first try.` : `${name}: not attempted.`);+ const line = (name, [r, t]) => h('p', 'fb', t ? translate('firstTryScore', { name, r, t }) : translate('notAttempted', { name }));progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });- const home = h('a', 'btn quiet', 'All chapters');+ const home = h('a', 'btn quiet', translate('allChapters'));home.href = $('bHome').href;- const again = h('button', 'btn' + (CHAPTER.next ? ' quiet' : ' go'), ['Watch again', kbd(CHAPTER.next ? 'R' : 'Enter')]);+ const again = h('button', 'btn' + (CHAPTER.next ? ' quiet' : ' go'), [translate('watchAgain'), kbd(CHAPTER.next ? 'R' : 'Enter')]);again.onclick = restart;- const next = CHAPTER.next && h('button', 'btn go', ['Next chapter', kbd('Enter')]);+ const next = CHAPTER.next && h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);if (next) next.onclick = () => { location.href = CHAPTER.next; };P.keys = e => e.key === 'Enter' ? ((next ? next.onclick() : restart()), true)- : (e.key === 'r' || e.key === 'R') ? (restart(), true) : false;+ : isShortcut(e, 'r') ? (restart(), true) : false;const guide = mascotEl(240);- c.append(h('div', 'finwrap', [guide, h('p', 'kicker', `Chapter ${CHAPTER.number} complete`), h('p', 'prompt', CHAPTER.title),- line('Quick checks', sum('c-')), line('Chapter practice', sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again])]));+ c.append(h('div', 'finwrap', [guide, h('p', 'kicker', translate('chapterComplete', { n: CHAPTER.number })), h('p', 'prompt', CHAPTER.title),+ line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again])]));setTimeout(() => mood(guide, 'happy'), 400);}@@ -978,15 +1076,15 @@ function mood(el, m) {if (m) el.classList.add(m);}// A sequence of questions in one card. Each question: { id, prompt, build(body, api) -> { check?, reveal, lock? } }.-function quiz(pos, qs, done, label = 'Quick check') {+function quiz(pos, qs, done, label = translate('quickCheck')) {const c = card(pos, 'quiz');let k = 0;const show = () => {const q = qs[k];let first = true, resolved = false;const fb = h('div', 'fb'), body = h('div', 'body'), acts = h('div', 'acts');- const bCheck = h('button', 'btn', ['Check', kbd('Enter')]), bShow = h('button', 'btn quiet', ['Show answer', kbd('S')]);- const bNext = h('button', 'btn go', [k < qs.length - 1 ? 'Next question' : 'Continue', kbd('Enter')]);+ const bCheck = h('button', 'btn', [translate('check'), kbd('Enter')]), bShow = h('button', 'btn quiet', [translate('showAnswer'), kbd('S')]);+ const bNext = h('button', 'btn go', [k < qs.length - 1 ? translate('nextQuestion') : translate('continue'), kbd('Enter')]);bShow.hidden = bNext.hidden = true;const guide = pos.cls === 'band' || pos.cls === 'side' ? mascotEl(pos.cls === 'band' ? 108 : 70) : null;const say = (cls, parts) => { fb.className = 'fb ' + cls; fb.replaceChildren(rich(parts, 24)); fb.style.animation = 'none'; void fb.offsetWidth; fb.style.animation = ''; };@@ -1001,7 +1099,7 @@ function quiz(pos, qs, done, label = 'Quick check') {grade(ok, msg, score) {if (resolved) return;if (first) { if (!Object.hasOwn(SCORE, q.id)) SCORE[q.id] = score || { right: +ok, total: 1 }; first = false; }- say(ok ? 'ok' : 'no', [ok ? 'Correct. ' : 'Not quite. ', ...[].concat(msg || [])]);+ say(ok ? 'ok' : 'no', [ok ? translate('correct') : translate('notQuite'), ...[].concat(msg || [])]);if (guide) {mood(guide, ok ? 'happy' : 'oops');if (!ok) setTimeout(() => { if (guide.classList.contains('oops')) mood(guide, null); }, 1600);@@ -1012,18 +1110,18 @@ function quiz(pos, qs, done, label = 'Quick check') {const ctl = q.build(body, api);if (ctl.check) { bCheck.onclick = () => ctl.check(); acts.append(bCheck); }acts.append(bShow, bNext);- bShow.onclick = () => { say('', ['Answer: ', ...[].concat(ctl.reveal())]); resolve(); };+ bShow.onclick = () => { say('', [translate('answerPrefix'), ...[].concat(ctl.reveal())]); resolve(); };bNext.onclick = () => { if (k < qs.length - 1) { k++; show(); } else done(); };P.keys = e => {if (e.key === 'Enter' && resolved) { bNext.click(); return true; }if (!resolved && ctl.key?.(e)) return true;if (e.key === 'Enter' && !resolved && ctl.check) { bCheck.click(); return true; }- if ((e.key === 's' || e.key === 'S') && !bShow.hidden) { bShow.click(); return true; }+ if (isShortcut(e, 's') && !bShow.hidden) { bShow.click(); return true; }return false;};- const kick = label + (qs.length > 1 ? ` ${k + 1} of ${qs.length}` : '');+ const kick = label + (qs.length > 1 ? ' ' + translate('countOf', { k: k + 1, n: qs.length }) : '');const head = h('div', 'head', [h('p', 'kicker', kick), h('p', 'prompt', [rich(q.prompt, pos.cls.startsWith('screen') ? 38 : 28)])]); // match the prompt's type size- if (ctl.hint) head.append(h('p', 'keys', ['Keys: ', ...ctl.hint]));+ if (ctl.hint) head.append(h('p', 'keys', [translate('keysPrefix'), ...ctl.hint]));c.replaceChildren(...(guide ? [guide] : []), head, fb, body, acts);};show();@@ -1065,7 +1163,7 @@ const tap = (values, right, yes, no, onRight) => (body, api) => {g.classList.add('hit');g.setAttribute('tabindex', 0);g.setAttribute('role', 'button');- g.setAttribute('aria-label', `The point ${num(v)}`);+ g.setAttribute('aria-label', translate('pointLabel', { v: num(v) }));mk('circle', { r: 30, class: 'ring' }, g);const act = () => {if (locked) return;@@ -1081,7 +1179,7 @@ const tap = (values, right, yes, no, onRight) => (body, api) => {return {reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },lock() { locked = true; },- hint: [kbd('←'), kbd('→'), ' move along the line, ', kbd('Enter'), ' choose'],+ hint: [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')],key(e) {const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;if (!d || locked) return false;@@ -1114,7 +1212,7 @@ const tapEls = (row, idx, right, yes, no, onRight) => (body, api) => {return {reveal() { hits[idx.indexOf(right)].classList.add('good'); onRight?.(); return yes; },lock() { locked = true; },- hint: [kbd('←'), kbd('→'), ' move, ', kbd('Enter'), ' choose'],+ 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;@@ -1147,7 +1245,7 @@ const pickEls = (items, right, yes, no, onRight) => (body, api) => {return {reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },lock() { locked = true; },- hint: [kbd('←'), kbd('→'), ' move, ', kbd('Enter'), ' choose, or click'],+ 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;@@ -1199,7 +1297,7 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =check() {const right = rows.filter(judge).length;const all = right === rows.length;- api.grade(all, single ? rows[0].it.why : all ? [] : [`${right} of ${rows.length} right. Fix the rows marked ✗ and check again.`], { right, total: rows.length });+ api.grade(all, single ? rows[0].it.why : all ? [] : [translate('rowsRight', { r: right, n: rows.length })], { right, total: rows.length });},reveal() {for (const r of rows) {@@ -1207,10 +1305,10 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =judge(r);if (!single) r.why.replaceChildren(rich(r.it.why, 20));}- return single ? rows[0].it.why : 'the correct choices are now selected.';+ return single ? rows[0].it.why : translate('choicesShown');},lock() { locked = true; showCur(); rows.forEach(r => r.bs.forEach(b => { b.disabled = true; })); },- hint: [...(single ? [] : [kbd('↑'), kbd('↓'), ' row, ']), ...(/\d/.test(hot[0]) ? [kbd(hot[0]), '–', kbd(hot[hot.length - 1])] : hot.map(kbd)), ' choose'],+ hint: [...(single ? [] : [kbd('↑'), kbd('↓'), translate('hintRow')]), ...(/\d/.test(hot[0]) ? [kbd(hot[0]), '–', kbd(hot[hot.length - 1])] : hot.map(kbd)), translate('hintChoose')],key(e) {if (locked) return false;if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && !single) {@@ -1218,7 +1316,7 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =showCur();return true;}- const j = hot.findIndex(x => x.toLowerCase() === e.key.toLowerCase());+ const j = hot.findIndex(x => isShortcut(e, x));if (j < 0) return false;rows[cur].bs[j].click();if (!multi && cur < rows.length - 1) { cur++; showCur(); }@@ -1227,9 +1325,10 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =};};// Exact value of a typed answer: integer, decimal, fraction a/b or mixed number "w a/b"; returns [num, den] or null.-// Accepts −, – or - as the sign. Never evaluates the text as code.+// Accepts −, – or - as the sign, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.function rat(str) {- const t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');+ if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a commalet m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }m = t.match(/^(-?)(?:(\d+) )?(\d+) ?\/ ?(\d+)$/);@@ -1254,7 +1353,7 @@ const blanks = rowsIn => (body, api) => {flush();const b = h('input', 'box');Object.assign(b, { type: 'text', inputMode: 'decimal', autocomplete: 'off', spellcheck: false });- b.setAttribute('aria-label', 'Answer');+ b.setAttribute('aria-label', translate('answerBox'));b.dataset.ans = p.box;if (p.lowest) b.dataset.lowest = '1';b.style.width = `${Math.max(2, String(p.box).length) + 2}ch`;@@ -1294,7 +1393,7 @@ const blanks = rowsIn => (body, api) => {check() {const right = rows.filter(judge).length, done = right === rows.length;const msg = single ? (done ? rows[0].it.why : rows[0].it.hint ?? rows[0].it.why)- : done ? [] : [`${right} of ${rows.length} right. Fix the rows marked ✗ and check again.`];+ : done ? [] : [translate('rowsRight', { r: right, n: rows.length })];api.grade(done, msg, { right, total: rows.length });},reveal() {@@ -1303,10 +1402,11 @@ const blanks = rowsIn => (body, api) => {judge(r);if (!single) r.why.replaceChildren(rich(r.it.why, 20));}- return single ? rows[0].it.why : 'the correct numbers are filled in.';+ return single ? rows[0].it.why : translate('numbersShown');},lock() { all.forEach(b => { b.disabled = true; }); },- hint: [all.some(b => b.dataset.ans.includes('/')) ? 'type numbers like 3/4 or −2 1/4, ' : 'type the number, ', kbd('Tab'), ' next box, ', kbd('Enter'), ' check, ', kbd('Esc'), ' leave the box'],+ hint: [translate(all.some(b => b.dataset.ans.includes('/')) ? 'hintTypeFraction' : all.some(b => /[.,]/.test(b.dataset.ans)) ? 'hintTypeDecimal' : 'hintTypeNumber'),+ kbd('Tab'), translate('hintNextBox'), kbd('Enter'), translate('hintCheck'), kbd('Esc'), translate('hintLeaveBox')],};};// Drag number chips into the stage number map. items: [parts, smallest ring, explanation].@@ -1322,7 +1422,7 @@ const sorter = (items, trayXY) => (body, api) => {const svg = $('stage');const pt = e => { const p = svg.createSVGPoint(); p.x = e.clientX; p.y = e.clientY; return p.matrixTransform(svg.getScreenCTM().inverse()); };let sel = null, drag = null, locked = false;- const label = c => c.setAttribute('aria-label', `${c.say}, ${c.region ? 'placed in ' + NAME[c.region] : 'not placed'}`);+ const label = c => c.setAttribute('aria-label', c.region ? translate('chipPlaced', { x: c.say, ring: NAME[c.region] }) : translate('chipNotPlaced', { x: c.say }));const outline = (c, colr, w = 2.5) => { c._rect.setAttribute('stroke', colr); c._rect.setAttribute('stroke-width', w); };const choose = c => {if (sel) outline(sel, COL.chalk);@@ -1384,7 +1484,7 @@ const sorter = (items, trayXY) => (body, api) => {const notes = h('ul');for (const c of chips) {c.querySelector('.mark')?.remove();- if (!c.region) { notes.append(h('li', '', `${c.say} is not placed yet.`)); continue; }+ if (!c.region) { notes.append(h('li', '', translate('notPlacedYet', { x: c.say }))); continue; }const ok = c.region === c.answer;right += ok;outline(c, ok ? COL.good : COL.bad, 4);@@ -1392,11 +1492,11 @@ const sorter = (items, trayXY) => (body, api) => {const w = +c._rect.getAttribute('width');T(c, ok ? '✓' : '✗', { x: w / 2 + 4, y: -16, size: 26, fill: ok ? COL.good : COL.bad, weight: 700 }).classList.add('mark');if (!ok) notes.append(h('li', '', c.region === 'real'- ? `${c.say}: every real number is rational or irrational, so that space has no numbers of its own.`+ ? translate('realRingIsEmpty', { x: c.say }): c.why));}const all = right === chips.length;- api.grade(all, all ? [] : [`${right} of ${chips.length} in the right ring.`, notes], { right, total: chips.length });+ api.grade(all, all ? [] : [translate('ringsRight', { r: right, n: chips.length }), notes], { right, total: chips.length });},reveal() {const count = {};@@ -1408,10 +1508,10 @@ const sorter = (items, trayXY) => (body, api) => {outline(c, COL.good, 4);fx(c, { x, y }, i * .12, .8);});- return 'every number is now in its smallest ring.';+ return translate('ringsShown');},lock() { locked = true; choose(null); },- hint: [kbd('←'), kbd('→'), ' pick a number, ', kbd('1'), '–', kbd('6'), ' choose its ring'],+ hint: [kbd('←'), kbd('→'), translate('hintPickNumber'), kbd('1'), '–', kbd('6'), translate('hintPickRing')],key(e) {if (locked) return false;const d = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 0;@@ -1534,7 +1634,7 @@ function buildSegs() {const s = h('button', 'seg' + (b.ask ? ' ask' : ''), [h('i')]);s.style.flex = TIMINGS[b.id].dur + (b.ask ? 12 : 0);s.title = b.title;- s.setAttribute('aria-label', `Go to step ${i + 1}: ${b.title}`);+ s.setAttribute('aria-label', translate('goToStep', { n: i + 1, title: b.title }));s.onclick = () => { hideCover(); seek(i, true); };$('segs').append(s);return s.firstChild;@@ -1611,8 +1711,8 @@ document.addEventListener('keydown', e => {else if (k === 'ArrowLeft' && free) back1();else if (k === 'ArrowRight' && free) { if (P.i < BEATS.length - 1) seek(P.i + 1); }else if (k === 'Home') restart();- else if (k === 'c' || k === 'C') setCaptions(!captions);- else if (k === 'f' || k === 'F') toggleFull();+ else if (isShortcut(e, 'c')) setCaptions(!captions);+ else if (isShortcut(e, 'f')) toggleFull();else used = false;if (used) e.preventDefault();});@@ -1636,12 +1736,12 @@ function progress(f) {} catch {}}function boot() {- $('coverK').textContent = `Chapter ${CHAPTER.number}`;+ $('coverK').textContent = translate('chapterNumber', { n: CHAPTER.number });$('coverT').textContent = CHAPTER.title;$('bHome').href = `../#ch${String(CHAPTER.number).padStart(2, '0')}`;progress(p => { p.last = CHAPTER.number; });- document.getElementById('stage').setAttribute('aria-label', `Lesson animation: ${CHAPTER.title}`);- $('coverMeta').textContent = `About ${CHAPTER.minutes} minutes, with sound and quick checks.`;+ document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));+ $('coverMeta').textContent = translate('aboutMinutes', { n: num(CHAPTER.minutes) });buildSegs();const qs = new URLSearchParams(location.search);if (qs.has('beat')) {diff --git a/.claude/skills/papermorph/assets/templates/book.html b/.claude/skills/papermorph/assets/templates/book.htmlindex 427ef4f..37a8ec0 100644--- a/.claude/skills/papermorph/assets/templates/book.html+++ b/.claude/skills/papermorph/assets/templates/book.html@@ -154,8 +154,8 @@ main#contents { padding-bottom: 80px; }.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.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; } }@@ -199,7 +199,7 @@ main#contents { padding-bottom: 80px; }<h1>BOOK <i>&</i> TITLE</h1><p class="lede">ONE OR TWO SENTENCES ABOUT WHAT THE READER WILL SEE AND DO.</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>@@ -207,7 +207,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>BOOK <i>&</i> TITLE</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>BOOK <i>&</i> TITLE</strong></a><span class="prog" id="prog"></span></header><div id="units"></div>@@ -215,6 +215,40 @@ main#contents { padding-bottom: 80px; }<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: '{n} chapters', metaUnits: '{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')));+// 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.['First unit', [['First chapter', 8]]],@@ -233,10 +267,10 @@ const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isIntegerlet n = 0, total = 0, i = 0; // i staggers the entrance, in reading orderconst 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++}"><svg class="unit-art" viewBox="0 0 600 180" aria-hidden="true">${UNIT_ART[u] || ''}</svg><h2><span>Unit ${u + 1}</span>${esc(name)}</h2><div class="grid">` ++ return `<section class="unit" style="--c:${HUES[u % HUES.length]};--i:${i++}"><svg class="unit-art" viewBox="0 0 600 180" aria-hidden="true">${UNIT_ART[u] || ''}</svg><h2><span>${translate('unit', { n: u + 1 })}</span>${esc(name)}</h2><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>`;+ 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('');total = n;@@ -244,14 +278,15 @@ total = n;const seen = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) { e.target.classList.add('seen'); seen.unobserve(e.target); } }), { threshold: .25 });document.querySelectorAll('.unit').forEach(u => seen.observe(u));const finished = [...done].filter(k => k <= total).length;-document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapter${total === 1 ? '' : 's'}`;-document.getElementById('meta').textContent = `${total} chapters · ${UNITS.length} units · with sound`;+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 = `Continue · Chapter ${P.last}`;+ r.textContent = translate('resume', { n: P.last });}// The guide, drawn the same way as in the lessons.diff --git a/.claude/skills/papermorph/assets/templates/chapter.html b/.claude/skills/papermorph/assets/templates/chapter.htmlindex 5411e57..2c859b6 100644--- a/.claude/skills/papermorph/assets/templates/chapter.html+++ b/.claude/skills/papermorph/assets/templates/chapter.html@@ -14,6 +14,7 @@'use strict';// A starting skeleton, not a design. Replace every beat; keep the shape: intro, lesson beats with// quick checks between them, a summary, full-screen practice, finish. Beat ids match narration.en.json.+// <html lang> sets the interface text, language the audio folder: keep both, and the timings path above, in the book's language.const CHAPTER = { number: 1, title: 'CHAPTER TITLE', minutes: 8, language: 'en' }; // match the audio folder; set next once the next chapter exists/* ---------- chapter drawing helpers ---------- */diff --git a/.claude/skills/papermorph/references/authoring.md b/.claude/skills/papermorph/references/authoring.mdindex 680e071..76a8317 100644--- a/.claude/skills/papermorph/references/authoring.md+++ b/.claude/skills/papermorph/references/authoring.md@@ -49,6 +49,7 @@ Principles that held up over a whole book:- Question beats get one short line ("Quick check. Find the mean."); the card holds the question.- `tts.py` caches word timings beside the narration JSON; the output folder receives `<beat>.mp3` and `timings.js` (duration, marks, sentence captions). Moving or adding `[[marks]]` reuses the spoken-text cache and recalculates timings. Existing caches made with raw-text keys are reused for an unchanged beat and then upgraded; changing its marks before that upgrade may require one new synthesis.- Audio is replaced only after synthesis and timing validation succeed, and each completed beat is cached immediately. After a later failure, rerun the same command to reuse completed beats rather than regenerating the chapter.+- Another language: write `narration.<lang>.json` from the template with a voice for that language (`uv run --with edge-tts edge-tts --list-voices`); marks and captions work the same way. Beat ids and mark names stay ASCII.## Questionsdiff --git a/.claude/skills/papermorph/references/engine.md b/.claude/skills/papermorph/references/engine.mdindex 71a4950..6098d21 100644--- a/.claude/skills/papermorph/references/engine.md+++ b/.claude/skills/papermorph/references/engine.md@@ -60,7 +60,7 @@ quiz(position, [{ id: 'c-mean', prompt: ['Find the mean of ', $m('7, 3, 9'), '.'- `grid(rows, cols, {multi, text})` — rows `{parts, ans: [keys], why, fx?}`, cols `[[key, label, colour?, hotkey?]]`; with `text: true` parts are rich text (math via `$m`). ↑/↓ change rows.- `tap(values, right, why, v => wrongWhy, onRight?)` points on the number line; `tapEls(row, idx, right, …)` tokens of a `tokens` row; `pickEls([{el, box: [x,y,w,h], label}], right, …)` any drawn objects; `pickPoint(P, [x,y], why, (x,y) => wrongWhy, onRight?, test?)` grid points (arrows + Enter or click); `sorter(items, trayXY)` drag into the set diagram (keys 1–6).- Answer animations run on their own clock: `fx`, `fxp`, `pulseFx`, `shakeFx`, `floatText`, `qlayer()` (a layer cleared with the question). They are finished automatically when the beat is left.-- A new type: `build(body, api)` returns `{ reveal, check?, lock?, key?(e), hint? }` and calls `api.grade(ok, message, {right, total})`. `key` handles its shortcuts (return true when used); `hint` lists the keys under the prompt. Every action needs a key; the help overlay (`?`) lists the global ones.+- A new type: `build(body, api)` returns `{ reveal, check?, lock?, key?(e), hint? }` and calls `api.grade(ok, message, {right, total})`. `key` handles its shortcuts (return true when used); `hint` lists the keys under the prompt. Every action needs a key; the help overlay (`?`) lists the global ones. Match letter keys with `isShortcut(e, 'x')`, which also accepts the same physical key on a non-Latin layout, and take its texts from `translate()`.- Scores: `SCORE[id]` keeps the first try across revisits and step jumps; restarting the chapter clears it. A multi-row question scores one per row. A correct retry changes the feedback, not the first-attempt score.## Player@@ -73,6 +73,13 @@ Treat saved progress as optional: malformed JSON, `null` or a non-object value sKeep `<link rel="expect" href="#bar" blocking="render">` in every chapter's head; without it Chromium may paint before the player exists and cancel the page transition from the contents page.+## Interface language++- `LANGUAGE` comes from the page's `<html lang>`; a language without a `TRANSLATIONS` block uses English. It is read when the engine loads, before `CHAPTER` exists; `CHAPTER.language` only picks the audio folder.+- `translate(key, vars)` returns the interface text from `TRANSLATIONS[LANGUAGE]`, falling back to English: `translate('chapterNumber', { n: 3 })`. Plural forms are chosen by `vars.n`. Chapters may use it for their own labels, e.g. `translate('chapterPractice') + ' ' + translate('countOf', { k: 1, n: 2 })`; the default `quiz` label is `translate('quickCheck')`.+- `DECIMAL_SIGN` is the language's `decimalSign`: `num()` writes it and answer boxes accept it besides `.`. Write decimals in chapter text the same way.+- `isShortcut(e, letter)` matches a letter key on any keyboard layout. The global keys (C, F), Show answer (S), replay (R) and `grid` letters (T/F) use it.+## Traps- `M()` italicises 1–2 letter lowercase runs (variables) and runs of capitals, but keeps common short English words upright (by, my, an, if, in, is, of, or, …; capitalised: By, If, In, …). In maths write `by`, `my`, `an`, `By` to keep them italic. Units inside `M()` turn italic too: write them as words in `T()` text ("meters"). Never put an English sentence in `M()`.@@ -80,4 +87,5 @@ Keep `<link rel="expect" href="#bar" blocking="render">` in every chapter's head- Prefix chapter-specific helpers when their names might collide with engine globals (`rect`, `popIn`, `eqLine`, `fit`, `slot`, `Y0`, …); a redeclaration stops the page script.- Drag handling: re-parent (append) the element before `setPointerCapture`; moving a node drops its capture.- A card whose content is too long for `BAND` should become several `blanks` rows in a wider side card.+- A `grid` needs a card at least 560 px wide: its rows keep a 170 px column for the item, so in `RIGHT` (330 px) the option buttons overflow, sooner with longer translated labels.- When a question beat is continued early, the engine finishes the beat's pending tweens first; don't rely on half-finished fades.diff --git a/.claude/skills/papermorph/references/review.md b/.claude/skills/papermorph/references/review.mdindex 1287a0e..48816b9 100644--- a/.claude/skills/papermorph/references/review.md+++ b/.claude/skills/papermorph/references/review.md@@ -27,7 +27,7 @@ Report the delivery result and any unresolved defects in a few lines. A new visu## Targeted interaction tests-For changes to playback, question types or grading, run existing tests that exercise the changed behavior. If needed, adapt `assets/templates/e2e.py` into `tools/<book>/e2e_chNN.py`; set `URL` to the actual chapter URL. Check the relevant wrong/right feedback, Show answer and continuation, or pause/replay/seek behavior. Shared timing/replay changes warrant the whole book's blank check and existing affected tests; ordinary new chapters use the delivery pass above.+For changes to playback, question types or grading, run existing tests that exercise the changed behavior. If needed, adapt `assets/templates/e2e.py` into `tools/<book>/e2e_chNN.py`; set `URL` to the actual chapter URL. In another language, match that language's feedback and finish-card text. For changes to interface text, number formats or letter shortcuts, run `scripts/check_i18n.py` (no server needed); it also compares English pages with `main`. Check the relevant wrong/right feedback, Show answer and continuation, or pause/replay/seek behavior. Shared timing/replay changes warrant the whole book's blank check and existing affected tests; ordinary new chapters use the delivery pass above.For scoring changes, verify a wrong first attempt stays recorded after leaving and revisiting the question, and that restarting clears it. For progress changes, check book isolation and loading with missing or malformed stored data. Apply common fixes to the affected book engines and the Skill engine/template, preserving book-specific helpers and legacy keys.diff --git a/.claude/skills/papermorph/references/site.md b/.claude/skills/papermorph/references/site.mdindex 3dbd529..c35771c 100644--- a/.claude/skills/papermorph/references/site.md+++ b/.claude/skills/papermorph/references/site.md@@ -18,7 +18,7 @@ cp "$SKILL/assets/templates/chapter.html" "$BOOK_SITE/ch01/index.html"cp "$SKILL/assets/templates/narration.en.json" "content/$BOOK_ID/ch01/narration.en.json"```-Use the agreed primary language: rename the narration source, load `audio/<lang>/timings.js`, and set `CHAPTER.language` to match (default `en`). Choose the voice and translate the template's visible UI text as needed before the pilot.+Use the agreed primary language: rename the narration source, load `audio/<lang>/timings.js`, and set `CHAPTER.language` to match (default `en`), with `<html lang="<lang>">` in `index.html` and every chapter for the interface text ([Languages](#languages)). Choose the voice and translate the template's visible UI text as needed before the pilot.Each book has its own engine, source materials, narration and optional tests. The engine and cover derive the same progress key from the book's URL folder. Keep existing books on their current paths; their legacy progress remains intact.@@ -53,3 +53,5 @@ Open `http://localhost:8765/<book>/`. Confirm the cover opens the contents, read## LanguagesNarration and on-screen text are written in one language first. A second language comes after the book is done and approved: keep beat ids and question ids stable, add `narration.<lang>.json` and audio per language, and decide with the user how switching behaves mid-lesson before building it.++A page's `<html lang>` picks the interface text of the player, questions, finish card, cover and contents from `TRANSLATIONS` in `lib/engine.js` and `index.html`; `CHAPTER.language` picks only the audio folder, so set both alike. A language without a block there, or a missing key, falls back to English. For a new language, add a block with the same keys to both files before the pilot: a value is a string or plural forms `{ one, few, many, other }` chosen by `Intl.PluralRules`, and `decimalSign` sets how `num()` writes decimals and which sign answer boxes accept. Right-to-left scripts also need layout work the engine does not do. Keep beat ids and `[[mark]]` names ASCII in every language: they are file names and JS keys, and `tts.py` prints them.diff --git a/.claude/skills/papermorph/scripts/check_i18n.py b/.claude/skills/papermorph/scripts/check_i18n.pynew file mode 100644index 0000000..0580133--- /dev/null+++ b/.claude/skills/papermorph/scripts/check_i18n.py@@ -0,0 +1,271 @@+#!/usr/bin/env python3+"""Interface-language regression for the Skill engine and the cover/contents template.++ uv run --with playwright .claude/skills/papermorph/scripts/check_i18n.py++No server is needed: the check answers every request itself with the Skill's chapter and book+templates, its engine and a real MP3 from an existing book. English pages are compared with the+engine and template at BASE_REF (default main) so that English output stays identical; set+BASE_REF to another commit, or to an empty string to skip that comparison. No files are generated.+"""+import asyncio+import json+import os+import subprocess+from pathlib import Path+from urllib.parse import urlparse++from playwright.async_api import async_playwright++SKILL = Path(__file__).resolve().parents[1]+ROOT = SKILL.parents[2]+SITE = ROOT / "site"+BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8767").rstrip("/")+BASE_REF = os.environ.get("BASE_REF", "main")+ENGINE = SKILL / "assets/engine/engine.js"+TEMPLATES = SKILL / "assets/templates"+TIMING = {"dur": 30, "marks": {"sub": 1, "note": 2, "w1": 3, "w2": 4}, "cues": []}+TIMINGS = "const TIMINGS = " + json.dumps({beat: TIMING for beat in ("intro", "idea", "q1", "wrap", "final1", "finish")})+# Page variants: (html lang, engine and book template from BASE_REF instead of the working tree).+VARIANTS = {"base": ("en", True), "en": ("en", False), "ru": ("ru", False), "de": ("de", False)}+++def at_base_ref(path):+ """The file as committed at BASE_REF, or None when the comparison is skipped."""+ if not BASE_REF:+ return None+ relative = path.relative_to(ROOT).as_posix()+ result = subprocess.run(["git", "show", f"{BASE_REF}:{relative}"], cwd=ROOT, capture_output=True)+ return result.stdout.decode("utf-8") if result.returncode == 0 else None+++BASE_FILES = {"engine": at_base_ref(ENGINE), "book": at_base_ref(TEMPLATES / "book.html")}+++def with_language(html, language):+ return html.replace('<html lang="en">', f'<html lang="{language}">', 1)+++async def answer(route):+ variant, _, rest = urlparse(route.request.url).path.split("/__i18n__/")[1].partition("/")+ language, from_base = VARIANTS[variant]+ if rest == "ch01/":+ html = (TEMPLATES / "chapter.html").read_text(encoding="utf-8")+ await route.fulfill(content_type="text/html", body=with_language(html, language))+ elif rest == "":+ html = BASE_FILES["book"] if from_base else (TEMPLATES / "book.html").read_text(encoding="utf-8")+ await route.fulfill(content_type="text/html", body=with_language(html, language))+ elif rest == "unit-art.js":+ await route.fulfill(path=TEMPLATES / "unit-art.js")+ elif rest == "lib/engine.js":+ if from_base:+ await route.fulfill(content_type="text/javascript", body=BASE_FILES["engine"])+ else:+ await route.fulfill(path=ENGINE)+ elif rest == "lib/engine.css":+ await route.fulfill(path=SKILL / "assets/engine/engine.css")+ elif rest.endswith("timings.js"):+ await route.fulfill(content_type="text/javascript", body=TIMINGS)+ else:+ # The template has no narrated assets; exercise it with an existing, real MP3.+ await route.fulfill(path=SITE / "math-notebook/ch01/audio/en/intro.mp3")+++async def open_page(browser, path, errors):+ page = await browser.new_page(viewport={"width": 1440, "height": 900})+ page.on("pageerror", lambda error: errors.append(f"{path}: {error}"))+ page.on("console", lambda message: message.type == "error" and errors.append(f"{path}: {message.text}"))+ page.on("response", lambda response: response.status >= 400 and errors.append(response.url))+ page.on("requestfailed", lambda request: request.failure != "net::ERR_ABORTED" and errors.append(request.url))+ await page.route("**/__i18n__/**", answer)+ await page.goto(f"{BASE}/__i18n__/{path}")+ return page+++async def open_lesson(browser, variant, errors):+ page = await open_page(browser, f"{variant}/ch01/", errors)+ await page.wait_for_function("typeof P !== 'undefined' && P.audio")+ return page+++async def press(page, key, code):+ """A keydown as a layout produces it: key is the typed character, code the physical key."""+ await page.evaluate("([key, code]) => document.dispatchEvent(new KeyboardEvent('keydown', { key, code, bubbles: true }))", [key, code])+ await page.wait_for_timeout(60)+++async def lesson_snapshot(page):+ """Player markup, then the quick check before and after a wrong answer, then the finish card."""+ shots = [await page.evaluate("document.getElementById('frame').outerHTML")]+ await page.evaluate("seek(2, false)")+ await page.wait_for_timeout(200)+ shots.append(await page.evaluate("document.getElementById('ui').innerHTML"))+ await page.locator(".box").fill("6")+ await page.locator(".box").press("Enter")+ shots.append(await page.evaluate("document.getElementById('ui').innerHTML"))+ await page.evaluate("seek(BEATS.length - 1, false)")+ await page.wait_for_timeout(600)+ shots.append(await page.evaluate("document.getElementById('ui').innerHTML"))+ return shots+++async def check_english_unchanged(browser, errors):+ if not all(BASE_FILES.values()):+ print(f"SKIP English identity: engine or book template not found at BASE_REF={BASE_REF!r}")+ return+ before = await open_lesson(browser, "base", errors)+ after = await open_lesson(browser, "en", errors)+ names = ("player markup", "quick check", "wrong-answer feedback", "finish card")+ for name, old, new in zip(names, await lesson_snapshot(before), await lesson_snapshot(after)):+ assert old.replace("/__i18n__/base/", "/__i18n__/en/") == new, f"English {name} changed" # links carry the page's own path+ assert await after.evaluate("rat('0,75') === null && num(2.5) === '2.5' && num(-3) === '−3'"), "English numbers changed"+ await before.close()+ await after.close()++ marks = "e => [e.innerText, getComputedStyle(e, '::before').content, getComputedStyle(e, '::after').content].join('|')"+ texts = []+ for variant in ("base", "en"):+ page = await open_page(browser, f"{variant}/", errors)+ await page.evaluate(f"localStorage.setItem('animebook:progress:/__i18n__/{variant}/', JSON.stringify({{ done: [1], last: 1 }}))")+ await page.reload()+ texts.append([await page.evaluate("document.body.innerText"), await page.locator(".ch").first.evaluate(marks),+ await page.locator(".home").get_attribute("aria-label")])+ await page.close()+ assert texts[0] == texts[1], f"English cover/contents changed:\n{texts[0]}\n{texts[1]}"+ print(f"PASS English unchanged against {BASE_REF}: player, quick check, feedback, finish card, cover and contents")+++async def check_russian_lesson(browser, errors):+ page = await open_lesson(browser, "ru", errors)+ text = lambda selector: page.locator(selector).first.text_content() # as written, before CSS case and spacing+ assert await text("#coverK") == "Глава 1"+ assert "Начать урок" in await text("#cover .go")+ assert await text("#coverMeta") == "Около 8 минут, со звуком и проверками."+ assert "Пробел — начать" in await text("#cover small")+ assert await page.locator("#help h2").text_content() == "Горячие клавиши"+ assert await page.locator(".paused-mark").text_content() == "Пауза. Нажмите пробел или щёлкните, чтобы продолжить."+ for role, name in (("button", "Настроить громкость"), ("slider", "Громкость"), ("button", "Субтитры (C)"),+ ("button", "Пуск или пауза (пробел)"), ("link", "Все главы"), ("button", "Перейти к шагу 3: Quick check")):+ assert await page.get_by_role(role, name=name, exact=True).count() == 1, f"no {role} named {name!r}"+ assert await page.get_attribute("#stage", "aria-label") == "Анимация урока: CHAPTER TITLE"++ # Plural forms, fallbacks and numbers.+ assert await page.evaluate("""[1, 3, 8, 21].map(n => translate('aboutMinutes', { n })).join('|')""") == (+ "Около 1 минуты, со звуком и проверками.|Около 3 минут, со звуком и проверками.|"+ "Около 8 минут, со звуком и проверками.|Около 21 минуты, со звуком и проверками.")+ assert await page.evaluate("[1, 3, 5].map(n => translate('stepsLeftOfZero', { n })).join('|')") == (+ "1 шаг влево от 0|3 шага влево от 0|5 шагов влево от 0")+ assert await page.evaluate("translate('noSuchKey') === 'noSuchKey'")+ assert await page.evaluate("num(2.5) === '2,5' && num(-3) === '−3' && num(-0.5) === '−0,5'")+ assert await page.evaluate("rat('0,75').join() === '75,100' && rat('0.75').join() === '75,100' && rat('−2 1/4').join() === '-9,4'")+ assert await page.evaluate("rat('1,000,5') === null && rat('3,') === null")+ assert await page.evaluate("""isShortcut({ key: 'а', code: 'KeyF' }, 'f') && isShortcut({ key: 'F', code: 'KeyF' }, 'f')+ && !isShortcut({ key: 'a', code: 'KeyF' }, 'f') && !isShortcut({ key: '1', code: 'Digit1' }, 'f')"""), "layout-independent letters"++ # Global shortcuts typed on a Russian layout.+ await page.locator("#cover").click()+ await page.wait_for_function("P.started && P.audio.currentTime > .1")+ for key in ("с", "с"):+ before = await page.get_attribute("#bCC", "aria-pressed")+ await press(page, key, "KeyC")+ assert await page.get_attribute("#bCC", "aria-pressed") != before, "С toggles captions"+ await page.evaluate("document.documentElement.requestFullscreen = () => (window.fullScreenRequested = true, Promise.resolve())")+ await press(page, "а", "KeyF")+ assert await page.evaluate("window.fullScreenRequested === true"), "А opens full screen"++ # The template's quick check: labels, hint, wrong answer, Show answer by Ы.+ await page.evaluate("seek(2, false)")+ await page.wait_for_timeout(200)+ assert await text(".card .kicker") == "Проверь себя"+ assert "введите число" in await text(".card .keys") and (await text(".card .keys")).startswith("Клавиши:")+ assert "Проверить" in await text(".card .acts")+ await page.locator(".box").fill("6")+ await page.locator(".box").press("Enter")+ assert (await text(".card .fb")).startswith("Не совсем.")+ await page.locator(".box").press("Escape")+ await press(page, "ы", "KeyS")+ assert (await text(".card .fb")).startswith("Ответ:"), "Ы shows the answer"+ assert "Продолжить" in await text(".card .acts")++ # Decimal comma in an answer box, True/False keys on a Russian layout, row messages.+ await page.evaluate("""clearCards(); quiz(SCREEN, [+ { id: 'x-dec', prompt: ['Три четверти десятичной дробью'], build: blanks([{ parts: ['3/4 = ', { box: '0.75' }], why: 'ок' }]) },+ { id: 'x-tf', prompt: ['Верно ли?'], build: grid([{ parts: ['5 > 3'], ans: ['t'], why: 'ок' }], TF, { multi: false }) },+ { id: 'x-rows', prompt: ['Две строки'], build: grid([{ parts: ['1'], ans: ['t'], why: 'а' }, { parts: ['2'], ans: ['f'], why: 'б' }], TF, { multi: false }) },+ ], () => { window.quizDone = true; })""")+ await page.wait_for_timeout(100)+ assert "вводите числа вида 0,75" in await text(".card .keys")+ assert await text(".card .kicker") == "Проверь себя 1 из 3"+ await page.locator(".box").fill("0,75")+ await page.locator(".box").press("Enter")+ assert (await text(".card .fb")).startswith("Верно."), "0,75 is accepted"+ await page.keyboard.press("Enter")+ assert "Верно" in await text(".card .opts") and "Неверно" in await text(".card .opts")+ await press(page, "е", "KeyT")+ assert await page.locator(".card .opt").nth(0).get_attribute("aria-pressed") == "true", "Е picks True"+ await page.keyboard.press("Enter")+ assert (await text(".card .fb")).startswith("Верно.")+ await page.keyboard.press("Enter")+ await press(page, "е", "KeyT")+ await press(page, "е", "KeyT")+ await page.keyboard.press("Enter")+ assert (await text(".card .fb")).startswith("Не совсем. Верно 1 из 2. Исправьте строки с ✗ и проверьте снова.")+ await press(page, "ы", "KeyS")+ assert await text(".card .fb") == "Ответ: правильные варианты отмечены."++ # Finish card with a first try recorded, and R on a Russian layout.+ await page.evaluate("seek(BEATS.length - 1, false)")+ await page.wait_for_timeout(200)+ card = await text(".card")+ for line in ("Глава 1 пройдена", "Проверь себя: 0 из 1 верно с первой попытки.", "Практика по главе: не выполнялось.",+ "Все главы", "Смотреть снова"):+ assert line in card, f"finish card lacks {line!r}"+ await press(page, "к", "KeyR")+ await page.wait_for_function("P.i === 0")+ print("PASS Russian lesson: cover, help, bar labels, plurals, numbers, keys on a Russian layout, questions, finish card")+ await page.close()+++async def check_other_language(browser, errors):+ page = await open_lesson(browser, "de", errors)+ assert await page.locator("#coverK").text_content() == "Chapter 1"+ assert await page.evaluate("translate('startLesson') === 'Start lesson' && num(2.5) === '2.5'")+ print("PASS unknown language falls back to English")+ await page.close()+++async def check_russian_book(browser, errors):+ page = await open_page(browser, "ru/", errors)+ text = lambda selector: page.locator(selector).first.text_content() # as written, before CSS case and spacing+ assert (await text("#cover .btn.go")).startswith("Открыть книгу")+ assert await text("#meta") == "1 глава · 1 раздел · со звуком"+ assert await text("#prog") == "1 глава"+ assert await text(".unit h2 span") == "Раздел 1"+ assert await text(".ch small") == "8 мин"+ assert await page.locator(".home").get_attribute("aria-label") == "К обложке"+ await page.evaluate("localStorage.setItem('animebook:progress:/__i18n__/ru/', JSON.stringify({ done: [1], last: 1 }))")+ await page.reload()+ assert await text("#prog") == "Пройдено 1 из 1"+ assert await text("#resume") == "Продолжить · Глава 1"+ marks = await page.locator(".ch").first.evaluate(+ "e => [getComputedStyle(e.querySelector('small'), '::before').content, getComputedStyle(e.querySelector('small'), '::after').content]")+ assert marks == ['"✓ Пройдено · "', '" · Открыта последней"'], marks+ print("PASS Russian cover and contents: buttons, plurals, progress, finished and last-opened marks")+ await page.close()+++async def main():+ errors = []+ async with async_playwright() as playwright:+ browser = await playwright.chromium.launch(args=["--autoplay-policy=no-user-gesture-required"])+ await check_english_unchanged(browser, errors)+ await check_russian_lesson(browser, errors)+ await check_other_language(browser, errors)+ await check_russian_book(browser, errors)+ await browser.close()+ assert not errors, errors+ print("PASS no page errors, console errors or failed requests")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/README.md b/README.mdindex f2e2b44..3e88fed 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@ This Skill takes it further: books you can explore, listen to, and interact withPDF -> Book plan -> Storyboards -> Narration -> Animation & quizzes -> Web book```-**Today:** Opus 5.5 only. No image models, multilingual support, or BGM yet.+**Today:** Opus 5.5 only. Books in English or Russian; no image models or BGM yet.**Planned:** Image models and storyboarding for interactive picture books and humanities documentaries.