@openbooknetwork/hesap 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +116 -2
  3. package/package.json +45 -4
  4. package/scripts/assemble.mjs +40 -0
  5. package/src/client.css +240 -0
  6. package/src/client.js +111 -0
  7. package/src/families/counters/bonds.js +424 -0
  8. package/src/families/counters/client.css +150 -0
  9. package/src/families/counters/client.js +22 -0
  10. package/src/families/counters/count-figures.js +166 -0
  11. package/src/families/counters/count-goals.js +57 -0
  12. package/src/families/counters/count-model.js +57 -0
  13. package/src/families/counters/count.js +322 -0
  14. package/src/families/counters/count.mjs +88 -0
  15. package/src/families/counters/counter.js +52 -0
  16. package/src/families/counters/driver.js +16 -0
  17. package/src/families/counters/figures.js +172 -0
  18. package/src/families/counters/frame.js +28 -0
  19. package/src/families/counters/goals.js +75 -0
  20. package/src/families/counters/i18n/en.yaml +86 -0
  21. package/src/families/counters/i18n/tr.yaml +86 -0
  22. package/src/families/counters/index.mjs +104 -0
  23. package/src/families/counters/model.js +86 -0
  24. package/src/families/counters/move.js +44 -0
  25. package/src/families/counters/places.js +45 -0
  26. package/src/families.mjs +5 -0
  27. package/src/i18n/en.yaml +101 -0
  28. package/src/i18n/tr.yaml +101 -0
  29. package/src/index.mjs +82 -0
  30. package/src/kit/dom.js +32 -0
  31. package/src/kit/drag.js +40 -0
  32. package/src/kit/format.js +34 -0
  33. package/src/kit/goal.js +49 -0
  34. package/src/kit/i18n/en.yaml +15 -0
  35. package/src/kit/i18n/tr.yaml +15 -0
  36. package/src/kit/kit.css +89 -0
  37. package/src/kit/motion.js +44 -0
  38. package/src/kit/panel.js +70 -0
  39. package/src/kit/play.js +26 -0
  40. package/src/kit/random.js +35 -0
  41. package/src/kit/text.js +25 -0
  42. package/src/node.mjs +50 -0
