Skip to content

An AI skill that turns books into animated, narrated, interactive web experiences

chore(site): sync engine with citations and item banks into every book

yzr365e702ea25f
diff --git a/site/elementary-algebra/lib/contents.css b/site/elementary-algebra/lib/contents.css
index 3f59f10..d8f7f70 100644
--- a/site/elementary-algebra/lib/contents.css
+++ b/site/elementary-algebra/lib/contents.css
@@ -26,6 +26,8 @@ a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
#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; }
+/* #references is its own view: the full list, reached from one link at the end of the contents. */
+body:not(.refsview) #refpage, .refsview #cover, .refsview #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; }
@@ -92,6 +94,26 @@ main#contents { padding-bottom: 80px; }
.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; } }
+/* ---------- references: every source the book cites, linked to its DOI or catalogue record ---------- */
+.refs-more { max-width: 1212px; margin: 44px auto 0; padding: 0 16px; }
+.refs-more[hidden] { display: none; }
+.refs-more a { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 14px; padding: 16px 20px; border-radius: 16px; background: var(--panel);
+ border: 1.5px solid var(--edge); text-decoration: none; transition: border-color .3s; }
+.refs-more a:hover { border-color: var(--dim); }
+.refs-more b { font: 500 22px/1.2 var(--book); }
+.refs-more span { color: var(--dim); font-size: 15px; }
+.refs-more i { margin-left: auto; font-style: normal; color: var(--quiz); font-weight: 600; font-size: 15px; }
+#refpage { padding-bottom: 80px; }
+.top .back { display: inline-flex; align-items: center; gap: 8px; padding: 6px 4px; font-weight: 600; text-decoration: none; color: var(--quiz); border-radius: 8px; }
+.top .rp-book { margin-left: auto; font: 500 18px/1.2 var(--book); color: var(--dim); }
+.top .rp-book i { color: var(--task); }
+.refs { max-width: 1212px; margin: 32px auto 0; padding: 0 16px; }
+.refs h1 { margin: 0 0 8px; font: 500 clamp(32px, 5vw, 44px)/1.1 var(--book); view-transition-name: none; }
+.refs .lead { margin: 0 0 26px; max-width: 46em; color: var(--dim); }
+.refs ol { margin: 0; padding: 0; list-style: none; color: var(--dim); font-size: 16px; line-height: 1.5; }
+.refs li { margin: 0 0 10px; padding-left: 2em; text-indent: -2em; }
+.refs a { color: var(--chalk); text-underline-offset: 3px; overflow-wrap: anywhere; }
+.refs a:hover { color: var(--quiz); }
.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); }
diff --git a/site/elementary-algebra/lib/contents.js b/site/elementary-algebra/lib/contents.js
index 6b3272b..7022eb5 100644
--- a/site/elementary-algebra/lib/contents.js
+++ b/site/elementary-algebra/lib/contents.js
@@ -1,6 +1,7 @@
/* 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. */
+ Contents.book({ units, start, hues }) with its chapter list. With refs.js (REFS, built by the skill's
+ scripts/refs.py) loaded first, the page also gets its References view (#references). */
'use strict';
// Observe aborted incoming transitions before the first rendering opportunity.
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
@@ -15,6 +16,10 @@ const Contents = (() => {
metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: { one: ' + {n} sample', other: ' + {n} samples' }, samples: 'Sample chapters, another look',
chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',
doneMark: '✓ Finished · ', lastMark: ' · Last opened',
+ references: 'References', viewAll: 'View all →', backToContents: '← Contents',
+ refsLead: 'Every work cited in the lessons. Each link opens the work’s DOI or library record in a new tab; works with no reliable online record are listed without a link.',
+ refsCount: { one: '{n} work cited in the lessons', other: '{n} works cited in the lessons' },
+ refsAllLinked: ', each linked to its source', refsSomeLinked: ', {n} linked to their sources',
},
ru: {
open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',
@@ -25,6 +30,10 @@ const Contents = (() => {
samples: 'Пробные главы в другом стиле',
chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',
doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',
+ references: 'Список литературы', viewAll: 'Весь список →', backToContents: '← Оглавление',
+ refsLead: 'Все работы, которые цитируются в уроках. Ссылка открывает DOI или библиотечную запись в новой вкладке; работы без надёжной записи в сети даны без ссылки.',
+ refsCount: { one: '{n} работа цитируется в уроках', few: '{n} работы цитируются в уроках', many: '{n} работ цитируются в уроках', other: '{n} работы цитируются в уроках' },
+ refsAllLinked: ', у каждой есть ссылка на источник', refsSomeLinked: ', ссылок на источник: {n}',
},
zh: {
open: '打开这本书', toCover: '返回封面', resume: '继续 · 第 {n} 章', unit: '第 {n} 单元', minutes: '{n} 分钟',
@@ -32,6 +41,9 @@ const Contents = (() => {
metaSamples: ' + {n} 个示例章', samples: '示例章,另一种风格',
chapterCount: '{n} 章', finished: '已完成 {done} / {n}',
doneMark: '✓ 已完成 · ', lastMark: ' · 上次打开',
+ references: '参考文献', viewAll: '查看全部 →', backToContents: '← 目录',
+ refsLead: '课程中引用的全部作品。每个链接会在新标签页中打开该作品的 DOI 或图书馆记录;没有可靠在线记录的作品不附链接。',
+ refsCount: '课程中引用了 {n} 部作品', refsAllLinked: ',均链接到来源', refsSomeLinked: ',其中 {n} 部链接到来源',
},
ja: {
open: '本を開く', toCover: '表紙に戻る', resume: '続きから · 第{n}章', unit: '単元 {n}', minutes: '{n}分',
@@ -39,6 +51,9 @@ const Contents = (() => {
metaSamples: ' + サンプル{n}章', samples: 'サンプル章(別のスタイル)',
chapterCount: '{n}章', finished: '{n}章中 {done}章 完了',
doneMark: '✓ 完了 · ', lastMark: ' · 最後に開いた章',
+ references: '参考文献', viewAll: 'すべて見る →', backToContents: '← 目次',
+ refsLead: '授業で引用したすべての著作です。リンクは著作の DOI または図書館の記録を新しいタブで開きます。信頼できるオンライン記録のない著作はリンクなしで載せています。',
+ refsCount: '授業で引用した著作 {n} 件', refsAllLinked: '、すべて出典へのリンクつき', refsSomeLinked: '、うち {n} 件は出典へのリンクつき',
},
};
const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
@@ -54,7 +69,7 @@ const Contents = (() => {
}
const $ = id => document.getElementById(id);
const id = n => 'ch' + String(n).padStart(2, '0');
- const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
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.
@@ -114,6 +129,20 @@ const Contents = (() => {
}
}
+ // The References view, from refs.js: full entries, each linked to its DOI or catalogue record. It appears as one
+ // link at the end of the contents only when the book cites something.
+ function references() {
+ const all = Object.values(typeof REFS === 'object' && REFS ? REFS : {});
+ if (!$('refList') || !all.length) return;
+ $('refList').innerHTML = all.sort((a, b) => a.ref.localeCompare(b.ref)).map(r => `<li>${esc(r.ref)}${r.url
+ ? ` <a href="${esc(r.url)}" target="_blank" rel="noopener">${esc(r.url.replace(/^https?:\/\//, ''))}</a>` : ''}</li>`).join('');
+ const linked = all.filter(r => r.url).length;
+ $('refsCount').textContent = translate('refsCount', { n: all.length }) +
+ (linked === all.length ? translate('refsAllLinked') : translate('refsSomeLinked', { n: linked }));
+ $('rpBook').innerHTML = document.querySelector('#contents .home strong')?.innerHTML || '';
+ $('refsMore').hidden = false;
+ }
+
// 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 = '';
@@ -134,21 +163,24 @@ const Contents = (() => {
}
}
- // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.
+ // The cover, the contents and the references share this page: no hash or #book shows the cover, #references the
+ // reference list, #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 refs = location.hash === '#references';
+ const open = location.hash.length > 1 && location.hash !== '#book' && !refs;
const apply = () => {
document.body.classList.toggle('open', open);
+ document.body.classList.toggle('refsview', refs);
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');
+ const heading = document.querySelector(refs ? '#refsTitle' : open ? '#contents .home' : '#cover h1');
heading?.setAttribute('tabindex', '-1');
heading?.focus({ preventScroll: true });
}
@@ -184,6 +216,7 @@ const Contents = (() => {
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));
+ references();
guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');
views();
}
diff --git a/site/elementary-algebra/lib/engine.css b/site/elementary-algebra/lib/engine.css
index 9b9be00..9e8e535 100644
--- a/site/elementary-algebra/lib/engine.css
+++ b/site/elementary-algebra/lib/engine.css
@@ -221,6 +221,22 @@ svg.m { display: inline-block; overflow: visible; }
@media (prefers-reduced-motion: reduce) { .card, .fb, .opt, .grid .mark, .mascot * { animation: none !important; } }
a.icon { text-decoration: none; }
+/* Citations (cite() and plain-text labels found in refs.js) and the finish card's source list open the source in a new tab. */
+a.cite { cursor: pointer; }
+a.cite text, a.cite tspan { text-decoration: underline; text-decoration-thickness: 1.5px; text-underline-offset: 5px; }
+a.cite:hover text, a.cite:hover tspan { fill: var(--quiz); }
+a.cite:focus { outline: none; }
+a.cite:focus-visible text, a.cite:focus-visible tspan { fill: var(--task); }
+a.cite:focus-visible { outline: 3px solid var(--task); outline-offset: 6px; border-radius: 4px; }
+#ui a.cite { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
+#ui a.cite:hover { color: var(--quiz); }
+.fin .srcs { margin: 26px 0 0; max-width: 1100px; font-size: 19px; line-height: 1.45; color: var(--dim); text-align: left; }
+.fin .srcs h2 { margin: 0 0 6px; font-size: 18px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
+.fin .srcs ol { margin: 0; padding-left: 0; list-style: none; max-height: 190px; overflow: auto; }
+.fin .srcs li { padding-left: 2em; text-indent: -2em; margin: 0 0 6px; }
+.fin .srcs a { color: var(--chalk); text-underline-offset: 3px; }
+.fin .srcs a:hover { color: var(--quiz); }
+.fin .srcs a:focus-visible { outline: 3px solid var(--task); outline-offset: 2px; }
a.btn { text-decoration: none; display: inline-block; }
/* Page-to-page motion: the contents card grows into this frame, and shrinks back on the way out. */
@view-transition { navigation: auto; }
diff --git a/site/elementary-algebra/lib/engine.js b/site/elementary-algebra/lib/engine.js
index cb6d40b..a33c7db 100644
--- a/site/elementary-algebra/lib/engine.js
+++ b/site/elementary-algebra/lib/engine.js
@@ -38,7 +38,7 @@ const TRANSLATIONS = {
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',
+ chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice', sources: 'Sources in this chapter', opensSource: '{label}, opens the source in a new tab',
firstTryScore: '{name}: {r} of {t} right on the first try.', notAttempted: '{name}: not attempted.',
watchAgain: 'Watch again', nextChapter: 'Next chapter',
},
@@ -74,7 +74,7 @@ const TRANSLATIONS = {
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: 'Практика по главе',
+ chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе', sources: 'Источники этой главы', opensSource: '{label}, источник откроется в новой вкладке',
firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',
watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',
},
@@ -108,7 +108,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 左边 {n} 步',
natural: '正整数', whole: '非负整数', integers: '整数', rational: '有理数', irrational: '无理数', real: '实数', integerColumn: '整数',
trueLabel: '对', falseLabel: '错',
- chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习',
+ chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习', sources: '本章引用的文献', opensSource: '{label},在新标签页中打开来源',
firstTryScore: '{name}:第一次就答对 {r} / {t}。', notAttempted: '{name}:未作答。',
watchAgain: '再看一遍', nextChapter: '下一章',
},
@@ -142,7 +142,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 から左へ {n}',
natural: '自然数', whole: '0 以上の整数', integers: '整数', rational: '有理数', irrational: '無理数', real: '実数', integerColumn: '整数',
trueLabel: '正しい', falseLabel: '誤り',
- chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習',
+ chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習', sources: 'この章の出典', opensSource: '{label}(出典を新しいタブで開く)',
firstTryScore: '{name}:1 回目で {t} 問中 {r} 問正解。', notAttempted: '{name}:未挑戦。',
watchAgain: 'もう一度見る', nextChapter: '次の章へ',
},
@@ -298,6 +298,81 @@ function T(parent, str, { x = 0, y = 0, size = 30, fill = COL.chalk, font = UI,
t.style.whiteSpace = 'pre';
return put(t, { x, y, o });
}
+// A citation drawn in the picture that opens its source (REFS from ../refs.js, built by scripts/refs.py) in a new tab.
+// cite(p, key, opts) takes T's options; str overrides the label (default REFS[key].cite). Returns the <a>; animate it like T.
+const CITED = new Set();
+function cite(parent, key, { str, ...opts } = {}) {
+ const r = (typeof REFS === 'object' && REFS) ? REFS[key] : null;
+ if (!r) throw new Error(`cite: no reference "${key}" in refs.js`);
+ CITED.add(key);
+ if (!r.url) return T(parent, str || r.cite, opts);
+ linkStage();
+ const a = mk('a', { class: 'cite', href: r.url, target: '_blank', rel: 'noopener', 'aria-label': translate('opensSource', { label: r.cite }) }, parent);
+ const { o = 1, x = 0, y = 0, ...rest } = opts;
+ T(a, str || r.cite, { ...rest, fill: rest.fill || COL.chalk });
+ return put(a, { x, y, o });
+}
+// Any text in the picture or a card that equals a reference's cite label or one of its match strings (case-insensitive)
+// becomes a link to the source, so chapters write citations as plain text. Watched by citeObs (set up after the player).
+let CITE_RE = null, CITE_KEY = null;
+function citeIndex() {
+ if (CITE_RE !== null) return CITE_RE;
+ CITE_KEY = new Map();
+ for (const [k, r] of Object.entries(typeof REFS === 'object' && REFS ? REFS : {}))
+ for (const s of [r.cite, ...(r.match || [])]) if (s) CITE_KEY.set(s.toLowerCase(), k);
+ const alts = [...CITE_KEY.keys()].sort((a, b) => b.length - a.length).map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ return (CITE_RE = alts.length ? new RegExp(alts.join('|'), 'gi') : false);
+}
+function autoCite(root) {
+ const re = citeIndex();
+ if (!re) return;
+ const nodes = [];
+ if (root.nodeType === 3) nodes.push(root);
+ else if (root.nodeType === 1) for (let w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n; (n = w.nextNode());) nodes.push(n);
+ for (const n of nodes) {
+ const host = n.parentElement;
+ if (!host || host.closest('a, button, input, script, style, kbd')) continue; // no links inside controls
+ const ms = [...n.data.matchAll(re)];
+ if (!ms.length) continue;
+ const svg = host.namespaceURI === NS, frag = document.createDocumentFragment();
+ let i = 0, made = 0;
+ for (const m of ms) {
+ const k = CITE_KEY.get(m[0].toLowerCase()), r = REFS[k];
+ CITED.add(k);
+ if (!r.url) continue; // a work with no reliable online record stays plain text but is still listed
+ frag.append(n.data.slice(i, m.index));
+ const a = svg ? mk('a', { href: r.url }) : document.createElement('a');
+ if (!svg) a.href = r.url;
+ a.setAttribute('class', 'cite');
+ a.setAttribute('target', '_blank');
+ a.setAttribute('rel', 'noopener');
+ a.setAttribute('aria-label', translate('opensSource', { label: m[0] }));
+ if (svg) mk('tspan', {}, a).textContent = m[0]; else a.textContent = m[0];
+ frag.append(a);
+ i = m.index + m[0].length;
+ made++;
+ }
+ if (!made) continue; // replacing the node unchanged would re-trigger the observer
+ if (svg) linkStage();
+ frag.append(n.data.slice(i));
+ n.replaceWith(frag);
+ }
+}
+// The stage is announced as one image; once it holds a link it becomes a group, so the link stays reachable.
+function linkStage() { document.getElementById('stage').setAttribute('role', 'group'); }
+// Links that have faded out (or sit in a faded group) must not take clicks or Tab focus.
+function syncLinks() {
+ for (const a of scene.querySelectorAll('a.cite')) {
+ let o = 1;
+ for (let e = a; e && e !== scene; e = e.parentNode) o *= +(e.getAttribute('opacity') ?? 1);
+ const on = o > .5;
+ if (on === a._on) continue;
+ a._on = on;
+ a.style.pointerEvents = on ? '' : 'none';
+ if (on) { a.removeAttribute('tabindex'); a.removeAttribute('aria-hidden'); }
+ else { a.setAttribute('tabindex', '-1'); a.setAttribute('aria-hidden', 'true'); }
+ }
+}
const ctx2d = document.createElement('canvas').getContext('2d');
function textW(str, size, italic = false) { ctx2d.font = `${italic ? 'italic ' : ''}${size}px ${MATH}`; return ctx2d.measureText(str).width; }
const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|so|up|we|my)(?![A-Za-z]))[a-z]{1,2}|(?!(?:If|In|It|Is|On|At|No|So|Or|An|As|To|By|Up)(?![A-Za-z]))[a-z]?[A-Z]{1,3}[a-z]?)(?![A-Za-z])/g; // capitals: A, PV, nRT // short lowercase runs are variables (a, x, ab), except short English words
@@ -1244,7 +1319,7 @@ function finishCard() {
: isShortcut(e, 'r') ? (restart(), true) : false;
const guide = mascotEl(240);
c.append(h('div', 'finwrap', [guide, h('p', 'kicker', translate('chapterComplete', { n: CHAPTER.label ?? 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])]));
+ line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again]), sources()].filter(Boolean)));
setTimeout(() => mood(guide, 'happy'), 400);
}
@@ -1253,6 +1328,19 @@ const $ = id => document.getElementById(id);
// The volume control (volume.js, volume.css) lives in its own files next to this one, the same in every book.
document.head.append(Object.assign(document.createElement('script'), { src: new URL('volume.js', document.currentScript.src) }));
const kbd = s => h('kbd', '', s);
+// The chapter's sources: every key passed to cite() plus CHAPTER.refs, as full references that link to the source.
+function sources() {
+ for (const m of citeObs.takeRecords()) for (const n of m.addedNodes) autoCite(n); // link text added just now (a seek to the end)
+ const keys = [...new Set([...(CHAPTER.refs || []), ...CITED])].filter(k => typeof REFS === 'object' && REFS?.[k]);
+ if (!keys.length) return null;
+ const items = keys.map(k => REFS[k]).sort((a, b) => a.ref.localeCompare(b.ref)).map(r => {
+ if (!r.url) return h('li', '', r.ref);
+ const a = h('a', '', r.url.replace(/^https?:\/\//, ''));
+ Object.assign(a, { href: r.url, target: '_blank', rel: 'noopener' });
+ return h('li', '', [r.ref + ' ', a]);
+ });
+ return h('section', 'srcs', [h('h2', '', translate('sources')), h('ol', '', items)]);
+}
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
const SCORE = {}; // question id -> first-attempt {right, total}
@@ -1391,6 +1479,13 @@ 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; },
};
};
+// A choice question from the chapter's item bank: ITEMS from ./items.js, built by scripts/items.py from the
+// mcq-item-writer JSON. mcq('ID', onRight?) returns a quiz entry, so quiz(TOPR, [mcq('MB-03-01')], done) asks it.
+function mcq(id, onRight) {
+ const it = (typeof ITEMS === 'object' && ITEMS) ? ITEMS[id] : null;
+ if (!it) throw new Error(`mcq: no item "${id}" in items.js`);
+ return { id, prompt: it.prompt, build: choice(it.opts, it.right, it.why, it.no, onRight) };
+}
// 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) => {
@@ -1898,6 +1993,7 @@ function frame(now) {
evalTo(P.t);
if (P.t >= P.end) beatDone();
}
+ syncLinks();
ui();
requestAnimationFrame(frame);
}
@@ -1957,9 +2053,13 @@ const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
const restart = () => { for (const k in SCORE) delete SCORE[k]; hideCover(); seek(0, true); };
$('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
+ if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
});
+const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
+citeObs.observe(scene, { childList: true, subtree: true });
+citeObs.observe($('ui'), { childList: true, subtree: true });
$('bPlay').onclick = togglePlay;
$('bBack').onclick = () => { hideCover(); back1(); };
$('bRestart').onclick = restart;
diff --git a/site/joke-collection/lib/contents.css b/site/joke-collection/lib/contents.css
index 3f59f10..d8f7f70 100644
--- a/site/joke-collection/lib/contents.css
+++ b/site/joke-collection/lib/contents.css
@@ -26,6 +26,8 @@ a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
#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; }
+/* #references is its own view: the full list, reached from one link at the end of the contents. */
+body:not(.refsview) #refpage, .refsview #cover, .refsview #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; }
@@ -92,6 +94,26 @@ main#contents { padding-bottom: 80px; }
.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; } }
+/* ---------- references: every source the book cites, linked to its DOI or catalogue record ---------- */
+.refs-more { max-width: 1212px; margin: 44px auto 0; padding: 0 16px; }
+.refs-more[hidden] { display: none; }
+.refs-more a { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 14px; padding: 16px 20px; border-radius: 16px; background: var(--panel);
+ border: 1.5px solid var(--edge); text-decoration: none; transition: border-color .3s; }
+.refs-more a:hover { border-color: var(--dim); }
+.refs-more b { font: 500 22px/1.2 var(--book); }
+.refs-more span { color: var(--dim); font-size: 15px; }
+.refs-more i { margin-left: auto; font-style: normal; color: var(--quiz); font-weight: 600; font-size: 15px; }
+#refpage { padding-bottom: 80px; }
+.top .back { display: inline-flex; align-items: center; gap: 8px; padding: 6px 4px; font-weight: 600; text-decoration: none; color: var(--quiz); border-radius: 8px; }
+.top .rp-book { margin-left: auto; font: 500 18px/1.2 var(--book); color: var(--dim); }
+.top .rp-book i { color: var(--task); }
+.refs { max-width: 1212px; margin: 32px auto 0; padding: 0 16px; }
+.refs h1 { margin: 0 0 8px; font: 500 clamp(32px, 5vw, 44px)/1.1 var(--book); view-transition-name: none; }
+.refs .lead { margin: 0 0 26px; max-width: 46em; color: var(--dim); }
+.refs ol { margin: 0; padding: 0; list-style: none; color: var(--dim); font-size: 16px; line-height: 1.5; }
+.refs li { margin: 0 0 10px; padding-left: 2em; text-indent: -2em; }
+.refs a { color: var(--chalk); text-underline-offset: 3px; overflow-wrap: anywhere; }
+.refs a:hover { color: var(--quiz); }
.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); }
diff --git a/site/joke-collection/lib/contents.js b/site/joke-collection/lib/contents.js
index 6b3272b..7022eb5 100644
--- a/site/joke-collection/lib/contents.js
+++ b/site/joke-collection/lib/contents.js
@@ -1,6 +1,7 @@
/* 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. */
+ Contents.book({ units, start, hues }) with its chapter list. With refs.js (REFS, built by the skill's
+ scripts/refs.py) loaded first, the page also gets its References view (#references). */
'use strict';
// Observe aborted incoming transitions before the first rendering opportunity.
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
@@ -15,6 +16,10 @@ const Contents = (() => {
metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: { one: ' + {n} sample', other: ' + {n} samples' }, samples: 'Sample chapters, another look',
chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',
doneMark: '✓ Finished · ', lastMark: ' · Last opened',
+ references: 'References', viewAll: 'View all →', backToContents: '← Contents',
+ refsLead: 'Every work cited in the lessons. Each link opens the work’s DOI or library record in a new tab; works with no reliable online record are listed without a link.',
+ refsCount: { one: '{n} work cited in the lessons', other: '{n} works cited in the lessons' },
+ refsAllLinked: ', each linked to its source', refsSomeLinked: ', {n} linked to their sources',
},
ru: {
open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',
@@ -25,6 +30,10 @@ const Contents = (() => {
samples: 'Пробные главы в другом стиле',
chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',
doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',
+ references: 'Список литературы', viewAll: 'Весь список →', backToContents: '← Оглавление',
+ refsLead: 'Все работы, которые цитируются в уроках. Ссылка открывает DOI или библиотечную запись в новой вкладке; работы без надёжной записи в сети даны без ссылки.',
+ refsCount: { one: '{n} работа цитируется в уроках', few: '{n} работы цитируются в уроках', many: '{n} работ цитируются в уроках', other: '{n} работы цитируются в уроках' },
+ refsAllLinked: ', у каждой есть ссылка на источник', refsSomeLinked: ', ссылок на источник: {n}',
},
zh: {
open: '打开这本书', toCover: '返回封面', resume: '继续 · 第 {n} 章', unit: '第 {n} 单元', minutes: '{n} 分钟',
@@ -32,6 +41,9 @@ const Contents = (() => {
metaSamples: ' + {n} 个示例章', samples: '示例章,另一种风格',
chapterCount: '{n} 章', finished: '已完成 {done} / {n}',
doneMark: '✓ 已完成 · ', lastMark: ' · 上次打开',
+ references: '参考文献', viewAll: '查看全部 →', backToContents: '← 目录',
+ refsLead: '课程中引用的全部作品。每个链接会在新标签页中打开该作品的 DOI 或图书馆记录;没有可靠在线记录的作品不附链接。',
+ refsCount: '课程中引用了 {n} 部作品', refsAllLinked: ',均链接到来源', refsSomeLinked: ',其中 {n} 部链接到来源',
},
ja: {
open: '本を開く', toCover: '表紙に戻る', resume: '続きから · 第{n}章', unit: '単元 {n}', minutes: '{n}分',
@@ -39,6 +51,9 @@ const Contents = (() => {
metaSamples: ' + サンプル{n}章', samples: 'サンプル章(別のスタイル)',
chapterCount: '{n}章', finished: '{n}章中 {done}章 完了',
doneMark: '✓ 完了 · ', lastMark: ' · 最後に開いた章',
+ references: '参考文献', viewAll: 'すべて見る →', backToContents: '← 目次',
+ refsLead: '授業で引用したすべての著作です。リンクは著作の DOI または図書館の記録を新しいタブで開きます。信頼できるオンライン記録のない著作はリンクなしで載せています。',
+ refsCount: '授業で引用した著作 {n} 件', refsAllLinked: '、すべて出典へのリンクつき', refsSomeLinked: '、うち {n} 件は出典へのリンクつき',
},
};
const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
@@ -54,7 +69,7 @@ const Contents = (() => {
}
const $ = id => document.getElementById(id);
const id = n => 'ch' + String(n).padStart(2, '0');
- const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
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.
@@ -114,6 +129,20 @@ const Contents = (() => {
}
}
+ // The References view, from refs.js: full entries, each linked to its DOI or catalogue record. It appears as one
+ // link at the end of the contents only when the book cites something.
+ function references() {
+ const all = Object.values(typeof REFS === 'object' && REFS ? REFS : {});
+ if (!$('refList') || !all.length) return;
+ $('refList').innerHTML = all.sort((a, b) => a.ref.localeCompare(b.ref)).map(r => `<li>${esc(r.ref)}${r.url
+ ? ` <a href="${esc(r.url)}" target="_blank" rel="noopener">${esc(r.url.replace(/^https?:\/\//, ''))}</a>` : ''}</li>`).join('');
+ const linked = all.filter(r => r.url).length;
+ $('refsCount').textContent = translate('refsCount', { n: all.length }) +
+ (linked === all.length ? translate('refsAllLinked') : translate('refsSomeLinked', { n: linked }));
+ $('rpBook').innerHTML = document.querySelector('#contents .home strong')?.innerHTML || '';
+ $('refsMore').hidden = false;
+ }
+
// 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 = '';
@@ -134,21 +163,24 @@ const Contents = (() => {
}
}
- // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.
+ // The cover, the contents and the references share this page: no hash or #book shows the cover, #references the
+ // reference list, #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 refs = location.hash === '#references';
+ const open = location.hash.length > 1 && location.hash !== '#book' && !refs;
const apply = () => {
document.body.classList.toggle('open', open);
+ document.body.classList.toggle('refsview', refs);
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');
+ const heading = document.querySelector(refs ? '#refsTitle' : open ? '#contents .home' : '#cover h1');
heading?.setAttribute('tabindex', '-1');
heading?.focus({ preventScroll: true });
}
@@ -184,6 +216,7 @@ const Contents = (() => {
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));
+ references();
guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');
views();
}
diff --git a/site/joke-collection/lib/engine.css b/site/joke-collection/lib/engine.css
index 9b9be00..9e8e535 100644
--- a/site/joke-collection/lib/engine.css
+++ b/site/joke-collection/lib/engine.css
@@ -221,6 +221,22 @@ svg.m { display: inline-block; overflow: visible; }
@media (prefers-reduced-motion: reduce) { .card, .fb, .opt, .grid .mark, .mascot * { animation: none !important; } }
a.icon { text-decoration: none; }
+/* Citations (cite() and plain-text labels found in refs.js) and the finish card's source list open the source in a new tab. */
+a.cite { cursor: pointer; }
+a.cite text, a.cite tspan { text-decoration: underline; text-decoration-thickness: 1.5px; text-underline-offset: 5px; }
+a.cite:hover text, a.cite:hover tspan { fill: var(--quiz); }
+a.cite:focus { outline: none; }
+a.cite:focus-visible text, a.cite:focus-visible tspan { fill: var(--task); }
+a.cite:focus-visible { outline: 3px solid var(--task); outline-offset: 6px; border-radius: 4px; }
+#ui a.cite { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
+#ui a.cite:hover { color: var(--quiz); }
+.fin .srcs { margin: 26px 0 0; max-width: 1100px; font-size: 19px; line-height: 1.45; color: var(--dim); text-align: left; }
+.fin .srcs h2 { margin: 0 0 6px; font-size: 18px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
+.fin .srcs ol { margin: 0; padding-left: 0; list-style: none; max-height: 190px; overflow: auto; }
+.fin .srcs li { padding-left: 2em; text-indent: -2em; margin: 0 0 6px; }
+.fin .srcs a { color: var(--chalk); text-underline-offset: 3px; }
+.fin .srcs a:hover { color: var(--quiz); }
+.fin .srcs a:focus-visible { outline: 3px solid var(--task); outline-offset: 2px; }
a.btn { text-decoration: none; display: inline-block; }
/* Page-to-page motion: the contents card grows into this frame, and shrinks back on the way out. */
@view-transition { navigation: auto; }
diff --git a/site/joke-collection/lib/engine.js b/site/joke-collection/lib/engine.js
index cb6d40b..a33c7db 100644
--- a/site/joke-collection/lib/engine.js
+++ b/site/joke-collection/lib/engine.js
@@ -38,7 +38,7 @@ const TRANSLATIONS = {
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',
+ chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice', sources: 'Sources in this chapter', opensSource: '{label}, opens the source in a new tab',
firstTryScore: '{name}: {r} of {t} right on the first try.', notAttempted: '{name}: not attempted.',
watchAgain: 'Watch again', nextChapter: 'Next chapter',
},
@@ -74,7 +74,7 @@ const TRANSLATIONS = {
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: 'Практика по главе',
+ chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе', sources: 'Источники этой главы', opensSource: '{label}, источник откроется в новой вкладке',
firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',
watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',
},
@@ -108,7 +108,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 左边 {n} 步',
natural: '正整数', whole: '非负整数', integers: '整数', rational: '有理数', irrational: '无理数', real: '实数', integerColumn: '整数',
trueLabel: '对', falseLabel: '错',
- chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习',
+ chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习', sources: '本章引用的文献', opensSource: '{label},在新标签页中打开来源',
firstTryScore: '{name}:第一次就答对 {r} / {t}。', notAttempted: '{name}:未作答。',
watchAgain: '再看一遍', nextChapter: '下一章',
},
@@ -142,7 +142,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 から左へ {n}',
natural: '自然数', whole: '0 以上の整数', integers: '整数', rational: '有理数', irrational: '無理数', real: '実数', integerColumn: '整数',
trueLabel: '正しい', falseLabel: '誤り',
- chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習',
+ chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習', sources: 'この章の出典', opensSource: '{label}(出典を新しいタブで開く)',
firstTryScore: '{name}:1 回目で {t} 問中 {r} 問正解。', notAttempted: '{name}:未挑戦。',
watchAgain: 'もう一度見る', nextChapter: '次の章へ',
},
@@ -298,6 +298,81 @@ function T(parent, str, { x = 0, y = 0, size = 30, fill = COL.chalk, font = UI,
t.style.whiteSpace = 'pre';
return put(t, { x, y, o });
}
+// A citation drawn in the picture that opens its source (REFS from ../refs.js, built by scripts/refs.py) in a new tab.
+// cite(p, key, opts) takes T's options; str overrides the label (default REFS[key].cite). Returns the <a>; animate it like T.
+const CITED = new Set();
+function cite(parent, key, { str, ...opts } = {}) {
+ const r = (typeof REFS === 'object' && REFS) ? REFS[key] : null;
+ if (!r) throw new Error(`cite: no reference "${key}" in refs.js`);
+ CITED.add(key);
+ if (!r.url) return T(parent, str || r.cite, opts);
+ linkStage();
+ const a = mk('a', { class: 'cite', href: r.url, target: '_blank', rel: 'noopener', 'aria-label': translate('opensSource', { label: r.cite }) }, parent);
+ const { o = 1, x = 0, y = 0, ...rest } = opts;
+ T(a, str || r.cite, { ...rest, fill: rest.fill || COL.chalk });
+ return put(a, { x, y, o });
+}
+// Any text in the picture or a card that equals a reference's cite label or one of its match strings (case-insensitive)
+// becomes a link to the source, so chapters write citations as plain text. Watched by citeObs (set up after the player).
+let CITE_RE = null, CITE_KEY = null;
+function citeIndex() {
+ if (CITE_RE !== null) return CITE_RE;
+ CITE_KEY = new Map();
+ for (const [k, r] of Object.entries(typeof REFS === 'object' && REFS ? REFS : {}))
+ for (const s of [r.cite, ...(r.match || [])]) if (s) CITE_KEY.set(s.toLowerCase(), k);
+ const alts = [...CITE_KEY.keys()].sort((a, b) => b.length - a.length).map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ return (CITE_RE = alts.length ? new RegExp(alts.join('|'), 'gi') : false);
+}
+function autoCite(root) {
+ const re = citeIndex();
+ if (!re) return;
+ const nodes = [];
+ if (root.nodeType === 3) nodes.push(root);
+ else if (root.nodeType === 1) for (let w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n; (n = w.nextNode());) nodes.push(n);
+ for (const n of nodes) {
+ const host = n.parentElement;
+ if (!host || host.closest('a, button, input, script, style, kbd')) continue; // no links inside controls
+ const ms = [...n.data.matchAll(re)];
+ if (!ms.length) continue;
+ const svg = host.namespaceURI === NS, frag = document.createDocumentFragment();
+ let i = 0, made = 0;
+ for (const m of ms) {
+ const k = CITE_KEY.get(m[0].toLowerCase()), r = REFS[k];
+ CITED.add(k);
+ if (!r.url) continue; // a work with no reliable online record stays plain text but is still listed
+ frag.append(n.data.slice(i, m.index));
+ const a = svg ? mk('a', { href: r.url }) : document.createElement('a');
+ if (!svg) a.href = r.url;
+ a.setAttribute('class', 'cite');
+ a.setAttribute('target', '_blank');
+ a.setAttribute('rel', 'noopener');
+ a.setAttribute('aria-label', translate('opensSource', { label: m[0] }));
+ if (svg) mk('tspan', {}, a).textContent = m[0]; else a.textContent = m[0];
+ frag.append(a);
+ i = m.index + m[0].length;
+ made++;
+ }
+ if (!made) continue; // replacing the node unchanged would re-trigger the observer
+ if (svg) linkStage();
+ frag.append(n.data.slice(i));
+ n.replaceWith(frag);
+ }
+}
+// The stage is announced as one image; once it holds a link it becomes a group, so the link stays reachable.
+function linkStage() { document.getElementById('stage').setAttribute('role', 'group'); }
+// Links that have faded out (or sit in a faded group) must not take clicks or Tab focus.
+function syncLinks() {
+ for (const a of scene.querySelectorAll('a.cite')) {
+ let o = 1;
+ for (let e = a; e && e !== scene; e = e.parentNode) o *= +(e.getAttribute('opacity') ?? 1);
+ const on = o > .5;
+ if (on === a._on) continue;
+ a._on = on;
+ a.style.pointerEvents = on ? '' : 'none';
+ if (on) { a.removeAttribute('tabindex'); a.removeAttribute('aria-hidden'); }
+ else { a.setAttribute('tabindex', '-1'); a.setAttribute('aria-hidden', 'true'); }
+ }
+}
const ctx2d = document.createElement('canvas').getContext('2d');
function textW(str, size, italic = false) { ctx2d.font = `${italic ? 'italic ' : ''}${size}px ${MATH}`; return ctx2d.measureText(str).width; }
const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|so|up|we|my)(?![A-Za-z]))[a-z]{1,2}|(?!(?:If|In|It|Is|On|At|No|So|Or|An|As|To|By|Up)(?![A-Za-z]))[a-z]?[A-Z]{1,3}[a-z]?)(?![A-Za-z])/g; // capitals: A, PV, nRT // short lowercase runs are variables (a, x, ab), except short English words
@@ -1244,7 +1319,7 @@ function finishCard() {
: isShortcut(e, 'r') ? (restart(), true) : false;
const guide = mascotEl(240);
c.append(h('div', 'finwrap', [guide, h('p', 'kicker', translate('chapterComplete', { n: CHAPTER.label ?? 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])]));
+ line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again]), sources()].filter(Boolean)));
setTimeout(() => mood(guide, 'happy'), 400);
}
@@ -1253,6 +1328,19 @@ const $ = id => document.getElementById(id);
// The volume control (volume.js, volume.css) lives in its own files next to this one, the same in every book.
document.head.append(Object.assign(document.createElement('script'), { src: new URL('volume.js', document.currentScript.src) }));
const kbd = s => h('kbd', '', s);
+// The chapter's sources: every key passed to cite() plus CHAPTER.refs, as full references that link to the source.
+function sources() {
+ for (const m of citeObs.takeRecords()) for (const n of m.addedNodes) autoCite(n); // link text added just now (a seek to the end)
+ const keys = [...new Set([...(CHAPTER.refs || []), ...CITED])].filter(k => typeof REFS === 'object' && REFS?.[k]);
+ if (!keys.length) return null;
+ const items = keys.map(k => REFS[k]).sort((a, b) => a.ref.localeCompare(b.ref)).map(r => {
+ if (!r.url) return h('li', '', r.ref);
+ const a = h('a', '', r.url.replace(/^https?:\/\//, ''));
+ Object.assign(a, { href: r.url, target: '_blank', rel: 'noopener' });
+ return h('li', '', [r.ref + ' ', a]);
+ });
+ return h('section', 'srcs', [h('h2', '', translate('sources')), h('ol', '', items)]);
+}
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
const SCORE = {}; // question id -> first-attempt {right, total}
@@ -1391,6 +1479,13 @@ 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; },
};
};
+// A choice question from the chapter's item bank: ITEMS from ./items.js, built by scripts/items.py from the
+// mcq-item-writer JSON. mcq('ID', onRight?) returns a quiz entry, so quiz(TOPR, [mcq('MB-03-01')], done) asks it.
+function mcq(id, onRight) {
+ const it = (typeof ITEMS === 'object' && ITEMS) ? ITEMS[id] : null;
+ if (!it) throw new Error(`mcq: no item "${id}" in items.js`);
+ return { id, prompt: it.prompt, build: choice(it.opts, it.right, it.why, it.no, onRight) };
+}
// 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) => {
@@ -1898,6 +1993,7 @@ function frame(now) {
evalTo(P.t);
if (P.t >= P.end) beatDone();
}
+ syncLinks();
ui();
requestAnimationFrame(frame);
}
@@ -1957,9 +2053,13 @@ const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
const restart = () => { for (const k in SCORE) delete SCORE[k]; hideCover(); seek(0, true); };
$('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
+ if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
});
+const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
+citeObs.observe(scene, { childList: true, subtree: true });
+citeObs.observe($('ui'), { childList: true, subtree: true });
$('bPlay').onclick = togglePlay;
$('bBack').onclick = () => { hideCover(); back1(); };
$('bRestart').onclick = restart;
diff --git a/site/little-red-riding-hood/lib/contents.css b/site/little-red-riding-hood/lib/contents.css
index 3f59f10..d8f7f70 100644
--- a/site/little-red-riding-hood/lib/contents.css
+++ b/site/little-red-riding-hood/lib/contents.css
@@ -26,6 +26,8 @@ a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
#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; }
+/* #references is its own view: the full list, reached from one link at the end of the contents. */
+body:not(.refsview) #refpage, .refsview #cover, .refsview #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; }
@@ -92,6 +94,26 @@ main#contents { padding-bottom: 80px; }
.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; } }
+/* ---------- references: every source the book cites, linked to its DOI or catalogue record ---------- */
+.refs-more { max-width: 1212px; margin: 44px auto 0; padding: 0 16px; }
+.refs-more[hidden] { display: none; }
+.refs-more a { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 14px; padding: 16px 20px; border-radius: 16px; background: var(--panel);
+ border: 1.5px solid var(--edge); text-decoration: none; transition: border-color .3s; }
+.refs-more a:hover { border-color: var(--dim); }
+.refs-more b { font: 500 22px/1.2 var(--book); }
+.refs-more span { color: var(--dim); font-size: 15px; }
+.refs-more i { margin-left: auto; font-style: normal; color: var(--quiz); font-weight: 600; font-size: 15px; }
+#refpage { padding-bottom: 80px; }
+.top .back { display: inline-flex; align-items: center; gap: 8px; padding: 6px 4px; font-weight: 600; text-decoration: none; color: var(--quiz); border-radius: 8px; }
+.top .rp-book { margin-left: auto; font: 500 18px/1.2 var(--book); color: var(--dim); }
+.top .rp-book i { color: var(--task); }
+.refs { max-width: 1212px; margin: 32px auto 0; padding: 0 16px; }
+.refs h1 { margin: 0 0 8px; font: 500 clamp(32px, 5vw, 44px)/1.1 var(--book); view-transition-name: none; }
+.refs .lead { margin: 0 0 26px; max-width: 46em; color: var(--dim); }
+.refs ol { margin: 0; padding: 0; list-style: none; color: var(--dim); font-size: 16px; line-height: 1.5; }
+.refs li { margin: 0 0 10px; padding-left: 2em; text-indent: -2em; }
+.refs a { color: var(--chalk); text-underline-offset: 3px; overflow-wrap: anywhere; }
+.refs a:hover { color: var(--quiz); }
.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); }
diff --git a/site/little-red-riding-hood/lib/contents.js b/site/little-red-riding-hood/lib/contents.js
index 6b3272b..7022eb5 100644
--- a/site/little-red-riding-hood/lib/contents.js
+++ b/site/little-red-riding-hood/lib/contents.js
@@ -1,6 +1,7 @@
/* 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. */
+ Contents.book({ units, start, hues }) with its chapter list. With refs.js (REFS, built by the skill's
+ scripts/refs.py) loaded first, the page also gets its References view (#references). */
'use strict';
// Observe aborted incoming transitions before the first rendering opportunity.
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
@@ -15,6 +16,10 @@ const Contents = (() => {
metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: { one: ' + {n} sample', other: ' + {n} samples' }, samples: 'Sample chapters, another look',
chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',
doneMark: '✓ Finished · ', lastMark: ' · Last opened',
+ references: 'References', viewAll: 'View all →', backToContents: '← Contents',
+ refsLead: 'Every work cited in the lessons. Each link opens the work’s DOI or library record in a new tab; works with no reliable online record are listed without a link.',
+ refsCount: { one: '{n} work cited in the lessons', other: '{n} works cited in the lessons' },
+ refsAllLinked: ', each linked to its source', refsSomeLinked: ', {n} linked to their sources',
},
ru: {
open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',
@@ -25,6 +30,10 @@ const Contents = (() => {
samples: 'Пробные главы в другом стиле',
chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',
doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',
+ references: 'Список литературы', viewAll: 'Весь список →', backToContents: '← Оглавление',
+ refsLead: 'Все работы, которые цитируются в уроках. Ссылка открывает DOI или библиотечную запись в новой вкладке; работы без надёжной записи в сети даны без ссылки.',
+ refsCount: { one: '{n} работа цитируется в уроках', few: '{n} работы цитируются в уроках', many: '{n} работ цитируются в уроках', other: '{n} работы цитируются в уроках' },
+ refsAllLinked: ', у каждой есть ссылка на источник', refsSomeLinked: ', ссылок на источник: {n}',
},
zh: {
open: '打开这本书', toCover: '返回封面', resume: '继续 · 第 {n} 章', unit: '第 {n} 单元', minutes: '{n} 分钟',
@@ -32,6 +41,9 @@ const Contents = (() => {
metaSamples: ' + {n} 个示例章', samples: '示例章,另一种风格',
chapterCount: '{n} 章', finished: '已完成 {done} / {n}',
doneMark: '✓ 已完成 · ', lastMark: ' · 上次打开',
+ references: '参考文献', viewAll: '查看全部 →', backToContents: '← 目录',
+ refsLead: '课程中引用的全部作品。每个链接会在新标签页中打开该作品的 DOI 或图书馆记录;没有可靠在线记录的作品不附链接。',
+ refsCount: '课程中引用了 {n} 部作品', refsAllLinked: ',均链接到来源', refsSomeLinked: ',其中 {n} 部链接到来源',
},
ja: {
open: '本を開く', toCover: '表紙に戻る', resume: '続きから · 第{n}章', unit: '単元 {n}', minutes: '{n}分',
@@ -39,6 +51,9 @@ const Contents = (() => {
metaSamples: ' + サンプル{n}章', samples: 'サンプル章(別のスタイル)',
chapterCount: '{n}章', finished: '{n}章中 {done}章 完了',
doneMark: '✓ 完了 · ', lastMark: ' · 最後に開いた章',
+ references: '参考文献', viewAll: 'すべて見る →', backToContents: '← 目次',
+ refsLead: '授業で引用したすべての著作です。リンクは著作の DOI または図書館の記録を新しいタブで開きます。信頼できるオンライン記録のない著作はリンクなしで載せています。',
+ refsCount: '授業で引用した著作 {n} 件', refsAllLinked: '、すべて出典へのリンクつき', refsSomeLinked: '、うち {n} 件は出典へのリンクつき',
},
};
const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
@@ -54,7 +69,7 @@ const Contents = (() => {
}
const $ = id => document.getElementById(id);
const id = n => 'ch' + String(n).padStart(2, '0');
- const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
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.
@@ -114,6 +129,20 @@ const Contents = (() => {
}
}
+ // The References view, from refs.js: full entries, each linked to its DOI or catalogue record. It appears as one
+ // link at the end of the contents only when the book cites something.
+ function references() {
+ const all = Object.values(typeof REFS === 'object' && REFS ? REFS : {});
+ if (!$('refList') || !all.length) return;
+ $('refList').innerHTML = all.sort((a, b) => a.ref.localeCompare(b.ref)).map(r => `<li>${esc(r.ref)}${r.url
+ ? ` <a href="${esc(r.url)}" target="_blank" rel="noopener">${esc(r.url.replace(/^https?:\/\//, ''))}</a>` : ''}</li>`).join('');
+ const linked = all.filter(r => r.url).length;
+ $('refsCount').textContent = translate('refsCount', { n: all.length }) +
+ (linked === all.length ? translate('refsAllLinked') : translate('refsSomeLinked', { n: linked }));
+ $('rpBook').innerHTML = document.querySelector('#contents .home strong')?.innerHTML || '';
+ $('refsMore').hidden = false;
+ }
+
// 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 = '';
@@ -134,21 +163,24 @@ const Contents = (() => {
}
}
- // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.
+ // The cover, the contents and the references share this page: no hash or #book shows the cover, #references the
+ // reference list, #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 refs = location.hash === '#references';
+ const open = location.hash.length > 1 && location.hash !== '#book' && !refs;
const apply = () => {
document.body.classList.toggle('open', open);
+ document.body.classList.toggle('refsview', refs);
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');
+ const heading = document.querySelector(refs ? '#refsTitle' : open ? '#contents .home' : '#cover h1');
heading?.setAttribute('tabindex', '-1');
heading?.focus({ preventScroll: true });
}
@@ -184,6 +216,7 @@ const Contents = (() => {
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));
+ references();
guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');
views();
}
diff --git a/site/little-red-riding-hood/lib/engine.css b/site/little-red-riding-hood/lib/engine.css
index 9b9be00..9e8e535 100644
--- a/site/little-red-riding-hood/lib/engine.css
+++ b/site/little-red-riding-hood/lib/engine.css
@@ -221,6 +221,22 @@ svg.m { display: inline-block; overflow: visible; }
@media (prefers-reduced-motion: reduce) { .card, .fb, .opt, .grid .mark, .mascot * { animation: none !important; } }
a.icon { text-decoration: none; }
+/* Citations (cite() and plain-text labels found in refs.js) and the finish card's source list open the source in a new tab. */
+a.cite { cursor: pointer; }
+a.cite text, a.cite tspan { text-decoration: underline; text-decoration-thickness: 1.5px; text-underline-offset: 5px; }
+a.cite:hover text, a.cite:hover tspan { fill: var(--quiz); }
+a.cite:focus { outline: none; }
+a.cite:focus-visible text, a.cite:focus-visible tspan { fill: var(--task); }
+a.cite:focus-visible { outline: 3px solid var(--task); outline-offset: 6px; border-radius: 4px; }
+#ui a.cite { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
+#ui a.cite:hover { color: var(--quiz); }
+.fin .srcs { margin: 26px 0 0; max-width: 1100px; font-size: 19px; line-height: 1.45; color: var(--dim); text-align: left; }
+.fin .srcs h2 { margin: 0 0 6px; font-size: 18px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
+.fin .srcs ol { margin: 0; padding-left: 0; list-style: none; max-height: 190px; overflow: auto; }
+.fin .srcs li { padding-left: 2em; text-indent: -2em; margin: 0 0 6px; }
+.fin .srcs a { color: var(--chalk); text-underline-offset: 3px; }
+.fin .srcs a:hover { color: var(--quiz); }
+.fin .srcs a:focus-visible { outline: 3px solid var(--task); outline-offset: 2px; }
a.btn { text-decoration: none; display: inline-block; }
/* Page-to-page motion: the contents card grows into this frame, and shrinks back on the way out. */
@view-transition { navigation: auto; }
diff --git a/site/little-red-riding-hood/lib/engine.js b/site/little-red-riding-hood/lib/engine.js
index cb6d40b..a33c7db 100644
--- a/site/little-red-riding-hood/lib/engine.js
+++ b/site/little-red-riding-hood/lib/engine.js
@@ -38,7 +38,7 @@ const TRANSLATIONS = {
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',
+ chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice', sources: 'Sources in this chapter', opensSource: '{label}, opens the source in a new tab',
firstTryScore: '{name}: {r} of {t} right on the first try.', notAttempted: '{name}: not attempted.',
watchAgain: 'Watch again', nextChapter: 'Next chapter',
},
@@ -74,7 +74,7 @@ const TRANSLATIONS = {
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: 'Практика по главе',
+ chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе', sources: 'Источники этой главы', opensSource: '{label}, источник откроется в новой вкладке',
firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',
watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',
},
@@ -108,7 +108,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 左边 {n} 步',
natural: '正整数', whole: '非负整数', integers: '整数', rational: '有理数', irrational: '无理数', real: '实数', integerColumn: '整数',
trueLabel: '对', falseLabel: '错',
- chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习',
+ chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习', sources: '本章引用的文献', opensSource: '{label},在新标签页中打开来源',
firstTryScore: '{name}:第一次就答对 {r} / {t}。', notAttempted: '{name}:未作答。',
watchAgain: '再看一遍', nextChapter: '下一章',
},
@@ -142,7 +142,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 から左へ {n}',
natural: '自然数', whole: '0 以上の整数', integers: '整数', rational: '有理数', irrational: '無理数', real: '実数', integerColumn: '整数',
trueLabel: '正しい', falseLabel: '誤り',
- chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習',
+ chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習', sources: 'この章の出典', opensSource: '{label}(出典を新しいタブで開く)',
firstTryScore: '{name}:1 回目で {t} 問中 {r} 問正解。', notAttempted: '{name}:未挑戦。',
watchAgain: 'もう一度見る', nextChapter: '次の章へ',
},
@@ -298,6 +298,81 @@ function T(parent, str, { x = 0, y = 0, size = 30, fill = COL.chalk, font = UI,
t.style.whiteSpace = 'pre';
return put(t, { x, y, o });
}
+// A citation drawn in the picture that opens its source (REFS from ../refs.js, built by scripts/refs.py) in a new tab.
+// cite(p, key, opts) takes T's options; str overrides the label (default REFS[key].cite). Returns the <a>; animate it like T.
+const CITED = new Set();
+function cite(parent, key, { str, ...opts } = {}) {
+ const r = (typeof REFS === 'object' && REFS) ? REFS[key] : null;
+ if (!r) throw new Error(`cite: no reference "${key}" in refs.js`);
+ CITED.add(key);
+ if (!r.url) return T(parent, str || r.cite, opts);
+ linkStage();
+ const a = mk('a', { class: 'cite', href: r.url, target: '_blank', rel: 'noopener', 'aria-label': translate('opensSource', { label: r.cite }) }, parent);
+ const { o = 1, x = 0, y = 0, ...rest } = opts;
+ T(a, str || r.cite, { ...rest, fill: rest.fill || COL.chalk });
+ return put(a, { x, y, o });
+}
+// Any text in the picture or a card that equals a reference's cite label or one of its match strings (case-insensitive)
+// becomes a link to the source, so chapters write citations as plain text. Watched by citeObs (set up after the player).
+let CITE_RE = null, CITE_KEY = null;
+function citeIndex() {
+ if (CITE_RE !== null) return CITE_RE;
+ CITE_KEY = new Map();
+ for (const [k, r] of Object.entries(typeof REFS === 'object' && REFS ? REFS : {}))
+ for (const s of [r.cite, ...(r.match || [])]) if (s) CITE_KEY.set(s.toLowerCase(), k);
+ const alts = [...CITE_KEY.keys()].sort((a, b) => b.length - a.length).map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ return (CITE_RE = alts.length ? new RegExp(alts.join('|'), 'gi') : false);
+}
+function autoCite(root) {
+ const re = citeIndex();
+ if (!re) return;
+ const nodes = [];
+ if (root.nodeType === 3) nodes.push(root);
+ else if (root.nodeType === 1) for (let w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n; (n = w.nextNode());) nodes.push(n);
+ for (const n of nodes) {
+ const host = n.parentElement;
+ if (!host || host.closest('a, button, input, script, style, kbd')) continue; // no links inside controls
+ const ms = [...n.data.matchAll(re)];
+ if (!ms.length) continue;
+ const svg = host.namespaceURI === NS, frag = document.createDocumentFragment();
+ let i = 0, made = 0;
+ for (const m of ms) {
+ const k = CITE_KEY.get(m[0].toLowerCase()), r = REFS[k];
+ CITED.add(k);
+ if (!r.url) continue; // a work with no reliable online record stays plain text but is still listed
+ frag.append(n.data.slice(i, m.index));
+ const a = svg ? mk('a', { href: r.url }) : document.createElement('a');
+ if (!svg) a.href = r.url;
+ a.setAttribute('class', 'cite');
+ a.setAttribute('target', '_blank');
+ a.setAttribute('rel', 'noopener');
+ a.setAttribute('aria-label', translate('opensSource', { label: m[0] }));
+ if (svg) mk('tspan', {}, a).textContent = m[0]; else a.textContent = m[0];
+ frag.append(a);
+ i = m.index + m[0].length;
+ made++;
+ }
+ if (!made) continue; // replacing the node unchanged would re-trigger the observer
+ if (svg) linkStage();
+ frag.append(n.data.slice(i));
+ n.replaceWith(frag);
+ }
+}
+// The stage is announced as one image; once it holds a link it becomes a group, so the link stays reachable.
+function linkStage() { document.getElementById('stage').setAttribute('role', 'group'); }
+// Links that have faded out (or sit in a faded group) must not take clicks or Tab focus.
+function syncLinks() {
+ for (const a of scene.querySelectorAll('a.cite')) {
+ let o = 1;
+ for (let e = a; e && e !== scene; e = e.parentNode) o *= +(e.getAttribute('opacity') ?? 1);
+ const on = o > .5;
+ if (on === a._on) continue;
+ a._on = on;
+ a.style.pointerEvents = on ? '' : 'none';
+ if (on) { a.removeAttribute('tabindex'); a.removeAttribute('aria-hidden'); }
+ else { a.setAttribute('tabindex', '-1'); a.setAttribute('aria-hidden', 'true'); }
+ }
+}
const ctx2d = document.createElement('canvas').getContext('2d');
function textW(str, size, italic = false) { ctx2d.font = `${italic ? 'italic ' : ''}${size}px ${MATH}`; return ctx2d.measureText(str).width; }
const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|so|up|we|my)(?![A-Za-z]))[a-z]{1,2}|(?!(?:If|In|It|Is|On|At|No|So|Or|An|As|To|By|Up)(?![A-Za-z]))[a-z]?[A-Z]{1,3}[a-z]?)(?![A-Za-z])/g; // capitals: A, PV, nRT // short lowercase runs are variables (a, x, ab), except short English words
@@ -1244,7 +1319,7 @@ function finishCard() {
: isShortcut(e, 'r') ? (restart(), true) : false;
const guide = mascotEl(240);
c.append(h('div', 'finwrap', [guide, h('p', 'kicker', translate('chapterComplete', { n: CHAPTER.label ?? 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])]));
+ line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again]), sources()].filter(Boolean)));
setTimeout(() => mood(guide, 'happy'), 400);
}
@@ -1253,6 +1328,19 @@ const $ = id => document.getElementById(id);
// The volume control (volume.js, volume.css) lives in its own files next to this one, the same in every book.
document.head.append(Object.assign(document.createElement('script'), { src: new URL('volume.js', document.currentScript.src) }));
const kbd = s => h('kbd', '', s);
+// The chapter's sources: every key passed to cite() plus CHAPTER.refs, as full references that link to the source.
+function sources() {
+ for (const m of citeObs.takeRecords()) for (const n of m.addedNodes) autoCite(n); // link text added just now (a seek to the end)
+ const keys = [...new Set([...(CHAPTER.refs || []), ...CITED])].filter(k => typeof REFS === 'object' && REFS?.[k]);
+ if (!keys.length) return null;
+ const items = keys.map(k => REFS[k]).sort((a, b) => a.ref.localeCompare(b.ref)).map(r => {
+ if (!r.url) return h('li', '', r.ref);
+ const a = h('a', '', r.url.replace(/^https?:\/\//, ''));
+ Object.assign(a, { href: r.url, target: '_blank', rel: 'noopener' });
+ return h('li', '', [r.ref + ' ', a]);
+ });
+ return h('section', 'srcs', [h('h2', '', translate('sources')), h('ol', '', items)]);
+}
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
const SCORE = {}; // question id -> first-attempt {right, total}
@@ -1391,6 +1479,13 @@ 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; },
};
};
+// A choice question from the chapter's item bank: ITEMS from ./items.js, built by scripts/items.py from the
+// mcq-item-writer JSON. mcq('ID', onRight?) returns a quiz entry, so quiz(TOPR, [mcq('MB-03-01')], done) asks it.
+function mcq(id, onRight) {
+ const it = (typeof ITEMS === 'object' && ITEMS) ? ITEMS[id] : null;
+ if (!it) throw new Error(`mcq: no item "${id}" in items.js`);
+ return { id, prompt: it.prompt, build: choice(it.opts, it.right, it.why, it.no, onRight) };
+}
// 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) => {
@@ -1898,6 +1993,7 @@ function frame(now) {
evalTo(P.t);
if (P.t >= P.end) beatDone();
}
+ syncLinks();
ui();
requestAnimationFrame(frame);
}
@@ -1957,9 +2053,13 @@ const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
const restart = () => { for (const k in SCORE) delete SCORE[k]; hideCover(); seek(0, true); };
$('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
+ if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
});
+const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
+citeObs.observe(scene, { childList: true, subtree: true });
+citeObs.observe($('ui'), { childList: true, subtree: true });
$('bPlay').onclick = togglePlay;
$('bBack').onclick = () => { hideCover(); back1(); };
$('bRestart').onclick = restart;
diff --git a/site/math-notebook/lib/contents.css b/site/math-notebook/lib/contents.css
index 3f59f10..d8f7f70 100644
--- a/site/math-notebook/lib/contents.css
+++ b/site/math-notebook/lib/contents.css
@@ -26,6 +26,8 @@ a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
#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; }
+/* #references is its own view: the full list, reached from one link at the end of the contents. */
+body:not(.refsview) #refpage, .refsview #cover, .refsview #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; }
@@ -92,6 +94,26 @@ main#contents { padding-bottom: 80px; }
.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; } }
+/* ---------- references: every source the book cites, linked to its DOI or catalogue record ---------- */
+.refs-more { max-width: 1212px; margin: 44px auto 0; padding: 0 16px; }
+.refs-more[hidden] { display: none; }
+.refs-more a { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 14px; padding: 16px 20px; border-radius: 16px; background: var(--panel);
+ border: 1.5px solid var(--edge); text-decoration: none; transition: border-color .3s; }
+.refs-more a:hover { border-color: var(--dim); }
+.refs-more b { font: 500 22px/1.2 var(--book); }
+.refs-more span { color: var(--dim); font-size: 15px; }
+.refs-more i { margin-left: auto; font-style: normal; color: var(--quiz); font-weight: 600; font-size: 15px; }
+#refpage { padding-bottom: 80px; }
+.top .back { display: inline-flex; align-items: center; gap: 8px; padding: 6px 4px; font-weight: 600; text-decoration: none; color: var(--quiz); border-radius: 8px; }
+.top .rp-book { margin-left: auto; font: 500 18px/1.2 var(--book); color: var(--dim); }
+.top .rp-book i { color: var(--task); }
+.refs { max-width: 1212px; margin: 32px auto 0; padding: 0 16px; }
+.refs h1 { margin: 0 0 8px; font: 500 clamp(32px, 5vw, 44px)/1.1 var(--book); view-transition-name: none; }
+.refs .lead { margin: 0 0 26px; max-width: 46em; color: var(--dim); }
+.refs ol { margin: 0; padding: 0; list-style: none; color: var(--dim); font-size: 16px; line-height: 1.5; }
+.refs li { margin: 0 0 10px; padding-left: 2em; text-indent: -2em; }
+.refs a { color: var(--chalk); text-underline-offset: 3px; overflow-wrap: anywhere; }
+.refs a:hover { color: var(--quiz); }
.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); }
diff --git a/site/math-notebook/lib/contents.js b/site/math-notebook/lib/contents.js
index 6b3272b..7022eb5 100644
--- a/site/math-notebook/lib/contents.js
+++ b/site/math-notebook/lib/contents.js
@@ -1,6 +1,7 @@
/* 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. */
+ Contents.book({ units, start, hues }) with its chapter list. With refs.js (REFS, built by the skill's
+ scripts/refs.py) loaded first, the page also gets its References view (#references). */
'use strict';
// Observe aborted incoming transitions before the first rendering opportunity.
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
@@ -15,6 +16,10 @@ const Contents = (() => {
metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: { one: ' + {n} sample', other: ' + {n} samples' }, samples: 'Sample chapters, another look',
chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',
doneMark: '✓ Finished · ', lastMark: ' · Last opened',
+ references: 'References', viewAll: 'View all →', backToContents: '← Contents',
+ refsLead: 'Every work cited in the lessons. Each link opens the work’s DOI or library record in a new tab; works with no reliable online record are listed without a link.',
+ refsCount: { one: '{n} work cited in the lessons', other: '{n} works cited in the lessons' },
+ refsAllLinked: ', each linked to its source', refsSomeLinked: ', {n} linked to their sources',
},
ru: {
open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',
@@ -25,6 +30,10 @@ const Contents = (() => {
samples: 'Пробные главы в другом стиле',
chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',
doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',
+ references: 'Список литературы', viewAll: 'Весь список →', backToContents: '← Оглавление',
+ refsLead: 'Все работы, которые цитируются в уроках. Ссылка открывает DOI или библиотечную запись в новой вкладке; работы без надёжной записи в сети даны без ссылки.',
+ refsCount: { one: '{n} работа цитируется в уроках', few: '{n} работы цитируются в уроках', many: '{n} работ цитируются в уроках', other: '{n} работы цитируются в уроках' },
+ refsAllLinked: ', у каждой есть ссылка на источник', refsSomeLinked: ', ссылок на источник: {n}',
},
zh: {
open: '打开这本书', toCover: '返回封面', resume: '继续 · 第 {n} 章', unit: '第 {n} 单元', minutes: '{n} 分钟',
@@ -32,6 +41,9 @@ const Contents = (() => {
metaSamples: ' + {n} 个示例章', samples: '示例章,另一种风格',
chapterCount: '{n} 章', finished: '已完成 {done} / {n}',
doneMark: '✓ 已完成 · ', lastMark: ' · 上次打开',
+ references: '参考文献', viewAll: '查看全部 →', backToContents: '← 目录',
+ refsLead: '课程中引用的全部作品。每个链接会在新标签页中打开该作品的 DOI 或图书馆记录;没有可靠在线记录的作品不附链接。',
+ refsCount: '课程中引用了 {n} 部作品', refsAllLinked: ',均链接到来源', refsSomeLinked: ',其中 {n} 部链接到来源',
},
ja: {
open: '本を開く', toCover: '表紙に戻る', resume: '続きから · 第{n}章', unit: '単元 {n}', minutes: '{n}分',
@@ -39,6 +51,9 @@ const Contents = (() => {
metaSamples: ' + サンプル{n}章', samples: 'サンプル章(別のスタイル)',
chapterCount: '{n}章', finished: '{n}章中 {done}章 完了',
doneMark: '✓ 完了 · ', lastMark: ' · 最後に開いた章',
+ references: '参考文献', viewAll: 'すべて見る →', backToContents: '← 目次',
+ refsLead: '授業で引用したすべての著作です。リンクは著作の DOI または図書館の記録を新しいタブで開きます。信頼できるオンライン記録のない著作はリンクなしで載せています。',
+ refsCount: '授業で引用した著作 {n} 件', refsAllLinked: '、すべて出典へのリンクつき', refsSomeLinked: '、うち {n} 件は出典へのリンクつき',
},
};
const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
@@ -54,7 +69,7 @@ const Contents = (() => {
}
const $ = id => document.getElementById(id);
const id = n => 'ch' + String(n).padStart(2, '0');
- const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
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.
@@ -114,6 +129,20 @@ const Contents = (() => {
}
}
+ // The References view, from refs.js: full entries, each linked to its DOI or catalogue record. It appears as one
+ // link at the end of the contents only when the book cites something.
+ function references() {
+ const all = Object.values(typeof REFS === 'object' && REFS ? REFS : {});
+ if (!$('refList') || !all.length) return;
+ $('refList').innerHTML = all.sort((a, b) => a.ref.localeCompare(b.ref)).map(r => `<li>${esc(r.ref)}${r.url
+ ? ` <a href="${esc(r.url)}" target="_blank" rel="noopener">${esc(r.url.replace(/^https?:\/\//, ''))}</a>` : ''}</li>`).join('');
+ const linked = all.filter(r => r.url).length;
+ $('refsCount').textContent = translate('refsCount', { n: all.length }) +
+ (linked === all.length ? translate('refsAllLinked') : translate('refsSomeLinked', { n: linked }));
+ $('rpBook').innerHTML = document.querySelector('#contents .home strong')?.innerHTML || '';
+ $('refsMore').hidden = false;
+ }
+
// 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 = '';
@@ -134,21 +163,24 @@ const Contents = (() => {
}
}
- // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.
+ // The cover, the contents and the references share this page: no hash or #book shows the cover, #references the
+ // reference list, #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 refs = location.hash === '#references';
+ const open = location.hash.length > 1 && location.hash !== '#book' && !refs;
const apply = () => {
document.body.classList.toggle('open', open);
+ document.body.classList.toggle('refsview', refs);
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');
+ const heading = document.querySelector(refs ? '#refsTitle' : open ? '#contents .home' : '#cover h1');
heading?.setAttribute('tabindex', '-1');
heading?.focus({ preventScroll: true });
}
@@ -184,6 +216,7 @@ const Contents = (() => {
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));
+ references();
guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');
views();
}
diff --git a/site/math-notebook/lib/engine.css b/site/math-notebook/lib/engine.css
index 9b9be00..9e8e535 100644
--- a/site/math-notebook/lib/engine.css
+++ b/site/math-notebook/lib/engine.css
@@ -221,6 +221,22 @@ svg.m { display: inline-block; overflow: visible; }
@media (prefers-reduced-motion: reduce) { .card, .fb, .opt, .grid .mark, .mascot * { animation: none !important; } }
a.icon { text-decoration: none; }
+/* Citations (cite() and plain-text labels found in refs.js) and the finish card's source list open the source in a new tab. */
+a.cite { cursor: pointer; }
+a.cite text, a.cite tspan { text-decoration: underline; text-decoration-thickness: 1.5px; text-underline-offset: 5px; }
+a.cite:hover text, a.cite:hover tspan { fill: var(--quiz); }
+a.cite:focus { outline: none; }
+a.cite:focus-visible text, a.cite:focus-visible tspan { fill: var(--task); }
+a.cite:focus-visible { outline: 3px solid var(--task); outline-offset: 6px; border-radius: 4px; }
+#ui a.cite { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
+#ui a.cite:hover { color: var(--quiz); }
+.fin .srcs { margin: 26px 0 0; max-width: 1100px; font-size: 19px; line-height: 1.45; color: var(--dim); text-align: left; }
+.fin .srcs h2 { margin: 0 0 6px; font-size: 18px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
+.fin .srcs ol { margin: 0; padding-left: 0; list-style: none; max-height: 190px; overflow: auto; }
+.fin .srcs li { padding-left: 2em; text-indent: -2em; margin: 0 0 6px; }
+.fin .srcs a { color: var(--chalk); text-underline-offset: 3px; }
+.fin .srcs a:hover { color: var(--quiz); }
+.fin .srcs a:focus-visible { outline: 3px solid var(--task); outline-offset: 2px; }
a.btn { text-decoration: none; display: inline-block; }
/* Page-to-page motion: the contents card grows into this frame, and shrinks back on the way out. */
@view-transition { navigation: auto; }
diff --git a/site/math-notebook/lib/engine.js b/site/math-notebook/lib/engine.js
index cb6d40b..a33c7db 100644
--- a/site/math-notebook/lib/engine.js
+++ b/site/math-notebook/lib/engine.js
@@ -38,7 +38,7 @@ const TRANSLATIONS = {
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',
+ chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice', sources: 'Sources in this chapter', opensSource: '{label}, opens the source in a new tab',
firstTryScore: '{name}: {r} of {t} right on the first try.', notAttempted: '{name}: not attempted.',
watchAgain: 'Watch again', nextChapter: 'Next chapter',
},
@@ -74,7 +74,7 @@ const TRANSLATIONS = {
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: 'Практика по главе',
+ chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе', sources: 'Источники этой главы', opensSource: '{label}, источник откроется в новой вкладке',
firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',
watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',
},
@@ -108,7 +108,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 左边 {n} 步',
natural: '正整数', whole: '非负整数', integers: '整数', rational: '有理数', irrational: '无理数', real: '实数', integerColumn: '整数',
trueLabel: '对', falseLabel: '错',
- chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习',
+ chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习', sources: '本章引用的文献', opensSource: '{label},在新标签页中打开来源',
firstTryScore: '{name}:第一次就答对 {r} / {t}。', notAttempted: '{name}:未作答。',
watchAgain: '再看一遍', nextChapter: '下一章',
},
@@ -142,7 +142,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 から左へ {n}',
natural: '自然数', whole: '0 以上の整数', integers: '整数', rational: '有理数', irrational: '無理数', real: '実数', integerColumn: '整数',
trueLabel: '正しい', falseLabel: '誤り',
- chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習',
+ chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習', sources: 'この章の出典', opensSource: '{label}(出典を新しいタブで開く)',
firstTryScore: '{name}:1 回目で {t} 問中 {r} 問正解。', notAttempted: '{name}:未挑戦。',
watchAgain: 'もう一度見る', nextChapter: '次の章へ',
},
@@ -298,6 +298,81 @@ function T(parent, str, { x = 0, y = 0, size = 30, fill = COL.chalk, font = UI,
t.style.whiteSpace = 'pre';
return put(t, { x, y, o });
}
+// A citation drawn in the picture that opens its source (REFS from ../refs.js, built by scripts/refs.py) in a new tab.
+// cite(p, key, opts) takes T's options; str overrides the label (default REFS[key].cite). Returns the <a>; animate it like T.
+const CITED = new Set();
+function cite(parent, key, { str, ...opts } = {}) {
+ const r = (typeof REFS === 'object' && REFS) ? REFS[key] : null;
+ if (!r) throw new Error(`cite: no reference "${key}" in refs.js`);
+ CITED.add(key);
+ if (!r.url) return T(parent, str || r.cite, opts);
+ linkStage();
+ const a = mk('a', { class: 'cite', href: r.url, target: '_blank', rel: 'noopener', 'aria-label': translate('opensSource', { label: r.cite }) }, parent);
+ const { o = 1, x = 0, y = 0, ...rest } = opts;
+ T(a, str || r.cite, { ...rest, fill: rest.fill || COL.chalk });
+ return put(a, { x, y, o });
+}
+// Any text in the picture or a card that equals a reference's cite label or one of its match strings (case-insensitive)
+// becomes a link to the source, so chapters write citations as plain text. Watched by citeObs (set up after the player).
+let CITE_RE = null, CITE_KEY = null;
+function citeIndex() {
+ if (CITE_RE !== null) return CITE_RE;
+ CITE_KEY = new Map();
+ for (const [k, r] of Object.entries(typeof REFS === 'object' && REFS ? REFS : {}))
+ for (const s of [r.cite, ...(r.match || [])]) if (s) CITE_KEY.set(s.toLowerCase(), k);
+ const alts = [...CITE_KEY.keys()].sort((a, b) => b.length - a.length).map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ return (CITE_RE = alts.length ? new RegExp(alts.join('|'), 'gi') : false);
+}
+function autoCite(root) {
+ const re = citeIndex();
+ if (!re) return;
+ const nodes = [];
+ if (root.nodeType === 3) nodes.push(root);
+ else if (root.nodeType === 1) for (let w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n; (n = w.nextNode());) nodes.push(n);
+ for (const n of nodes) {
+ const host = n.parentElement;
+ if (!host || host.closest('a, button, input, script, style, kbd')) continue; // no links inside controls
+ const ms = [...n.data.matchAll(re)];
+ if (!ms.length) continue;
+ const svg = host.namespaceURI === NS, frag = document.createDocumentFragment();
+ let i = 0, made = 0;
+ for (const m of ms) {
+ const k = CITE_KEY.get(m[0].toLowerCase()), r = REFS[k];
+ CITED.add(k);
+ if (!r.url) continue; // a work with no reliable online record stays plain text but is still listed
+ frag.append(n.data.slice(i, m.index));
+ const a = svg ? mk('a', { href: r.url }) : document.createElement('a');
+ if (!svg) a.href = r.url;
+ a.setAttribute('class', 'cite');
+ a.setAttribute('target', '_blank');
+ a.setAttribute('rel', 'noopener');
+ a.setAttribute('aria-label', translate('opensSource', { label: m[0] }));
+ if (svg) mk('tspan', {}, a).textContent = m[0]; else a.textContent = m[0];
+ frag.append(a);
+ i = m.index + m[0].length;
+ made++;
+ }
+ if (!made) continue; // replacing the node unchanged would re-trigger the observer
+ if (svg) linkStage();
+ frag.append(n.data.slice(i));
+ n.replaceWith(frag);
+ }
+}
+// The stage is announced as one image; once it holds a link it becomes a group, so the link stays reachable.
+function linkStage() { document.getElementById('stage').setAttribute('role', 'group'); }
+// Links that have faded out (or sit in a faded group) must not take clicks or Tab focus.
+function syncLinks() {
+ for (const a of scene.querySelectorAll('a.cite')) {
+ let o = 1;
+ for (let e = a; e && e !== scene; e = e.parentNode) o *= +(e.getAttribute('opacity') ?? 1);
+ const on = o > .5;
+ if (on === a._on) continue;
+ a._on = on;
+ a.style.pointerEvents = on ? '' : 'none';
+ if (on) { a.removeAttribute('tabindex'); a.removeAttribute('aria-hidden'); }
+ else { a.setAttribute('tabindex', '-1'); a.setAttribute('aria-hidden', 'true'); }
+ }
+}
const ctx2d = document.createElement('canvas').getContext('2d');
function textW(str, size, italic = false) { ctx2d.font = `${italic ? 'italic ' : ''}${size}px ${MATH}`; return ctx2d.measureText(str).width; }
const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|so|up|we|my)(?![A-Za-z]))[a-z]{1,2}|(?!(?:If|In|It|Is|On|At|No|So|Or|An|As|To|By|Up)(?![A-Za-z]))[a-z]?[A-Z]{1,3}[a-z]?)(?![A-Za-z])/g; // capitals: A, PV, nRT // short lowercase runs are variables (a, x, ab), except short English words
@@ -1244,7 +1319,7 @@ function finishCard() {
: isShortcut(e, 'r') ? (restart(), true) : false;
const guide = mascotEl(240);
c.append(h('div', 'finwrap', [guide, h('p', 'kicker', translate('chapterComplete', { n: CHAPTER.label ?? 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])]));
+ line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again]), sources()].filter(Boolean)));
setTimeout(() => mood(guide, 'happy'), 400);
}
@@ -1253,6 +1328,19 @@ const $ = id => document.getElementById(id);
// The volume control (volume.js, volume.css) lives in its own files next to this one, the same in every book.
document.head.append(Object.assign(document.createElement('script'), { src: new URL('volume.js', document.currentScript.src) }));
const kbd = s => h('kbd', '', s);
+// The chapter's sources: every key passed to cite() plus CHAPTER.refs, as full references that link to the source.
+function sources() {
+ for (const m of citeObs.takeRecords()) for (const n of m.addedNodes) autoCite(n); // link text added just now (a seek to the end)
+ const keys = [...new Set([...(CHAPTER.refs || []), ...CITED])].filter(k => typeof REFS === 'object' && REFS?.[k]);
+ if (!keys.length) return null;
+ const items = keys.map(k => REFS[k]).sort((a, b) => a.ref.localeCompare(b.ref)).map(r => {
+ if (!r.url) return h('li', '', r.ref);
+ const a = h('a', '', r.url.replace(/^https?:\/\//, ''));
+ Object.assign(a, { href: r.url, target: '_blank', rel: 'noopener' });
+ return h('li', '', [r.ref + ' ', a]);
+ });
+ return h('section', 'srcs', [h('h2', '', translate('sources')), h('ol', '', items)]);
+}
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
const SCORE = {}; // question id -> first-attempt {right, total}
@@ -1391,6 +1479,13 @@ 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; },
};
};
+// A choice question from the chapter's item bank: ITEMS from ./items.js, built by scripts/items.py from the
+// mcq-item-writer JSON. mcq('ID', onRight?) returns a quiz entry, so quiz(TOPR, [mcq('MB-03-01')], done) asks it.
+function mcq(id, onRight) {
+ const it = (typeof ITEMS === 'object' && ITEMS) ? ITEMS[id] : null;
+ if (!it) throw new Error(`mcq: no item "${id}" in items.js`);
+ return { id, prompt: it.prompt, build: choice(it.opts, it.right, it.why, it.no, onRight) };
+}
// 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) => {
@@ -1898,6 +1993,7 @@ function frame(now) {
evalTo(P.t);
if (P.t >= P.end) beatDone();
}
+ syncLinks();
ui();
requestAnimationFrame(frame);
}
@@ -1957,9 +2053,13 @@ const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
const restart = () => { for (const k in SCORE) delete SCORE[k]; hideCover(); seek(0, true); };
$('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
+ if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
});
+const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
+citeObs.observe(scene, { childList: true, subtree: true });
+citeObs.observe($('ui'), { childList: true, subtree: true });
$('bPlay').onclick = togglePlay;
$('bBack').onclick = () => { hideCover(); back1(); };
$('bRestart').onclick = restart;
diff --git a/site/physics-notebook/lib/contents.css b/site/physics-notebook/lib/contents.css
index 3f59f10..d8f7f70 100644
--- a/site/physics-notebook/lib/contents.css
+++ b/site/physics-notebook/lib/contents.css
@@ -26,6 +26,8 @@ a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
#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; }
+/* #references is its own view: the full list, reached from one link at the end of the contents. */
+body:not(.refsview) #refpage, .refsview #cover, .refsview #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; }
@@ -92,6 +94,26 @@ main#contents { padding-bottom: 80px; }
.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; } }
+/* ---------- references: every source the book cites, linked to its DOI or catalogue record ---------- */
+.refs-more { max-width: 1212px; margin: 44px auto 0; padding: 0 16px; }
+.refs-more[hidden] { display: none; }
+.refs-more a { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 14px; padding: 16px 20px; border-radius: 16px; background: var(--panel);
+ border: 1.5px solid var(--edge); text-decoration: none; transition: border-color .3s; }
+.refs-more a:hover { border-color: var(--dim); }
+.refs-more b { font: 500 22px/1.2 var(--book); }
+.refs-more span { color: var(--dim); font-size: 15px; }
+.refs-more i { margin-left: auto; font-style: normal; color: var(--quiz); font-weight: 600; font-size: 15px; }
+#refpage { padding-bottom: 80px; }
+.top .back { display: inline-flex; align-items: center; gap: 8px; padding: 6px 4px; font-weight: 600; text-decoration: none; color: var(--quiz); border-radius: 8px; }
+.top .rp-book { margin-left: auto; font: 500 18px/1.2 var(--book); color: var(--dim); }
+.top .rp-book i { color: var(--task); }
+.refs { max-width: 1212px; margin: 32px auto 0; padding: 0 16px; }
+.refs h1 { margin: 0 0 8px; font: 500 clamp(32px, 5vw, 44px)/1.1 var(--book); view-transition-name: none; }
+.refs .lead { margin: 0 0 26px; max-width: 46em; color: var(--dim); }
+.refs ol { margin: 0; padding: 0; list-style: none; color: var(--dim); font-size: 16px; line-height: 1.5; }
+.refs li { margin: 0 0 10px; padding-left: 2em; text-indent: -2em; }
+.refs a { color: var(--chalk); text-underline-offset: 3px; overflow-wrap: anywhere; }
+.refs a:hover { color: var(--quiz); }
.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); }
diff --git a/site/physics-notebook/lib/contents.js b/site/physics-notebook/lib/contents.js
index 6b3272b..7022eb5 100644
--- a/site/physics-notebook/lib/contents.js
+++ b/site/physics-notebook/lib/contents.js
@@ -1,6 +1,7 @@
/* 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. */
+ Contents.book({ units, start, hues }) with its chapter list. With refs.js (REFS, built by the skill's
+ scripts/refs.py) loaded first, the page also gets its References view (#references). */
'use strict';
// Observe aborted incoming transitions before the first rendering opportunity.
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
@@ -15,6 +16,10 @@ const Contents = (() => {
metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: { one: ' + {n} sample', other: ' + {n} samples' }, samples: 'Sample chapters, another look',
chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',
doneMark: '✓ Finished · ', lastMark: ' · Last opened',
+ references: 'References', viewAll: 'View all →', backToContents: '← Contents',
+ refsLead: 'Every work cited in the lessons. Each link opens the work’s DOI or library record in a new tab; works with no reliable online record are listed without a link.',
+ refsCount: { one: '{n} work cited in the lessons', other: '{n} works cited in the lessons' },
+ refsAllLinked: ', each linked to its source', refsSomeLinked: ', {n} linked to their sources',
},
ru: {
open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',
@@ -25,6 +30,10 @@ const Contents = (() => {
samples: 'Пробные главы в другом стиле',
chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',
doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',
+ references: 'Список литературы', viewAll: 'Весь список →', backToContents: '← Оглавление',
+ refsLead: 'Все работы, которые цитируются в уроках. Ссылка открывает DOI или библиотечную запись в новой вкладке; работы без надёжной записи в сети даны без ссылки.',
+ refsCount: { one: '{n} работа цитируется в уроках', few: '{n} работы цитируются в уроках', many: '{n} работ цитируются в уроках', other: '{n} работы цитируются в уроках' },
+ refsAllLinked: ', у каждой есть ссылка на источник', refsSomeLinked: ', ссылок на источник: {n}',
},
zh: {
open: '打开这本书', toCover: '返回封面', resume: '继续 · 第 {n} 章', unit: '第 {n} 单元', minutes: '{n} 分钟',
@@ -32,6 +41,9 @@ const Contents = (() => {
metaSamples: ' + {n} 个示例章', samples: '示例章,另一种风格',
chapterCount: '{n} 章', finished: '已完成 {done} / {n}',
doneMark: '✓ 已完成 · ', lastMark: ' · 上次打开',
+ references: '参考文献', viewAll: '查看全部 →', backToContents: '← 目录',
+ refsLead: '课程中引用的全部作品。每个链接会在新标签页中打开该作品的 DOI 或图书馆记录;没有可靠在线记录的作品不附链接。',
+ refsCount: '课程中引用了 {n} 部作品', refsAllLinked: ',均链接到来源', refsSomeLinked: ',其中 {n} 部链接到来源',
},
ja: {
open: '本を開く', toCover: '表紙に戻る', resume: '続きから · 第{n}章', unit: '単元 {n}', minutes: '{n}分',
@@ -39,6 +51,9 @@ const Contents = (() => {
metaSamples: ' + サンプル{n}章', samples: 'サンプル章(別のスタイル)',
chapterCount: '{n}章', finished: '{n}章中 {done}章 完了',
doneMark: '✓ 完了 · ', lastMark: ' · 最後に開いた章',
+ references: '参考文献', viewAll: 'すべて見る →', backToContents: '← 目次',
+ refsLead: '授業で引用したすべての著作です。リンクは著作の DOI または図書館の記録を新しいタブで開きます。信頼できるオンライン記録のない著作はリンクなしで載せています。',
+ refsCount: '授業で引用した著作 {n} 件', refsAllLinked: '、すべて出典へのリンクつき', refsSomeLinked: '、うち {n} 件は出典へのリンクつき',
},
};
const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
@@ -54,7 +69,7 @@ const Contents = (() => {
}
const $ = id => document.getElementById(id);
const id = n => 'ch' + String(n).padStart(2, '0');
- const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
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.
@@ -114,6 +129,20 @@ const Contents = (() => {
}
}
+ // The References view, from refs.js: full entries, each linked to its DOI or catalogue record. It appears as one
+ // link at the end of the contents only when the book cites something.
+ function references() {
+ const all = Object.values(typeof REFS === 'object' && REFS ? REFS : {});
+ if (!$('refList') || !all.length) return;
+ $('refList').innerHTML = all.sort((a, b) => a.ref.localeCompare(b.ref)).map(r => `<li>${esc(r.ref)}${r.url
+ ? ` <a href="${esc(r.url)}" target="_blank" rel="noopener">${esc(r.url.replace(/^https?:\/\//, ''))}</a>` : ''}</li>`).join('');
+ const linked = all.filter(r => r.url).length;
+ $('refsCount').textContent = translate('refsCount', { n: all.length }) +
+ (linked === all.length ? translate('refsAllLinked') : translate('refsSomeLinked', { n: linked }));
+ $('rpBook').innerHTML = document.querySelector('#contents .home strong')?.innerHTML || '';
+ $('refsMore').hidden = false;
+ }
+
// 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 = '';
@@ -134,21 +163,24 @@ const Contents = (() => {
}
}
- // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.
+ // The cover, the contents and the references share this page: no hash or #book shows the cover, #references the
+ // reference list, #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 refs = location.hash === '#references';
+ const open = location.hash.length > 1 && location.hash !== '#book' && !refs;
const apply = () => {
document.body.classList.toggle('open', open);
+ document.body.classList.toggle('refsview', refs);
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');
+ const heading = document.querySelector(refs ? '#refsTitle' : open ? '#contents .home' : '#cover h1');
heading?.setAttribute('tabindex', '-1');
heading?.focus({ preventScroll: true });
}
@@ -184,6 +216,7 @@ const Contents = (() => {
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));
+ references();
guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');
views();
}
diff --git a/site/physics-notebook/lib/engine.css b/site/physics-notebook/lib/engine.css
index 9b9be00..9e8e535 100644
--- a/site/physics-notebook/lib/engine.css
+++ b/site/physics-notebook/lib/engine.css
@@ -221,6 +221,22 @@ svg.m { display: inline-block; overflow: visible; }
@media (prefers-reduced-motion: reduce) { .card, .fb, .opt, .grid .mark, .mascot * { animation: none !important; } }
a.icon { text-decoration: none; }
+/* Citations (cite() and plain-text labels found in refs.js) and the finish card's source list open the source in a new tab. */
+a.cite { cursor: pointer; }
+a.cite text, a.cite tspan { text-decoration: underline; text-decoration-thickness: 1.5px; text-underline-offset: 5px; }
+a.cite:hover text, a.cite:hover tspan { fill: var(--quiz); }
+a.cite:focus { outline: none; }
+a.cite:focus-visible text, a.cite:focus-visible tspan { fill: var(--task); }
+a.cite:focus-visible { outline: 3px solid var(--task); outline-offset: 6px; border-radius: 4px; }
+#ui a.cite { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
+#ui a.cite:hover { color: var(--quiz); }
+.fin .srcs { margin: 26px 0 0; max-width: 1100px; font-size: 19px; line-height: 1.45; color: var(--dim); text-align: left; }
+.fin .srcs h2 { margin: 0 0 6px; font-size: 18px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
+.fin .srcs ol { margin: 0; padding-left: 0; list-style: none; max-height: 190px; overflow: auto; }
+.fin .srcs li { padding-left: 2em; text-indent: -2em; margin: 0 0 6px; }
+.fin .srcs a { color: var(--chalk); text-underline-offset: 3px; }
+.fin .srcs a:hover { color: var(--quiz); }
+.fin .srcs a:focus-visible { outline: 3px solid var(--task); outline-offset: 2px; }
a.btn { text-decoration: none; display: inline-block; }
/* Page-to-page motion: the contents card grows into this frame, and shrinks back on the way out. */
@view-transition { navigation: auto; }
diff --git a/site/physics-notebook/lib/engine.js b/site/physics-notebook/lib/engine.js
index cb6d40b..a33c7db 100644
--- a/site/physics-notebook/lib/engine.js
+++ b/site/physics-notebook/lib/engine.js
@@ -38,7 +38,7 @@ const TRANSLATIONS = {
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',
+ chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice', sources: 'Sources in this chapter', opensSource: '{label}, opens the source in a new tab',
firstTryScore: '{name}: {r} of {t} right on the first try.', notAttempted: '{name}: not attempted.',
watchAgain: 'Watch again', nextChapter: 'Next chapter',
},
@@ -74,7 +74,7 @@ const TRANSLATIONS = {
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: 'Практика по главе',
+ chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе', sources: 'Источники этой главы', opensSource: '{label}, источник откроется в новой вкладке',
firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',
watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',
},
@@ -108,7 +108,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 左边 {n} 步',
natural: '正整数', whole: '非负整数', integers: '整数', rational: '有理数', irrational: '无理数', real: '实数', integerColumn: '整数',
trueLabel: '对', falseLabel: '错',
- chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习',
+ chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习', sources: '本章引用的文献', opensSource: '{label},在新标签页中打开来源',
firstTryScore: '{name}:第一次就答对 {r} / {t}。', notAttempted: '{name}:未作答。',
watchAgain: '再看一遍', nextChapter: '下一章',
},
@@ -142,7 +142,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 から左へ {n}',
natural: '自然数', whole: '0 以上の整数', integers: '整数', rational: '有理数', irrational: '無理数', real: '実数', integerColumn: '整数',
trueLabel: '正しい', falseLabel: '誤り',
- chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習',
+ chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習', sources: 'この章の出典', opensSource: '{label}(出典を新しいタブで開く)',
firstTryScore: '{name}:1 回目で {t} 問中 {r} 問正解。', notAttempted: '{name}:未挑戦。',
watchAgain: 'もう一度見る', nextChapter: '次の章へ',
},
@@ -298,6 +298,81 @@ function T(parent, str, { x = 0, y = 0, size = 30, fill = COL.chalk, font = UI,
t.style.whiteSpace = 'pre';
return put(t, { x, y, o });
}
+// A citation drawn in the picture that opens its source (REFS from ../refs.js, built by scripts/refs.py) in a new tab.
+// cite(p, key, opts) takes T's options; str overrides the label (default REFS[key].cite). Returns the <a>; animate it like T.
+const CITED = new Set();
+function cite(parent, key, { str, ...opts } = {}) {
+ const r = (typeof REFS === 'object' && REFS) ? REFS[key] : null;
+ if (!r) throw new Error(`cite: no reference "${key}" in refs.js`);
+ CITED.add(key);
+ if (!r.url) return T(parent, str || r.cite, opts);
+ linkStage();
+ const a = mk('a', { class: 'cite', href: r.url, target: '_blank', rel: 'noopener', 'aria-label': translate('opensSource', { label: r.cite }) }, parent);
+ const { o = 1, x = 0, y = 0, ...rest } = opts;
+ T(a, str || r.cite, { ...rest, fill: rest.fill || COL.chalk });
+ return put(a, { x, y, o });
+}
+// Any text in the picture or a card that equals a reference's cite label or one of its match strings (case-insensitive)
+// becomes a link to the source, so chapters write citations as plain text. Watched by citeObs (set up after the player).
+let CITE_RE = null, CITE_KEY = null;
+function citeIndex() {
+ if (CITE_RE !== null) return CITE_RE;
+ CITE_KEY = new Map();
+ for (const [k, r] of Object.entries(typeof REFS === 'object' && REFS ? REFS : {}))
+ for (const s of [r.cite, ...(r.match || [])]) if (s) CITE_KEY.set(s.toLowerCase(), k);
+ const alts = [...CITE_KEY.keys()].sort((a, b) => b.length - a.length).map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ return (CITE_RE = alts.length ? new RegExp(alts.join('|'), 'gi') : false);
+}
+function autoCite(root) {
+ const re = citeIndex();
+ if (!re) return;
+ const nodes = [];
+ if (root.nodeType === 3) nodes.push(root);
+ else if (root.nodeType === 1) for (let w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n; (n = w.nextNode());) nodes.push(n);
+ for (const n of nodes) {
+ const host = n.parentElement;
+ if (!host || host.closest('a, button, input, script, style, kbd')) continue; // no links inside controls
+ const ms = [...n.data.matchAll(re)];
+ if (!ms.length) continue;
+ const svg = host.namespaceURI === NS, frag = document.createDocumentFragment();
+ let i = 0, made = 0;
+ for (const m of ms) {
+ const k = CITE_KEY.get(m[0].toLowerCase()), r = REFS[k];
+ CITED.add(k);
+ if (!r.url) continue; // a work with no reliable online record stays plain text but is still listed
+ frag.append(n.data.slice(i, m.index));
+ const a = svg ? mk('a', { href: r.url }) : document.createElement('a');
+ if (!svg) a.href = r.url;
+ a.setAttribute('class', 'cite');
+ a.setAttribute('target', '_blank');
+ a.setAttribute('rel', 'noopener');
+ a.setAttribute('aria-label', translate('opensSource', { label: m[0] }));
+ if (svg) mk('tspan', {}, a).textContent = m[0]; else a.textContent = m[0];
+ frag.append(a);
+ i = m.index + m[0].length;
+ made++;
+ }
+ if (!made) continue; // replacing the node unchanged would re-trigger the observer
+ if (svg) linkStage();
+ frag.append(n.data.slice(i));
+ n.replaceWith(frag);
+ }
+}
+// The stage is announced as one image; once it holds a link it becomes a group, so the link stays reachable.
+function linkStage() { document.getElementById('stage').setAttribute('role', 'group'); }
+// Links that have faded out (or sit in a faded group) must not take clicks or Tab focus.
+function syncLinks() {
+ for (const a of scene.querySelectorAll('a.cite')) {
+ let o = 1;
+ for (let e = a; e && e !== scene; e = e.parentNode) o *= +(e.getAttribute('opacity') ?? 1);
+ const on = o > .5;
+ if (on === a._on) continue;
+ a._on = on;
+ a.style.pointerEvents = on ? '' : 'none';
+ if (on) { a.removeAttribute('tabindex'); a.removeAttribute('aria-hidden'); }
+ else { a.setAttribute('tabindex', '-1'); a.setAttribute('aria-hidden', 'true'); }
+ }
+}
const ctx2d = document.createElement('canvas').getContext('2d');
function textW(str, size, italic = false) { ctx2d.font = `${italic ? 'italic ' : ''}${size}px ${MATH}`; return ctx2d.measureText(str).width; }
const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|so|up|we|my)(?![A-Za-z]))[a-z]{1,2}|(?!(?:If|In|It|Is|On|At|No|So|Or|An|As|To|By|Up)(?![A-Za-z]))[a-z]?[A-Z]{1,3}[a-z]?)(?![A-Za-z])/g; // capitals: A, PV, nRT // short lowercase runs are variables (a, x, ab), except short English words
@@ -1244,7 +1319,7 @@ function finishCard() {
: isShortcut(e, 'r') ? (restart(), true) : false;
const guide = mascotEl(240);
c.append(h('div', 'finwrap', [guide, h('p', 'kicker', translate('chapterComplete', { n: CHAPTER.label ?? 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])]));
+ line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again]), sources()].filter(Boolean)));
setTimeout(() => mood(guide, 'happy'), 400);
}
@@ -1253,6 +1328,19 @@ const $ = id => document.getElementById(id);
// The volume control (volume.js, volume.css) lives in its own files next to this one, the same in every book.
document.head.append(Object.assign(document.createElement('script'), { src: new URL('volume.js', document.currentScript.src) }));
const kbd = s => h('kbd', '', s);
+// The chapter's sources: every key passed to cite() plus CHAPTER.refs, as full references that link to the source.
+function sources() {
+ for (const m of citeObs.takeRecords()) for (const n of m.addedNodes) autoCite(n); // link text added just now (a seek to the end)
+ const keys = [...new Set([...(CHAPTER.refs || []), ...CITED])].filter(k => typeof REFS === 'object' && REFS?.[k]);
+ if (!keys.length) return null;
+ const items = keys.map(k => REFS[k]).sort((a, b) => a.ref.localeCompare(b.ref)).map(r => {
+ if (!r.url) return h('li', '', r.ref);
+ const a = h('a', '', r.url.replace(/^https?:\/\//, ''));
+ Object.assign(a, { href: r.url, target: '_blank', rel: 'noopener' });
+ return h('li', '', [r.ref + ' ', a]);
+ });
+ return h('section', 'srcs', [h('h2', '', translate('sources')), h('ol', '', items)]);
+}
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
const SCORE = {}; // question id -> first-attempt {right, total}
@@ -1391,6 +1479,13 @@ 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; },
};
};
+// A choice question from the chapter's item bank: ITEMS from ./items.js, built by scripts/items.py from the
+// mcq-item-writer JSON. mcq('ID', onRight?) returns a quiz entry, so quiz(TOPR, [mcq('MB-03-01')], done) asks it.
+function mcq(id, onRight) {
+ const it = (typeof ITEMS === 'object' && ITEMS) ? ITEMS[id] : null;
+ if (!it) throw new Error(`mcq: no item "${id}" in items.js`);
+ return { id, prompt: it.prompt, build: choice(it.opts, it.right, it.why, it.no, onRight) };
+}
// 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) => {
@@ -1898,6 +1993,7 @@ function frame(now) {
evalTo(P.t);
if (P.t >= P.end) beatDone();
}
+ syncLinks();
ui();
requestAnimationFrame(frame);
}
@@ -1957,9 +2053,13 @@ const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
const restart = () => { for (const k in SCORE) delete SCORE[k]; hideCover(); seek(0, true); };
$('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
+ if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
});
+const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
+citeObs.observe(scene, { childList: true, subtree: true });
+citeObs.observe($('ui'), { childList: true, subtree: true });
$('bPlay').onclick = togglePlay;
$('bBack').onclick = () => { hideCover(); back1(); };
$('bRestart').onclick = restart;
diff --git a/site/science/lib/contents.css b/site/science/lib/contents.css
index 3f59f10..d8f7f70 100644
--- a/site/science/lib/contents.css
+++ b/site/science/lib/contents.css
@@ -26,6 +26,8 @@ a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
#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; }
+/* #references is its own view: the full list, reached from one link at the end of the contents. */
+body:not(.refsview) #refpage, .refsview #cover, .refsview #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; }
@@ -92,6 +94,26 @@ main#contents { padding-bottom: 80px; }
.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; } }
+/* ---------- references: every source the book cites, linked to its DOI or catalogue record ---------- */
+.refs-more { max-width: 1212px; margin: 44px auto 0; padding: 0 16px; }
+.refs-more[hidden] { display: none; }
+.refs-more a { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 14px; padding: 16px 20px; border-radius: 16px; background: var(--panel);
+ border: 1.5px solid var(--edge); text-decoration: none; transition: border-color .3s; }
+.refs-more a:hover { border-color: var(--dim); }
+.refs-more b { font: 500 22px/1.2 var(--book); }
+.refs-more span { color: var(--dim); font-size: 15px; }
+.refs-more i { margin-left: auto; font-style: normal; color: var(--quiz); font-weight: 600; font-size: 15px; }
+#refpage { padding-bottom: 80px; }
+.top .back { display: inline-flex; align-items: center; gap: 8px; padding: 6px 4px; font-weight: 600; text-decoration: none; color: var(--quiz); border-radius: 8px; }
+.top .rp-book { margin-left: auto; font: 500 18px/1.2 var(--book); color: var(--dim); }
+.top .rp-book i { color: var(--task); }
+.refs { max-width: 1212px; margin: 32px auto 0; padding: 0 16px; }
+.refs h1 { margin: 0 0 8px; font: 500 clamp(32px, 5vw, 44px)/1.1 var(--book); view-transition-name: none; }
+.refs .lead { margin: 0 0 26px; max-width: 46em; color: var(--dim); }
+.refs ol { margin: 0; padding: 0; list-style: none; color: var(--dim); font-size: 16px; line-height: 1.5; }
+.refs li { margin: 0 0 10px; padding-left: 2em; text-indent: -2em; }
+.refs a { color: var(--chalk); text-underline-offset: 3px; overflow-wrap: anywhere; }
+.refs a:hover { color: var(--quiz); }
.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); }
diff --git a/site/science/lib/contents.js b/site/science/lib/contents.js
index 6b3272b..7022eb5 100644
--- a/site/science/lib/contents.js
+++ b/site/science/lib/contents.js
@@ -1,6 +1,7 @@
/* 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. */
+ Contents.book({ units, start, hues }) with its chapter list. With refs.js (REFS, built by the skill's
+ scripts/refs.py) loaded first, the page also gets its References view (#references). */
'use strict';
// Observe aborted incoming transitions before the first rendering opportunity.
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
@@ -15,6 +16,10 @@ const Contents = (() => {
metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: { one: ' + {n} sample', other: ' + {n} samples' }, samples: 'Sample chapters, another look',
chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',
doneMark: '✓ Finished · ', lastMark: ' · Last opened',
+ references: 'References', viewAll: 'View all →', backToContents: '← Contents',
+ refsLead: 'Every work cited in the lessons. Each link opens the work’s DOI or library record in a new tab; works with no reliable online record are listed without a link.',
+ refsCount: { one: '{n} work cited in the lessons', other: '{n} works cited in the lessons' },
+ refsAllLinked: ', each linked to its source', refsSomeLinked: ', {n} linked to their sources',
},
ru: {
open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',
@@ -25,6 +30,10 @@ const Contents = (() => {
samples: 'Пробные главы в другом стиле',
chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',
doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',
+ references: 'Список литературы', viewAll: 'Весь список →', backToContents: '← Оглавление',
+ refsLead: 'Все работы, которые цитируются в уроках. Ссылка открывает DOI или библиотечную запись в новой вкладке; работы без надёжной записи в сети даны без ссылки.',
+ refsCount: { one: '{n} работа цитируется в уроках', few: '{n} работы цитируются в уроках', many: '{n} работ цитируются в уроках', other: '{n} работы цитируются в уроках' },
+ refsAllLinked: ', у каждой есть ссылка на источник', refsSomeLinked: ', ссылок на источник: {n}',
},
zh: {
open: '打开这本书', toCover: '返回封面', resume: '继续 · 第 {n} 章', unit: '第 {n} 单元', minutes: '{n} 分钟',
@@ -32,6 +41,9 @@ const Contents = (() => {
metaSamples: ' + {n} 个示例章', samples: '示例章,另一种风格',
chapterCount: '{n} 章', finished: '已完成 {done} / {n}',
doneMark: '✓ 已完成 · ', lastMark: ' · 上次打开',
+ references: '参考文献', viewAll: '查看全部 →', backToContents: '← 目录',
+ refsLead: '课程中引用的全部作品。每个链接会在新标签页中打开该作品的 DOI 或图书馆记录;没有可靠在线记录的作品不附链接。',
+ refsCount: '课程中引用了 {n} 部作品', refsAllLinked: ',均链接到来源', refsSomeLinked: ',其中 {n} 部链接到来源',
},
ja: {
open: '本を開く', toCover: '表紙に戻る', resume: '続きから · 第{n}章', unit: '単元 {n}', minutes: '{n}分',
@@ -39,6 +51,9 @@ const Contents = (() => {
metaSamples: ' + サンプル{n}章', samples: 'サンプル章(別のスタイル)',
chapterCount: '{n}章', finished: '{n}章中 {done}章 完了',
doneMark: '✓ 完了 · ', lastMark: ' · 最後に開いた章',
+ references: '参考文献', viewAll: 'すべて見る →', backToContents: '← 目次',
+ refsLead: '授業で引用したすべての著作です。リンクは著作の DOI または図書館の記録を新しいタブで開きます。信頼できるオンライン記録のない著作はリンクなしで載せています。',
+ refsCount: '授業で引用した著作 {n} 件', refsAllLinked: '、すべて出典へのリンクつき', refsSomeLinked: '、うち {n} 件は出典へのリンクつき',
},
};
const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
@@ -54,7 +69,7 @@ const Contents = (() => {
}
const $ = id => document.getElementById(id);
const id = n => 'ch' + String(n).padStart(2, '0');
- const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
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.
@@ -114,6 +129,20 @@ const Contents = (() => {
}
}
+ // The References view, from refs.js: full entries, each linked to its DOI or catalogue record. It appears as one
+ // link at the end of the contents only when the book cites something.
+ function references() {
+ const all = Object.values(typeof REFS === 'object' && REFS ? REFS : {});
+ if (!$('refList') || !all.length) return;
+ $('refList').innerHTML = all.sort((a, b) => a.ref.localeCompare(b.ref)).map(r => `<li>${esc(r.ref)}${r.url
+ ? ` <a href="${esc(r.url)}" target="_blank" rel="noopener">${esc(r.url.replace(/^https?:\/\//, ''))}</a>` : ''}</li>`).join('');
+ const linked = all.filter(r => r.url).length;
+ $('refsCount').textContent = translate('refsCount', { n: all.length }) +
+ (linked === all.length ? translate('refsAllLinked') : translate('refsSomeLinked', { n: linked }));
+ $('rpBook').innerHTML = document.querySelector('#contents .home strong')?.innerHTML || '';
+ $('refsMore').hidden = false;
+ }
+
// 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 = '';
@@ -134,21 +163,24 @@ const Contents = (() => {
}
}
- // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.
+ // The cover, the contents and the references share this page: no hash or #book shows the cover, #references the
+ // reference list, #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 refs = location.hash === '#references';
+ const open = location.hash.length > 1 && location.hash !== '#book' && !refs;
const apply = () => {
document.body.classList.toggle('open', open);
+ document.body.classList.toggle('refsview', refs);
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');
+ const heading = document.querySelector(refs ? '#refsTitle' : open ? '#contents .home' : '#cover h1');
heading?.setAttribute('tabindex', '-1');
heading?.focus({ preventScroll: true });
}
@@ -184,6 +216,7 @@ const Contents = (() => {
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));
+ references();
guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');
views();
}
diff --git a/site/science/lib/engine.css b/site/science/lib/engine.css
index 9b9be00..9e8e535 100644
--- a/site/science/lib/engine.css
+++ b/site/science/lib/engine.css
@@ -221,6 +221,22 @@ svg.m { display: inline-block; overflow: visible; }
@media (prefers-reduced-motion: reduce) { .card, .fb, .opt, .grid .mark, .mascot * { animation: none !important; } }
a.icon { text-decoration: none; }
+/* Citations (cite() and plain-text labels found in refs.js) and the finish card's source list open the source in a new tab. */
+a.cite { cursor: pointer; }
+a.cite text, a.cite tspan { text-decoration: underline; text-decoration-thickness: 1.5px; text-underline-offset: 5px; }
+a.cite:hover text, a.cite:hover tspan { fill: var(--quiz); }
+a.cite:focus { outline: none; }
+a.cite:focus-visible text, a.cite:focus-visible tspan { fill: var(--task); }
+a.cite:focus-visible { outline: 3px solid var(--task); outline-offset: 6px; border-radius: 4px; }
+#ui a.cite { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
+#ui a.cite:hover { color: var(--quiz); }
+.fin .srcs { margin: 26px 0 0; max-width: 1100px; font-size: 19px; line-height: 1.45; color: var(--dim); text-align: left; }
+.fin .srcs h2 { margin: 0 0 6px; font-size: 18px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
+.fin .srcs ol { margin: 0; padding-left: 0; list-style: none; max-height: 190px; overflow: auto; }
+.fin .srcs li { padding-left: 2em; text-indent: -2em; margin: 0 0 6px; }
+.fin .srcs a { color: var(--chalk); text-underline-offset: 3px; }
+.fin .srcs a:hover { color: var(--quiz); }
+.fin .srcs a:focus-visible { outline: 3px solid var(--task); outline-offset: 2px; }
a.btn { text-decoration: none; display: inline-block; }
/* Page-to-page motion: the contents card grows into this frame, and shrinks back on the way out. */
@view-transition { navigation: auto; }
diff --git a/site/science/lib/engine.js b/site/science/lib/engine.js
index cb6d40b..a33c7db 100644
--- a/site/science/lib/engine.js
+++ b/site/science/lib/engine.js
@@ -38,7 +38,7 @@ const TRANSLATIONS = {
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',
+ chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice', sources: 'Sources in this chapter', opensSource: '{label}, opens the source in a new tab',
firstTryScore: '{name}: {r} of {t} right on the first try.', notAttempted: '{name}: not attempted.',
watchAgain: 'Watch again', nextChapter: 'Next chapter',
},
@@ -74,7 +74,7 @@ const TRANSLATIONS = {
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: 'Практика по главе',
+ chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе', sources: 'Источники этой главы', opensSource: '{label}, источник откроется в новой вкладке',
firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',
watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',
},
@@ -108,7 +108,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 左边 {n} 步',
natural: '正整数', whole: '非负整数', integers: '整数', rational: '有理数', irrational: '无理数', real: '实数', integerColumn: '整数',
trueLabel: '对', falseLabel: '错',
- chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习',
+ chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习', sources: '本章引用的文献', opensSource: '{label},在新标签页中打开来源',
firstTryScore: '{name}:第一次就答对 {r} / {t}。', notAttempted: '{name}:未作答。',
watchAgain: '再看一遍', nextChapter: '下一章',
},
@@ -142,7 +142,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 から左へ {n}',
natural: '自然数', whole: '0 以上の整数', integers: '整数', rational: '有理数', irrational: '無理数', real: '実数', integerColumn: '整数',
trueLabel: '正しい', falseLabel: '誤り',
- chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習',
+ chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習', sources: 'この章の出典', opensSource: '{label}(出典を新しいタブで開く)',
firstTryScore: '{name}:1 回目で {t} 問中 {r} 問正解。', notAttempted: '{name}:未挑戦。',
watchAgain: 'もう一度見る', nextChapter: '次の章へ',
},
@@ -298,6 +298,81 @@ function T(parent, str, { x = 0, y = 0, size = 30, fill = COL.chalk, font = UI,
t.style.whiteSpace = 'pre';
return put(t, { x, y, o });
}
+// A citation drawn in the picture that opens its source (REFS from ../refs.js, built by scripts/refs.py) in a new tab.
+// cite(p, key, opts) takes T's options; str overrides the label (default REFS[key].cite). Returns the <a>; animate it like T.
+const CITED = new Set();
+function cite(parent, key, { str, ...opts } = {}) {
+ const r = (typeof REFS === 'object' && REFS) ? REFS[key] : null;
+ if (!r) throw new Error(`cite: no reference "${key}" in refs.js`);
+ CITED.add(key);
+ if (!r.url) return T(parent, str || r.cite, opts);
+ linkStage();
+ const a = mk('a', { class: 'cite', href: r.url, target: '_blank', rel: 'noopener', 'aria-label': translate('opensSource', { label: r.cite }) }, parent);
+ const { o = 1, x = 0, y = 0, ...rest } = opts;
+ T(a, str || r.cite, { ...rest, fill: rest.fill || COL.chalk });
+ return put(a, { x, y, o });
+}
+// Any text in the picture or a card that equals a reference's cite label or one of its match strings (case-insensitive)
+// becomes a link to the source, so chapters write citations as plain text. Watched by citeObs (set up after the player).
+let CITE_RE = null, CITE_KEY = null;
+function citeIndex() {
+ if (CITE_RE !== null) return CITE_RE;
+ CITE_KEY = new Map();
+ for (const [k, r] of Object.entries(typeof REFS === 'object' && REFS ? REFS : {}))
+ for (const s of [r.cite, ...(r.match || [])]) if (s) CITE_KEY.set(s.toLowerCase(), k);
+ const alts = [...CITE_KEY.keys()].sort((a, b) => b.length - a.length).map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ return (CITE_RE = alts.length ? new RegExp(alts.join('|'), 'gi') : false);
+}
+function autoCite(root) {
+ const re = citeIndex();
+ if (!re) return;
+ const nodes = [];
+ if (root.nodeType === 3) nodes.push(root);
+ else if (root.nodeType === 1) for (let w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n; (n = w.nextNode());) nodes.push(n);
+ for (const n of nodes) {
+ const host = n.parentElement;
+ if (!host || host.closest('a, button, input, script, style, kbd')) continue; // no links inside controls
+ const ms = [...n.data.matchAll(re)];
+ if (!ms.length) continue;
+ const svg = host.namespaceURI === NS, frag = document.createDocumentFragment();
+ let i = 0, made = 0;
+ for (const m of ms) {
+ const k = CITE_KEY.get(m[0].toLowerCase()), r = REFS[k];
+ CITED.add(k);
+ if (!r.url) continue; // a work with no reliable online record stays plain text but is still listed
+ frag.append(n.data.slice(i, m.index));
+ const a = svg ? mk('a', { href: r.url }) : document.createElement('a');
+ if (!svg) a.href = r.url;
+ a.setAttribute('class', 'cite');
+ a.setAttribute('target', '_blank');
+ a.setAttribute('rel', 'noopener');
+ a.setAttribute('aria-label', translate('opensSource', { label: m[0] }));
+ if (svg) mk('tspan', {}, a).textContent = m[0]; else a.textContent = m[0];
+ frag.append(a);
+ i = m.index + m[0].length;
+ made++;
+ }
+ if (!made) continue; // replacing the node unchanged would re-trigger the observer
+ if (svg) linkStage();
+ frag.append(n.data.slice(i));
+ n.replaceWith(frag);
+ }
+}
+// The stage is announced as one image; once it holds a link it becomes a group, so the link stays reachable.
+function linkStage() { document.getElementById('stage').setAttribute('role', 'group'); }
+// Links that have faded out (or sit in a faded group) must not take clicks or Tab focus.
+function syncLinks() {
+ for (const a of scene.querySelectorAll('a.cite')) {
+ let o = 1;
+ for (let e = a; e && e !== scene; e = e.parentNode) o *= +(e.getAttribute('opacity') ?? 1);
+ const on = o > .5;
+ if (on === a._on) continue;
+ a._on = on;
+ a.style.pointerEvents = on ? '' : 'none';
+ if (on) { a.removeAttribute('tabindex'); a.removeAttribute('aria-hidden'); }
+ else { a.setAttribute('tabindex', '-1'); a.setAttribute('aria-hidden', 'true'); }
+ }
+}
const ctx2d = document.createElement('canvas').getContext('2d');
function textW(str, size, italic = false) { ctx2d.font = `${italic ? 'italic ' : ''}${size}px ${MATH}`; return ctx2d.measureText(str).width; }
const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|so|up|we|my)(?![A-Za-z]))[a-z]{1,2}|(?!(?:If|In|It|Is|On|At|No|So|Or|An|As|To|By|Up)(?![A-Za-z]))[a-z]?[A-Z]{1,3}[a-z]?)(?![A-Za-z])/g; // capitals: A, PV, nRT // short lowercase runs are variables (a, x, ab), except short English words
@@ -1244,7 +1319,7 @@ function finishCard() {
: isShortcut(e, 'r') ? (restart(), true) : false;
const guide = mascotEl(240);
c.append(h('div', 'finwrap', [guide, h('p', 'kicker', translate('chapterComplete', { n: CHAPTER.label ?? 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])]));
+ line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again]), sources()].filter(Boolean)));
setTimeout(() => mood(guide, 'happy'), 400);
}
@@ -1253,6 +1328,19 @@ const $ = id => document.getElementById(id);
// The volume control (volume.js, volume.css) lives in its own files next to this one, the same in every book.
document.head.append(Object.assign(document.createElement('script'), { src: new URL('volume.js', document.currentScript.src) }));
const kbd = s => h('kbd', '', s);
+// The chapter's sources: every key passed to cite() plus CHAPTER.refs, as full references that link to the source.
+function sources() {
+ for (const m of citeObs.takeRecords()) for (const n of m.addedNodes) autoCite(n); // link text added just now (a seek to the end)
+ const keys = [...new Set([...(CHAPTER.refs || []), ...CITED])].filter(k => typeof REFS === 'object' && REFS?.[k]);
+ if (!keys.length) return null;
+ const items = keys.map(k => REFS[k]).sort((a, b) => a.ref.localeCompare(b.ref)).map(r => {
+ if (!r.url) return h('li', '', r.ref);
+ const a = h('a', '', r.url.replace(/^https?:\/\//, ''));
+ Object.assign(a, { href: r.url, target: '_blank', rel: 'noopener' });
+ return h('li', '', [r.ref + ' ', a]);
+ });
+ return h('section', 'srcs', [h('h2', '', translate('sources')), h('ol', '', items)]);
+}
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
const SCORE = {}; // question id -> first-attempt {right, total}
@@ -1391,6 +1479,13 @@ 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; },
};
};
+// A choice question from the chapter's item bank: ITEMS from ./items.js, built by scripts/items.py from the
+// mcq-item-writer JSON. mcq('ID', onRight?) returns a quiz entry, so quiz(TOPR, [mcq('MB-03-01')], done) asks it.
+function mcq(id, onRight) {
+ const it = (typeof ITEMS === 'object' && ITEMS) ? ITEMS[id] : null;
+ if (!it) throw new Error(`mcq: no item "${id}" in items.js`);
+ return { id, prompt: it.prompt, build: choice(it.opts, it.right, it.why, it.no, onRight) };
+}
// 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) => {
@@ -1898,6 +1993,7 @@ function frame(now) {
evalTo(P.t);
if (P.t >= P.end) beatDone();
}
+ syncLinks();
ui();
requestAnimationFrame(frame);
}
@@ -1957,9 +2053,13 @@ const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
const restart = () => { for (const k in SCORE) delete SCORE[k]; hideCover(); seek(0, true); };
$('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
+ if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
});
+const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
+citeObs.observe(scene, { childList: true, subtree: true });
+citeObs.observe($('ui'), { childList: true, subtree: true });
$('bPlay').onclick = togglePlay;
$('bBack').onclick = () => { hideCover(); back1(); };
$('bRestart').onclick = restart;
diff --git a/site/three-little-pigs/lib/contents.css b/site/three-little-pigs/lib/contents.css
index 3f59f10..d8f7f70 100644
--- a/site/three-little-pigs/lib/contents.css
+++ b/site/three-little-pigs/lib/contents.css
@@ -26,6 +26,8 @@ a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
#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; }
+/* #references is its own view: the full list, reached from one link at the end of the contents. */
+body:not(.refsview) #refpage, .refsview #cover, .refsview #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; }
@@ -92,6 +94,26 @@ main#contents { padding-bottom: 80px; }
.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; } }
+/* ---------- references: every source the book cites, linked to its DOI or catalogue record ---------- */
+.refs-more { max-width: 1212px; margin: 44px auto 0; padding: 0 16px; }
+.refs-more[hidden] { display: none; }
+.refs-more a { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 14px; padding: 16px 20px; border-radius: 16px; background: var(--panel);
+ border: 1.5px solid var(--edge); text-decoration: none; transition: border-color .3s; }
+.refs-more a:hover { border-color: var(--dim); }
+.refs-more b { font: 500 22px/1.2 var(--book); }
+.refs-more span { color: var(--dim); font-size: 15px; }
+.refs-more i { margin-left: auto; font-style: normal; color: var(--quiz); font-weight: 600; font-size: 15px; }
+#refpage { padding-bottom: 80px; }
+.top .back { display: inline-flex; align-items: center; gap: 8px; padding: 6px 4px; font-weight: 600; text-decoration: none; color: var(--quiz); border-radius: 8px; }
+.top .rp-book { margin-left: auto; font: 500 18px/1.2 var(--book); color: var(--dim); }
+.top .rp-book i { color: var(--task); }
+.refs { max-width: 1212px; margin: 32px auto 0; padding: 0 16px; }
+.refs h1 { margin: 0 0 8px; font: 500 clamp(32px, 5vw, 44px)/1.1 var(--book); view-transition-name: none; }
+.refs .lead { margin: 0 0 26px; max-width: 46em; color: var(--dim); }
+.refs ol { margin: 0; padding: 0; list-style: none; color: var(--dim); font-size: 16px; line-height: 1.5; }
+.refs li { margin: 0 0 10px; padding-left: 2em; text-indent: -2em; }
+.refs a { color: var(--chalk); text-underline-offset: 3px; overflow-wrap: anywhere; }
+.refs a:hover { color: var(--quiz); }
.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); }
diff --git a/site/three-little-pigs/lib/contents.js b/site/three-little-pigs/lib/contents.js
index 6b3272b..7022eb5 100644
--- a/site/three-little-pigs/lib/contents.js
+++ b/site/three-little-pigs/lib/contents.js
@@ -1,6 +1,7 @@
/* 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. */
+ Contents.book({ units, start, hues }) with its chapter list. With refs.js (REFS, built by the skill's
+ scripts/refs.py) loaded first, the page also gets its References view (#references). */
'use strict';
// Observe aborted incoming transitions before the first rendering opportunity.
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
@@ -15,6 +16,10 @@ const Contents = (() => {
metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: { one: ' + {n} sample', other: ' + {n} samples' }, samples: 'Sample chapters, another look',
chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',
doneMark: '✓ Finished · ', lastMark: ' · Last opened',
+ references: 'References', viewAll: 'View all →', backToContents: '← Contents',
+ refsLead: 'Every work cited in the lessons. Each link opens the work’s DOI or library record in a new tab; works with no reliable online record are listed without a link.',
+ refsCount: { one: '{n} work cited in the lessons', other: '{n} works cited in the lessons' },
+ refsAllLinked: ', each linked to its source', refsSomeLinked: ', {n} linked to their sources',
},
ru: {
open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',
@@ -25,6 +30,10 @@ const Contents = (() => {
samples: 'Пробные главы в другом стиле',
chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',
doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',
+ references: 'Список литературы', viewAll: 'Весь список →', backToContents: '← Оглавление',
+ refsLead: 'Все работы, которые цитируются в уроках. Ссылка открывает DOI или библиотечную запись в новой вкладке; работы без надёжной записи в сети даны без ссылки.',
+ refsCount: { one: '{n} работа цитируется в уроках', few: '{n} работы цитируются в уроках', many: '{n} работ цитируются в уроках', other: '{n} работы цитируются в уроках' },
+ refsAllLinked: ', у каждой есть ссылка на источник', refsSomeLinked: ', ссылок на источник: {n}',
},
zh: {
open: '打开这本书', toCover: '返回封面', resume: '继续 · 第 {n} 章', unit: '第 {n} 单元', minutes: '{n} 分钟',
@@ -32,6 +41,9 @@ const Contents = (() => {
metaSamples: ' + {n} 个示例章', samples: '示例章,另一种风格',
chapterCount: '{n} 章', finished: '已完成 {done} / {n}',
doneMark: '✓ 已完成 · ', lastMark: ' · 上次打开',
+ references: '参考文献', viewAll: '查看全部 →', backToContents: '← 目录',
+ refsLead: '课程中引用的全部作品。每个链接会在新标签页中打开该作品的 DOI 或图书馆记录;没有可靠在线记录的作品不附链接。',
+ refsCount: '课程中引用了 {n} 部作品', refsAllLinked: ',均链接到来源', refsSomeLinked: ',其中 {n} 部链接到来源',
},
ja: {
open: '本を開く', toCover: '表紙に戻る', resume: '続きから · 第{n}章', unit: '単元 {n}', minutes: '{n}分',
@@ -39,6 +51,9 @@ const Contents = (() => {
metaSamples: ' + サンプル{n}章', samples: 'サンプル章(別のスタイル)',
chapterCount: '{n}章', finished: '{n}章中 {done}章 完了',
doneMark: '✓ 完了 · ', lastMark: ' · 最後に開いた章',
+ references: '参考文献', viewAll: 'すべて見る →', backToContents: '← 目次',
+ refsLead: '授業で引用したすべての著作です。リンクは著作の DOI または図書館の記録を新しいタブで開きます。信頼できるオンライン記録のない著作はリンクなしで載せています。',
+ refsCount: '授業で引用した著作 {n} 件', refsAllLinked: '、すべて出典へのリンクつき', refsSomeLinked: '、うち {n} 件は出典へのリンクつき',
},
};
const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
@@ -54,7 +69,7 @@ const Contents = (() => {
}
const $ = id => document.getElementById(id);
const id = n => 'ch' + String(n).padStart(2, '0');
- const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
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.
@@ -114,6 +129,20 @@ const Contents = (() => {
}
}
+ // The References view, from refs.js: full entries, each linked to its DOI or catalogue record. It appears as one
+ // link at the end of the contents only when the book cites something.
+ function references() {
+ const all = Object.values(typeof REFS === 'object' && REFS ? REFS : {});
+ if (!$('refList') || !all.length) return;
+ $('refList').innerHTML = all.sort((a, b) => a.ref.localeCompare(b.ref)).map(r => `<li>${esc(r.ref)}${r.url
+ ? ` <a href="${esc(r.url)}" target="_blank" rel="noopener">${esc(r.url.replace(/^https?:\/\//, ''))}</a>` : ''}</li>`).join('');
+ const linked = all.filter(r => r.url).length;
+ $('refsCount').textContent = translate('refsCount', { n: all.length }) +
+ (linked === all.length ? translate('refsAllLinked') : translate('refsSomeLinked', { n: linked }));
+ $('rpBook').innerHTML = document.querySelector('#contents .home strong')?.innerHTML || '';
+ $('refsMore').hidden = false;
+ }
+
// 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 = '';
@@ -134,21 +163,24 @@ const Contents = (() => {
}
}
- // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.
+ // The cover, the contents and the references share this page: no hash or #book shows the cover, #references the
+ // reference list, #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 refs = location.hash === '#references';
+ const open = location.hash.length > 1 && location.hash !== '#book' && !refs;
const apply = () => {
document.body.classList.toggle('open', open);
+ document.body.classList.toggle('refsview', refs);
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');
+ const heading = document.querySelector(refs ? '#refsTitle' : open ? '#contents .home' : '#cover h1');
heading?.setAttribute('tabindex', '-1');
heading?.focus({ preventScroll: true });
}
@@ -184,6 +216,7 @@ const Contents = (() => {
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));
+ references();
guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');
views();
}
diff --git a/site/three-little-pigs/lib/engine.css b/site/three-little-pigs/lib/engine.css
index 9b9be00..9e8e535 100644
--- a/site/three-little-pigs/lib/engine.css
+++ b/site/three-little-pigs/lib/engine.css
@@ -221,6 +221,22 @@ svg.m { display: inline-block; overflow: visible; }
@media (prefers-reduced-motion: reduce) { .card, .fb, .opt, .grid .mark, .mascot * { animation: none !important; } }
a.icon { text-decoration: none; }
+/* Citations (cite() and plain-text labels found in refs.js) and the finish card's source list open the source in a new tab. */
+a.cite { cursor: pointer; }
+a.cite text, a.cite tspan { text-decoration: underline; text-decoration-thickness: 1.5px; text-underline-offset: 5px; }
+a.cite:hover text, a.cite:hover tspan { fill: var(--quiz); }
+a.cite:focus { outline: none; }
+a.cite:focus-visible text, a.cite:focus-visible tspan { fill: var(--task); }
+a.cite:focus-visible { outline: 3px solid var(--task); outline-offset: 6px; border-radius: 4px; }
+#ui a.cite { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
+#ui a.cite:hover { color: var(--quiz); }
+.fin .srcs { margin: 26px 0 0; max-width: 1100px; font-size: 19px; line-height: 1.45; color: var(--dim); text-align: left; }
+.fin .srcs h2 { margin: 0 0 6px; font-size: 18px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
+.fin .srcs ol { margin: 0; padding-left: 0; list-style: none; max-height: 190px; overflow: auto; }
+.fin .srcs li { padding-left: 2em; text-indent: -2em; margin: 0 0 6px; }
+.fin .srcs a { color: var(--chalk); text-underline-offset: 3px; }
+.fin .srcs a:hover { color: var(--quiz); }
+.fin .srcs a:focus-visible { outline: 3px solid var(--task); outline-offset: 2px; }
a.btn { text-decoration: none; display: inline-block; }
/* Page-to-page motion: the contents card grows into this frame, and shrinks back on the way out. */
@view-transition { navigation: auto; }
diff --git a/site/three-little-pigs/lib/engine.js b/site/three-little-pigs/lib/engine.js
index cb6d40b..a33c7db 100644
--- a/site/three-little-pigs/lib/engine.js
+++ b/site/three-little-pigs/lib/engine.js
@@ -38,7 +38,7 @@ const TRANSLATIONS = {
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',
+ chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice', sources: 'Sources in this chapter', opensSource: '{label}, opens the source in a new tab',
firstTryScore: '{name}: {r} of {t} right on the first try.', notAttempted: '{name}: not attempted.',
watchAgain: 'Watch again', nextChapter: 'Next chapter',
},
@@ -74,7 +74,7 @@ const TRANSLATIONS = {
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: 'Практика по главе',
+ chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе', sources: 'Источники этой главы', opensSource: '{label}, источник откроется в новой вкладке',
firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',
watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',
},
@@ -108,7 +108,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 左边 {n} 步',
natural: '正整数', whole: '非负整数', integers: '整数', rational: '有理数', irrational: '无理数', real: '实数', integerColumn: '整数',
trueLabel: '对', falseLabel: '错',
- chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习',
+ chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习', sources: '本章引用的文献', opensSource: '{label},在新标签页中打开来源',
firstTryScore: '{name}:第一次就答对 {r} / {t}。', notAttempted: '{name}:未作答。',
watchAgain: '再看一遍', nextChapter: '下一章',
},
@@ -142,7 +142,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 から左へ {n}',
natural: '自然数', whole: '0 以上の整数', integers: '整数', rational: '有理数', irrational: '無理数', real: '実数', integerColumn: '整数',
trueLabel: '正しい', falseLabel: '誤り',
- chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習',
+ chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習', sources: 'この章の出典', opensSource: '{label}(出典を新しいタブで開く)',
firstTryScore: '{name}:1 回目で {t} 問中 {r} 問正解。', notAttempted: '{name}:未挑戦。',
watchAgain: 'もう一度見る', nextChapter: '次の章へ',
},
@@ -298,6 +298,81 @@ function T(parent, str, { x = 0, y = 0, size = 30, fill = COL.chalk, font = UI,
t.style.whiteSpace = 'pre';
return put(t, { x, y, o });
}
+// A citation drawn in the picture that opens its source (REFS from ../refs.js, built by scripts/refs.py) in a new tab.
+// cite(p, key, opts) takes T's options; str overrides the label (default REFS[key].cite). Returns the <a>; animate it like T.
+const CITED = new Set();
+function cite(parent, key, { str, ...opts } = {}) {
+ const r = (typeof REFS === 'object' && REFS) ? REFS[key] : null;
+ if (!r) throw new Error(`cite: no reference "${key}" in refs.js`);
+ CITED.add(key);
+ if (!r.url) return T(parent, str || r.cite, opts);
+ linkStage();
+ const a = mk('a', { class: 'cite', href: r.url, target: '_blank', rel: 'noopener', 'aria-label': translate('opensSource', { label: r.cite }) }, parent);
+ const { o = 1, x = 0, y = 0, ...rest } = opts;
+ T(a, str || r.cite, { ...rest, fill: rest.fill || COL.chalk });
+ return put(a, { x, y, o });
+}
+// Any text in the picture or a card that equals a reference's cite label or one of its match strings (case-insensitive)
+// becomes a link to the source, so chapters write citations as plain text. Watched by citeObs (set up after the player).
+let CITE_RE = null, CITE_KEY = null;
+function citeIndex() {
+ if (CITE_RE !== null) return CITE_RE;
+ CITE_KEY = new Map();
+ for (const [k, r] of Object.entries(typeof REFS === 'object' && REFS ? REFS : {}))
+ for (const s of [r.cite, ...(r.match || [])]) if (s) CITE_KEY.set(s.toLowerCase(), k);
+ const alts = [...CITE_KEY.keys()].sort((a, b) => b.length - a.length).map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ return (CITE_RE = alts.length ? new RegExp(alts.join('|'), 'gi') : false);
+}
+function autoCite(root) {
+ const re = citeIndex();
+ if (!re) return;
+ const nodes = [];
+ if (root.nodeType === 3) nodes.push(root);
+ else if (root.nodeType === 1) for (let w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n; (n = w.nextNode());) nodes.push(n);
+ for (const n of nodes) {
+ const host = n.parentElement;
+ if (!host || host.closest('a, button, input, script, style, kbd')) continue; // no links inside controls
+ const ms = [...n.data.matchAll(re)];
+ if (!ms.length) continue;
+ const svg = host.namespaceURI === NS, frag = document.createDocumentFragment();
+ let i = 0, made = 0;
+ for (const m of ms) {
+ const k = CITE_KEY.get(m[0].toLowerCase()), r = REFS[k];
+ CITED.add(k);
+ if (!r.url) continue; // a work with no reliable online record stays plain text but is still listed
+ frag.append(n.data.slice(i, m.index));
+ const a = svg ? mk('a', { href: r.url }) : document.createElement('a');
+ if (!svg) a.href = r.url;
+ a.setAttribute('class', 'cite');
+ a.setAttribute('target', '_blank');
+ a.setAttribute('rel', 'noopener');
+ a.setAttribute('aria-label', translate('opensSource', { label: m[0] }));
+ if (svg) mk('tspan', {}, a).textContent = m[0]; else a.textContent = m[0];
+ frag.append(a);
+ i = m.index + m[0].length;
+ made++;
+ }
+ if (!made) continue; // replacing the node unchanged would re-trigger the observer
+ if (svg) linkStage();
+ frag.append(n.data.slice(i));
+ n.replaceWith(frag);
+ }
+}
+// The stage is announced as one image; once it holds a link it becomes a group, so the link stays reachable.
+function linkStage() { document.getElementById('stage').setAttribute('role', 'group'); }
+// Links that have faded out (or sit in a faded group) must not take clicks or Tab focus.
+function syncLinks() {
+ for (const a of scene.querySelectorAll('a.cite')) {
+ let o = 1;
+ for (let e = a; e && e !== scene; e = e.parentNode) o *= +(e.getAttribute('opacity') ?? 1);
+ const on = o > .5;
+ if (on === a._on) continue;
+ a._on = on;
+ a.style.pointerEvents = on ? '' : 'none';
+ if (on) { a.removeAttribute('tabindex'); a.removeAttribute('aria-hidden'); }
+ else { a.setAttribute('tabindex', '-1'); a.setAttribute('aria-hidden', 'true'); }
+ }
+}
const ctx2d = document.createElement('canvas').getContext('2d');
function textW(str, size, italic = false) { ctx2d.font = `${italic ? 'italic ' : ''}${size}px ${MATH}`; return ctx2d.measureText(str).width; }
const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|so|up|we|my)(?![A-Za-z]))[a-z]{1,2}|(?!(?:If|In|It|Is|On|At|No|So|Or|An|As|To|By|Up)(?![A-Za-z]))[a-z]?[A-Z]{1,3}[a-z]?)(?![A-Za-z])/g; // capitals: A, PV, nRT // short lowercase runs are variables (a, x, ab), except short English words
@@ -1244,7 +1319,7 @@ function finishCard() {
: isShortcut(e, 'r') ? (restart(), true) : false;
const guide = mascotEl(240);
c.append(h('div', 'finwrap', [guide, h('p', 'kicker', translate('chapterComplete', { n: CHAPTER.label ?? 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])]));
+ line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again]), sources()].filter(Boolean)));
setTimeout(() => mood(guide, 'happy'), 400);
}
@@ -1253,6 +1328,19 @@ const $ = id => document.getElementById(id);
// The volume control (volume.js, volume.css) lives in its own files next to this one, the same in every book.
document.head.append(Object.assign(document.createElement('script'), { src: new URL('volume.js', document.currentScript.src) }));
const kbd = s => h('kbd', '', s);
+// The chapter's sources: every key passed to cite() plus CHAPTER.refs, as full references that link to the source.
+function sources() {
+ for (const m of citeObs.takeRecords()) for (const n of m.addedNodes) autoCite(n); // link text added just now (a seek to the end)
+ const keys = [...new Set([...(CHAPTER.refs || []), ...CITED])].filter(k => typeof REFS === 'object' && REFS?.[k]);
+ if (!keys.length) return null;
+ const items = keys.map(k => REFS[k]).sort((a, b) => a.ref.localeCompare(b.ref)).map(r => {
+ if (!r.url) return h('li', '', r.ref);
+ const a = h('a', '', r.url.replace(/^https?:\/\//, ''));
+ Object.assign(a, { href: r.url, target: '_blank', rel: 'noopener' });
+ return h('li', '', [r.ref + ' ', a]);
+ });
+ return h('section', 'srcs', [h('h2', '', translate('sources')), h('ol', '', items)]);
+}
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
const SCORE = {}; // question id -> first-attempt {right, total}
@@ -1391,6 +1479,13 @@ 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; },
};
};
+// A choice question from the chapter's item bank: ITEMS from ./items.js, built by scripts/items.py from the
+// mcq-item-writer JSON. mcq('ID', onRight?) returns a quiz entry, so quiz(TOPR, [mcq('MB-03-01')], done) asks it.
+function mcq(id, onRight) {
+ const it = (typeof ITEMS === 'object' && ITEMS) ? ITEMS[id] : null;
+ if (!it) throw new Error(`mcq: no item "${id}" in items.js`);
+ return { id, prompt: it.prompt, build: choice(it.opts, it.right, it.why, it.no, onRight) };
+}
// 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) => {
@@ -1898,6 +1993,7 @@ function frame(now) {
evalTo(P.t);
if (P.t >= P.end) beatDone();
}
+ syncLinks();
ui();
requestAnimationFrame(frame);
}
@@ -1957,9 +2053,13 @@ const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
const restart = () => { for (const k in SCORE) delete SCORE[k]; hideCover(); seek(0, true); };
$('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
+ if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
});
+const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
+citeObs.observe(scene, { childList: true, subtree: true });
+citeObs.observe($('ui'), { childList: true, subtree: true });
$('bPlay').onclick = togglePlay;
$('bBack').onclick = () => { hideCover(); back1(); };
$('bRestart').onclick = restart;