@openbooknetwork/hesap 0.3.0 → 0.3.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 (40) hide show
  1. package/package.json +1 -1
  2. package/src/client.css +168 -0
  3. package/src/families/counters/add-figures.js +85 -0
  4. package/src/families/counters/add-goals.js +82 -0
  5. package/src/families/counters/add-model.js +82 -0
  6. package/src/families/counters/add.js +442 -0
  7. package/src/families/counters/add.mjs +102 -0
  8. package/src/families/counters/bonds.js +51 -12
  9. package/src/families/counters/client.css +40 -0
  10. package/src/families/counters/client.js +2 -1
  11. package/src/families/counters/count.js +4 -5
  12. package/src/families/counters/counter.js +14 -0
  13. package/src/families/counters/figures.js +12 -4
  14. package/src/families/counters/goals.js +1 -9
  15. package/src/families/counters/i18n/en.yaml +89 -45
  16. package/src/families/counters/i18n/tr.yaml +56 -12
  17. package/src/families/counters/index.mjs +5 -3
  18. package/src/families/counters/match-model.js +10 -1
  19. package/src/families/counters/match.js +31 -11
  20. package/src/families/counters/match.mjs +7 -1
  21. package/src/families/line/client.css +118 -0
  22. package/src/families/line/client.js +12 -0
  23. package/src/families/line/figures.js +143 -0
  24. package/src/families/line/goals.js +168 -0
  25. package/src/families/line/i18n/en.yaml +61 -0
  26. package/src/families/line/i18n/tr.yaml +61 -0
  27. package/src/families/line/index.mjs +227 -0
  28. package/src/families/line/lens.js +49 -0
  29. package/src/families/line/line.js +624 -0
  30. package/src/families/line/model.js +219 -0
  31. package/src/families.mjs +2 -1
  32. package/src/i18n/en.yaml +158 -46
  33. package/src/i18n/tr.yaml +124 -12
  34. package/src/kit/i18n/en.yaml +8 -1
  35. package/src/kit/i18n/tr.yaml +7 -0
  36. package/src/kit/kit.css +9 -0
  37. package/src/kit/panel.js +2 -0
  38. package/src/kit/random.js +9 -0
  39. package/src/kit/written.js +70 -0
  40. package/src/node.mjs +3 -1