@@ -0,0 +1,34 @@
1
+ // How numbers and worked formulas are written in a language. The browser and the build both use it, so a page's
2
+ // text and its live values agree.
3
+ const MINUS = '−';
4
+ // fill puts values into a string's {name} places. A string with one {x} takes a plain value.
5
+ export function fill(s, vars) {
6
+ if (vars === undefined || vars === null || s === undefined) return s;
7
+ return typeof vars === 'object' ? s.replace(/\{(\w+)\}/g, (m, k) => vars[k] ?? m) : s.replace('{x}', () => vars);
8
+ }
9
+ export function numbers(lang) {
10
+ const nf = (min, max) => new Intl.NumberFormat(lang, { minimumFractionDigits: min, maximumFractionDigits: max, useGrouping: false });
11
+ const grouped = new Intl.NumberFormat(lang, { maximumFractionDigits: 0 });
12
+ const comma = nf(1, 1).format(0.5).includes(',');
13
+ // -0 is written as 0, and a negative number takes the real minus sign.
14
+ const sign = s => /^-0([.,]0*)?$/.test(s) ? s.slice(1) : s.replace(/^-/, MINUS);
15
+ return {
16
+ comma,
17
+ // fmt writes a number with up to max decimals, and fix with exactly n.
18
+ fmt: (n, max = 2) => sign(nf(0, max).format(n)),
19
+ fix: (n, digits) => sign(nf(digits, digits).format(n)),
20
+ // int writes a count with the language's grouping of thousands. fmt and fix write a measure, which has none.
21
+ int: n => sign(grouped.format(n)),
22
+ // A pair of coordinates takes a semicolon where the language writes decimals with a comma.
23
+ pair: (a, b, max = 2) => `(${sign(nf(0, max).format(a))}${comma ? '; ' : ', '}${sign(nf(0, max).format(b))})`,
24
+ // tex writes a number for KaTeX, which needs braces round a decimal comma and a plain minus.
25
+ tex: (n, max = 2) => nf(0, max).format(n).replace(/^-0([.,]0*)?$/, '0').replace(',', '{,}'),
26
+ // brace makes a number that is written already safe for KaTeX, which spaces a bare comma as punctuation.
27
+ brace: s => s.replace(/,/g, '{,}'),
28
+ // percent writes a share such as 0.25 as 25%, with the sign on the side the language puts it.
29
+ percent: (n, max = 0) => new Intl.NumberFormat(lang, { style: 'percent', maximumFractionDigits: max }).format(n),
30
+ };
31
+ }
32
+ // aligned sets the steps of a worked formula under one another at their equals signs. The first step is the name
33
+ // and each later step starts with its relation, such as "= 12".
34
+ export const aligned = ([what, ...rest], gap = '0.4em') => `\\begin{aligned} ${what} &${rest.join(` \\\\[${gap}] &`)} \\end{aligned}`;
@@ -0,0 +1,49 @@
1
+ // The line a challenge page shows above its controls: the goal in words, whether it is reached, a hint and another
2
+ // target. Every family judges with its own goal and shows the result here.
3
+ import { h, icon } from './dom.js';
4
+ import { button } from './panel.js';
5
+
6
+ // T gives the shared strings. hint is a function that shows or hides the family's hint and is left out on a page
7
+ // without one, and another moves to the next target. actions are more buttons for the line. A quiet line is for a
8
+ // page whose title states the goal: it has no goal text and says nothing until the goal is reached.
9
+ export function goalRow({ T, hint, another, motion, actions = [], quiet = false }) {
10
+ const text = h('p', { class: 'hesap-goal-text' }), state = h('span', { class: 'hesap-goal-state', role: 'status' });
11
+ const hintText = h('p', { class: 'hesap-hint', hidden: true });
12
+ let done = false, hinted = false;
13
+ // A hint is words, or an element the family built, such as a formula. kept says the hint opens again after a
14
+ // change of language, so the family shows it without marking it as new.
15
+ const toggle = kept => {
16
+ hinted = !hinted; hintBtn.setAttribute('aria-expanded', hinted);
17
+ const words = hint(hinted, kept); hintText.replaceChildren(...(words ? [words] : [])); hintText.hidden = !hinted || !words;
18
+ };
19
+ const hintBtn = hint ? button({ label: T('hint'), act: 'hint', press: () => toggle(false) }) : null;
20
+ hintBtn?.setAttribute('aria-expanded', 'false');
21
+ text.hidden = quiet;
22
+ const el = h('div', { class: `hesap-goal${quiet ? ' hesap-quiet' : ''}` }, [text, state, another ? button({ label: T('another'), act: 'another', press: another }) : null, hintBtn, ...actions, hintText].filter(Boolean));
23
+ return {
24
+ el, text, hintText,
25
+ // say writes the goal. A family that sets formulas in the goal writes into text itself.
26
+ say(words) { if (words instanceof Node) text.replaceChildren(words); else if (text.textContent !== (words ?? '')) text.textContent = words ?? ''; },
27
+ // show says whether the goal is reached. note is a line of progress for a goal not reached yet. It returns true
28
+ // the first time the goal is reached, when the family cheers.
29
+ show(reached, note) {
30
+ const words = reached ? T('solved') : note ?? (quiet ? '' : T('not-yet'));
31
+ if (state.dataset.words !== words) { state.dataset.words = words; state.replaceChildren(...(reached ? [icon('tick'), h('b', {}, words)] : [words])); }
32
+ el.classList.toggle('solved', reached);
33
+ const first = reached && !done; done = reached;
34
+ if (first) motion?.pop(state);
35
+ return first;
36
+ },
37
+ reached: () => done,
38
+ hinted: () => hinted,
39
+ // keep carries over the state of the line this one replaces, when a change of language builds the panel again.
40
+ // A goal reached already stays reached without its pop, and an open hint opens again.
41
+ keep(old) {
42
+ if (!old) return;
43
+ done = old.reached();
44
+ if (old.hinted() && hintBtn && !hinted) toggle(true);
45
+ },
46
+ // reset closes the hint and forgets the last result, for another target.
47
+ reset() { done = false; hinted = false; hintBtn?.setAttribute('aria-expanded', 'false'); hintText.hidden = true; },
48
+ };
49
+ }
@@ -0,0 +1,15 @@
1
+ hint: Move the figure and watch the numbers follow it.
2
+ tab_map: Figure
3
+ map_data: Data
4
+ map_view: View
5
+ chronology: Contents
6
+ layout_center: Figure in the middle
7
+ view_reset: Reset
8
+ hesap_start: Start
9
+ hesap_time: Time
10
+ hesap_reset: Start again
11
+ hesap_undo: Undo
12
+ hesap_hint: Hint
13
+ hesap_another: Another one
14
+ hesap_solved: Solved
15
+ hesap_not-yet: Not solved yet.
@@ -0,0 +1,15 @@
1
+ hint: Şekli hareket ettirin ve sayıların onu izleyişine bakın.
2
+ tab_map: Şekil
3
+ map_data: Veri
4
+ map_view: Görünüm
5
+ chronology: İçindekiler
6
+ layout_center: Şekil ortada
7
+ view_reset: Sıfırla
8
+ hesap_start: Başlat
9
+ hesap_time: Zaman
10
+ hesap_reset: Baştan başla
11
+ hesap_undo: Geri al
12
+ hesap_hint: İpucu
13
+ hesap_another: Bir tane daha
14
+ hesap_solved: Çözüldü
15
+ hesap_not-yet: Henüz çözülmedi.
@@ -0,0 +1,89 @@
1
+ /* Hesap has a layer of its own, so nothing in a figure rises over a phone's text. Each family draws inside its own
2
+ box, which fills the viewport while one of its pages shows. */
3
+ .hesap{position:absolute;inset:0;background:var(--paper);isolation:isolate;user-select:none;-webkit-user-select:none;font-family:var(--body);color:var(--ink)}
4
+ .hesap-family{position:absolute;inset:0;display:flex;flex-direction:column}
5
+ .hesap-family[hidden],.hesap-stage[hidden],.hesap-panel[hidden],.hesap-cover[hidden],.hesap-panel [hidden]{display:none}
6
+ .hesap-cover{position:absolute;inset:0;width:100%;height:100%;object-fit:contain}
7
+ .hesap-stage{flex:1;min-height:0;position:relative}
8
+ /* On a screen with room the readouts stand above the figure in large type. */
9
+ .hesap-head{padding:.857rem 1.143rem 0}
10
+ .hesap-head[hidden]{display:none}
11
+ .hesap-head .hesap-out{gap:.571rem 1.714rem;align-items:flex-end}
12
+ .hesap-head .hesap-chip{flex-direction:column;align-items:flex-start;gap:.071rem;border:0;border-radius:0;padding:0;background:none;box-shadow:none}
13
+ .hesap-head .hesap-chip small{font-size:.857rem}
14
+ .hesap-head .hesap-chip b{font-family:var(--display);font-size:2.286rem;line-height:1.1;text-align:start}
15
+ .hesap-head .hesap-chip.hot b,.hesap-head .hesap-chip[aria-pressed="true"] b{color:var(--accent)}
16
+ .hesap-head .hesap-btn{margin-inline-start:auto}
17
+
18
+ /* The panel under the figure holds a challenge's line, then the controls, then the readouts. */
19
+ .hesap-panel{position:relative;border-top:1px solid var(--rule);background:var(--panel);padding:.571rem .857rem;display:flex;flex-direction:column;gap:.5rem}
20
+ .hesap-ctls,.hesap-acts{display:flex;flex-wrap:wrap;gap:.429rem .857rem;align-items:center}
21
+ .hesap-acts{margin-inline-start:auto}
22
+ .hesap-out{display:flex;flex-wrap:wrap;gap:.357rem .429rem;align-items:center}
23
+ .hesap-panel .hot{outline:2px solid var(--accent);outline-offset:2px}
24
+
25
+ /* A slider takes the room the other controls leave on its row. */
26
+ .hesap-ctl{flex:1 1 14rem;display:flex;align-items:center;gap:.571rem;min-height:44px;border-radius:6px}
27
+ .hesap-ctl span{color:var(--ink-2);white-space:nowrap}
28
+ .hesap-ctl input{flex:1;min-width:0;min-height:44px;margin:0;accent-color:var(--accent)}
29
+ .hesap-ctl output{font-variant-numeric:tabular-nums;font-weight:700;text-align:end;min-width:3ch}
30
+
31
+ .hesap-btn,.hesap-seg button,.hesap-step button{min-height:44px;min-width:44px;border:1px solid var(--rule);background:var(--paper);color:var(--ink);font:inherit;cursor:pointer;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;gap:.357rem;padding:0 .714rem;white-space:nowrap}
32
+ .hesap-btn:disabled,.hesap-step button:disabled{opacity:.45;cursor:default}
33
+ .hesap-icon{width:18px;height:18px;flex:none}
34
+ :is(.hesap-btn,.hesap-seg button,.hesap-step button,.hesap-chip):focus-visible{outline:2px solid var(--accent);outline-offset:2px}
35
+ .hesap-btn[aria-pressed="true"]{background:var(--ink);color:var(--paper);border-color:var(--ink)}
36
+ /* The one button that starts something stands out. */
37
+ .hesap-primary{background:var(--accent);border-color:var(--accent);color:var(--paper);font-weight:700;padding:0 1.143rem}
38
+
39
+ .hesap-seg{display:inline-flex;align-items:center}
40
+ .hesap-seg-name{color:var(--ink-2);font-size:.857rem;margin-inline-end:.429rem}
41
+ .hesap-seg button{border-radius:0;margin-inline-start:-1px;font-variant-numeric:tabular-nums;padding:0 .571rem}
42
+ .hesap-seg button:first-of-type{border-start-start-radius:6px;border-end-start-radius:6px;margin-inline-start:0}
43
+ .hesap-seg button:last-of-type{border-start-end-radius:6px;border-end-end-radius:6px}
44
+ .hesap-seg button[aria-pressed="true"]{background:var(--ink);color:var(--paper);border-color:var(--ink);position:relative}
45
+
46
+ .hesap-step{display:inline-flex;align-items:center;gap:.357rem}
47
+ .hesap-step span{color:var(--ink-2);margin-inline-end:.214rem}
48
+ .hesap-step output{min-width:2.5ch;text-align:center;font-weight:700;font-variant-numeric:tabular-nums}
49
+
50
+ .hesap-chip{display:inline-flex;gap:.429rem;align-items:baseline;border:1px solid var(--rule);border-radius:999px;padding:.286rem .786rem;background:var(--paper);color:var(--ink);font:inherit}
51
+ button.hesap-chip{cursor:pointer;min-height:36px;align-items:center}
52
+ .hesap-chip small{color:var(--ink-2);font-size:.857rem;white-space:nowrap}
53
+ .hesap-chip b{font-variant-numeric:tabular-nums;text-align:end}
54
+ .hesap-swatch{width:.714rem;height:.714rem;border-radius:50%;flex:none;align-self:center;background:currentColor}
55
+ .hesap-short{display:none}
56
+ .hesap-chip.hot{outline:none;border-color:var(--accent);box-shadow:inset 0 0 0 1px var(--accent)}
57
+ .hesap-chip[aria-pressed="true"]{border-color:var(--ink);box-shadow:inset 0 0 0 1px var(--ink)}
58
+
59
+ /* A challenge's line holds the goal, whether it is reached, another target and a hint. The goal takes a line of its
60
+ own, so a longer status keeps the panel's height. */
61
+ .hesap-goal{display:flex;flex-wrap:wrap;align-items:center;gap:.286rem .571rem}
62
+ .hesap-goal-text{margin:0;flex-basis:100%;font-weight:600}
63
+ .hesap-goal-state{display:inline-flex;align-items:center;gap:.286rem;color:var(--ink-2);flex:1;min-width:0}
64
+ .hesap-goal.solved .hesap-goal-state{color:var(--accent)}
65
+ .hesap-goal-state svg{width:20px;height:20px}
66
+ .hesap-hint{margin:0;flex-basis:100%;color:var(--ink-2)}
67
+ .hesap-hint[hidden]{display:none}
68
+
69
+ /* The values in the text follow the figure. A worked formula takes its own line, and scrolls sideways on a narrow
70
+ screen. */
71
+ aside.story .place[data-live]{font-variant-numeric:tabular-nums;font-weight:700}
72
+ aside.story .place[data-formula],aside.story .place[data-formula]:is(:hover,:focus-visible,.on){display:block;text-decoration:none;background:none;overflow-x:auto;overflow-y:hidden;padding:.143rem 0}
73
+ aside.story .place[data-formula] .katex-display{margin:0;text-align:start}
74
+ aside.story .place[data-formula] .katex-display>.katex{text-align:start}
75
+
76
+ @media (max-width:900px){
77
+ .hesap-panel{padding:.429rem .571rem;gap:.357rem}
78
+ .hesap-ctls,.hesap-acts{gap:.286rem .571rem}
79
+ .hesap-btn,.hesap-seg button,.hesap-step button{min-height:42px}
80
+ .hesap-chip{padding:.214rem .643rem}
81
+ .hesap-chip small{font-size:.786rem}
82
+ .hesap-long{display:none}
83
+ .hesap-short{display:inline}
84
+ /* A compact button shows its glyph alone. */
85
+ .hesap-compact{min-width:44px;padding:0}
86
+ .hesap-compact span{display:none}
87
+ /* The peek card sits above the panel. A figure stays clear of the card by leaving --hesap-peek free at its foot. */
88
+ .peek{bottom:calc(var(--hesap-panel,0px) + .571rem)}
89
+ }
@@ -0,0 +1,44 @@
1
+ // A tracker runs anime.js animations and remembers the ones still running, so a page change can stop them all.
2
+ // Times are in milliseconds.
3
+ export function tracker() {
4
+ // live maps each running animation to what runs when a page change cuts it short.
5
+ const { animate, createTimeline, stagger } = window.anime, live = new Map(), groups = new Set();
6
+ // CSS transforms on SVG scale and turn an element about its own middle.
7
+ const centre = els => { for (const e of [els].flat()) if (e?.style) { e.style.transformBox = 'fill-box'; e.style.transformOrigin = 'center'; } return els; };
8
+ // anime.js keeps one then for each animation, so an animation ends through onComplete and done runs there. A
9
+ // run that stop cuts short never reaches done, and cut runs in its place, to take away what the run added.
10
+ function run(targets, params, done, cut) {
11
+ const a = animate(targets, { ...params, onComplete: () => { live.delete(a); params.onComplete?.(); done?.(); } });
12
+ live.set(a, cut);
13
+ return a;
14
+ }
15
+ // An effect on an element that stays on the page goes back to where it began when it is cut short.
16
+ const effect = (targets, params) => { const a = run(targets, params, null, () => a.revert()); return a; };
17
+ // timeline runs phases one after another. Each phase is the params of one animation with its targets.
18
+ function timeline(phases, done, defaults = {}, cut) {
19
+ const tl = createTimeline({ defaults, onComplete: () => { live.delete(tl); done?.(); } });
20
+ for (const { targets, at, ...params } of phases) tl.add(targets, params, at);
21
+ live.set(tl, cut);
22
+ return tl;
23
+ }
24
+ return {
25
+ run, timeline, stagger, centre,
26
+ // group gives a tracker of its own, so a family can stop one kind of animation and let the others run. The
27
+ // page's stop ends every group too.
28
+ group() { const g = tracker(); groups.add(g); return g; },
29
+ stop() {
30
+ const cuts = [...live];
31
+ live.clear();
32
+ for (const [a, cut] of cuts) { a.pause(); cut?.(); }
33
+ for (const g of groups) g.stop();
34
+ },
35
+ // adopt prepares every element of class a under root for scaling about its middle.
36
+ adopt(root) { centre([...root.querySelectorAll('.a')]); },
37
+ // A value that changed jumps once.
38
+ flash: el => effect(centre(el), { scale: [1, 1.08, 1], duration: 320, ease: 'outQuad' }),
39
+ pop: el => effect(centre(el), { scale: [1, 1.25, 1], duration: 320, ease: 'outQuad' }),
40
+ pulse: el => effect(centre(el), { scale: [1, 1.08, 1], duration: 420, ease: 'outQuad' }),
41
+ // The parts that reach a goal swell once, one after another.
42
+ cheer: els => els.length ? effect(centre(els), { scale: [1, 1.2, 1], duration: 520, delay: stagger(Math.min(60, 400 / els.length)), ease: 'outBack' }) : null,
43
+ };
44
+ }
@@ -0,0 +1,70 @@
1
+ // The controls and readouts docked under a figure. Every family builds its panel from these parts, so a slider, a
2
+ // chip and a button look and behave the same on every page.
3
+ import { h, icon } from './dom.js';
4
+ import { math } from './text.js';
5
+
6
+ // slider is a labelled range input with its value written beside it. write turns the number into words, input runs
7
+ // while the reader drags, and change runs when the reader lets go. A slider with no value to read, such as time,
8
+ // passes output: false, and its value is still spoken.
9
+ export function slider({ id, label, min, max, step = 1, value, write = String, input, change, output = true, cls = '' }) {
10
+ const range = h('input', { type: 'range', min, max, step }), out = h('output', { hidden: !output });
11
+ const row = h('label', { class: `hesap-ctl ${cls}`.trim(), 'data-ref': id }, [h('span', {}, label), range, out]);
12
+ const show = v => { const words = write(v); out.textContent = words; range.setAttribute('aria-valuetext', words); };
13
+ const set = v => { range.value = v; show(Number(range.value)); };
14
+ range.addEventListener('input', () => { show(Number(range.value)); input?.(Number(range.value)); });
15
+ range.addEventListener('change', () => change?.(Number(range.value)));
16
+ set(value);
17
+ // width keeps the value's room steady while it changes, counted in characters.
18
+ return { el: row, range, set, show, get: () => Number(range.value), width: ch => { out.style.minWidth = `${ch}ch`; } };
19
+ }
20
+ // chip is a readout: a name and a value that follows the figure. A chip the reader can press is a button. swatch
21
+ // is a class for a dot of the colour the figure draws the measure in, and short is a name for a phone.
22
+ export function chip({ id, label, short, swatch, press, cls = '' }) {
23
+ const small = h('small', {}, short ? [h('span', { class: 'hesap-long' }, label), h('span', { class: 'hesap-short' }, short)] : label ?? ''), b = h('b');
24
+ const dot = swatch ? [h('i', { class: `hesap-swatch ${swatch}`, 'aria-hidden': 'true' })] : [];
25
+ const el = h(press ? 'button' : 'span', { class: `hesap-chip ${cls}`.trim(), 'data-ref': id, type: press ? 'button' : null }, label === null ? [...dot, b] : [...dot, small, b]);
26
+ if (press) el.addEventListener('click', () => press(id));
27
+ return {
28
+ el, id, value: b,
29
+ // set writes a new value and says whether it changed, so the family can mark the change.
30
+ set(text) { if (b.textContent === text) return false; const first = !b.textContent; b.textContent = text; return !first; },
31
+ // name writes the readout's name. A chip with a short name keeps it, and takes a new one as the second word.
32
+ name(text, brief) {
33
+ const long = small.querySelector('.hesap-long');
34
+ if (!long) { if (small.textContent !== text) small.textContent = text; return; }
35
+ long.textContent = text;
36
+ if (brief !== undefined) small.querySelector('.hesap-short').textContent = brief;
37
+ },
38
+ // tex sets the value as a formula.
39
+ tex(source, options) { math(b, source, false, options); },
40
+ width: ch => { b.style.minWidth = `${ch}ch`; },
41
+ };
42
+ }
43
+ // button is an action. A primary button starts something, and at most one stands on a page. A compact button with
44
+ // a glyph shows the glyph alone on a phone and keeps its label as its name.
45
+ export function button({ label, act, press, primary = false, glyph = null, compact = false, cls = '' }) {
46
+ const el = h('button', { type: 'button', class: `hesap-btn${primary ? ' hesap-primary' : ''}${compact && glyph ? ' hesap-compact' : ''} ${cls}`.trim(), 'data-act': act, 'aria-label': compact ? label : null, title: compact ? label : null }, [...(glyph ? [icon(glyph)] : []), h('span', {}, label)]);
47
+ if (press) el.addEventListener('click', press);
48
+ return el;
49
+ }
50
+ // segment is one choice out of a few, each a button. items are [value, words] pairs.
51
+ export function segment({ id, label, items, value, pick }) {
52
+ const buttons = items.map(([v, words]) => h('button', { type: 'button', 'data-v': v }, words));
53
+ const el = h('div', { class: 'hesap-seg', role: 'group', 'aria-label': label, 'data-ref': id }, [...(label ? [h('span', { class: 'hesap-seg-name' }, label)] : []), ...buttons]);
54
+ const set = v => { value = v; buttons.forEach((b, i) => b.setAttribute('aria-pressed', String(items[i][0]) === String(v))); };
55
+ buttons.forEach((b, i) => b.addEventListener('click', () => { if (String(items[i][0]) === String(value)) return; set(items[i][0]); pick(items[i][0]); }));
56
+ set(value);
57
+ return { el, set, get: () => value };
58
+ }
59
+ // stepper is a whole number with a button on each side to take one away or add one.
60
+ export function stepper({ id, label, min, max, step = 1, value, write = String, change }) {
61
+ const out = h('output'), less = h('button', { type: 'button', 'aria-label': `${label} −` }, '−'), more = h('button', { type: 'button', 'aria-label': `${label} +` }, '+');
62
+ const el = h('div', { class: 'hesap-step', role: 'group', 'aria-label': label, 'data-ref': id }, [h('span', {}, label), less, out, more]);
63
+ const set = v => { value = Math.max(min, Math.min(max, v)); out.textContent = write(value); less.disabled = value <= min; more.disabled = value >= max; };
64
+ less.addEventListener('click', () => { set(value - step); change(value); });
65
+ more.addEventListener('click', () => { set(value + step); change(value); });
66
+ set(value);
67
+ return { el, set, get: () => value };
68
+ }
69
+ // row groups parts of the panel: ctl for controls, out for readouts, acts for buttons.
70
+ export const row = (kind, parts) => h('div', { class: `hesap-${kind}` }, parts.filter(Boolean).map(p => p.el ?? p));
@@ -0,0 +1,26 @@
1
+ // A run that plays by itself. Start plays it once to its end, and a slider beside it goes back and forth through
2
+ // the same run. There is no Pause: a reader who drags the slider takes over.
3
+ // player drives time t from 0 to 1 over duration milliseconds. at draws the run at t, and now reads where the run
4
+ // stands. ease maps the share of time that has passed to t.
5
+ export function player({ duration, at, now, moving, ease = x => x, onState }) {
6
+ let raf = 0;
7
+ const state = on => onState?.(on);
8
+ function halt() { if (!raf) return; cancelAnimationFrame(raf); raf = 0; state(false); }
9
+ // A run that has ended plays again from the beginning, and again runs first to let the family draw a new one.
10
+ function start(again) {
11
+ halt();
12
+ let from = now();
13
+ if (from >= 1) { again?.(); from = 0; }
14
+ if (!moving()) return at(1);
15
+ const span = duration * (1 - from); let t0 = 0;
16
+ state(true);
17
+ const step = t => {
18
+ t0 ||= t;
19
+ const x = Math.min(1, (t - t0) / span);
20
+ at(from + (1 - from) * ease(x));
21
+ if (x < 1) raf = requestAnimationFrame(step); else { raf = 0; state(false); }
22
+ };
23
+ raf = requestAnimationFrame(step);
24
+ }
25
+ return { start, halt, playing: () => !!raf };
26
+ }
@@ -0,0 +1,35 @@
1
+ // Seeded random numbers. One seed always gives the same numbers, so a test replays a run and a build checks the
2
+ // challenges a page can draw. A reader's page takes a fresh seed each time.
3
+
4
+ // mulberry32 is small, fast and even enough for coins, dice and drawn challenges.
5
+ export function generator(seed) {
6
+ let a = seed >>> 0;
7
+ return () => {
8
+ a = a + 0x6D2B79F5 | 0;
9
+ let t = Math.imul(a ^ a >>> 15, 1 | a);
10
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
11
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
12
+ };
13
+ }
14
+
15
+ // hash runs FNV-1a over a text, to make a page's own seed when its page.yaml names none.
16
+ export function hash(text) {
17
+ let h = 0x811c9dc5;
18
+ for (const c of String(text)) h = Math.imul(h ^ c.codePointAt(0), 0x01000193);
19
+ return h >>> 0;
20
+ }
21
+
22
+ // seedOf uses the page's seed for the first run and makes a new one for each run after it.
23
+ export const seedOf = (base, run) => run ? hash(`${base}:${run}`) : base >>> 0;
24
+
25
+ // fresh gives a seed no reader can predict, for a challenge drawn as its page opens.
26
+ export const fresh = () => (globalThis.crypto?.getRandomValues ? globalThis.crypto.getRandomValues(new Uint32Array(1))[0] : Math.floor(Math.random() * 4294967296)) >>> 0;
27
+
28
+ // dice wraps a seed in the draws a goal needs: a whole number in a range, one of a list, a list in a new order and
29
+ // a few of a list.
30
+ export function dice(seed) {
31
+ const next = generator(seed);
32
+ const int = (lo, hi) => lo + Math.floor(next() * (hi - lo + 1));
33
+ const shuffle = items => { const a = [...items]; for (let i = a.length - 1; i > 0; i--) { const j = int(0, i); [a[i], a[j]] = [a[j], a[i]]; } return a; };
34
+ return { next, int, pick: items => items[int(0, items.length - 1)], shuffle, some: (items, n) => shuffle(items).slice(0, n) };
35
+ }
@@ -0,0 +1,25 @@
1
+ // The values in a page's text follow the figure. A text links a value as [words](@id) and a worked formula as
2
+ // [words](@formula-id), and kitap leaves a span with data-ref in their place.
3
+ // live writes every link of the story. value gives the words of an id or null for a link the family does not own,
4
+ // and formula gives the TeX of a worked formula. tex gives the TeX of a value that is set as a formula in its line,
5
+ // such as a fraction, and null for a value written as words.
6
+ export function live(host, { value, formula, tex, katex = {} }) {
7
+ for (const span of host.el.story.querySelectorAll('.place[data-ref]')) {
8
+ const id = span.dataset.ref;
9
+ if (id.startsWith('formula-')) {
10
+ const tex = formula?.(id.slice(8));
11
+ if (tex == null || span.dataset.tex === tex) continue;
12
+ span.dataset.tex = tex; span.dataset.formula = ''; span.removeAttribute('tabindex');
13
+ window.katex.render(tex, span, { displayMode: true, throwOnError: false, ...katex });
14
+ continue;
15
+ }
16
+ const source = tex?.(id);
17
+ if (source != null) { math(span, source, false, katex); span.dataset.live = ''; continue; }
18
+ const text = value(id);
19
+ if (text == null) continue;
20
+ if (span.textContent !== text) span.textContent = text;
21
+ span.dataset.live = '';
22
+ }
23
+ }
24
+ // math sets a short piece of TeX inside an element. options go to KaTeX, such as trust for \\htmlClass.
25
+ export const math = (node, tex, display = false, options = {}) => { if (node.dataset.tex !== tex) { node.dataset.tex = tex; window.katex.render(tex, node, { displayMode: display, throwOnError: false, ...options }); } return node; };
package/src/node.mjs ADDED
@@ -0,0 +1,50 @@
1
+ // What every family's Node half shares: escaping, the link pattern of a text, the links object kitap asks for and
2
+ // the checks every challenge gets.
3
+ import { dice } from './kit/random.js';
4
+
5
+ export const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
6
+ export const list = ids => [...ids].join(', ');
7
+ // A text links a measure, a control or a worked formula as [words](@id).
8
+ export const LINK = /\[([^\]]+)\]\(@([^)\s]+)\)/g;
9
+
10
+ // links tells kitap which ids a page's text may link. has says whether an id exists, and offers names what to link.
11
+ export const links = (has, offers) => ({
12
+ has, attr: id => ` data-ref="${esc(id)}"`, names: () => [],
13
+ missing: (name, id) => `[${name}](@${id}) links to "${id}", link ${offers}`,
14
+ });
15
+
16
+ // challenge finds the goal a page names and fails a page whose goal is unknown or belongs to another scene. A goal
17
+ // lists the scenes it works on as scenes, and a goal without the list works on every scene of its family.
18
+ export function challenge(c, goals, { scene, at, ctx }) {
19
+ const goal = goals[c.goal];
20
+ if (!goal) { ctx.fail(at, `challenge.goal is "${c.goal}", the goals are ${list(Object.keys(goals))}`); return null; }
21
+ if (goal.scenes && !goal.scenes.includes(scene)) { ctx.fail(at, `challenge.goal ${c.goal} works on ${list(goal.scenes)}, this page shows ${scene}`); return null; }
22
+ return goal;
23
+ }
24
+ // drawn checks a goal whose target the page draws as it opens. It draws SAMPLES targets from seeds 1 to SAMPLES and
25
+ // fails the page when the goal has nothing to draw, when a draw is solved as the page opens, or when the page's
26
+ // controls cannot reach it. starts gives the page's state for a target, and the goal's reach names what stops a
27
+ // target from being reached.
28
+ const SAMPLES = 300;
29
+ export function drawn(goal, c, spec, { at, ctx, starts }) {
30
+ for (let seed = 1; seed <= SAMPLES; seed++) {
31
+ let target;
32
+ try { target = goal.draw(c, spec, dice(seed)); } catch (err) { return ctx.fail(at, `challenge.goal ${c.goal} cannot draw a target: ${err.message}`); }
33
+ if (target === null || target === undefined) return ctx.fail(at, `challenge.goal ${c.goal} draws nothing from what the page declares, widen its ranges`);
34
+ const state = starts(spec, target), words = JSON.stringify(target);
35
+ if (goal.holds(state, spec, c, target).done) return ctx.fail(at, `challenge.goal ${c.goal} can draw ${words}, which is reached as the page opens`);
36
+ const stop = goal.reach?.(spec, c, target);
37
+ if (stop) return ctx.fail(at, `challenge.goal ${c.goal} can draw ${words}, and ${stop}`);
38
+ }
39
+ }
40
+ // hidden fails a page whose readout shows a measure that gives the challenge's answer away.
41
+ export function hidden(readout, hides, at, ctx) {
42
+ for (const id of readout) if (hides.includes(id)) ctx.fail(at, `readout names "${id}", which gives the challenge's answer away, leave it out`);
43
+ }
44
+ // value reads a field that is a number, a slider or a stepper as its starting value and its control's range.
45
+ export function value(v) {
46
+ if (v == null) return { n: null, ctl: null };
47
+ if (typeof v === 'number') return { n: v, ctl: null };
48
+ const kind = v.slider ? 'slider' : 'stepper', [lo, hi] = v[kind];
49
+ return { n: v.start ?? lo, ctl: { kind, lo, hi } };
50
+ }