@openbooknetwork/hesap 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,414 @@
1
+ // The bonds scene: a whole and its two parts. Counters sit in the parts of a diagram, in two hands, in ten frames, as
2
+ // pins in a lane or as cars in a car park. The reader drags them between parts, taps cells, sets a part or the whole,
3
+ // swaps the parts, fills a frame and lifts a cup, and a list logs each split found.
4
+ import { modeOf, capOf, opening, counts, lay, blueOf, contextOf, measuresOf } from './model.js';
5
+ import { GOALS, PILE, challengeStart, another } from './goals.js';
6
+ import { counter, show, put, R } from './counter.js';
7
+ import { frames } from './frame.js';
8
+ import { arrange } from './places.js';
9
+ import { parts, numerals, hands, splits, pins, park, trays, trayPile } from './figures.js';
10
+ import { carry, press } from './move.js';
11
+ import { driver } from './driver.js';
12
+ import { svg as el, svgPoint } from '../../kit/dom.js';
13
+ import { slider, stepper, chip, button, row } from '../../kit/panel.js';
14
+ import { goalRow } from '../../kit/goal.js';
15
+ import { live } from '../../kit/text.js';
16
+ import { numbers } from '../../kit/format.js';
17
+ import { dice, fresh } from '../../kit/random.js';
18
+
19
+ const MAX = 1.7; // A figure grows to at most this scale on a wide stage.
20
+ const PAD = 14; // The figure keeps this far from the stage's edges, in pixels.
21
+ const LIFT = -0.8; // A lifted cup rises this far, in radii of the part it covers, and fades so the part shows.
22
+
23
+ export default function bonds({ host, stage, panel, T, lang, moving, motion: fx }) {
24
+ const go = driver(fx);
25
+ const back = el('g'), layer = el('g', { class: 'counters-layer' }), over = el('g');
26
+ const svg = el('svg', { class: 'counters-svg' }, [back, layer, over]);
27
+ stage.appendChild(svg);
28
+ // spec is the page. s holds the counters: the ids in each place and the colour of each id. st holds the counts,
29
+ // geo the places and parts of the figure as drawn, and nodes the drawn counter of each id. target is the
30
+ // challenge's draw, and cs the reader's answer to it.
31
+ let spec = null, s = null, st = null, geo = null, area = { w: 0, h: 0 }, nodes = new Map(), seq = 0, hold = null;
32
+ let goal = null, chips = [], target = null, cs = null, blueCtl = null, liftBtn = null, fillBtn = null, cupAt = null, pinned = [];
33
+
34
+ const int = n => numbers(lang()).int(n);
35
+ const label = id => T(`${contextOf(spec)}-${id}`) ?? T(id);
36
+ const mode = () => modeOf(spec);
37
+ const newId = colour => { const id = `k${seq++}`; s.colour[id] = colour; return id; };
38
+ const many = (n, colour) => Array.from({ length: n }, () => newId(colour));
39
+ new ResizeObserver(() => { const r = svg.getBoundingClientRect(); if (spec && (Math.round(r.width) !== area.w || Math.round(r.height) !== area.h)) build(); }).observe(svg);
40
+
41
+ // begin sets the counters as the page opens, and draws a new target on a challenge page.
42
+ function begin() {
43
+ seq = 0; hold = null;
44
+ const c = spec.challenge;
45
+ if (c) {
46
+ target = another(GOALS[c.goal], c, spec, dice(fresh()), target);
47
+ cs = challengeStart(); s = { colour: {} };
48
+ if (c.goal === 'make-whole') Object.assign(s, { red: many(target.part, 'a'), blue: [] });
49
+ else Object.assign(s, { left: many(target.part, 'a'), tray: [], pile: many(PILE, 'b') });
50
+ return;
51
+ }
52
+ const o = opening(spec);
53
+ if (mode() === 'parts') { s = o; return; }
54
+ s = { ...o, colour: {} };
55
+ s.cells = o.cells.map(c => c ? newId(c.colour) : null);
56
+ if (spec.look === 'cars') s.gate = newId('a');
57
+ }
58
+
59
+ // relay lays red and then blue counters in the cells, and a counter that keeps its colour keeps its id.
60
+ function relay(red, blue) {
61
+ const was = s.cells;
62
+ s.cells = lay(spec, red, blue, i => was[i] ? { id: was[i], colour: s.colour[was[i]] } : null, () => `k${seq++}`).map(c => {
63
+ if (c) s.colour[c.id] = c.colour;
64
+ return c?.id ?? null;
65
+ });
66
+ }
67
+
68
+ // measure counts the counters. A challenge shows no counts, so its answer stays hidden.
69
+ function measure() {
70
+ if (spec.challenge) return {};
71
+ if (mode() === 'parts') return counts(spec, s);
72
+ return counts(spec, { ...s, cells: s.cells.map(id => id && { colour: s.colour[id] }) });
73
+ }
74
+
75
+ // blocksOf lists the blocks of the figure, each with the ways it can be set out.
76
+ function blocksOf() {
77
+ const c = spec.challenge, most = spec.wholeCtl?.hi ?? spec.whole ?? 0, out = [];
78
+ if (c?.goal === 'make-whole') {
79
+ out.push({ role: 'trays', ways: trays({ red: Math.min(c.part[1], c.whole - 1), blue: c.whole, labels: [T('two-first'), T('two-second')] }) }, { role: 'frames', ways: frames(spec.frames) });
80
+ } else if (c) {
81
+ out.push({ role: 'diagram', ways: parts({ max: [Math.min(c.part?.[1] ?? 19, c.whole[1] - 1), 0], cupped: true, gap: 26, r: 11 }) }, { role: 'tray', ways: trayPile({ size: PILE, labels: [T('tray'), T('pile')] }) });
82
+ } else if (spec.look === 'hands') out.push({ role: 'diagram', ways: hands({ max: most }) });
83
+ else if (spec.look === 'pins') out.push({ role: 'pins', ways: pins() });
84
+ else if (spec.look === 'cars') out.push({ role: 'park', ways: park() });
85
+ else if (mode() === 'parts') out.push({ role: 'diagram', ways: parts({ max: [most, most] }) });
86
+ else {
87
+ if (spec.look === 'diagram') out.push({ role: 'diagram', ways: numerals({ cupped: spec.cup }) });
88
+ out.push({ role: 'frames', ways: frames(spec.frames) });
89
+ }
90
+ if (spec.list) {
91
+ const ways = mode() === 'parts' ? most + 1 : capOf(spec) + 1;
92
+ out.push({ role: 'list', ways: splits(ways) });
93
+ }
94
+ return out;
95
+ }
96
+
97
+ // build draws the figure to fit the stage and puts every counter in its place.
98
+ function build() {
99
+ const r = svg.getBoundingClientRect(); area = { w: Math.round(r.width), h: Math.round(r.height) };
100
+ if (!area.w || !area.h) { geo = null; return; } // A phone is showing the text, so the figure is drawn when the stage shows.
101
+ const blocks = blocksOf(), best = arrange(blocks.map(b => b.ways), Math.max(1, area.w - 2 * PAD), Math.max(1, area.h - 2 * PAD)), scale = Math.min(MAX, best.scale);
102
+ const cx = best.w / 2, cy = best.h / 2;
103
+ svg.setAttribute('viewBox', `${cx - area.w / 2 / scale} ${cy - area.h / 2 / scale} ${area.w / scale} ${area.h / scale}`);
104
+ geo = { places: {}, refs: {} };
105
+ const drawn = [], lids = [];
106
+ best.items.forEach((it, i) => {
107
+ const role = blocks[i].role, d = it.v.draw(it.x, it.y);
108
+ drawn.push(...d.nodes);
109
+ if (d.cells) geo.places.cells = { pos: k => d.cells[k], r: R, all: d.cells };
110
+ Object.assign(geo.places, d.places ?? {});
111
+ geo.refs[role] = d.refs ?? {};
112
+ if (d.refs?.cup) lids.push(d.refs.cup.g);
113
+ });
114
+ back.replaceChildren(...drawn, ...targets()); over.replaceChildren(...lids);
115
+ for (const n of nodes.values()) n.tween?.pause();
116
+ layer.replaceChildren(); nodes = new Map();
117
+ svg.classList.toggle('counters-tapping', !!spec.tap);
118
+ cupAt = null; pinned = [];
119
+ wire(); render('jump');
120
+ }
121
+
122
+ // targets gives a tap target for each cell of a frame on a page where the reader taps cells.
123
+ function targets() {
124
+ if (!spec.tap || !geo.places.cells) return [];
125
+ return geo.places.cells.all.map((c, i) => {
126
+ const t = el('rect', { class: 'counters-cell', x: c.x - 22, y: c.y - 22, width: 44, height: 44, rx: 4, tabindex: 0, role: 'button', 'aria-label': T('cell', int(i + 1)) });
127
+ press(t, () => tapCell(i));
128
+ return t;
129
+ });
130
+ }
131
+
132
+ // wire lets the reader tap the pins, the spaces of the car park, the tray, the pile and the cup.
133
+ function wire() {
134
+ for (const p of geo.refs.pins?.pins ?? []) press(p.g, () => tapCell(Number(p.g.dataset.cell)));
135
+ for (const sp of geo.refs.park?.spaces ?? []) press(sp, () => parkIn(Number(sp.dataset.cell)));
136
+ for (const t of geo.refs.tray?.press ?? []) press(t, () => { const from = t.dataset.place, id = s[from].at(-1); if (id) tapAt(id, from); });
137
+ const cup = geo.refs.diagram?.cup;
138
+ if (cup) { cup.g.setAttribute('tabindex', 0); cup.g.setAttribute('role', 'button'); cup.g.setAttribute('aria-label', T('cup')); press(cup.g, lift); }
139
+ }
140
+
141
+ // where gives the place of every counter on show.
142
+ function where() {
143
+ const out = new Map(), P = geo.places, c = spec.challenge;
144
+ const packed = name => (s[name] ?? []).forEach((id, i, all) => out.set(id, { ...P[name].pos(i, all.length), r: P[name].r }));
145
+ if (c?.goal === 'make-whole') {
146
+ if (!cs.checked) { packed('red'); packed('blue'); return out; }
147
+ // A check drops the red and then the blue counters into the cells, and the blue ones with no cell stay out.
148
+ const all = [...s.red, ...s.blue], cap = P.cells.all.length;
149
+ all.slice(0, cap).forEach((id, i) => out.set(id, { ...P.cells.pos(i), r: R }));
150
+ all.slice(cap).forEach((id, i) => out.set(id, { ...P.blue.pos(i), r: R }));
151
+ return out;
152
+ }
153
+ if (c) { packed('left'); packed('tray'); packed('pile'); return out; }
154
+ if (mode() === 'parts') { packed('left'); packed('right'); return out; }
155
+ if (spec.look === 'pins') return out;
156
+ s.cells.forEach((id, i) => { if (id) out.set(id, { ...P.cells.pos(i), r: R }); });
157
+ if (s.gate) out.set(s.gate, { ...P.gate.pos(), r: R });
158
+ return out;
159
+ }
160
+
161
+ // render moves every counter to its place. After a change the reader made, counters glide, arrive and leave.
162
+ function render(how) {
163
+ if (!geo) return;
164
+ st = measure();
165
+ const to = where(), anim = how === 'move' && moving();
166
+ let k = 0;
167
+ for (const [id, n] of nodes) if (!to.has(id)) {
168
+ nodes.delete(id); n.tween?.pause();
169
+ if (anim) leave(n); else n.g.remove();
170
+ }
171
+ for (const [id, p] of to) {
172
+ let n = nodes.get(id);
173
+ if (!n) {
174
+ n = make(id, p); nodes.set(id, n); layer.append(n.g); put(n, p);
175
+ if (anim) go.pop(n.pop, 25 * k++);
176
+ continue;
177
+ }
178
+ if (n === hold || (n.at.x === p.x && n.at.y === p.y)) continue;
179
+ n.tween?.pause();
180
+ if (anim) n.tween = go.tween(n.at, { x: p.x, y: p.y }, () => show(n)); else put(n, p);
181
+ }
182
+ paint(anim); refresh();
183
+ }
184
+ // A car drives back to the entrance as it leaves, and any other counter shrinks away.
185
+ function leave(n) {
186
+ const gone = () => n.g.remove();
187
+ if (spec.look !== 'cars') return go.vanish(n.pop, gone);
188
+ const gate = geo.places.gate.pos();
189
+ n.tween = go.tween(n.at, { x: gate.x, y: gate.y }, () => show(n), 320);
190
+ go.vanish(n.pop, gone);
191
+ }
192
+
193
+ // make draws a counter and lets the reader carry it, where the page allows.
194
+ function make(id, p) {
195
+ const n = counter(spec.look === 'hands' ? 'bead' : spec.look === 'cars' ? 'car' : 'disc', s.colour[id], p.r, Number(String(id).replace(/\D/g, '')) || 0);
196
+ const c = spec.challenge;
197
+ const homes = c?.goal === 'hidden-part' ? ['tray', 'pile'] : !c && mode() === 'parts' ? ['left', 'right'] : spec.look === 'cars' ? ['cells', 'gate'] : null;
198
+ const from = () => homes?.find(h => h === 'cells' ? s.cells.includes(id) : h === 'gate' ? s.gate === id : s[h]?.includes(id));
199
+ if (!homes || !from()) return n;
200
+ n.g.setAttribute('tabindex', 0); n.g.setAttribute('role', 'button'); n.g.setAttribute('aria-label', T(spec.look === 'cars' ? 'car' : 'counter'));
201
+ n.g.classList.add('counters-moves');
202
+ let dx = 0, dy = 0;
203
+ carry(n.g, {
204
+ point: e => svgPoint(svg, e), raise: () => layer.append(n.g),
205
+ start(q) { if (!from()) return false; n.tween?.pause(); hold = n; dx = n.at.x - q.x; dy = n.at.y - q.y; },
206
+ move(q) { put(n, { x: q.x + dx, y: q.y + dy }); },
207
+ drop(q) { hold = null; if (!q || !dropAt(id, from(), { x: q.x + dx, y: q.y + dy }, homes)) render('move'); },
208
+ tap() { hold = null; tapAt(id, from()); },
209
+ });
210
+ return n;
211
+ }
212
+
213
+ // dropAt moves a counter to the place it was let go over, and says whether it moved.
214
+ function dropAt(id, from, q, homes) {
215
+ if (spec.look === 'cars') {
216
+ const cells = geo.places.cells.all, i = cells.findIndex(c => Math.abs(c.x - q.x) < 21 && Math.abs(c.y - q.y) < 32);
217
+ if (i >= 0 && !s.cells[i]) { take(id, from); s.cells[i] = id; if (from === 'gate') s.gate = newId('a'); return changed(); }
218
+ if (from === 'cells' && i < 0 && geo.refs.park.aisle(q)) { take(id, from); return changed(); }
219
+ return false;
220
+ }
221
+ const to = homes.find(h => h !== from && geo.places[h].hit?.(q));
222
+ if (!to) return false;
223
+ take(id, from); s[to].push(id); lower();
224
+ return changed();
225
+ }
226
+ // A tap moves a counter to the other part, to the tray or back to the pile. A tap on a parked car drives it out,
227
+ // and a tap on the waiting car parks it in the free space nearest the entrance.
228
+ function tapAt(id, from) {
229
+ if (spec.look === 'cars') {
230
+ if (from === 'cells') { take(id, from); return changed(); }
231
+ const gate = geo.places.gate.pos(), free = geo.places.cells.all.map((c, i) => ({ i, d: Math.hypot(c.x - gate.x, c.y - gate.y) })).filter(c => !s.cells[c.i]).sort((a, b) => a.d - b.d)[0];
232
+ if (free) parkIn(free.i);
233
+ return;
234
+ }
235
+ const to = { left: 'right', right: 'left', tray: 'pile', pile: 'tray' }[from];
236
+ take(id, from); s[to].push(id); lower();
237
+ changed();
238
+ }
239
+ function take(id, from) {
240
+ if (from === 'cells') s.cells[s.cells.indexOf(id)] = null;
241
+ else if (from === 'gate') s.gate = null;
242
+ else s[from].splice(s[from].indexOf(id), 1);
243
+ }
244
+ // A change to the tray puts a lifted cup back, so the reader lifts it again to check.
245
+ function lower() { if (spec.challenge?.goal === 'hidden-part' && cs.lifted) { cs.lifted = false; liftWords(); } }
246
+
247
+ // A tap on a cell adds a counter of the page's part or takes it away. A tap on a pin knocks it down or stands it up.
248
+ function tapCell(i) {
249
+ if (spec.look === 'pins') { s.cells[i] = s.cells[i] ? null : newId('a'); return changed(); }
250
+ const colour = spec.tap === 'second' ? 'b' : 'a', id = s.cells[i];
251
+ if (!id) s.cells[i] = newId(colour);
252
+ else if (s.colour[id] === colour) s.cells[i] = null;
253
+ else return;
254
+ changed();
255
+ }
256
+ // parkIn drives the waiting car into a free space.
257
+ function parkIn(i) {
258
+ if (s.cells[i]) return;
259
+ s.cells[i] = s.gate; s.gate = newId('a');
260
+ changed();
261
+ }
262
+
263
+ // changed logs the split the reader made and moves the counters. It says true for the drop that called it.
264
+ function changed() {
265
+ if (spec.list) { const first = measure().first; if (!s.found.includes(first)) s.found.push(first); }
266
+ render('move');
267
+ return true;
268
+ }
269
+
270
+ // paint writes the numbers of the figure and sets its cup, list, pins and sign.
271
+ function paint(anim) {
272
+ const d = geo.refs.diagram, c = spec.challenge;
273
+ if (d) {
274
+ const whole = c ? target.whole : st.whole, hidden = c ? target.whole - target.part : st.second;
275
+ if (d.whole) d.whole.textContent = int(whole);
276
+ const [a, b] = d.badges;
277
+ if (a) a.textContent = int(c ? target.part : st.first);
278
+ if (b) b.textContent = int(st.second);
279
+ if (d.cup) { d.hidden.textContent = int(hidden); cup(anim); }
280
+ }
281
+ const list = geo.refs.list;
282
+ if (list) {
283
+ // The list keeps a slot for the largest whole the page reaches and shows the slots of the whole on show.
284
+ const first = st.first, whole = mode() === 'parts' ? st.whole : capOf(spec);
285
+ list.title.textContent = T(mode() === 'parts' ? 'list-splits' : 'list-pairs', int(whole));
286
+ list.slots.forEach((slot, i) => {
287
+ slot.g.toggleAttribute('hidden', i > whole);
288
+ const found = s.found.includes(i), words = found ? T('pair', { a: int(i), b: int(whole - i) }) : '';
289
+ if (slot.text.textContent !== words) { slot.text.textContent = words; if (found && anim) go.pop(slot.g); }
290
+ slot.g.classList.toggle('counters-found', found); slot.g.classList.toggle('counters-now', i === first);
291
+ });
292
+ }
293
+ for (const [i, p] of (geo.refs.pins?.pins ?? []).entries()) {
294
+ const up = !!s.cells[i], was = pinned[i];
295
+ p.g.classList.toggle('counters-down', !up); p.g.setAttribute('aria-label', T(up ? 'pin-up' : 'pin-down', int(i + 1)));
296
+ const a = up ? 0 : 80, draw = () => p.body.setAttribute('transform', `rotate(${p.tilt.a}) scale(${1 - p.tilt.a / 400})`);
297
+ if (was !== undefined && was !== up && anim) { p.tween?.pause(); p.tween = go.tween(p.tilt, { a }, draw, 420, up ? 'outBack' : 'outBounce'); }
298
+ else { p.tilt.a = a; draw(); }
299
+ pinned[i] = up;
300
+ }
301
+ // A knocked pin lies behind the pins still standing, and the pins at the back stand behind those in front.
302
+ const lane = geo.refs.pins?.lane;
303
+ if (lane) for (const p of [...geo.refs.pins.pins].reverse().sort((a, b) => !!s.cells[a.g.dataset.cell] - !!s.cells[b.g.dataset.cell])) lane.parentNode.appendChild(p.g);
304
+ const sign = geo.refs.park?.sign;
305
+ if (sign) { sign.word.textContent = T('free'); if (sign.num.textContent !== int(st.empty)) { sign.num.textContent = int(st.empty); if (anim) go.flash(sign.num); } }
306
+ if (c?.goal === 'make-whole') for (const [i, id] of s.blue.entries()) nodes.get(id)?.g.classList.toggle('counters-over', cs.checked && s.red.length + i >= geo.places.cells.all.length);
307
+ }
308
+
309
+ // cup sets the cup over the hidden part, or lifted off it.
310
+ function cup(anim) {
311
+ const d = geo.refs.diagram.cup, up = spec.challenge ? cs.lifted : s.lifted;
312
+ const to = up ? { x: 0, y: LIFT * d.r, o: 0.18 } : { x: 0, y: 0, o: 1 };
313
+ const draw = () => { d.g.setAttribute('transform', `translate(${d.home.x + cupAt.x} ${d.home.y + cupAt.y})`); d.g.style.opacity = cupAt.o; };
314
+ d.g.setAttribute('aria-pressed', String(up));
315
+ if (!cupAt) { cupAt = { ...to }; return draw(); }
316
+ if (cupAt.x === to.x && cupAt.y === to.y) return draw();
317
+ cupAt.tween?.pause();
318
+ if (anim) cupAt.tween = go.tween(cupAt, to, draw, 480, 'outBack'); else { Object.assign(cupAt, to); draw(); }
319
+ }
320
+ // lift raises the cup or puts it back. Under a lifted cup, a page's blue counters swell when they match the part.
321
+ function lift() {
322
+ if (spec.challenge) cs.lifted = !cs.lifted; else s.lifted = !s.lifted;
323
+ liftWords(); render('move');
324
+ if (!spec.challenge && s.lifted && st.added === st.second && moving()) go.cheer(s.cells.filter(id => id && s.colour[id] === 'b').map(id => nodes.get(id)?.pop).filter(Boolean));
325
+ }
326
+ const liftWords = () => { if (liftBtn) liftBtn.querySelector('span').textContent = T((spec.challenge ? cs.lifted : s.lifted) ? 'lower' : 'lift'); };
327
+
328
+ // refresh writes every value that follows the counters, in the readouts and the text, and judges a challenge.
329
+ function refresh() {
330
+ for (const k of chips) if (k.set(int(st[k.id])) && moving()) go.flash(k.el);
331
+ const ids = measuresOf(spec);
332
+ live(host, { value: id => ids.includes(id) ? int(st[id]) : null });
333
+ judge();
334
+ }
335
+ function judge() {
336
+ const c = spec.challenge;
337
+ if (!c || !goal) return;
338
+ const g = GOALS[c.goal], words = g.words(c, target, { int });
339
+ goal.say(T(c.goal === 'make-whole' && spec.frames > 1 ? 'goal-make-whole-two' : `goal-${c.goal}`, words));
340
+ const r = g.holds({ ...cs, blue: s.blue?.length ?? 0, tray: s.tray?.length ?? 0 }, spec, c, target);
341
+ const first = goal.show(r.done, r.note ? T(`note-${r.note}`) : undefined);
342
+ if (first && moving()) go.cheer([...nodes.values()].filter(n => c.goal === 'make-whole' ? !n.g.classList.contains('counters-over') : s.tray.some(id => nodes.get(id) === n)).map(n => n.pop));
343
+ }
344
+
345
+ // The panel holds a challenge's line, the page's controls and its readouts.
346
+ function drawPanel() {
347
+ const c = spec.challenge, ctls = [];
348
+ goal = blueCtl = liftBtn = fillBtn = null; chips = [];
349
+ if (c) {
350
+ goal = goalRow({ T, motion: moving() ? fx : null, hint: on => on ? T(`hint-${c.goal}`, GOALS[c.goal].words(c, target, { int })) : null,
351
+ another: () => { begin(); goal.reset(); blueCtl?.set(0); liftWords(); build(); } });
352
+ if (c.goal === 'make-whole') {
353
+ blueCtl = slider({ id: 'blue', label: T('blue'), min: 0, max: c.whole, value: 0, write: int, input: setBlue, change: setBlue });
354
+ blueCtl.width(2);
355
+ ctls.push(blueCtl, button({ label: T('check'), act: 'check', primary: true, press: () => { if (cs.checked) return; cs.checked = true; render('move'); } }));
356
+ } else ctls.push(liftBtn = button({ label: T('lift'), act: 'lift', primary: true, press: lift }));
357
+ } else {
358
+ if (spec.wholeCtl) ctls.push(stepper({ id: 'whole', label: T('ctl-whole'), min: spec.wholeCtl.lo, max: spec.wholeCtl.hi, value: spec.whole, write: int, change: setWhole }));
359
+ const f = spec.firstCtl;
360
+ if (f?.kind === 'slider') { const k = slider({ id: 'first', label: label('first'), min: f.lo, max: f.hi, value: spec.first, write: int, input: setFirst }); k.width(2); ctls.push(k); }
361
+ if (f?.kind === 'stepper') ctls.push(stepper({ id: 'first', label: label('first'), min: f.lo, max: f.hi, value: spec.first, write: int, change: setFirst }));
362
+ if (spec.swap) ctls.push(button({ label: T('swap'), act: 'swap', press: () => { [s.left, s.right] = [s.right, s.left]; changed(); } }));
363
+ if (spec.fill) ctls.push(fillBtn = button({ label: T(s.extra ? 'unfill' : 'fill'), act: 'fill', press: fill }));
364
+ if (spec.cup) ctls.push(liftBtn = button({ label: T(s.lifted ? 'lower' : 'lift'), act: 'lift', press: lift }));
365
+ chips = spec.readout.map(id => chip({ id, label: label(id) }));
366
+ for (const k of chips) k.width(2);
367
+ }
368
+ panel.replaceChildren(...[goal?.el, ctls.length ? row('ctls', ctls) : null, chips.length ? row('out', chips) : null].filter(Boolean));
369
+ }
370
+
371
+ // A blue count the reader sets puts that many blue counters in their tray and takes back the last check.
372
+ function setBlue(v) {
373
+ if (v === s.blue.length && !cs.checked) return;
374
+ cs.checked = false;
375
+ while (s.blue.length < v) s.blue.push(newId('b'));
376
+ s.blue.length = v;
377
+ render('move');
378
+ }
379
+ // A new whole adds blue counters to the second part or takes them away, and the list starts again.
380
+ function setWhole(v) {
381
+ if (mode() === 'parts') {
382
+ while (s.left.length + s.right.length < v) s.right.push(newId('b'));
383
+ while (s.left.length + s.right.length > v) (s.right.length ? s.right : s.left).pop();
384
+ s.found = [];
385
+ } else relay(spec.first, v - spec.first);
386
+ changed();
387
+ }
388
+ function setFirst(v) { relay(v, blueOf(spec, v, spec.whole)); changed(); }
389
+ // fill puts ten red counters in the second frame, or takes them out again.
390
+ function fill() {
391
+ s.extra = !s.extra;
392
+ for (let i = 10; i < 20; i++) s.cells[i] = s.extra ? newId('a') : null;
393
+ fillBtn.querySelector('span').textContent = T(s.extra ? 'unfill' : 'fill');
394
+ changed();
395
+ }
396
+
397
+ function point(id, on) {
398
+ if (!spec) return;
399
+ for (const part of svg.querySelectorAll(`[data-ref="${id}"]`)) part.classList.toggle('counters-hot', on);
400
+ for (const part of panel.querySelectorAll('[data-ref]')) part.classList.toggle('hot', on && part.dataset.ref === id);
401
+ }
402
+ function stop() { for (const n of nodes.values()) n.tween?.pause(); hold = null; }
403
+
404
+ return {
405
+ show(page) {
406
+ stop(); spec = page; target = null;
407
+ begin(); st = measure(); drawPanel(); build();
408
+ if (!geo) refresh();
409
+ },
410
+ hide() { stop(); spec = null; geo = null; back.replaceChildren(); layer.replaceChildren(); over.replaceChildren(); nodes = new Map(); },
411
+ point,
412
+ lang() { if (!spec) return; const was = goal; drawPanel(); goal?.keep(was); liftWords(); build(); if (!geo) refresh(); },
413
+ };
414
+ }
@@ -0,0 +1,96 @@
1
+ /* counters: the colours are theme tokens and the two counter colours of the family, so a theme switch needs no
2
+ redraw. */
3
+ .hesap-counters .counters-svg{position:absolute;left:0;top:0;width:100%;height:100%;touch-action:none;font-family:var(--body);overflow:visible}
4
+ .hesap-counters text{fill:var(--ink);text-anchor:middle;dominant-baseline:central;pointer-events:none;font-variant-numeric:tabular-nums}
5
+ .hesap-counters .counters-a{--c:var(--z-counters-red,#d1453b)}
6
+ .hesap-counters .counters-b{--c:var(--z-counters-blue,#2a6bd1)}
7
+
8
+ /* A counter is a disc, a bead or a car, with a touch target round it. */
9
+ .hesap-counters .counters-hit{fill:transparent}
10
+ .hesap-counters .counters-body{fill:var(--c);stroke:var(--paper);stroke-width:1.5}
11
+ .hesap-counters .counters-ring{fill:none;stroke:var(--paper);stroke-width:2;opacity:.6}
12
+ .hesap-counters .counters-shine{fill:var(--paper);opacity:.55}
13
+ .hesap-counters .counters-glass{fill:var(--paper);opacity:.7}
14
+ .hesap-counters .counters-bead .counters-body{fill:var(--z-counters-blue,#2a6bd1)}
15
+ /* The cars of a car park come in six paints. */
16
+ .hesap-counters .counters-paint-0 .counters-body{fill:#d1453b}
17
+ .hesap-counters .counters-paint-1 .counters-body{fill:#2a6bd1}
18
+ .hesap-counters .counters-paint-2 .counters-body{fill:#2e9d5b}
19
+ .hesap-counters .counters-paint-3 .counters-body{fill:#d99a1f}
20
+ .hesap-counters .counters-paint-4 .counters-body{fill:#8a56c9}
21
+ .hesap-counters .counters-paint-5 .counters-body{fill:#1f9aa3}
22
+ .hesap-counters .counters-moves{cursor:grab;outline:none}
23
+ .hesap-counters .counters-moves.drag{cursor:grabbing}
24
+ .hesap-counters .counters-moves:focus-visible .counters-hit{stroke:var(--accent);stroke-width:2.5}
25
+ .hesap-counters .counters-tapping .counters-layer{pointer-events:none}
26
+ .hesap-counters .counters-over .counters-body{stroke:var(--ink);stroke-width:2.5;stroke-dasharray:4 3}
27
+
28
+ /* The part-whole diagram: the whole above, the two parts below, joined by lines. */
29
+ .hesap-counters .counters-link{stroke:var(--rule);stroke-width:3}
30
+ .hesap-counters .counters-whole{fill:var(--panel);stroke:var(--ink);stroke-width:2.5}
31
+ .hesap-counters .counters-part{fill:var(--paper);stroke:var(--ink-2);stroke-width:2}
32
+ .hesap-counters .counters-a-ring{stroke:var(--z-counters-red,#d1453b);stroke-width:3}
33
+ .hesap-counters .counters-b-ring{stroke:var(--z-counters-blue,#2a6bd1);stroke-width:3}
34
+ .hesap-counters .counters-big{font-size:28px;font-weight:700}
35
+ .hesap-counters .counters-badge{font-size:20px;font-weight:700;fill:var(--ink-2)}
36
+ .hesap-counters .counters-hot{stroke:var(--accent);stroke-width:4}
37
+ .hesap-counters g.counters-hot .counters-slot-box{stroke:var(--accent)}
38
+
39
+ /* The cup hides a part until the reader lifts it. */
40
+ .hesap-counters .counters-cup{cursor:pointer;outline:none}
41
+ .hesap-counters .counters-cup-body{fill:var(--ink-2);stroke:var(--ink);stroke-width:2}
42
+ .hesap-counters .counters-cup-rim,.hesap-counters .counters-cup-knob{fill:var(--ink);stroke:none}
43
+ .hesap-counters .counters-cup:focus-visible .counters-cup-body{stroke:var(--accent);stroke-width:4}
44
+
45
+ /* The hands hold the beads on their palms. */
46
+ .hesap-counters .counters-hand{fill:var(--panel);stroke:var(--ink-2);stroke-width:2}
47
+ .hesap-counters .counters-palm{stroke-width:2.5}
48
+
49
+ /* Ten frames, and the cells a reader taps. */
50
+ .hesap-counters .counters-frame-box{fill:var(--paper);stroke:var(--ink);stroke-width:2.5}
51
+ .hesap-counters .counters-frame line{stroke:var(--ink-2);stroke-width:1.5}
52
+ .hesap-counters .counters-cell{fill:transparent;cursor:pointer;outline:none}
53
+ .hesap-counters .counters-cell:hover{fill:var(--accent);fill-opacity:.1}
54
+ .hesap-counters .counters-cell:focus-visible{stroke:var(--accent);stroke-width:3}
55
+
56
+ /* The list keeps a slot for each split, and a slot fills when the reader finds its split. */
57
+ .hesap-counters .counters-list-title{font-size:15px;font-weight:600;fill:var(--ink-2)}
58
+ .hesap-counters .counters-slot-box{fill:none;stroke:var(--rule);stroke-width:1.5;stroke-dasharray:4 4}
59
+ .hesap-counters .counters-slot-text{font-size:15px;font-weight:600}
60
+ .hesap-counters .counters-found .counters-slot-box{fill:var(--panel);stroke:var(--ink-2);stroke-dasharray:none}
61
+ .hesap-counters .counters-now .counters-slot-box{stroke:var(--accent);stroke-width:2.5}
62
+ .hesap-counters .counters-slot[hidden]{display:none}
63
+
64
+ /* The lane of pins: a pin falls over when the reader knocks it down. */
65
+ .hesap-counters .counters-lane{fill:var(--panel);stroke:var(--rule);stroke-width:2}
66
+ .hesap-counters .counters-pin{cursor:pointer;outline:none}
67
+ .hesap-counters .counters-pin-shape{fill:var(--paper);stroke:var(--ink);stroke-width:2}
68
+ .hesap-counters .counters-pin-stripe{fill:var(--z-counters-red,#d1453b)}
69
+ .hesap-counters .counters-spot{fill:var(--rule)}
70
+ .hesap-counters .counters-down .counters-pin-body{opacity:.45}
71
+ .hesap-counters .counters-pin:focus-visible .counters-hit{stroke:var(--accent);stroke-width:2.5}
72
+
73
+ /* The car park: two rows of spaces, an aisle, and a sign that shows the free spaces. */
74
+ .hesap-counters .counters-ground{fill:var(--panel);stroke:var(--rule);stroke-width:2}
75
+ .hesap-counters .counters-space{fill:transparent;cursor:pointer;outline:none}
76
+ .hesap-counters .counters-space:hover{fill:var(--accent);fill-opacity:.1}
77
+ .hesap-counters .counters-space:focus-visible{stroke:var(--accent);stroke-width:3}
78
+ .hesap-counters .counters-bay{stroke:var(--ink-2);stroke-width:2}
79
+ .hesap-counters .counters-road{stroke:var(--rule);stroke-width:3;stroke-dasharray:14 10}
80
+ .hesap-counters .counters-sign-box{fill:var(--ink);stroke:none}
81
+ .hesap-counters .counters-sign-word{fill:var(--paper);font-size:12px;font-weight:600}
82
+ .hesap-counters .counters-sign-num{fill:var(--paper);font-size:24px;font-weight:700}
83
+ .hesap-counters .counters-sign.counters-hot .counters-sign-box{fill:var(--accent)}
84
+
85
+ /* The trays of the challenges, and the pile the reader takes counters from. */
86
+ .hesap-counters .counters-tray{fill:var(--panel);stroke:var(--ink-2);stroke-width:2}
87
+ .hesap-counters .counters-tray-label{font-size:14px;font-weight:600;fill:var(--ink-2)}
88
+ .hesap-counters .counters-heap-floor{fill:var(--rule);opacity:.6}
89
+ .hesap-counters .counters-press{cursor:pointer;outline:none}
90
+ .hesap-counters rect.counters-press:not(.counters-tray){fill:transparent}
91
+ .hesap-counters .counters-press:focus-visible{stroke:var(--accent);stroke-width:3}
92
+
93
+ @media (max-width:900px){
94
+ /* The figure ends above the peek card, which covers the foot of the stage until the reader closes it. */
95
+ .hesap-counters .counters-svg{height:calc(100% - var(--hesap-peek,0px))}
96
+ }
@@ -0,0 +1,21 @@
1
+ // The browser half of the counters family. It hands each page to the scene the page names. The scenes share the
2
+ // family's counters, ten frames, places and motion.
3
+ import bonds from './bonds.js';
4
+
5
+ const SCENES = { bonds };
6
+
7
+ export default function counters(api) {
8
+ // made holds each scene once it has been made, and now is the scene on show.
9
+ const made = {};
10
+ let now = null;
11
+ return {
12
+ show(spec, page) {
13
+ const next = made[spec.scene] ??= SCENES[spec.scene](api);
14
+ if (now && now !== next) now.hide();
15
+ now = next; now.show(spec, page);
16
+ },
17
+ hide() { now?.hide(); now = null; },
18
+ point(id, on) { now?.point(id, on); },
19
+ lang() { now?.lang(); },
20
+ };
21
+ }
@@ -0,0 +1,32 @@
1
+ // A counter of the family: a disc, a bead or a car, in red or blue. Every scene of the family draws its counters here.
2
+ import { svg as el } from '../../kit/dom.js';
3
+
4
+ // The radius of a counter in the figure's units, and the reach of its touch target, about 44px across on a phone.
5
+ export const R = 16, HIT = 22;
6
+
7
+ function glyph(kind, r) {
8
+ if (kind === 'bead') return [el('circle', { class: 'counters-body', r }), el('circle', { class: 'counters-shine', r: r * 0.32, cx: -r * 0.35, cy: -r * 0.35 })];
9
+ if (kind === 'car') {
10
+ const w = r * 1.5, l = r * 2.5;
11
+ return [el('rect', { class: 'counters-body', x: -w / 2, y: -l / 2, width: w, height: l, rx: r * 0.45 }),
12
+ el('rect', { class: 'counters-glass', x: -w / 2 + 3, y: -l / 2 + l * 0.2, width: w - 6, height: l * 0.2, rx: 3 }),
13
+ el('rect', { class: 'counters-glass', x: -w / 2 + 3, y: l * 0.2, width: w - 6, height: l * 0.14, rx: 3 })];
14
+ }
15
+ return [el('circle', { class: 'counters-body', r }), el('circle', { class: 'counters-ring', r: r * 0.6 })];
16
+ }
17
+
18
+ // A car park holds cars of several colours, so each car takes one of PAINTS by its number.
19
+ const PAINTS = 6;
20
+
21
+ // counter makes the elements of one counter. g takes the place in the figure, and pop takes the motion, because a
22
+ // CSS transform on an element would override its transform attribute. n is the counter's number among its kind.
23
+ export function counter(kind, colour, r = R, n = 0) {
24
+ const pop = el('g', { class: 'counters-pop a' }, [el('circle', { class: 'counters-hit', r: Math.max(r, HIT) }), ...glyph(kind, r)]);
25
+ const paint = kind === 'car' ? ` counters-paint-${n % PAINTS}` : '';
26
+ const g = el('g', { class: `counters-counter counters-${colour} counters-${kind}${paint}` }, [pop]);
27
+ return { g, pop, at: { x: 0, y: 0 }, colour };
28
+ }
29
+
30
+ // show draws a counter where its at says, and put moves it there.
31
+ export const show = c => c.g.setAttribute('transform', `translate(${c.at.x} ${c.at.y})`);
32
+ export const put = (c, p) => { c.at.x = p.x; c.at.y = p.y; show(c); };
@@ -0,0 +1,16 @@
1
+ // The motion of the counters family, run on the page's motion tracker, in milliseconds. Every motion marks a change
2
+ // the reader made, and the scene skips it when the reader asked for less motion.
3
+ export function driver(fx) {
4
+ return {
5
+ // tween moves the numbers of a plain object, such as a counter's place, and draw follows each step.
6
+ tween: (obj, to, draw, duration = 380, ease = 'outCubic') => fx.run(obj, { ...to, duration, ease, onUpdate: draw }),
7
+ // A counter that arrives grows into its place, after delay milliseconds.
8
+ pop: (el, delay = 0) => fx.run(fx.centre(el), { scale: [0.2, 1.12, 1], opacity: [0, 1], duration: 340, delay, ease: 'outQuad' }),
9
+ // A counter that leaves shrinks away, and done takes it off the page also when a page change cuts it short.
10
+ vanish: (el, done) => fx.run(fx.centre(el), { scale: [1, 0.2], opacity: [1, 0], duration: 240, ease: 'inQuad' }, done, done),
11
+ // A value or a slot that changed jumps once.
12
+ flash: el => fx.flash(el),
13
+ // The counters that reach a goal swell one after another.
14
+ cheer: els => fx.cheer(els),
15
+ };
16
+ }