@@ -0,0 +1,442 @@
1
+ // The add scene: two groups of counters in two ten frames, with the written line of their calculation under them. On
2
+ // an addition page the first group is round and red and fills the cells from the first, and the second group is
3
+ // square and blue and fills the cells after it. The reader joins waiting counters by drag or tap, sends them back,
4
+ // sets a group with a stepper or throws two dice. On a take-away page the reader taps counters away, each leaving a
5
+ // dashed ring, or steps the number taken away. Two step lines show how a calculation across ten makes ten first. The
6
+ // shelf look sells jars of jam into two crates, and the tray look sows the seeds of a packet in a seed tray. A
7
+ // challenge writes its calculation open, and its counters move once the reader's numbers are right.
8
+ import { DIE, JARS, opening, counts, lineOf, leftOf, stepsOf, LINES, measuresOf, labelKeys, goalKey } from './add-model.js';
9
+ import { ADD_GOALS, addStart } from './add-goals.js';
10
+ import { counter, show, put, R } from './counter.js';
11
+ import { frames, CELL } from './frame.js';
12
+ import { waitTray, die, DIE_SIZE, shelfWays, crate, JAR_HIT, seedTray } from './add-figures.js';
13
+ import { carry, press } from './move.js';
14
+ import { driver } from './driver.js';
15
+ import { svg as el, svgPoint } from '../../kit/dom.js';
16
+ import { stepper, chip, button, segment, row, check } from '../../kit/panel.js';
17
+ import { goalRow } from '../../kit/goal.js';
18
+ import { live } from '../../kit/text.js';
19
+ import { numbers } from '../../kit/format.js';
20
+ import { dice, fresh, another } from '../../kit/random.js';
21
+ import { writtenLine, words, reading, widthOf, SIZE, STEP_SIZE, DASH } from '../../kit/written.js';
22
+
23
+ const MAX = 1.7; // A figure grows to at most this scale on a wide stage.
24
+ const PAD = 14; // The figure keeps this far from the stage's edges, in pixels.
25
+ const SPACE = 24; // The gap between the blocks of the figure and the written line.
26
+ const LINE = SIZE + 12, STEP_LINE = STEP_SIZE + 10; // The room of a written line and of a step line.
27
+ const DIE_ROOM = DIE_SIZE + 14; // The room above the frames and the tray for a die.
28
+ const NEAR = 16; // A counter let go this close to the frames joins them.
29
+ const JAR_R = 19; // A jar is drawn round this radius.
30
+ // The ids of the counters: r for the first group, b for the second and j for a jar.
31
+ const firstOf = id => id[0] === 'r';
32
+ // line makes a written line with the links that mark it whole.
33
+ const line = (whole, options) => Object.assign(writtenLine(options), { whole });
34
+ const RED_BLUE = { a: 'counters-a', b: 'counters-b' };
35
+
36
+ export default function add({ host, stage, panel, T, lang, moving, motion: fx }) {
37
+ const go = driver(fx);
38
+ const back = el('g'), layer = el('g', { class: 'counters-layer' }), front = el('g');
39
+ const dies = [die('first'), die('waiting')];
40
+ const svg = el('svg', { class: 'counters-svg' }, [back, layer, front]);
41
+ stage.appendChild(svg);
42
+ // base is the page as written, and spec the page with the steppers a challenge gives it. s holds the ids of the
43
+ // counters of each place: red in the frames, joined in the frames after them, later in the second frame of a split
44
+ // page and tray beside them, the tray or the seed packet. A take-away
45
+ // page holds the ids taken away in taken, and the shelf holds the jars of the morning in red, those of the
46
+ // afternoon in joined and the crate the segment picks. A challenge holds the numbers of its steppers in answer, and
47
+ // play counts the runs of its moving counters, so a change of a stepper stops a run. geo holds the places of the
48
+ // figure as drawn, and lines the written lines of the page.
49
+ let base = null, spec = null, s = null, geo = null, area = { w: 0, h: 0 }, nodes = new Map(), seq = 0, hold = null;
50
+ let chips = [], goal = null, target = null, solved = false, lines = [], play = 0;
51
+ const lit = new Set();
52
+
53
+ const int = n => numbers(lang()).int(n);
54
+ const ids = (n, k) => Array.from({ length: n }, () => `${k}${seq++}`);
55
+ // now gives the counts, and whether the figure shows the full ten that a step of making ten needs.
56
+ const now = () => ({ first: s.red.length, second: spec.take ? s.taken.size : s.joined.length + s.later.length, waiting: s.tray.length,
57
+ ten: spec.take ? s.red.slice(10).every(id => s.taken.has(id)) : s.red.length + s.joined.length >= 10 });
58
+ // A page with waiting shows the tray or the packet, and the reader moves its counters unless a challenge moves them.
59
+ const waits = () => spec.waiting != null;
60
+ const moves = () => waits() && !base.challenge;
61
+ const shelf = () => spec.look === 'shelf';
62
+ // A take-away page whose number taken away has no stepper takes taps on its counters.
63
+ const taps = () => spec.take && !spec.secondCtl && !base.challenge;
64
+ const goalOf = () => ADD_GOALS[base.challenge.goal];
65
+ new ResizeObserver(() => { const r = svg.getBoundingClientRect(); if (spec && (Math.round(r.width) !== area.w || Math.round(r.height) !== area.h)) build(); }).observe(svg);
66
+
67
+ // deal sets the counters as the page opens. A challenge draws its target and takes its steppers from its goal. A
68
+ // take-away page opens with its second number taken from the last cells, and the shelf with the jars sold in the
69
+ // morning and the afternoon in their crates.
70
+ function deal() {
71
+ const c = base.challenge;
72
+ spec = base; seq = 0; hold = null; solved = false;
73
+ if (c) { target = another(ADD_GOALS[c.goal], c, base, dice(fresh()), target); spec = { ...base, ...ADD_GOALS[c.goal].page(target) }; }
74
+ s = { answer: addStart(), checked: false };
75
+ place();
76
+ // The written lines: the line of the calculation, on the shelf the line of the jars left, and with written: ten
77
+ // the two steps of making ten.
78
+ const end = spec.take ? 'left' : 'sum', main = line(['written', 'reading'], { refs: { a: 'first', b: 'second', c: end }, cls: spec.take ? { a: 'counters-a' } : RED_BLUE });
79
+ lines = !spec.written ? [] : shelf() ? [main, line(['written-left', 'reading-left'], { refs: { b: 'sum', c: 'left' } })]
80
+ : spec.written === 'ten' ? [main, line(['written-to-ten', 'reading-to-ten'], { step: true, refs: { a: 'first', b: 'to-ten' }, cls: spec.take ? { a: 'counters-a' } : RED_BLUE }),
81
+ line(['written-rest', 'reading-rest'], { step: true, refs: { b: 'rest', c: end }, cls: spec.take ? {} : { b: 'counters-b' } })]
82
+ : [main];
83
+ front.replaceChildren(...lines.map(l => l.el), ...dies.map(d => d.g));
84
+ }
85
+ // place sets the counters as the page opens, and stops a run of moving counters.
86
+ function place() {
87
+ const o = opening(spec);
88
+ play++;
89
+ Object.assign(s, { red: [], joined: [], later: [], tray: [], taken: new Set(), jars: [], crate: s.crate ?? 'first', dice: spec.dice ? [o.first, o.waiting] : null });
90
+ if (shelf()) { s.jars = ids(JARS, 'j'); s.red = s.jars.slice(0, o.first); s.joined = s.jars.slice(o.first, o.first + o.second); }
91
+ else if (spec.take) { s.red = ids(o.first, 'r'); s.taken = new Set(s.red.slice(s.red.length - o.second)); }
92
+ else Object.assign(s, { red: ids(o.first, 'r'), joined: ids(o.second, 'b'), tray: ids(o.waiting, 'b') });
93
+ }
94
+ const holds = () => base.challenge ? goalOf().holds({ ...s.answer, checked: s.checked }, spec, base.challenge, target) : { done: false };
95
+
96
+ // framesLayout tries the frames side by side and one above the other, or the seed tray, with the tray or the seed
97
+ // packet beside them or under them, and keeps the way that fits the stage at the largest scale. Each die stands
98
+ // over its block.
99
+ function framesLayout(fit) {
100
+ const room = spec.dice ? DIE[1] : spec.second + (spec.waiting ?? 0), tray = waits() ? waitTray(room, spec.look === 'tray') : null, dieH = spec.dice ? DIE_ROOM : 0;
101
+ let best = null;
102
+ for (const fw of spec.look === 'tray' ? [seedTray()] : frames(2)) for (const beside of tray ? [true, false] : [null]) {
103
+ let w, h, f, t = null;
104
+ if (beside === null) { w = fw.w; h = dieH + fw.h; f = { x: 0, y: dieH }; }
105
+ else if (beside) { const hh = Math.max(fw.h, tray.h); w = fw.w + SPACE + tray.w; h = dieH + hh; f = { x: 0, y: dieH + (hh - fw.h) / 2 }; t = { x: fw.w + SPACE, y: dieH + (hh - tray.h) / 2 }; }
106
+ else { w = Math.max(fw.w, tray.w); h = dieH + fw.h + SPACE + dieH + tray.h; f = { x: (w - fw.w) / 2, y: dieH }; t = { x: (w - tray.w) / 2, y: dieH + fw.h + SPACE + dieH }; }
107
+ best = fit(best, w, h, dx => {
108
+ const fd = fw.draw(f.x + dx, f.y), td = tray && t ? tray.draw(t.x + dx, t.y) : null, box = { x: f.x + dx, y: f.y, w: fw.w, h: fw.h };
109
+ const over = (x, y, bw) => `translate(${x + bw / 2} ${y - DIE_ROOM + DIE_SIZE / 2})`;
110
+ dies[0].g.setAttribute('transform', over(box.x, box.y, box.w));
111
+ if (td) dies[1].g.setAttribute('transform', over(t.x + dx, t.y, tray.w));
112
+ // A tap on an empty cell joins the next waiting counter, so a phone needs no aim at a single counter. On a
113
+ // split seed tray it sows the seed in the row of that cell.
114
+ const row = i => spec.look === 'tray' && spec.split ? (i < 10 ? 'first' : 'second') : true;
115
+ const targets = moves() ? fd.cells.map((c, i) => { const rect = el('rect', { class: 'counters-cell', x: c.x - CELL / 2, y: c.y - CELL / 2, width: CELL, height: CELL, rx: 4 }); press(rect, () => joinNext(row(i))); return rect; }) : [];
116
+ return { nodes: [...fd.nodes, ...(td ? [td.box] : []), ...targets], cells: fd.cells, frames: box, tray: td, targets };
117
+ });
118
+ }
119
+ return best;
120
+ }
121
+ // shelfLayout sets the shelf above its two crates, which stand side by side or one above the other.
122
+ function shelfLayout(fit) {
123
+ const named = ['first', 'second'].map(k => crate(JARS, T(`add-shelf-${k}`), k));
124
+ let best = null;
125
+ for (const sw of shelfWays(JARS)) for (const k of [0, 1]) for (const beside of [true, false]) {
126
+ const crates = named.map(ways => ways[k]), one = crates[0];
127
+ const cw = beside ? 2 * one.w + SPACE : one.w, ch = beside ? one.h : 2 * one.h + SPACE;
128
+ const w = Math.max(sw.w, cw), h = sw.h + SPACE + ch;
129
+ best = fit(best, w, h, dx => {
130
+ const sd = sw.draw(dx + (w - sw.w) / 2, 0), x0 = dx + (w - cw) / 2, y0 = sw.h + SPACE;
131
+ const cd = crates.map((c, i) => c.draw(beside ? x0 + i * (c.w + SPACE) : x0, beside ? y0 : y0 + i * (c.h + SPACE)));
132
+ // A tap on the shelf sells its last jar, and a tap on a crate puts the crate's last jar back.
133
+ press(sd.area, () => { const id = s.jars.filter(j => !s.red.includes(j) && !s.joined.includes(j)).at(-1); if (id) sell(id); });
134
+ cd.forEach((c, i) => press(c.box, () => { const id = (i ? s.joined : s.red).at(-1); if (id) sell(id); }));
135
+ return { nodes: [...sd.nodes, ...cd.flatMap(c => c.nodes)], shelf: sd.pos, crates: cd, targets: [] };
136
+ });
137
+ }
138
+ return best;
139
+ }
140
+
141
+ // build draws the figure to fit the stage, with the written lines under it, and puts every counter in its place.
142
+ function build() {
143
+ const r = svg.getBoundingClientRect(); area = { w: Math.round(r.width), h: Math.round(r.height) };
144
+ if (!area.w || !area.h) { geo = null; return; } // A phone is showing the text, so the figure is drawn when the stage shows.
145
+ const room = k => k && spec.written === 'ten' ? STEP_LINE : LINE;
146
+ const lineW = lines.length ? widthOf('00 + 00 = 00') : 0, lineH = lines.length ? SPACE + lines.reduce((sum, l, k) => sum + room(k), 0) : 0;
147
+ // fit keeps the way of setting the figure out that shows it at the largest scale.
148
+ const fit = (best, w, h, draw) => {
149
+ const W = Math.max(w, lineW), H = h + lineH, scale = Math.min((area.w - 2 * PAD) / W, (area.h - 2 * PAD) / H);
150
+ return !best || scale > best.scale + 1e-6 ? { scale, w: W, h: H, top: h, draw: () => draw((W - w) / 2) } : best;
151
+ };
152
+ const L = shelf() ? shelfLayout(fit) : framesLayout(fit), scale = Math.min(MAX, L.scale);
153
+ svg.setAttribute('viewBox', `${L.w / 2 - area.w / 2 / scale} ${L.h / 2 - area.h / 2 / scale} ${area.w / scale} ${area.h / scale}`);
154
+ geo = L.draw();
155
+ back.replaceChildren(...geo.nodes);
156
+ for (const d of dies) d.g.setAttribute('display', spec.dice ? 'inline' : 'none');
157
+ let y = L.top + SPACE;
158
+ lines.forEach((l, k) => { l.at(L.w / 2, y + room(k) / 2 - 6); y += room(k); });
159
+ for (const n of nodes.values()) n.tween?.pause();
160
+ layer.replaceChildren(); nodes = new Map();
161
+ render('jump');
162
+ }
163
+
164
+ // where gives the place of every counter. The first group and the joined counters fill the cells in order, and
165
+ // the waiting counters stand in the tray. A counter taken away keeps its cell. A jar on the shelf stands in its
166
+ // own place, and a jar sold stands in its crate in the order it was sold.
167
+ function where() {
168
+ const out = new Map();
169
+ if (shelf()) {
170
+ s.jars.forEach((id, i) => out.set(id, geo.shelf(i)));
171
+ [s.red, s.joined].forEach((list, k) => list.forEach((id, i) => out.set(id, geo.crates[k].pos(i))));
172
+ return out;
173
+ }
174
+ [...s.red, ...s.joined].forEach((id, i) => out.set(id, geo.cells[i]));
175
+ s.later.forEach((id, i) => out.set(id, geo.cells[10 + i]));
176
+ s.tray.forEach((id, i) => out.set(id, geo.tray.pos(i)));
177
+ return out;
178
+ }
179
+
180
+ // render moves every counter to its place. After a change the reader made, counters glide, arrive and leave.
181
+ function render(how) {
182
+ solved = holds().done;
183
+ if (!geo) return refresh();
184
+ const to = where(), anim = how === 'move' && moving();
185
+ let k = 0;
186
+ for (const [id, n] of nodes) if (!to.has(id)) {
187
+ nodes.delete(id); n.tween?.pause();
188
+ if (anim) go.vanish(n.pop, () => n.g.remove()); else n.g.remove();
189
+ }
190
+ for (const [id, p] of to) {
191
+ let n = nodes.get(id);
192
+ if (!n) {
193
+ n = make(id); nodes.set(id, n); layer.append(n.g); put(n, p);
194
+ if (anim) go.pop(n.pop, 25 * k++);
195
+ continue;
196
+ }
197
+ if (n === hold || (n.at.x === p.x && n.at.y === p.y)) continue;
198
+ n.tween?.pause();
199
+ if (anim) n.tween = go.tween(n.at, { x: p.x, y: p.y }, () => show(n)); else put(n, p);
200
+ }
201
+ paint(anim); refresh();
202
+ }
203
+
204
+ // make draws a counter or a jar. A jar sells and comes back by tap. A counter of a take-away page with taps goes
205
+ // and comes back by tap, and carries the dashed ring it leaves. A counter of the second group on a page with a tray
206
+ // goes between the tray and the frames by drag and by tap.
207
+ function make(id) {
208
+ if (id[0] === 'j') {
209
+ const n = counter('jar', 'plain', JAR_R);
210
+ n.pop.prepend(el('rect', { class: 'counters-hit', x: -JAR_HIT.w / 2, y: -JAR_HIT.h / 2, width: JAR_HIT.w, height: JAR_HIT.h }));
211
+ n.g.setAttribute('tabindex', 0); n.g.setAttribute('role', 'button');
212
+ press(n.g, () => sell(id));
213
+ return n;
214
+ }
215
+ const kinds = spec.look === 'tray' ? ['seedling', 'sprout'] : ['disc', 'square'], n = counter(kinds[firstOf(id) ? 0 : 1], firstOf(id) ? 'a' : 'b');
216
+ // A sprout of the tray is a seed while it lies in the packet.
217
+ if (spec.look === 'tray' && !firstOf(id)) n.pop.append(el('ellipse', { class: 'counters-body counters-seed', rx: 5, ry: 7, transform: 'rotate(20)' }));
218
+ if (spec.take) {
219
+ n.pop.append(el('circle', { class: 'counters-void counters-gone', r: R - 2 }));
220
+ if (taps()) { n.g.setAttribute('tabindex', 0); n.g.setAttribute('role', 'button'); press(n.g, () => takeAway(id)); }
221
+ return n;
222
+ }
223
+ if (firstOf(id) || !moves()) return n;
224
+ n.g.setAttribute('tabindex', 0); n.g.setAttribute('role', 'button');
225
+ n.g.classList.add('counters-moves');
226
+ let dx = 0, dy = 0;
227
+ carry(n.g, {
228
+ point: e => svgPoint(svg, e), raise: () => layer.append(n.g),
229
+ start(q) { n.tween?.pause(); hold = n; dx = n.at.x - q.x; dy = n.at.y - q.y; },
230
+ move(q) { put(n, { x: q.x + dx, y: q.y + dy }); },
231
+ drop(q) { hold = null; if (!q || !moveTo(id, onFrames({ x: q.x + dx, y: q.y + dy }))) render('move'); },
232
+ tap() { hold = null; moveTo(id, s.tray.includes(id)); },
233
+ });
234
+ return n;
235
+ }
236
+ // onFrames says where a counter let go at p lands: 'first' or 'second' for the frame under it on a split page,
237
+ // true for the frames on any other page, and null off the frames.
238
+ const inside = (b, p) => p.x > b.x - NEAR && p.x < b.x + b.w + NEAR && p.y > b.y - NEAR && p.y < b.y + b.h + NEAR;
239
+ function onFrames(p) {
240
+ if (!inside(geo.frames, p)) return null;
241
+ if (!spec.split) return true;
242
+ const box = k => { const cs = geo.cells.slice(10 * k, 10 * k + 10), xs = cs.map(c => c.x), ys = cs.map(c => c.y); return { x: Math.min(...xs) - CELL / 2, y: Math.min(...ys) - CELL / 2, w: Math.max(...xs) - Math.min(...xs) + CELL, h: Math.max(...ys) - Math.min(...ys) + CELL }; };
243
+ const d = k => { const b = box(k); return Math.hypot(p.x - (b.x + b.w / 2), p.y - (b.y + b.h / 2)); };
244
+ return d(0) <= d(1) ? 'first' : 'second';
245
+ }
246
+ // moveTo joins a waiting counter to the frames, where it takes the next empty cell, or sends a joined counter back
247
+ // to the tray. On a split page a counter joins the frame it lands on, and the first frame once it is full passes
248
+ // it on to the second. It says whether the counter moved.
249
+ function moveTo(id, to) {
250
+ const from = [s.tray, s.joined, s.later].find(list => list.includes(id));
251
+ const into = !to ? s.tray : !spec.split || (to !== 'second' && s.red.length + s.joined.length < 10) ? s.joined : s.later;
252
+ if (!from || (to && from !== s.tray) || (!to && from === s.tray)) return false;
253
+ from.splice(from.indexOf(id), 1); into.push(id);
254
+ changed();
255
+ return true;
256
+ }
257
+ // joinNext joins the next waiting counter, in order or into the row given.
258
+ function joinNext(to = true) { const id = s.tray.at(-1); if (id) moveTo(id, to); }
259
+ // takeAway takes a counter away, or puts back the counter of a ring.
260
+ function takeAway(id) {
261
+ if (s.taken.has(id)) s.taken.delete(id); else s.taken.add(id);
262
+ s.checked = false;
263
+ changed();
264
+ if (moving()) go.pop(nodes.get(id)?.pop);
265
+ }
266
+ // sell moves a jar on the shelf into the crate the segment picks, and a jar in a crate back to its place.
267
+ function sell(id) {
268
+ const from = [s.red, s.joined].find(list => list.includes(id));
269
+ if (from) from.splice(from.indexOf(id), 1);
270
+ else (s.crate === 'first' ? s.red : s.joined).push(id);
271
+ changed();
272
+ }
273
+
274
+ // roll throws both dice: the first die's counters fill the frames, the second die's wait in the tray, and the
275
+ // counters joined before go.
276
+ function roll() {
277
+ const d = dice(fresh()), a = d.int(...DIE), b = d.int(...DIE);
278
+ s = { ...s, red: ids(a, 'r'), joined: [], tray: ids(b, 'b'), dice: [a, b] };
279
+ changed();
280
+ if (moving()) for (const x of dies) go.pop(x.pop);
281
+ }
282
+ // setGroup sets a number with its stepper. On an addition page it sets a group, and the second group's counters move
283
+ // on or back to stay after the first group's. On a take-away page the first number puts every counter back, and the
284
+ // number taken away takes counters from the last cell back.
285
+ function setGroup(k, v) {
286
+ if (spec.take && k === 'second') s.taken = new Set(s.red.slice(s.red.length - v));
287
+ else {
288
+ const list = k === 'first' ? s.red : s.joined;
289
+ if (list.length < v) list.push(...ids(v - list.length, k === 'first' ? 'r' : 'b'));
290
+ list.length = v;
291
+ if (spec.take) s.taken = new Set();
292
+ }
293
+ s.checked = false;
294
+ changed();
295
+ }
296
+ function changed() { render('move'); }
297
+
298
+ // paint turns the dice, writes the lines, opens the empty cells to taps and marks the counters taken away and the
299
+ // jars sold.
300
+ function paint(anim) {
301
+ if (s.dice) dies.forEach((d, k) => d.set(s.dice[k], T('add-die', int(s.dice[k]))));
302
+ const st = now(), steps = stepsOf(spec, st), g = base.challenge && goalOf();
303
+ // A challenge writes its drawn calculation open from the start, and its answer and steps once the goal holds.
304
+ const of = g ? [() => g.line(target, solved), () => solved && g.steps?.(target)[0], () => solved && g.steps?.(target)[1]]
305
+ : [() => lineOf(spec, st), () => shelf() ? leftOf(spec, st) : steps?.lines[0], () => steps?.lines[1]];
306
+ lines.forEach((l, k) => { if (l.set(of[k]() || null, int) && anim) go.flash(l.el); });
307
+ const used = new Set([...where().values()].map(p => geo.cells?.indexOf(p)));
308
+ geo.targets.forEach((t, i) => t.setAttribute('display', !used.has(i) && s.tray.length ? 'inline' : 'none'));
309
+ for (const [id, n] of nodes) {
310
+ if (spec.take) {
311
+ n.g.classList.toggle('counters-taken', s.taken.has(id));
312
+ if (taps()) n.g.setAttribute('aria-label', T(s.taken.has(id) ? 'add-take-ring' : 'add-take-counter'));
313
+ } else if (id[0] === 'j') {
314
+ const k = s.red.includes(id) ? 'first' : s.joined.includes(id) ? 'second' : null;
315
+ n.g.classList.toggle('counters-a', k === 'first'); n.g.classList.toggle('counters-b', k === 'second');
316
+ n.g.setAttribute('aria-label', k ? T('add-sold-jar', T(`add-shelf-${k}`)) : T('add-shelf-jar'));
317
+ } else if (!firstOf(id) && waits()) {
318
+ n.g.classList.toggle('counters-in-packet', spec.look === 'tray' && s.tray.includes(id));
319
+ if (moves()) n.g.setAttribute('aria-label', T(`add-${spec.look === 'tray' ? 'seed' : 'counter'}-${s.tray.includes(id) ? 'waiting' : 'joined'}`));
320
+ }
321
+ }
322
+ light();
323
+ }
324
+
325
+ // light marks the counters of each link the reader points at, and the numbers of the written lines.
326
+ const GROUPS = {
327
+ first: () => s.red, second: () => spec.take ? [...s.taken] : s.joined, sum: () => [...s.red, ...s.joined], waiting: () => s.tray,
328
+ left: () => shelf() ? s.jars.filter(id => !s.red.includes(id) && !s.joined.includes(id)) : spec.take ? s.red.filter(id => !s.taken.has(id)) : [],
329
+ // The parts of making ten: on an addition the second group's counters in the first frame and in the second, and
330
+ // on a take away the rings of the second frame and of the first. They light while the steps show.
331
+ 'to-ten': () => !stepsOf(spec, now()) ? [] : spec.take ? s.red.slice(10).filter(id => s.taken.has(id)) : [...s.red, ...s.joined].slice(s.red.length, 10),
332
+ rest: () => !stepsOf(spec, now()) ? [] : spec.take ? s.red.slice(0, 10).filter(id => s.taken.has(id)) : [...[...s.red, ...s.joined].slice(10), ...s.later],
333
+ };
334
+ function light() {
335
+ const on = new Set([...lit].flatMap(id => GROUPS[id]?.() ?? []));
336
+ for (const [id, n] of nodes) n.g.classList.toggle('counters-lit', on.has(id));
337
+ for (const d of dies) d.g.classList.toggle('counters-hot', lit.has(d.g.dataset.ref));
338
+ for (const part of back.querySelectorAll('[data-ref]')) part.classList.toggle('counters-hot', lit.has(part.dataset.ref));
339
+ }
340
+
341
+ // refresh writes every value that follows the counters, in the readouts and the text, and judges a challenge.
342
+ function refresh() {
343
+ const st = counts(spec, now()), ids = measuresOf(spec);
344
+ const value = id => {
345
+ const line = LINES[id]?.(spec, now());
346
+ if (id in LINES) return !line ? DASH : id.startsWith('written') ? words(line, int) : reading(line, int, T);
347
+ return st[id] == null ? DASH : int(st[id]);
348
+ };
349
+ for (const k of chips) if (k.set(value(k.id)) && moving()) go.flash(k.el);
350
+ live(host, { value: id => ids.includes(id) ? value(id) : null });
351
+ judge();
352
+ }
353
+ // vars gives a challenge's words: its numbers, the reader's numbers and step, and the lines of its done line.
354
+ function vars() {
355
+ const g = goalOf(), a = s.answer, steps = g.steps?.(target);
356
+ return { ...g.words(base.challenge, target, { int }), n: int(a.sum), calc: words(g.line(target, false), int), line: words(g.line(target, true), int),
357
+ step: target.sign ? words({ a: target.a, sign: target.sign, b: a.toTen, open: true }, int) : '', x: int(a.toTen), y: int(a.rest), toTen: steps ? words(steps[0], int) : '', rest: steps ? words(steps[1], int) : '' };
358
+ }
359
+ function judge() {
360
+ if (!goal) return;
361
+ const c = base.challenge, r = holds(), v = vars();
362
+ const key = k => goalKey(k, target, x => T(x) != null);
363
+ goal.say(T(r.done ? `goal-${c.goal}-done` : key(`goal-${c.goal}`), v));
364
+ goal.show(r.done, r.note ? T(key(`note-${c.goal}-${r.note}`), v) : undefined);
365
+ }
366
+ // hint gives the hint of a challenge, which on steps-to-ten differs for an addition and a subtraction.
367
+ const hint = () => T(`hint-${base.challenge.goal}${target.sign ? `-${target.sign === '+' ? 'plus' : 'minus'}` : ''}`, vars());
368
+
369
+ // check commits the reader's numbers. Once they are right the counters move: find-sum fills the frames with the
370
+ // first group and then joins the second, and steps-to-ten moves the to-ten counters and then the rest.
371
+ function commit() {
372
+ if (s.checked) return;
373
+ s.checked = true;
374
+ if (!holds().done) return render('move');
375
+ const run = play, g = base.challenge.goal, t = target;
376
+ const first = g === 'find-sum' ? () => { s.red = ids(t.a, 'r'); } : t.sign === '+' ? () => { s.joined.push(...s.tray.splice(-toTen())); } : () => { for (const id of s.red.slice(-toTen())) s.taken.add(id); };
377
+ const then = g === 'find-sum' ? () => { s.joined = ids(t.b, 'b'); } : t.sign === '+' ? () => { s.joined.push(...s.tray.splice(0)); } : () => { for (const id of s.red.slice(10 - (t.b - toTen()), 10).reverse()) s.taken.add(id); };
378
+ first(); render('move');
379
+ const last = () => { if (run !== play || !spec) return; then(); render('move'); if (moving()) go.cheer([...nodes.values()].map(n => n.pop)); };
380
+ if (moving()) setTimeout(last, 650); else last();
381
+ }
382
+ const toTen = () => target.sign === '+' ? 10 - target.a : target.a - 10;
383
+ // setAnswer keeps the number of a challenge's stepper. A change takes the check back and puts the counters as the
384
+ // page opened.
385
+ function setAnswer(k, v) {
386
+ s.answer[k] = v;
387
+ if (s.checked) { s.checked = false; place(); }
388
+ changed();
389
+ }
390
+
391
+ // name gives a readout or a stepper its name in the page's context, such as "Taken away" or "Morning".
392
+ const name = id => labelKeys(spec, id).map(k => T(k)).find(Boolean) ?? (id.startsWith('written') ? T('written') : id.startsWith('reading') ? T('written-reading') : T(`add-${id}`));
393
+ // The panel holds a challenge's line, the steppers, the segment of the shelf, Roll and Check, and the readouts. The
394
+ // written lines and their words take a line of the panel each, so the panel keeps its height as they change.
395
+ function drawPanel() {
396
+ const c = base.challenge, ctls = [];
397
+ for (const k of ['first', 'second']) {
398
+ const r = spec[`${k}Ctl`];
399
+ if (r) ctls.push(stepper({ id: k, label: name(k), min: r.lo, max: r.hi, value: now()[k], write: int, change: v => setGroup(k, v) }));
400
+ }
401
+ // A challenge's own steppers: Sum, Makes ten and The rest.
402
+ for (const [id, k] of [['sum', 'sum'], ['to-ten', 'toTen'], ['rest', 'rest']]) {
403
+ const r = spec[`${k}Ctl`];
404
+ if (r) ctls.push(stepper({ id, label: name(id), min: r.lo, max: r.hi, value: s.answer[k], write: int, change: v => setAnswer(k, v) }));
405
+ }
406
+ if (shelf()) ctls.push(segment({ id: 'crate', label: T('add-shelf-crate'), items: ['first', 'second'].map(k => [k, T(`add-shelf-${k}`)]), value: s.crate, pick: v => { s.crate = v; } }));
407
+ if (spec.dice) ctls.push(button({ label: T('add-roll'), act: 'roll', primary: true, press: roll }));
408
+ goal = null;
409
+ if (c) {
410
+ goal = goalRow({ T, motion: moving() ? fx : null, hint: on => on ? hint() : null,
411
+ another: () => { deal(); drawPanel(); build(); if (!geo) refresh(); } });
412
+ ctls.push(check({ T, press: commit }));
413
+ }
414
+ const wide = id => id in LINES;
415
+ chips = spec.readout.map(id => chip({ id, label: name(id), cls: wide(id) ? 'counters-chip-wide' : '' }));
416
+ for (const k of chips) if (!wide(k.id)) k.width(2);
417
+ panel.replaceChildren(...[goal?.el, ctls.length ? row('ctls', ctls) : null, chips.length ? row('out', chips) : null].filter(Boolean));
418
+ }
419
+
420
+ function point(id, on) {
421
+ if (!spec) return;
422
+ if (on) lit.add(id); else lit.delete(id);
423
+ for (const l of lines) l.light(id, on, l.whole);
424
+ if (geo) light();
425
+ for (const part of panel.querySelectorAll('[data-ref]')) part.classList.toggle('hot', on && part.dataset.ref === id);
426
+ }
427
+ function stop() { for (const n of nodes.values()) n.tween?.pause(); hold = null; }
428
+
429
+ return {
430
+ show(page) {
431
+ stop(); base = page; target = null; lit.clear(); deal();
432
+ drawPanel(); build();
433
+ if (!geo) render('jump');
434
+ },
435
+ hide() {
436
+ stop(); play++; spec = null; base = null; goal = null; geo = null; nodes = new Map(); lines = [];
437
+ for (const g of [back, layer, front]) g.replaceChildren();
438
+ },
439
+ point,
440
+ lang() { if (!spec) return; const was = goal; drawPanel(); goal?.keep(was); build(); if (!geo) render('jump'); },
441
+ };
442
+ }
@@ -0,0 +1,102 @@
1
+ // The Node half of the add scene: two groups of counters joined in two ten frames, counters taken away from one
2
+ // group, or the jars of a shop shelf, with the written lines of their calculation. It checks a page's fields and says
3
+ // what each link shows when the page opens.
4
+ import { schema } from '@openbooknetwork/kitap';
5
+ import { ADD_LOOKS, CELLS, JARS, DIE, opening, counts, LINES, measuresOf } from './add-model.js';
6
+ import { ADD_GOALS, addStart } from './add-goals.js';
7
+ import { words, reading, DASH } from '../../kit/written.js';
8
+ import { numbers } from '../../kit/format.js';
9
+ import { list, value, string, challenge, drawn } from '../../node.mjs';
10
+
11
+ const { z, check } = schema;
12
+ const Int = z.number().int();
13
+ const Range = z.tuple([Int, Int]);
14
+ const Stepper = z.object({ stepper: Range, start: Int.optional() }).strict();
15
+ const Fields = z.object({
16
+ look: z.enum(ADD_LOOKS).default('frames'), // Two ten frames, or the shop shelf or the seed tray of a world page.
17
+ first: z.union([Int, Stepper]).optional(), // The counters of the first group, round and red, as a number or on a stepper.
18
+ second: z.union([Int, Stepper]).optional(), // The counters of the second group in the frames, square and blue.
19
+ waiting: Int.optional(), // Counters of the second group that wait in a tray beside the frames.
20
+ dice: z.boolean().default(false), // Two dice and a Roll button set the first group and the counters waiting.
21
+ take: z.boolean().default(false), // The page takes counters away, and second counts the counters taken.
22
+ // The written line under the frames, and with ten the two steps of making ten under it.
23
+ written: z.union([z.literal(true), z.literal('ten')]).optional(),
24
+ split: z.boolean().default(false), // A counter dropped on a frame joins that frame, so the reader splits the group.
25
+ readout: z.array(z.string()).default([]),
26
+ // A challenge names a goal of add-goals.js and the range it draws its target from.
27
+ challenge: z.object({ goal: z.string(), first: Range.optional(), second: Range.optional(), sum: Range.optional() }).strict().optional(),
28
+ }).strict();
29
+
30
+ function read(fields, { at }, ctx) {
31
+ const pg = check(Fields, fields, at), fail = words => ctx.fail(at, words);
32
+ const first = value(pg.first), second = value(pg.second);
33
+ const spec = { ...pg, scene: 'add', first: first.n, firstCtl: first.ctl, second: second.n ?? 0, secondCtl: second.ctl, waiting: pg.waiting ?? null };
34
+ if (pg.challenge) { readChallenge(pg, spec, at, ctx); return { data: spec, has: () => false, offers: 'nothing, a challenge page draws its numbers as it opens' }; }
35
+ if (pg.look === 'shelf') return readShelf(pg, spec, first, second, fail);
36
+ if (pg.look === 'tray') for (const f of ['dice', 'take']) if (pg[f]) fail(`${f} belongs to the frames, the seed tray takes first, second, waiting, split, written and readout`);
37
+ if (first.n == null) fail('first is missing, write the counters of the first group, such as 5, or { stepper: [0, 10], start: 4 }');
38
+ for (const [v, name] of [[first, 'first'], [second, 'second']]) {
39
+ if (v.n == null) continue;
40
+ const lo = v.ctl?.lo ?? v.n, hi = v.ctl?.hi ?? v.n;
41
+ if (lo > hi || v.n < lo || v.n > hi) fail(`${name} has the range [${lo}, ${hi}] and starts at ${v.n}, write [low, high] and a start between them`);
42
+ else if (lo < 0 || hi > CELLS) fail(`${name} reaches ${v.ctl ? `[${lo}, ${hi}]` : v.n}, a group holds from 0 to ${CELLS} counters`);
43
+ }
44
+ if (pg.waiting != null) {
45
+ if (pg.waiting < 1 || pg.waiting > CELLS) fail(`waiting is ${pg.waiting}, write the counters that wait in the tray as a number from 1 to ${CELLS}`);
46
+ if (first.ctl || second.ctl) fail('waiting joins counters by hand, write first and second as numbers');
47
+ }
48
+ if (pg.dice) {
49
+ if (pg.waiting == null) fail('dice throws the first group and the counters waiting, write waiting as well');
50
+ if (pg.second !== undefined) fail('dice opens with no counter of the second group joined, leave second out');
51
+ for (const [n, name] of [[first.n, 'first'], [pg.waiting, 'waiting']]) if (n != null && (n < DIE[0] || n > DIE[1])) fail(`${name} is ${n}, a die shows ${DIE[0]} to ${DIE[1]}, write a number a die shows`);
52
+ }
53
+ if (pg.split && (pg.waiting == null || (first.n ?? 0) >= 10)) fail('split splits the waiting counters between the two frames or the two rows, write waiting and a first group below 10');
54
+ if (pg.take) {
55
+ for (const f of ['waiting', 'dice', 'split']) if (pg[f] !== undefined && pg[f] !== false) fail(`${f} joins counters, a take-away page takes them away, leave ${f} out`);
56
+ if (first.ctl && second.ctl) fail('first and second both have a stepper, give one of them a number');
57
+ const most = second.ctl?.hi ?? second.n ?? 0, least = first.ctl?.lo ?? first.n ?? 0;
58
+ if (most > least) fail(`second reaches ${most}, more than the ${least} counters of first, take away ${least} at most`);
59
+ }
60
+ const most = pg.take ? (first.ctl?.hi ?? first.n ?? 0) : (first.ctl?.hi ?? first.n ?? 0) + (second.ctl?.hi ?? second.n ?? 0) + (pg.waiting ?? 0);
61
+ if (most > CELLS) fail(`the counters reach ${most}, and the two frames hold ${CELLS}`);
62
+ return offered(pg, spec, fail);
63
+ }
64
+
65
+ // The shelf is a page of its own: the jars sold in the morning and in the afternoon as numbers, the written lines and
66
+ // the readouts.
67
+ function readShelf(pg, spec, first, second, fail) {
68
+ for (const f of ['waiting', 'dice', 'take', 'split']) if (pg[f] !== undefined && pg[f] !== false) fail(`${f} belongs to the frames, the shelf takes first, second, written and readout`);
69
+ if (pg.written === 'ten') fail('written: ten belongs to the frames and the seed tray, write written: true on the shelf');
70
+ if (first.ctl || second.ctl || first.n == null || first.n < 0 || second.n < 0 || first.n + second.n > JARS) fail(`first and second are the jars sold in the morning and in the afternoon, write them as numbers that come to ${JARS} at most`);
71
+ return offered(pg, spec, fail);
72
+ }
73
+
74
+ function offered(pg, spec, fail) {
75
+ const ids = measuresOf(spec);
76
+ for (const id of pg.readout) if (!ids.includes(id)) fail(`readout names "${id}", this page reads out ${list(ids)}`);
77
+ return { data: spec, has: id => ids.includes(id), offers: `one of ${list(ids)}` };
78
+ }
79
+
80
+ // A challenge page names its goal and the range the goal draws from, and may write the line once the goal holds. It
81
+ // leaves every other field out, and the goal gives the page its steppers.
82
+ function readChallenge(pg, spec, at, ctx) {
83
+ const c = pg.challenge, goal = challenge(c, ADD_GOALS, { scene: 'add', at, ctx });
84
+ if (!goal) return;
85
+ for (const [f, v] of Object.entries(pg)) if (!['challenge', 'look', 'written'].includes(f) && v !== undefined && v !== false && !(f === 'readout' && !v.length)) ctx.fail(at, `${f} is set by challenge.goal ${c.goal}, leave it out`);
86
+ if (pg.look !== 'frames') ctx.fail(at, `look is set by challenge.goal ${c.goal}, leave it out`);
87
+ const problem = goal.problem(c);
88
+ if (problem) return ctx.fail(at, `challenge.${problem}`);
89
+ drawn(goal, c, spec, { at, ctx, starts: addStart });
90
+ }
91
+
92
+ // A link shows a count, a written line or its words as the page opens.
93
+ function start(spec, lang, id) {
94
+ if (!measuresOf(spec).includes(id)) return null;
95
+ const s = opening(spec), int = numbers(lang).int;
96
+ const line = LINES[id]?.(spec, s), n = counts(spec, s)[id];
97
+ if (id.startsWith('written')) return line ? words(line, int) : DASH;
98
+ if (id.startsWith('reading')) return line ? reading(line, int, (key, vars) => string(lang, `hesap_${key}`, vars)) : DASH;
99
+ return n == null ? DASH : int(n);
100
+ }
101
+
102
+ export default { read, start };