@openbooknetwork/hesap 0.1.0 → 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.
package/README.md CHANGED
@@ -38,12 +38,16 @@ Scenes come in families. Each family is a folder under `src/families/`. A page n
38
38
 
39
39
  | Family | Scenes |
40
40
  |---|---|
41
- | `counters` | `bonds` |
41
+ | `counters` | `bonds`, `count` |
42
42
 
43
43
  `counters/bonds` shows a whole and its two parts: a part-whole diagram, one or two ten frames with counters of two
44
44
  colours, a cup that hides a part and a list of the splits found. Its `index.mjs` holds the schema of its fields,
45
45
  with a comment on every field.
46
46
 
47
+ `counters/count` counts objects one by one: apples, birds, cups, shells or counters that take the next number when
48
+ tapped, a closed box to count on from, counters that leave a tray, a marker in rows of ten, a bus and a staircase.
49
+ Its `count.mjs` holds the schema of its fields.
50
+
47
51
  The tag `prototypes` holds 13 more families from the prototype stories: `geo`, `axes`, `graph`, `wave`, `linear`,
48
52
  `chance`, `machine`, `parts`, `grid`, `venn`, `balance`, `network` and `proof`. A family comes back from there with
49
53
  the first story that needs it: `git checkout prototypes -- src/families/<id>`, then its line in `src/families.mjs`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openbooknetwork/hesap",
3
- "version": "0.1.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "description": "Hesap: the maths engine of the Open Book Network, figures a reader can move with the numbers and formulas that follow them",
6
6
  "keywords": [
package/src/client.css CHANGED
@@ -184,3 +184,57 @@ aside.story .place[data-formula] .katex-display>.katex{text-align:start}
184
184
  /* The figure ends above the peek card, which covers the foot of the stage until the reader closes it. */
185
185
  .hesap-counters .counters-svg{height:calc(100% - var(--hesap-peek,0px))}
186
186
  }
187
+
188
+ /* The count scene: the places objects lie in, the objects, and the numbers the reader gives them. */
189
+ .hesap-counters .counters-sand{fill:#e8d3a6;stroke:#c9ad78;stroke-width:2}
190
+ .hesap-counters .counters-table{fill:#b98a5a;stroke:#8a6238;stroke-width:2}
191
+ .hesap-counters .counters-awning-0{fill:#d1453b}
192
+ .hesap-counters .counters-awning-1{fill:#f4ede1}
193
+ .hesap-counters .counters-wire{fill:none;stroke:var(--ink);stroke-width:2.5}
194
+ .hesap-counters .counters-pole{stroke:var(--ink-2);stroke-width:6;stroke-linecap:round}
195
+ .hesap-counters .counters-row-label{font-size:16px;font-weight:700;fill:var(--ink-2)}
196
+ .hesap-counters .counters-stem{fill:none;stroke:#6b4a2b;stroke-width:2.5;stroke-linecap:round}
197
+ .hesap-counters .counters-leaf{fill:#3f9a4a}
198
+ .hesap-counters .counters-apple .counters-shine{fill:#fff;opacity:.45}
199
+ .hesap-counters .counters-bird .counters-body{fill:var(--ink-2)}
200
+ .hesap-counters .counters-eye{fill:var(--paper)}
201
+ .hesap-counters .counters-feet{stroke:#d99a1f;stroke-width:2}
202
+ .hesap-counters .counters-trail{fill:none;stroke:var(--accent);stroke-width:3;stroke-dasharray:7 6;stroke-linecap:round;stroke-linejoin:round;opacity:.8}
203
+ .hesap-counters .counters-shell .counters-body{fill:#f2a679;stroke:#c46a3c}
204
+ .hesap-counters .counters-ribs{stroke:#c46a3c;stroke-width:1.5;fill:none}
205
+ .hesap-counters .counters-skin{fill:#e0ac7e;stroke:var(--paper);stroke-width:1.5}
206
+ .hesap-counters .counters-legs{stroke:var(--ink);stroke-width:5;stroke-linecap:round}
207
+ .hesap-counters .counters-walker .counters-body{fill:var(--accent)}
208
+ .hesap-counters .counters-tag{pointer-events:none}
209
+ .hesap-counters .counters-tag-box{fill:var(--paper);stroke:var(--ink);stroke-width:1.5}
210
+ .hesap-counters .counters-tag-text{font-size:12px;font-weight:700}
211
+ .hesap-counters .counters-pale .counters-body{fill:var(--panel);stroke:var(--rule)}
212
+ .hesap-counters .counters-pale .counters-ring{display:none}
213
+ .hesap-counters .counters-marked .counters-body{stroke:var(--accent);stroke-width:3.5}
214
+ .hesap-counters .counters-gap{fill:none;stroke:var(--rule);stroke-width:2;stroke-dasharray:4 3;opacity:0;pointer-events:none;outline:none}
215
+ .hesap-counters .counters-gap-on{opacity:1;pointer-events:all;cursor:pointer}
216
+ .hesap-counters .counters-gap-on:focus-visible{stroke:var(--accent);stroke-width:3}
217
+ .hesap-counters g.counters-counter[role=button]{cursor:pointer;outline:none}
218
+ .hesap-counters g.counters-counter[role=button]:focus-visible .counters-hit{stroke:var(--accent);stroke-width:2.5}
219
+
220
+ /* The closed box, the room beside it, and the basket. */
221
+ .hesap-counters .counters-box{fill:#c99a62;stroke:#8a6238;stroke-width:2.5}
222
+ .hesap-counters .counters-lid{fill:#b5844e;stroke:#8a6238;stroke-width:2.5}
223
+ .hesap-counters .counters-tape{stroke:#e8d3a6;stroke-width:8}
224
+ .hesap-counters .counters-box-num{font-size:34px;font-weight:700;fill:#2b1d0e}
225
+ .hesap-counters .counters-box.counters-hot{stroke:var(--accent);stroke-width:4}
226
+ .hesap-counters .counters-beside{fill:none;stroke:var(--rule);stroke-width:2;stroke-dasharray:6 5}
227
+ .hesap-counters .counters-basket{fill:#c99a62;stroke:#8a6238;stroke-width:2.5}
228
+ .hesap-counters .counters-weave{stroke:#8a6238;stroke-width:1.5;opacity:.6}
229
+ .hesap-counters .counters-rim{fill:#b5844e;stroke:#8a6238;stroke-width:2}
230
+
231
+ /* The bus and its stop, and the staircase. */
232
+ .hesap-counters .counters-bus{fill:#d1453b;stroke:var(--ink);stroke-width:2.5}
233
+ .hesap-counters .counters-window,.hesap-counters .counters-glass-front{fill:#dfeaf5;stroke:var(--ink);stroke-width:1.5}
234
+ .hesap-counters .counters-door{fill:#9fb7cc;stroke:var(--ink);stroke-width:1.5}
235
+ .hesap-counters .counters-wheel{fill:var(--ink);stroke:var(--ink-2);stroke-width:5}
236
+ .hesap-counters .counters-stop{fill:#2e9d5b}
237
+ .hesap-counters .counters-stop-word{fill:#fff;font-size:12px;font-weight:700}
238
+ .hesap-counters .counters-kerb{stroke:var(--ink-2);stroke-width:3}
239
+ .hesap-counters .counters-stairs{fill:var(--panel);stroke:var(--ink-2);stroke-width:2;stroke-linejoin:round}
240
+ .hesap-counters .counters-step-num{font-size:11px;font-weight:600;fill:var(--ink-2)}
@@ -131,7 +131,7 @@ export default function bonds({ host, stage, panel, T, lang, moving, motion: fx
131
131
 
132
132
  // wire lets the reader tap the pins, the spaces of the car park, the tray, the pile and the cup.
133
133
  function wire() {
134
- for (const p of geo.refs.pins?.pins ?? []) press(p.g, () => tapCell(Number(p.g.dataset.cell)));
134
+ if (!spec.roll) for (const p of geo.refs.pins?.pins ?? []) press(p.g, () => tapCell(Number(p.g.dataset.cell)));
135
135
  for (const sp of geo.refs.park?.spaces ?? []) press(sp, () => parkIn(Number(sp.dataset.cell)));
136
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
137
  const cup = geo.refs.diagram?.cup;
@@ -196,7 +196,7 @@ export default function bonds({ host, stage, panel, T, lang, moving, motion: fx
196
196
  const c = spec.challenge;
197
197
  const homes = c?.goal === 'hidden-part' ? ['tray', 'pile'] : !c && mode() === 'parts' ? ['left', 'right'] : spec.look === 'cars' ? ['cells', 'gate'] : null;
198
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;
199
+ if (!homes || !from() || spec.still) return n;
200
200
  n.g.setAttribute('tabindex', 0); n.g.setAttribute('role', 'button'); n.g.setAttribute('aria-label', T(spec.look === 'cars' ? 'car' : 'counter'));
201
201
  n.g.classList.add('counters-moves');
202
202
  let dx = 0, dy = 0;
@@ -245,6 +245,15 @@ export default function bonds({ host, stage, panel, T, lang, moving, motion: fx
245
245
  function lower() { if (spec.challenge?.goal === 'hidden-part' && cs.lifted) { cs.lifted = false; liftWords(); } }
246
246
 
247
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
+ // roll knocks down a random number of the pins still standing, at least one, and setUp stands every pin again.
249
+ function roll() {
250
+ const up = s.cells.flatMap((id, i) => id ? [i] : []);
251
+ if (!up.length) return;
252
+ const d = dice(fresh());
253
+ for (const i of d.some(up, d.int(1, up.length))) s.cells[i] = null;
254
+ changed();
255
+ }
256
+ function setUp() { s.cells = s.cells.map(id => id ?? newId('a')); changed(); }
248
257
  function tapCell(i) {
249
258
  if (spec.look === 'pins') { s.cells[i] = s.cells[i] ? null : newId('a'); return changed(); }
250
259
  const colour = spec.tap === 'second' ? 'b' : 'a', id = s.cells[i];
@@ -362,6 +371,7 @@ export default function bonds({ host, stage, panel, T, lang, moving, motion: fx
362
371
  if (spec.swap) ctls.push(button({ label: T('swap'), act: 'swap', press: () => { [s.left, s.right] = [s.right, s.left]; changed(); } }));
363
372
  if (spec.fill) ctls.push(fillBtn = button({ label: T(s.extra ? 'unfill' : 'fill'), act: 'fill', press: fill }));
364
373
  if (spec.cup) ctls.push(liftBtn = button({ label: T(s.lifted ? 'lower' : 'lift'), act: 'lift', press: lift }));
374
+ if (spec.roll) ctls.push(button({ label: T('roll'), act: 'roll', primary: true, press: roll }), button({ label: T('set-up'), act: 'set-up', press: setUp }));
365
375
  chips = spec.readout.map(id => chip({ id, label: label(id) }));
366
376
  for (const k of chips) k.width(2);
367
377
  }
@@ -94,3 +94,57 @@
94
94
  /* The figure ends above the peek card, which covers the foot of the stage until the reader closes it. */
95
95
  .hesap-counters .counters-svg{height:calc(100% - var(--hesap-peek,0px))}
96
96
  }
97
+
98
+ /* The count scene: the places objects lie in, the objects, and the numbers the reader gives them. */
99
+ .hesap-counters .counters-sand{fill:#e8d3a6;stroke:#c9ad78;stroke-width:2}
100
+ .hesap-counters .counters-table{fill:#b98a5a;stroke:#8a6238;stroke-width:2}
101
+ .hesap-counters .counters-awning-0{fill:#d1453b}
102
+ .hesap-counters .counters-awning-1{fill:#f4ede1}
103
+ .hesap-counters .counters-wire{fill:none;stroke:var(--ink);stroke-width:2.5}
104
+ .hesap-counters .counters-pole{stroke:var(--ink-2);stroke-width:6;stroke-linecap:round}
105
+ .hesap-counters .counters-row-label{font-size:16px;font-weight:700;fill:var(--ink-2)}
106
+ .hesap-counters .counters-stem{fill:none;stroke:#6b4a2b;stroke-width:2.5;stroke-linecap:round}
107
+ .hesap-counters .counters-leaf{fill:#3f9a4a}
108
+ .hesap-counters .counters-apple .counters-shine{fill:#fff;opacity:.45}
109
+ .hesap-counters .counters-bird .counters-body{fill:var(--ink-2)}
110
+ .hesap-counters .counters-eye{fill:var(--paper)}
111
+ .hesap-counters .counters-feet{stroke:#d99a1f;stroke-width:2}
112
+ .hesap-counters .counters-trail{fill:none;stroke:var(--accent);stroke-width:3;stroke-dasharray:7 6;stroke-linecap:round;stroke-linejoin:round;opacity:.8}
113
+ .hesap-counters .counters-shell .counters-body{fill:#f2a679;stroke:#c46a3c}
114
+ .hesap-counters .counters-ribs{stroke:#c46a3c;stroke-width:1.5;fill:none}
115
+ .hesap-counters .counters-skin{fill:#e0ac7e;stroke:var(--paper);stroke-width:1.5}
116
+ .hesap-counters .counters-legs{stroke:var(--ink);stroke-width:5;stroke-linecap:round}
117
+ .hesap-counters .counters-walker .counters-body{fill:var(--accent)}
118
+ .hesap-counters .counters-tag{pointer-events:none}
119
+ .hesap-counters .counters-tag-box{fill:var(--paper);stroke:var(--ink);stroke-width:1.5}
120
+ .hesap-counters .counters-tag-text{font-size:12px;font-weight:700}
121
+ .hesap-counters .counters-pale .counters-body{fill:var(--panel);stroke:var(--rule)}
122
+ .hesap-counters .counters-pale .counters-ring{display:none}
123
+ .hesap-counters .counters-marked .counters-body{stroke:var(--accent);stroke-width:3.5}
124
+ .hesap-counters .counters-gap{fill:none;stroke:var(--rule);stroke-width:2;stroke-dasharray:4 3;opacity:0;pointer-events:none;outline:none}
125
+ .hesap-counters .counters-gap-on{opacity:1;pointer-events:all;cursor:pointer}
126
+ .hesap-counters .counters-gap-on:focus-visible{stroke:var(--accent);stroke-width:3}
127
+ .hesap-counters g.counters-counter[role=button]{cursor:pointer;outline:none}
128
+ .hesap-counters g.counters-counter[role=button]:focus-visible .counters-hit{stroke:var(--accent);stroke-width:2.5}
129
+
130
+ /* The closed box, the room beside it, and the basket. */
131
+ .hesap-counters .counters-box{fill:#c99a62;stroke:#8a6238;stroke-width:2.5}
132
+ .hesap-counters .counters-lid{fill:#b5844e;stroke:#8a6238;stroke-width:2.5}
133
+ .hesap-counters .counters-tape{stroke:#e8d3a6;stroke-width:8}
134
+ .hesap-counters .counters-box-num{font-size:34px;font-weight:700;fill:#2b1d0e}
135
+ .hesap-counters .counters-box.counters-hot{stroke:var(--accent);stroke-width:4}
136
+ .hesap-counters .counters-beside{fill:none;stroke:var(--rule);stroke-width:2;stroke-dasharray:6 5}
137
+ .hesap-counters .counters-basket{fill:#c99a62;stroke:#8a6238;stroke-width:2.5}
138
+ .hesap-counters .counters-weave{stroke:#8a6238;stroke-width:1.5;opacity:.6}
139
+ .hesap-counters .counters-rim{fill:#b5844e;stroke:#8a6238;stroke-width:2}
140
+
141
+ /* The bus and its stop, and the staircase. */
142
+ .hesap-counters .counters-bus{fill:#d1453b;stroke:var(--ink);stroke-width:2.5}
143
+ .hesap-counters .counters-window,.hesap-counters .counters-glass-front{fill:#dfeaf5;stroke:var(--ink);stroke-width:1.5}
144
+ .hesap-counters .counters-door{fill:#9fb7cc;stroke:var(--ink);stroke-width:1.5}
145
+ .hesap-counters .counters-wheel{fill:var(--ink);stroke:var(--ink-2);stroke-width:5}
146
+ .hesap-counters .counters-stop{fill:#2e9d5b}
147
+ .hesap-counters .counters-stop-word{fill:#fff;font-size:12px;font-weight:700}
148
+ .hesap-counters .counters-kerb{stroke:var(--ink-2);stroke-width:3}
149
+ .hesap-counters .counters-stairs{fill:var(--panel);stroke:var(--ink-2);stroke-width:2;stroke-linejoin:round}
150
+ .hesap-counters .counters-step-num{font-size:11px;font-weight:600;fill:var(--ink-2)}
@@ -1,8 +1,9 @@
1
1
  // The browser half of the counters family. It hands each page to the scene the page names. The scenes share the
2
2
  // family's counters, ten frames, places and motion.
3
3
  import bonds from './bonds.js';
4
+ import count from './count.js';
4
5
 
5
- const SCENES = { bonds };
6
+ const SCENES = { bonds, count };
6
7
 
7
8
  export default function counters(api) {
8
9
  // made holds each scene once it has been made, and now is the scene on show.
@@ -0,0 +1,166 @@
1
+ // The blocks a count figure is built from: the place the objects lie in, rows of ten, a closed box with room beside
2
+ // it, a pile, a basket, a bus with its stop and a staircase. A block offers one or more ways to be set out, each with
3
+ // its size and a draw that puts it at a corner. draw gives the block's nodes, its places for objects and the parts
4
+ // the scene updates.
5
+ import { svg as el } from '../../kit/dom.js';
6
+ import { generator, hash } from '../../kit/random.js';
7
+ import { R } from './counter.js';
8
+ import { txt } from './figures.js';
9
+ import { SEATS, STOP, STEPS } from './count-model.js';
10
+
11
+ const CELL = 60; // A loose object has a cell this wide of its own, and lies somewhere inside it.
12
+ export const ROW = 36; // Counters in rows of ten stand this far apart.
13
+ const FIVE = 8; // The extra gap after the fifth counter of a row.
14
+ const PAD = 18; // The edge of a tray or a table round its objects.
15
+ const near = (b, m = 20) => q => q.x > b.x - m && q.x < b.x + b.w + m && q.y > b.y - m && q.y < b.y + b.h + m;
16
+
17
+ // scatter lays n objects loose. Each takes a cell of a grid with cells to spare and lies off the cell's middle, and
18
+ // the same seed always lays them the same way.
19
+ function scatter(n, seed) {
20
+ const cols = Math.max(3, Math.ceil(Math.sqrt(n * 1.8))), rows = Math.max(2, Math.ceil(n * 1.25 / cols));
21
+ const rnd = generator(hash(seed)), cells = [...Array(cols * rows).keys()];
22
+ for (let i = cells.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [cells[i], cells[j]] = [cells[j], cells[i]]; }
23
+ const spots = cells.slice(0, n).sort((a, b) => a - b).map(c => ({ x: (c % cols + 0.5) * CELL + (rnd() - 0.5) * 16, y: (Math.floor(c / cols) + 0.5) * CELL + (rnd() - 0.5) * 16 }));
24
+ return { w: cols * CELL, h: rows * CELL, spots };
25
+ }
26
+
27
+ // place is the tray, the stall or the sand with n objects lying loose, or the wire with n in a row.
28
+ export function place(look, n) {
29
+ if (look === 'wire') return line(look, n);
30
+ const s = scatter(n, `${look}-${n}`), top = look === 'stall' ? 56 : 0, w = s.w + 2 * PAD, h = top + s.h + 2 * PAD;
31
+ return [{ w, h, draw(x, y) {
32
+ const box = { x: x + PAD, y: y + top + PAD, w: s.w, h: s.h }, spots = s.spots.map(p => ({ x: box.x + p.x, y: box.y + p.y }));
33
+ const nodes = look === 'stall' ? [...awning(x, y, w, top), el('rect', { class: 'counters-table', x, y: y + top, width: w, height: h - top, rx: 6 })]
34
+ : [el('rect', { class: `counters-${look}`, x, y, width: w, height: h, rx: look === 'sand' ? 36 : 14 })];
35
+ return { nodes, places: { slots: { pos: i => spots[i], all: spots, box } } };
36
+ } }];
37
+ }
38
+
39
+ // The striped awning over a market stall, with a scalloped edge.
40
+ function awning(x, y, w, h) {
41
+ const k = 8, sw = w / k, out = [];
42
+ for (let i = 0; i < k; i++) {
43
+ const sx = x + i * sw;
44
+ out.push(el('path', { class: `counters-awning counters-awning-${i % 2}`, d: `M ${sx} ${y} H ${sx + sw} V ${y + h - 16} A ${sw / 2} 10 0 0 1 ${sx} ${y + h - 16} Z` }));
45
+ }
46
+ return out;
47
+ }
48
+
49
+ // line is a wire between two poles with birds on it.
50
+ function line(look, n) {
51
+ const gap = 54, w = n * gap + 2 * PAD + 24, h = 120;
52
+ return [{ w, h, draw(x, y) {
53
+ const l = x + 12, r = x + w - 12, spots = [];
54
+ const nodes = [];
55
+ nodes.push(el('line', { class: 'counters-pole', x1: l, y1: y + 30, x2: l, y2: y + h }), el('line', { class: 'counters-pole', x1: r, y1: y + 30, x2: r, y2: y + h }),
56
+ el('path', { class: 'counters-wire', d: `M ${l} ${y + 48} Q ${(l + r) / 2} ${y + 76} ${r} ${y + 48}` }));
57
+ for (let i = 0; i < n; i++) { const bx = l + PAD + (i + 0.5) * gap, t = (bx - l) / (r - l); spots.push({ x: bx, y: y + 48 + 28 * t * (1 - t) - R * 0.85 }); }
58
+ return { nodes, places: { slots: { pos: i => spots[i], all: spots } } };
59
+ } }];
60
+ }
61
+
62
+ // rows stands n counters in rows of ten, with a gap after the fifth of each row and the count of each full row at
63
+ // its end.
64
+ export function rows(n) {
65
+ const lines = Math.ceil(n / 10), inner = 10 * ROW + FIVE, w = inner + 62, h = lines * ROW + 16;
66
+ return [{ w, h, draw(x, y) {
67
+ const ox = x + 8, oy = y + 8, spots = Array.from({ length: n }, (_, i) => ({ x: ox + (i % 10 + 0.5) * ROW + (i % 10 >= 5 ? FIVE : 0), y: oy + (Math.floor(i / 10) + 0.5) * ROW }));
68
+ const labels = [];
69
+ for (let k = 1; k <= lines; k++) if (n >= 10 * k) labels.push({ t: txt('counters-row-label', ox + inner + 32, oy + (k - 0.5) * ROW), n: 10 * k });
70
+ const nodes = [el('rect', { class: 'counters-tray', x, y, width: inner + 16, height: h, rx: 10 }), ...labels.map(l => l.t)];
71
+ return { nodes, places: { slots: { pos: i => spots[i], all: spots } }, refs: { labels } };
72
+ } }];
73
+ }
74
+
75
+ // boxRow is a closed box with its number on the front, and room beside it for cap counters in rows of six.
76
+ export function boxRow(cap) {
77
+ const bw = 96, bh = 84, cols = Math.min(6, cap), lines = Math.ceil(cap / 6), g = 42, sw = cols * g, sh = lines * g;
78
+ const ways = [{ w: bw + 28 + sw + 12, h: Math.max(bh + 18, sh + 12), side: true }, { w: Math.max(bw, sw + 12), h: bh + 18 + 28 + sh + 12, side: false }];
79
+ return ways.map(way => ({ w: way.w, h: way.h, draw(x, y) {
80
+ const bx = way.side ? x : x + (way.w - bw) / 2, by = way.side ? y + (way.h - bh - 18) / 2 + 18 : y + 18;
81
+ const sx = way.side ? x + bw + 28 + 6 : x + (way.w - sw) / 2, sy = way.side ? y + (way.h - sh) / 2 : by + bh + 28 + 6;
82
+ const strip = { x: sx - 6, y: sy - 6, w: sw + 12, h: sh + 12 };
83
+ const num = txt('counters-box-num', bx + bw / 2, by + bh / 2 + 6);
84
+ const nodes = [el('rect', { class: 'counters-box', x: bx, y: by, width: bw, height: bh, rx: 4, 'data-ref': 'box' }),
85
+ el('path', { class: 'counters-lid', d: `M ${bx - 6} ${by} L ${bx + 8} ${by - 16} L ${bx + bw - 8} ${by - 16} L ${bx + bw + 6} ${by} Z` }),
86
+ el('line', { class: 'counters-tape', x1: bx + bw / 2, y1: by - 16, x2: bx + bw / 2, y2: by + 12 }), num,
87
+ el('rect', { class: 'counters-beside', x: strip.x, y: strip.y, width: strip.w, height: strip.h, rx: 10 })];
88
+ const spots = Array.from({ length: cap }, (_, i) => ({ x: sx + (i % cols + 0.5) * g, y: sy + (Math.floor(i / cols) + 0.5) * g }));
89
+ const beside = { pos: i => spots[i], all: spots, hit: near(strip) };
90
+ return { nodes, places: { beside, slots: beside }, refs: { num } };
91
+ } }));
92
+ }
93
+
94
+ // pile heaps up n objects, widest at the bottom. A tap anywhere on it takes the top one.
95
+ export function pile(n, label) {
96
+ let wide = 1;
97
+ while (wide * (wide + 1) / 2 < n) wide++;
98
+ const counts = [];
99
+ for (let k = wide, left = n; left > 0; k--) { counts.push(Math.min(k, left)); left -= k; }
100
+ const gx = ROW * 0.92, gy = ROW * 0.72, w = wide * gx + 2 * R + 8, h = 24 + (counts.length - 1) * gy + 2 * R + 14;
101
+ return [{ w, h, draw(x, y) {
102
+ const base = { x: x + w / 2, y: y + h - R - 8 }, spots = [];
103
+ counts.forEach((c, row) => { for (let j = 0; j < c; j++) spots.push({ x: base.x + (j - (c - 1) / 2) * gx, y: base.y - row * gy }); });
104
+ const area = { x, y: y + 24, w, h: h - 24 };
105
+ const press = el('rect', { class: 'counters-press', x: area.x, y: area.y, width: area.w, height: area.h, tabindex: 0, role: 'button', 'data-place': 'pile', 'aria-label': label });
106
+ const nodes = [txt('counters-tray-label', x + w / 2, y + 8, label), el('ellipse', { class: 'counters-heap-floor', cx: base.x, cy: base.y + R + 2, rx: w / 2, ry: 7 }), press];
107
+ return { nodes, places: { pile: { pos: i => spots[i], hit: near(area) } }, refs: { press: [press] } };
108
+ } }];
109
+ }
110
+
111
+ // basket holds up to cap apples in rows of six.
112
+ export function basket(cap, label) {
113
+ const cols = 6, g = 36, lines = Math.ceil(cap / cols), w = cols * g + 32, h = 24 + lines * g + 30;
114
+ return [{ w, h, draw(x, y) {
115
+ const top = y + 24, area = { x, y: top, w, h: h - 24 };
116
+ const body = el('path', { class: 'counters-basket', d: `M ${x} ${top + 10} H ${x + w} L ${x + w - 12} ${y + h} H ${x + 12} Z` });
117
+ const weave = [];
118
+ for (let k = 1; k < 4; k++) weave.push(el('line', { class: 'counters-weave', x1: x + 3 * k, y1: top + 10 + k * (h - 34) / 4, x2: x + w - 3 * k, y2: top + 10 + k * (h - 34) / 4 }));
119
+ const press = el('rect', { class: 'counters-press', x: area.x, y: area.y, width: area.w, height: area.h, tabindex: 0, role: 'button', 'data-place': 'basket', 'aria-label': label });
120
+ const spots = Array.from({ length: cap }, (_, i) => ({ x: x + 16 + (i % cols + 0.5) * g, y: top + 18 + (Math.floor(i / cols) + 0.5) * g }));
121
+ const nodes = [txt('counters-tray-label', x + w / 2, y + 8, label), body, ...weave, el('rect', { class: 'counters-rim', x: x - 4, y: top + 4, width: w + 8, height: 12, rx: 6 }), press];
122
+ return { nodes, places: { basket: { pos: i => spots[i], hit: near(area) } }, refs: { press: [press] } };
123
+ } }];
124
+ }
125
+
126
+ // bus is a bus with two decks of six seats, beside a stop where people wait in two rows of five.
127
+ export function bus(sign) {
128
+ const win = 46, bw = 6 * win + 74, bh = 2 * 54 + 46, qw = 5 * 36 + 44, qh = 2 * 50 + 70;
129
+ const ways = [{ w: qw + 28 + bw, h: Math.max(bh, qh) + 4, side: true }, { w: Math.max(bw, qw), h: qh + 28 + bh + 4, side: false }];
130
+ return ways.map(way => ({ w: way.w, h: way.h, draw(x, y) {
131
+ const sx = x, sy = way.side ? y + way.h - qh - 4 : y, bx = way.side ? x + qw + 28 : x + (way.w - bw) / 2, by = way.side ? y + way.h - bh - 4 : y + qh + 28;
132
+ const seats = [], queue = [], nodes = [];
133
+ nodes.push(el('rect', { class: 'counters-bus', x: bx, y: by, width: bw, height: bh - 18, rx: 14 }),
134
+ el('rect', { class: 'counters-glass-front', x: bx + bw - 30, y: by + 14, width: 22, height: 54, rx: 5 }),
135
+ el('rect', { class: 'counters-door', x: bx + bw - 30, y: by + 76, width: 22, height: bh - 18 - 84, rx: 3 }));
136
+ for (let deck = 0; deck < 2; deck++) for (let k = 0; k < 6; k++) {
137
+ const wx = bx + 14 + k * win, wy = by + 12 + (1 - deck) * 58;
138
+ nodes.push(el('rect', { class: 'counters-window', x: wx, y: wy, width: win - 6, height: 44, rx: 6 }));
139
+ seats[deck * 6 + k] = { x: wx + (win - 6) / 2, y: wy + 26 };
140
+ }
141
+ for (const wx of [bx + 60, bx + bw - 60]) nodes.push(el('circle', { class: 'counters-wheel', cx: wx, cy: by + bh - 18, r: 18 }));
142
+ const post = sx + 14, word = txt('counters-stop-word', post, sy + 16, sign);
143
+ nodes.push(el('line', { class: 'counters-pole', x1: post, y1: sy + 6, x2: post, y2: sy + qh }), el('rect', { class: 'counters-stop', x: post - 18, y: sy, width: 36, height: 30, rx: 6 }), word,
144
+ el('line', { class: 'counters-kerb', x1: sx, y1: sy + qh, x2: sx + qw, y2: sy + qh }));
145
+ for (let i = 0; i < STOP; i++) queue.push({ x: sx + 44 + (i % 5 + 0.5) * 36, y: sy + 46 + Math.floor(i / 5) * 50 + 22 });
146
+ return { nodes, places: { seats: { pos: i => seats[i], all: seats.slice(0, SEATS) }, stop: { pos: i => queue[i] } }, refs: {} };
147
+ } }));
148
+ }
149
+
150
+ // stairs is a staircase of STEPS steps that climbs to the right, with each step's number on its front. A narrow
151
+ // stage takes the steep way, so a phone shows the numbers large enough to read.
152
+ export function stairs() {
153
+ return [[21, 15], [15, 19]].map(([tread, rise]) => ({ w: (STEPS + 2) * tread, h: STEPS * rise + 72, draw(x, y) {
154
+ const w = (STEPS + 2) * tread, h = STEPS * rise + 72;
155
+ const x0 = x, y0 = y + h - 6, pts = [`${x0},${y0}`];
156
+ for (let k = 1; k <= STEPS; k++) pts.push(`${x0 + k * tread},${y0 - (k - 1) * rise}`, `${x0 + k * tread},${y0 - k * rise}`);
157
+ pts.push(`${x0 + (STEPS + 2) * tread},${y0 - STEPS * rise}`, `${x0 + (STEPS + 2) * tread},${y0}`);
158
+ const labels = [];
159
+ for (let k = 1; k <= STEPS; k++) labels.push({ t: txt('counters-step-num', x0 + (k + 0.5) * tread, y0 - k * rise + 8), n: k });
160
+ const nodes = [el('polygon', { class: 'counters-stairs', points: pts.join(' ') }), el('line', { class: 'counters-kerb', x1: x0, y1: y0, x2: x0 + w, y2: y0 }), ...labels.map(l => l.t)];
161
+ const spot = k => ({ x: x0 + (k + 0.5) * tread, y: y0 - k * rise });
162
+ // at gives the step under a point, so the walker follows a drag one step at a time.
163
+ const at = q => Math.max(0, Math.min(STEPS, Math.round((q.x - x0) / tread - 0.5)));
164
+ return { nodes, places: { steps: { pos: spot, at } }, refs: { labels } };
165
+ } }));
166
+ }
@@ -0,0 +1,57 @@
1
+ // The goals a count page can name. The page declares ranges, and the goal draws a target from them each time the
2
+ // page opens and each time the reader asks for another one. Each goal holds once the reader presses Check on the
3
+ // right number. The build and the browser both use this file.
4
+
5
+ export const APPLES = 35; // The apples in the pile beside the basket.
6
+ export const LOOSE = 12; // The counters in the pile beside the box.
7
+ const span = (lo, hi) => Array.from({ length: Math.max(0, hi - lo + 1) }, (_, i) => lo + i);
8
+ const range = (r, lo, hi) => Array.isArray(r) && r.length === 2 && r.every(Number.isInteger) && r[0] <= r[1] && r[0] >= lo && r[1] <= hi;
9
+ const words = r => JSON.stringify(r ?? null);
10
+ // off judges a checked number against the target and says in which direction a wrong one is off.
11
+ const off = (n, want) => n === want ? { done: true } : { done: false, note: n > want ? 'more' : 'fewer' };
12
+
13
+ export const COUNT_GOALS = {
14
+ // The reader moves apples from a pile into the basket.
15
+ 'fill-basket': {
16
+ scenes: ['count'],
17
+ problem(c) {
18
+ return range(c.target, 1, APPLES) ? null : `target is ${words(c.target)}, write the apples to put in as [low, high] from 1 to ${APPLES}, such as [6, 30]`;
19
+ },
20
+ draw: (c, spec, dice) => ({ target: dice.int(c.target[0], c.target[1]) }),
21
+ holds: (state, spec, c, t) => state.checked ? off(state.basket, t.target) : { done: false },
22
+ words: (c, t, f) => ({ target: f.int(t.target) }),
23
+ },
24
+ // A closed box holds a number, and the reader puts counters beside it until box and counters make the target.
25
+ 'count-on': {
26
+ scenes: ['count'],
27
+ problem(c) {
28
+ if (!range(c.box, 1, 90)) return `box is ${words(c.box)}, write the number in the box as [low, high] from 1 to 90, such as [10, 60]`;
29
+ if (!range(c.more, 1, LOOSE)) return `more is ${words(c.more)}, write how far the target lies past the box as [low, high] from 1 to ${LOOSE}, such as [3, 9]`;
30
+ return null;
31
+ },
32
+ draw(c, spec, dice) { const box = dice.int(c.box[0], c.box[1]); return { box, target: box + dice.int(c.more[0], c.more[1]) }; },
33
+ holds: (state, spec, c, t) => state.checked ? off(t.box + state.beside, t.target) : { done: false },
34
+ words: (c, t, f) => ({ box: f.int(t.box), target: f.int(t.target) }),
35
+ },
36
+ // Counters stand in rows of ten, and the reader takes them away until the target is left. The target lies in a
37
+ // lower ten than the start, so counting back crosses a ten.
38
+ 'count-back': {
39
+ scenes: ['count'],
40
+ problem(c) {
41
+ if (!range(c.start, 2, 100)) return `start is ${words(c.start)}, write the counters as the page opens as [low, high] from 2 to 100, such as [25, 100]`;
42
+ if (!range(c.less, 1, 99)) return `less is ${words(c.less)}, write how many to take away as [low, high], such as [3, 12]`;
43
+ return null;
44
+ },
45
+ draw(c, spec, dice) {
46
+ const pairs = span(c.start[0], c.start[1]).flatMap(start => span(c.less[0], c.less[1]).map(d => ({ start, target: start - d })))
47
+ .filter(p => p.target >= 0 && Math.floor(p.target / 10) < Math.floor((p.start - 1) / 10));
48
+ return pairs.length ? dice.pick(pairs) : null;
49
+ },
50
+ holds: (state, spec, c, t) => state.checked ? off(state.left, t.target) : { done: false },
51
+ words: (c, t, f) => ({ start: f.int(t.start), target: f.int(t.target) }),
52
+ },
53
+ };
54
+
55
+ // The reader's state as a challenge opens: nothing checked, an empty basket, nothing beside the box and every counter
56
+ // of the rows in place.
57
+ export const countStart = (spec, t) => ({ checked: false, basket: 0, beside: 0, left: t?.start ?? 0 });
@@ -0,0 +1,57 @@
1
+ // What a count page holds and what it counts. The build and the browser both use this file, so a page's text and
2
+ // its live values agree.
3
+
4
+ // A page sets its objects out in one of these looks. bus and stairs are the world pages.
5
+ export const COUNT_LOOKS = ['tray', 'stall', 'wire', 'sand', 'bus', 'stairs'];
6
+ // What a tap on an object does: give it the next number, give it one more number even when it has one, show its own
7
+ // number in the rows, or take it out of the tray.
8
+ export const TAPS = ['tag', 'again', 'place', 'take'];
9
+ // The objects each look holds when they lie loose or stand in a row. Rows of ten hold up to 100.
10
+ export const ROOM = { tray: 20, stall: 20, sand: 20, wire: 12 };
11
+ export const SEATS = 12; // The seats of the bus, on two decks.
12
+ export const STOP = 10; // The people a bus stop holds.
13
+ export const STEPS = 20; // The steps of the staircase.
14
+
15
+ // modeOf names what a page does: a world page, a marker in the rows, a pile beside a box, or the page's tap.
16
+ export function modeOf(spec) {
17
+ if (spec.look === 'bus' || spec.look === 'stairs') return spec.look;
18
+ if (spec.marker != null) return 'marker';
19
+ if (spec.pile != null) return 'pile';
20
+ return spec.tap;
21
+ }
22
+
23
+ // The objects a page sets out as it opens: the page's number, or a hundred in rows of ten.
24
+ export const sizeOf = spec => spec.n ?? (spec.rows ? 100 : 0);
25
+
26
+ // opening gives the counts as the page opens. tags holds the numbers on each object, here says which objects are
27
+ // in the tray, and beside counts the counters next to the box. A counted page opens with every object numbered.
28
+ export function opening(spec) {
29
+ const n = sizeOf(spec), tags = Array.from({ length: n }, (_, i) => spec.counted ? [i + 1] : []);
30
+ return { tags, here: Array(n).fill(true), said: spec.counted ? n : 0, last: 0, beside: 0,
31
+ box: spec.box ?? 0, marker: spec.marker ?? 0, step: spec.step ?? 0, riders: spec.look === 'bus' ? n : 0 };
32
+ }
33
+
34
+ // counts gives every number a page can show. count is the page's one running number, and total shows how many once
35
+ // every object has exactly one number.
36
+ export function counts(spec, s) {
37
+ const mode = modeOf(spec);
38
+ if (mode === 'tag' || mode === 'again') {
39
+ const count = s.box + s.said;
40
+ return { count, total: s.tags.length && s.tags.every(t => t.length === 1) ? count : null };
41
+ }
42
+ const count = { place: s.last, take: s.here.filter(Boolean).length, marker: s.marker, pile: s.box + s.beside, bus: s.riders, stairs: s.step }[mode];
43
+ return { count };
44
+ }
45
+
46
+ // The context of a page picks the words of its readouts, such as "Passengers" on the bus.
47
+ export function contextOf(spec) {
48
+ const mode = modeOf(spec);
49
+ return mode === 'again' || mode === 'pile' ? 'tag' : mode;
50
+ }
51
+
52
+ // The measures a page can read out and link in its text.
53
+ export function measuresOf(spec) {
54
+ if (spec.challenge) return [];
55
+ const mode = modeOf(spec);
56
+ return mode === 'tag' || mode === 'again' ? ['count', 'total'] : ['count'];
57
+ }
@@ -0,0 +1,322 @@
1
+ // The count scene: objects counted one by one. The reader taps an object to give it the next number, counts on from
2
+ // a closed box, takes counters out of a tray, steps a marker through rows of ten, fills a bus and climbs a staircase.
3
+ import { modeOf, sizeOf, counts, contextOf, measuresOf, SEATS, STEPS } from './count-model.js';
4
+ import { COUNT_GOALS, APPLES, LOOSE, countStart } from './count-goals.js';
5
+ import { another } from './goals.js';
6
+ import { counter, show, put, R } from './counter.js';
7
+ import { arrange } from './places.js';
8
+ import { place, rows, boxRow, pile, basket, bus, stairs } from './count-figures.js';
9
+ import { carry, press } from './move.js';
10
+ import { driver } from './driver.js';
11
+ import { svg as el, svgPoint } from '../../kit/dom.js';
12
+ import { nudge } from '../../kit/drag.js';
13
+ import { 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
+ // The object each look counts, and the colour it takes.
22
+ const KIND = { tray: 'disc', stall: 'apple', wire: 'bird', sand: 'shell', bus: 'person', stairs: 'walker' };
23
+ const COLOUR = { apple: 'a' };
24
+ const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
25
+
26
+ export default function count({ host, stage, panel, T, lang, moving, motion: fx }) {
27
+ const go = driver(fx);
28
+ const back = el('g'), trail = el('polyline', { class: 'counters-trail' }), layer = el('g', { class: 'counters-layer' });
29
+ const svg = el('svg', { class: 'counters-svg' }, [back, trail, layer]);
30
+ stage.appendChild(svg);
31
+ // spec is the page. s holds its objects: the ids of the fixed places and whether each object is there, the ids of
32
+ // each list, the seats of the bus, the numbers on each object and where the reader dragged one. geo holds the places
33
+ // of the figure as drawn, nodes the drawn object of each id and gaps the empty place of each fixed place. target
34
+ // is a challenge's draw, and cs the reader's answer to it.
35
+ let spec = null, s = null, geo = null, area = { w: 0, h: 0 }, nodes = new Map(), gaps = [], seq = 0, hold = null;
36
+ let goal = null, chips = [], target = null, cs = null;
37
+
38
+ const int = n => numbers(lang()).int(n);
39
+ const label = id => T(`${contextOf(spec)}-${id}`) ?? T(id);
40
+ const modeNow = () => spec.challenge?.goal ?? modeOf(spec);
41
+ new ResizeObserver(() => { const r = svg.getBoundingClientRect(); if (spec && (Math.round(r.width) !== area.w || Math.round(r.height) !== area.h)) build(); }).observe(svg);
42
+
43
+ // begin sets the objects as the page opens, and draws a new target on a challenge page.
44
+ function begin() {
45
+ seq = 0; hold = null;
46
+ s = { ids: [], here: [], lists: { beside: [], pile: [], basket: [], stop: [] }, seats: Array(SEATS).fill(null), tags: new Map(), free: new Map(),
47
+ said: 0, last: 0, box: spec.box ?? 0, marker: spec.marker ?? 0, step: spec.step ?? 0, whole: false };
48
+ const fill = n => Array.from({ length: n }, () => `o${seq++}`);
49
+ const fixed = n => { s.ids = fill(n); s.here = s.ids.map(() => true); };
50
+ const c = spec.challenge;
51
+ if (c) {
52
+ target = another(COUNT_GOALS[c.goal], c, spec, dice(fresh()), target);
53
+ cs = countStart(spec, target);
54
+ if (c.goal === 'fill-basket') s.lists.pile = fill(APPLES);
55
+ else if (c.goal === 'count-on') { s.box = target.box; s.lists.pile = fill(LOOSE); }
56
+ else fixed(target.start);
57
+ return;
58
+ }
59
+ const mode = modeOf(spec);
60
+ if (mode === 'bus') { fill(spec.n).forEach((id, i) => { s.seats[i] = id; }); s.lists.stop = fill(spec.waiting); }
61
+ else if (mode === 'pile') s.lists.pile = fill(spec.pile);
62
+ else if (mode === 'stairs') s.ids = [];
63
+ else fixed(sizeOf(spec));
64
+ if (spec.counted) { s.ids.forEach((id, i) => s.tags.set(id, [i + 1])); s.said = s.ids.length; s.whole = true; }
65
+ }
66
+
67
+ const kindOf = id => id === 'walker' ? 'walker' : spec.challenge ? (spec.challenge.goal === 'fill-basket' ? 'apple' : 'disc') : KIND[spec.look];
68
+ // homeOf names the list or the seats an object is in, and otherOf the place a tap sends it to.
69
+ const homeOf = id => s.seats.includes(id) ? 'seats' : Object.keys(s.lists).find(k => s.lists[k].includes(id));
70
+ const otherOf = from => ({ pile: spec.challenge?.goal === 'fill-basket' ? 'basket' : 'beside', beside: 'pile', basket: 'pile', stop: 'seats', seats: 'stop' })[from];
71
+
72
+ // measure counts the objects. A challenge shows no counts, so its answer stays hidden.
73
+ function measure() {
74
+ if (spec.challenge) return {};
75
+ return counts(spec, { tags: s.ids.map(id => s.tags.get(id) ?? []), here: s.here, said: s.said, last: s.last, beside: s.lists.beside.length,
76
+ box: s.box, marker: s.marker, step: s.step, riders: s.seats.filter(Boolean).length });
77
+ }
78
+
79
+ // blocksOf lists the blocks of the figure, each with the ways it can be set out.
80
+ function blocksOf() {
81
+ const mode = modeNow();
82
+ if (mode === 'fill-basket') return [basket(APPLES, T('basket')), pile(APPLES, T('pile'))];
83
+ if (mode === 'count-on') return [boxRow(LOOSE), pile(LOOSE, T('pile'))];
84
+ if (mode === 'count-back') return [rows(target.start)];
85
+ if (mode === 'bus') return [bus(T('stop-sign'))];
86
+ if (mode === 'stairs') return [stairs()];
87
+ if (mode === 'pile') return [boxRow(spec.pile), pile(spec.pile, T('pile'))];
88
+ if (spec.box != null) return [boxRow(sizeOf(spec))];
89
+ return [spec.rows ? rows(sizeOf(spec)) : place(spec.look, sizeOf(spec))];
90
+ }
91
+
92
+ // build draws the figure to fit the stage and puts every object in its place.
93
+ function build() {
94
+ const r = svg.getBoundingClientRect(); area = { w: Math.round(r.width), h: Math.round(r.height) };
95
+ if (!area.w || !area.h) { geo = null; return; } // A phone is showing the text, so the figure is drawn when the stage shows.
96
+ const best = arrange(blocksOf(), Math.max(1, area.w - 2 * PAD), Math.max(1, area.h - 2 * PAD)), scale = Math.min(MAX, best.scale);
97
+ const cx = best.w / 2, cy = best.h / 2;
98
+ svg.setAttribute('viewBox', `${cx - area.w / 2 / scale} ${cy - area.h / 2 / scale} ${area.w / scale} ${area.h / scale}`);
99
+ geo = { places: {}, refs: { press: [] } };
100
+ const drawn = [];
101
+ for (const it of best.items) {
102
+ const d = it.v.draw(it.x, it.y), { press: presses = [], ...refs } = d.refs ?? {};
103
+ drawn.push(...d.nodes); Object.assign(geo.places, d.places ?? {}); Object.assign(geo.refs, refs); geo.refs.press.push(...presses);
104
+ }
105
+ gaps = gapsOf();
106
+ back.replaceChildren(...drawn, ...gaps);
107
+ for (const n of nodes.values()) n.tween?.pause();
108
+ layer.replaceChildren(); nodes = new Map();
109
+ for (const p of geo.refs.press) press(p, () => { const from = p.dataset.place, id = s.lists[from].at(-1); if (id) moveTo(id, otherOf(from)); });
110
+ render('jump');
111
+ }
112
+
113
+ // gapsOf gives an empty place for each fixed place on a page where counters leave the tray. A tap on an empty
114
+ // place puts its counter back.
115
+ function gapsOf() {
116
+ if (!['take', 'count-back'].includes(modeNow())) return [];
117
+ return s.ids.map((id, i) => {
118
+ const p = geo.places.slots.pos(i), g = el('circle', { class: 'counters-gap', cx: p.x, cy: p.y, r: R - 2, tabindex: 0, role: 'button', 'aria-label': T('gap') });
119
+ press(g, () => { if (!s.here[i]) { s.here[i] = true; changed(); } });
120
+ return g;
121
+ });
122
+ }
123
+
124
+ // where gives the place of every object on show.
125
+ function where() {
126
+ const out = new Map(), P = geo.places;
127
+ if (P.slots && s.ids.length) s.ids.forEach((id, i) => { if (s.here[i]) out.set(id, freeAt(id) ?? P.slots.pos(i)); });
128
+ for (const name of Object.keys(s.lists)) if (P[name]) s.lists[name].forEach((id, i) => out.set(id, P[name].pos(i)));
129
+ if (P.seats) s.seats.forEach((id, i) => { if (id) out.set(id, P.seats.pos(i)); });
130
+ if (P.steps) out.set('walker', P.steps.pos(s.step));
131
+ return out;
132
+ }
133
+ // A dragged object keeps its place in the tray as a share of the tray's width and height, so it stays put when
134
+ // the figure is drawn again at another size.
135
+ function freeAt(id) {
136
+ const f = s.free.get(id), b = geo.places.slots.box;
137
+ return f && b ? { x: b.x + f.u * b.w, y: b.y + f.v * b.h } : null;
138
+ }
139
+
140
+ // render moves every object to its place. After a change the reader made, objects glide, arrive and leave.
141
+ function render(how) {
142
+ if (!geo) return;
143
+ const to = where(), anim = how === 'move' && moving();
144
+ let k = 0;
145
+ for (const [id, n] of nodes) if (!to.has(id)) {
146
+ nodes.delete(id); n.tween?.pause();
147
+ if (anim) go.vanish(n.pop, () => n.g.remove()); else n.g.remove();
148
+ }
149
+ for (const [id, p] of to) {
150
+ let n = nodes.get(id);
151
+ if (!n) {
152
+ n = make(id); nodes.set(id, n); layer.append(n.g); put(n, p);
153
+ if (anim) go.pop(n.pop, 25 * k++);
154
+ continue;
155
+ }
156
+ if (n === hold || (n.at.x === p.x && n.at.y === p.y)) continue;
157
+ n.tween?.pause();
158
+ if (anim) n.tween = go.tween(n.at, { x: p.x, y: p.y }, () => show(n), id === 'walker' ? 260 : 380); else put(n, p);
159
+ }
160
+ paint(anim); refresh();
161
+ }
162
+
163
+ // make draws an object with room for its numbers, and lets the reader tap it or carry it where the page allows.
164
+ function make(id) {
165
+ const kind = kindOf(id), n = counter(kind, COLOUR[kind] ?? 'b', kind === 'walker' ? 22 : R, Number(id.slice(1)) || 0);
166
+ if (kind !== 'walker') {
167
+ const box = el('rect', { class: 'counters-tag-box', x: -9, y: -9, width: 18, height: 18, rx: 9 }), text = el('text', { class: 'counters-tag-text' });
168
+ n.tagPop = el('g', { class: 'counters-tag-pop' }, [box, text]);
169
+ n.tag = el('g', { class: 'counters-tag', transform: `translate(${R * 0.8} ${-R * 1.15})`, display: 'none' }, [n.tagPop]);
170
+ n.g.append(n.tag);
171
+ }
172
+ const mode = modeNow(), fixed = s.ids.includes(id), home = homeOf(id);
173
+ if (kind === 'walker') return walker(n);
174
+ if (mode === 'marker' || spec.counted || (!fixed && !home)) return n;
175
+ n.g.setAttribute('tabindex', 0); n.g.setAttribute('role', 'button'); n.g.setAttribute('aria-label', T(`kind-${kind}`));
176
+ if (fixed && !spec.drag) { press(n.g, () => tapFixed(id)); return n; }
177
+ if (home === 'seats' || home === 'stop') { press(n.g, () => moveTo(id, otherOf(homeOf(id)))); return n; }
178
+ n.g.classList.add('counters-moves');
179
+ let dx = 0, dy = 0;
180
+ carry(n.g, {
181
+ point: e => svgPoint(svg, e), raise: () => layer.append(n.g),
182
+ start(q) { n.tween?.pause(); hold = n; dx = n.at.x - q.x; dy = n.at.y - q.y; },
183
+ move(q) { put(n, { x: q.x + dx, y: q.y + dy }); },
184
+ drop(q) {
185
+ hold = null;
186
+ const p = q && { x: q.x + dx, y: q.y + dy };
187
+ if (fixed) { if (p) lay(id, p); render('move'); return; }
188
+ const to = otherOf(homeOf(id));
189
+ if (p && geo.places[to]?.hit?.(p)) moveTo(id, to); else render('move');
190
+ },
191
+ tap() { hold = null; if (fixed) tapFixed(id); else moveTo(id, otherOf(homeOf(id))); },
192
+ });
193
+ return n;
194
+ }
195
+ // The reader drags the walker along the staircase, and the walker moves to the step under the pointer. The arrow
196
+ // keys move a focused walker one step.
197
+ function walker(n) {
198
+ n.g.setAttribute('tabindex', 0); n.g.setAttribute('role', 'button'); n.g.setAttribute('aria-label', T('kind-walker'));
199
+ n.g.classList.add('counters-moves');
200
+ const go1 = k => { if (k !== s.step) { s.step = k; changed(); } };
201
+ carry(n.g, { point: e => svgPoint(svg, e), move(q) { go1(geo.places.steps.at(q)); }, drop() {}, tap() {} });
202
+ nudge(n.g, { step: (dx, dy) => go1(clamp(s.step + (dx > 0 || dy < 0 ? 1 : -1), 0, STEPS)) });
203
+ return n;
204
+ }
205
+ // lay keeps a dragged object where it was let go, inside the tray.
206
+ function lay(id, p) {
207
+ const b = geo.places.slots.box;
208
+ if (b) s.free.set(id, { u: clamp((p.x - b.x) / b.w, 0.03, 0.97), v: clamp((p.y - b.y) / b.h, 0.03, 0.97) });
209
+ }
210
+
211
+ // A tap on an object in a fixed place gives it the next number, gives it one more, shows its own number, or takes
212
+ // it out of the tray. An object that holds its number already shakes its number once.
213
+ function tapFixed(id) {
214
+ const i = s.ids.indexOf(id), tags = s.tags.get(id) ?? [], mode = modeNow();
215
+ if (mode === 'tag' && tags.length) { if (moving()) go.flash(nodes.get(id)?.tagPop); return; }
216
+ if (mode === 'tag' || mode === 'again') { s.said++; s.tags.set(id, [...tags, s.box + s.said]); }
217
+ else if (mode === 'place') { s.last = i + 1; s.tags.set(id, [i + 1]); }
218
+ else if (mode === 'take' || mode === 'count-back') s.here[i] = false;
219
+ changed();
220
+ }
221
+ // moveTo moves an object to a list, or to the first free seat of the bus.
222
+ function moveTo(id, to) {
223
+ const from = homeOf(id);
224
+ if (to === 'seats' && !s.seats.includes(null)) return;
225
+ if (from === 'seats') s.seats[s.seats.indexOf(id)] = null; else s.lists[from].splice(s.lists[from].indexOf(id), 1);
226
+ if (to === 'seats') s.seats[s.seats.indexOf(null)] = id; else s.lists[to].push(id);
227
+ changed();
228
+ }
229
+ // A change takes back a challenge's check, so the reader checks again.
230
+ function changed() { if (cs) cs.checked = false; render('move'); }
231
+
232
+ // paint writes the numbers on the objects, greys the counters past the marker, shows the empty places and writes the
233
+ // number on the box and the counts at the ends of the rows.
234
+ function paint(anim) {
235
+ const mode = modeNow();
236
+ for (const [id, n] of nodes) {
237
+ if (!n.tag) continue;
238
+ let nums = s.tags.get(id) ?? [];
239
+ if (mode === 'pile') { const k = s.lists.beside.indexOf(id); nums = k < 0 ? [] : [s.box + k + 1]; }
240
+ if (mode === 'marker') {
241
+ const at = s.ids.indexOf(id) + 1;
242
+ nums = at === s.marker ? [at] : [];
243
+ n.g.classList.toggle('counters-pale', at > s.marker); n.g.classList.toggle('counters-marked', at === s.marker);
244
+ }
245
+ tag(n, nums.map(int).join(', '), anim);
246
+ }
247
+ gaps.forEach((g, i) => g.classList.toggle('counters-gap-on', !s.here[i]));
248
+ // The trail joins the counted objects in the order of their numbers.
249
+ const path = spec.path ? s.ids.filter(id => s.tags.get(id)?.length).sort((a, b) => s.tags.get(a)[0] - s.tags.get(b)[0]).map(id => nodes.get(id)?.at).filter(Boolean) : [];
250
+ trail.setAttribute('points', path.map(p => `${p.x},${p.y}`).join(' '));
251
+ if (geo.refs.num) geo.refs.num.textContent = int(s.box);
252
+ for (const l of geo.refs.labels ?? []) l.t.textContent = int(l.n);
253
+ }
254
+ function tag(n, words, anim) {
255
+ const text = n.tagPop.lastChild;
256
+ if (text.textContent === words) return;
257
+ text.textContent = words;
258
+ n.tag.setAttribute('display', words ? 'inline' : 'none');
259
+ const w = Math.max(18, 9 + 7.6 * words.length);
260
+ n.tagPop.firstChild.setAttribute('width', w); n.tagPop.firstChild.setAttribute('x', -w / 2);
261
+ if (words && anim) go.pop(n.tagPop);
262
+ }
263
+
264
+ // refresh writes every value that follows the objects, in the readouts and the text, and judges a challenge. The
265
+ // objects swell once when every one of them holds its number.
266
+ function refresh() {
267
+ const st = measure(), words = id => st[id] == null ? '?' : int(st[id]), ids = measuresOf(spec);
268
+ for (const k of chips) if (k.set(words(k.id)) && moving()) go.flash(k.el);
269
+ live(host, { value: id => ids.includes(id) ? words(id) : null });
270
+ const whole = st.total != null;
271
+ if (whole && !s.whole && moving()) go.cheer([...nodes.values()].map(n => n.pop));
272
+ s.whole = whole;
273
+ judge();
274
+ }
275
+ function judge() {
276
+ const c = spec.challenge;
277
+ if (!c || !goal) return;
278
+ const g = COUNT_GOALS[c.goal];
279
+ goal.say(T(`goal-${c.goal}`, g.words(c, target, { int })));
280
+ const r = g.holds({ ...cs, basket: s.lists.basket.length, beside: s.lists.beside.length, left: s.here.filter(Boolean).length }, spec, c, target);
281
+ const first = goal.show(r.done, r.note ? T(`note-${c.goal}-${r.note}`) : undefined);
282
+ if (first && moving()) go.cheer([...nodes.values()].map(n => n.pop));
283
+ }
284
+
285
+ // The panel holds a challenge's line, the page's controls and its readouts.
286
+ function drawPanel() {
287
+ const c = spec.challenge, ctls = [];
288
+ goal = null; chips = [];
289
+ if (c) {
290
+ goal = goalRow({ T, motion: moving() ? fx : null, hint: on => on ? T(`hint-${c.goal}`, COUNT_GOALS[c.goal].words(c, target, { int })) : null,
291
+ another: () => { begin(); goal.reset(); build(); if (!geo) refresh(); } });
292
+ ctls.push(button({ label: T('check'), act: 'check', primary: true, press: () => { if (!cs.checked) { cs.checked = true; judge(); } } }));
293
+ } else {
294
+ const step = (id, key, ctl, value, set) => stepper({ id, label: T(key), min: ctl.lo, max: ctl.hi, value, write: int, change: v => { set(v); changed(); } });
295
+ if (spec.boxCtl) ctls.push(step('box', 'ctl-box', spec.boxCtl, s.box, v => { s.box = v; }));
296
+ if (spec.markerCtl) ctls.push(step('count', 'ctl-marker', spec.markerCtl, s.marker, v => { s.marker = v; }));
297
+ if (spec.stepCtl) ctls.push(step('count', 'ctl-step', spec.stepCtl, s.step, v => { s.step = v; }));
298
+ if (spec.clear) ctls.push(button({ label: T('clear'), act: 'clear', press: () => { s.tags.clear(); s.said = 0; s.last = 0; changed(); } }));
299
+ chips = spec.readout.map(id => chip({ id, label: label(id) }));
300
+ for (const k of chips) k.width(3);
301
+ }
302
+ panel.replaceChildren(...[goal?.el, ctls.length ? row('ctls', ctls) : null, chips.length ? row('out', chips) : null].filter(Boolean));
303
+ }
304
+
305
+ function point(id, on) {
306
+ if (!spec) return;
307
+ for (const part of svg.querySelectorAll(`[data-ref="${id}"]`)) part.classList.toggle('counters-hot', on);
308
+ for (const part of panel.querySelectorAll('[data-ref]')) part.classList.toggle('hot', on && part.dataset.ref === id);
309
+ }
310
+ function stop() { for (const n of nodes.values()) n.tween?.pause(); hold = null; }
311
+
312
+ return {
313
+ show(page) {
314
+ stop(); spec = page; target = null; cs = null;
315
+ begin(); drawPanel(); build();
316
+ if (!geo) refresh();
317
+ },
318
+ hide() { stop(); spec = null; geo = null; back.replaceChildren(); layer.replaceChildren(); trail.setAttribute('points', ''); nodes = new Map(); gaps = []; },
319
+ point,
320
+ lang() { if (!spec) return; const was = goal; drawPanel(); goal?.keep(was); build(); if (!geo) refresh(); },
321
+ };
322
+ }
@@ -0,0 +1,88 @@
1
+ // The Node half of the count scene: objects counted one by one. It checks a page's fields and says what each link
2
+ // shows when the page opens.
3
+ import { schema } from '@openbooknetwork/kitap';
4
+ import { COUNT_LOOKS, TAPS, ROOM, STOP, STEPS, modeOf, sizeOf, opening, counts, measuresOf } from './count-model.js';
5
+ import { COUNT_GOALS, LOOSE, countStart } from './count-goals.js';
6
+ import { numbers } from '../../kit/format.js';
7
+ import { list, challenge, drawn, value } from '../../node.mjs';
8
+
9
+ const { z, check } = schema;
10
+ const Int = z.number().int();
11
+ const Range = z.tuple([Int, Int]);
12
+ const Stepper = z.object({ stepper: Range, start: Int.optional() }).strict();
13
+ const Fields = z.object({
14
+ look: z.enum(COUNT_LOOKS).default('tray'), // The place the objects lie in, or a world page.
15
+ n: Int.min(0).max(100).optional(), // The objects as the page opens, or the passengers on the bus.
16
+ rows: z.boolean().default(false), // The objects stand in rows of ten, a hundred unless n says less.
17
+ tap: z.enum(TAPS).optional(), // What a tap on an object does.
18
+ drag: z.boolean().default(false), // The reader moves the objects anywhere in the tray.
19
+ clear: z.boolean().default(false), // A Clear button takes every number off.
20
+ path: z.boolean().default(false), // A line joins the objects in the order they were counted.
21
+ counted: z.boolean().default(false), // Every object holds its number as the page opens.
22
+ box: z.union([Int, Stepper]).optional(), // A closed box holds this many, and counting goes on from it.
23
+ pile: Int.min(1).max(LOOSE).optional(), // A pile of counters to put beside the box.
24
+ marker: z.union([Int, Stepper]).optional(), // A marker on one counter of the rows.
25
+ waiting: Int.min(0).max(STOP).optional(), // The people at the bus stop.
26
+ step: z.union([Int, Stepper]).optional(), // The step of the staircase the walker stands on.
27
+ readout: z.array(z.string()).default([]),
28
+ // A challenge names a goal of count-goals.js and the ranges it draws its targets from.
29
+ challenge: z.object({ goal: z.string(), target: Range.optional(), box: Range.optional(), more: Range.optional(),
30
+ start: Range.optional(), less: Range.optional() }).strict().optional(),
31
+ }).strict();
32
+
33
+ // The fields each kind of page uses. read fails a field that the page's kind leaves unused.
34
+ const USES = {
35
+ tag: ['look', 'n', 'rows', 'tap', 'drag', 'clear', 'path', 'counted', 'box'], again: ['look', 'n', 'tap', 'clear'],
36
+ place: ['look', 'n', 'rows', 'tap'], take: ['look', 'n', 'rows', 'tap'], marker: ['look', 'n', 'rows', 'marker'],
37
+ pile: ['look', 'box', 'pile'], bus: ['look', 'n', 'waiting'], stairs: ['look', 'step'],
38
+ };
39
+ const DEFAULTS = { look: 'tray', rows: false, drag: false, clear: false, path: false, counted: false };
40
+
41
+ function read(fields, { at }, ctx) {
42
+ const pg = check(Fields, fields, at), fail = words => ctx.fail(at, words);
43
+ const box = value(pg.box), marker = value(pg.marker), step = value(pg.step);
44
+ const spec = { ...pg, scene: 'count', box: box.n, boxCtl: box.ctl, marker: marker.n, markerCtl: marker.ctl, step: step.n, stepCtl: step.ctl };
45
+ for (const [v, name] of [[box, 'box'], [marker, 'marker'], [step, 'step']]) if (v.ctl && (v.ctl.lo > v.ctl.hi || v.n < v.ctl.lo || v.n > v.ctl.hi)) fail(`${name} has the range [${v.ctl.lo}, ${v.ctl.hi}] and starts at ${v.n}, write [low, high] and a start between them`);
46
+ if (pg.challenge) { readChallenge(pg, spec, at, ctx); return { data: spec, has: () => false, offers: 'nothing, a challenge page draws its numbers as it opens' }; }
47
+
48
+ const mode = modeOf(spec), n = sizeOf(spec);
49
+ if (!mode) fail(`tap is missing, write what a tap on an object does: ${list(TAPS)}`);
50
+ for (const [f, v] of Object.entries(pg)) if (!['readout', ...(USES[mode] ?? [])].includes(f) && v !== undefined && v !== DEFAULTS[f]) fail(`${f} belongs to other pages, leave it out of this one`);
51
+ if (mode === 'stairs' && (step.n == null || step.n < 0 || (step.ctl?.hi ?? step.n) > STEPS)) fail(`step is missing or past the staircase, write a step from 0 to ${STEPS}, or { stepper: [0, ${STEPS}], start: 3 }`);
52
+ if (mode === 'bus' && (pg.n == null || pg.waiting == null || pg.n + pg.waiting > STOP)) fail(`n and waiting are the people on the bus and at the stop, write both, ${STOP} people in all at most`);
53
+ if (mode === 'pile' && (box.n == null || box.n < 0)) fail('box is missing, write the number the closed box holds, such as 5, or { stepper: [3, 20], start: 5 }');
54
+ if (mode === 'marker' && (!pg.rows || (marker.ctl?.lo ?? marker.n) < 1 || (marker.ctl?.hi ?? marker.n) > n)) fail(`marker stands on a counter of the rows, write rows: true and a marker from 1 to ${n}`);
55
+ if (['tag', 'again', 'place', 'take'].includes(mode)) {
56
+ const room = pg.rows ? 100 : ROOM[pg.look];
57
+ if (!room) fail(`the ${pg.look} look has no objects to tap, use one of ${list(Object.keys(ROOM))}`);
58
+ else if (!n || n > room) fail(`n is ${n || 'missing'}, the ${pg.rows ? 'rows hold' : `${pg.look} holds`} from 1 to ${room} objects`);
59
+ if (pg.rows && pg.look !== 'tray') fail('rows stand in the tray, leave look out');
60
+ if (mode === 'place' && !pg.rows) fail('a tap shows the number of a counter in the rows, write rows: true');
61
+ if (pg.drag && (pg.rows || pg.look === 'wire')) fail('drag moves loose objects, the rows and the wire hold theirs in place');
62
+ if (box.ctl) fail('box is a number on this page, the tapped objects count on from it');
63
+ if (pg.counted && (box.n != null || pg.clear)) fail('counted opens with the objects numbered from 1, leave box and clear out');
64
+ }
65
+ const ids = measuresOf(spec);
66
+ for (const id of pg.readout) if (!ids.includes(id)) fail(`readout names "${id}", this page reads out ${list(ids)}`);
67
+ return { data: spec, has: id => ids.includes(id), offers: `one of ${list(ids)}` };
68
+ }
69
+
70
+ // A challenge page names its goal, which draws from the page's ranges. Every target it can draw must be open as the
71
+ // page starts and in reach of the page's controls.
72
+ function readChallenge(pg, spec, at, ctx) {
73
+ const c = pg.challenge, goal = challenge(c, COUNT_GOALS, { scene: 'count', at, ctx });
74
+ if (!goal) return;
75
+ for (const [f, v] of Object.entries(pg)) if (f !== 'challenge' && v !== undefined && v !== DEFAULTS[f] && !(f === 'readout' && !v.length)) ctx.fail(at, `${f} is set by challenge.goal ${c.goal}, leave it out`);
76
+ const problem = goal.problem(c, spec);
77
+ if (problem) return ctx.fail(at, `challenge.${problem}`);
78
+ drawn(goal, c, spec, { at, ctx, starts: countStart });
79
+ }
80
+
81
+ // A link shows a count as the page opens. A total shows once every object has its number, so no text links it.
82
+ function start(spec, lang, id) {
83
+ if (!measuresOf(spec).includes(id)) return null;
84
+ const v = counts(spec, opening(spec))[id];
85
+ return v == null ? null : numbers(lang).int(v);
86
+ }
87
+
88
+ export default { read, start };
@@ -1,10 +1,30 @@
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.
1
+ // A counter of the family: a disc, a bead, a car, or one of the objects the count scene counts, such as an apple or a
2
+ // bird. Every scene of the family draws its counters here.
2
3
  import { svg as el } from '../../kit/dom.js';
3
4
 
4
5
  // The radius of a counter in the figure's units, and the reach of its touch target, about 44px across on a phone.
5
6
  export const R = 16, HIT = 22;
6
7
 
8
+ // The objects of the count scene. Each stands round 0, 0 inside a circle of radius r, apart from the walker, who
9
+ // stands on 0, 0.
10
+ const OBJECTS = {
11
+ apple: r => [el('path', { class: 'counters-stem', d: `M 0 ${-r * 0.7} Q 1 ${-r * 1.05} 4 ${-r * 1.2}` }), el('ellipse', { class: 'counters-leaf', cx: r * 0.42, cy: -r * 1.02, rx: r * 0.34, ry: r * 0.16, transform: `rotate(-25 ${r * 0.42} ${-r * 1.02})` }),
12
+ el('path', { class: 'counters-body', d: `M 0 ${-r * 0.62} C ${r * 0.5} ${-r * 0.95} ${r * 1.05} ${-r * 0.6} ${r * 0.95} 0 C ${r * 0.88} ${r * 0.62} ${r * 0.4} ${r * 0.98} 0 ${r * 0.82} C ${-r * 0.4} ${r * 0.98} ${-r * 0.88} ${r * 0.62} ${-r * 0.95} 0 C ${-r * 1.05} ${-r * 0.6} ${-r * 0.5} ${-r * 0.95} 0 ${-r * 0.62} Z` }),
13
+ el('ellipse', { class: 'counters-shine', cx: -r * 0.4, cy: -r * 0.25, rx: r * 0.16, ry: r * 0.28 })],
14
+ bird: r => [el('path', { class: 'counters-body', d: `M ${-r * 1.15} ${-r * 0.1} L ${-r * 0.55} ${-r * 0.15} Q ${-r * 0.2} ${-r * 0.75} ${r * 0.45} ${-r * 0.55} Q ${r * 0.95} ${-r * 0.95} ${r * 1.05} ${-r * 0.35} L ${r * 1.35} ${-r * 0.25} L ${r * 1.0} ${-r * 0.1} Q ${r * 0.85} ${r * 0.6} ${-r * 0.1} ${r * 0.55} Q ${-r * 0.6} ${r * 0.4} ${-r * 0.75} ${r * 0.1} Z` }),
15
+ el('circle', { class: 'counters-eye', cx: r * 0.72, cy: -r * 0.48, r: r * 0.1 }), el('path', { class: 'counters-feet', d: `M ${-r * 0.1} ${r * 0.5} L ${-r * 0.1} ${r * 0.85} M ${r * 0.25} ${r * 0.5} L ${r * 0.25} ${r * 0.85}` })],
16
+ shell: r => [el('path', { class: 'counters-body', d: `M 0 ${r * 0.9} L ${-r * 0.95} ${-r * 0.05} Q ${-r * 0.75} ${-r * 0.95} 0 ${-r * 0.95} Q ${r * 0.75} ${-r * 0.95} ${r * 0.95} ${-r * 0.05} Z` }),
17
+ el('path', { class: 'counters-ribs', d: [-0.6, -0.3, 0, 0.3, 0.6].map(k => `M 0 ${r * 0.8} L ${k * r * 1.1} ${-r * 0.8}`).join(' ') }),
18
+ el('rect', { class: 'counters-body', x: -r * 0.32, y: r * 0.72, width: r * 0.64, height: r * 0.3, rx: r * 0.1 })],
19
+ person: r => [el('path', { class: 'counters-body', d: `M ${-r * 0.8} ${r} Q ${-r * 0.8} ${r * 0.05} 0 ${r * 0.05} Q ${r * 0.8} ${r * 0.05} ${r * 0.8} ${r} Z` }),
20
+ el('circle', { class: 'counters-skin', cy: -r * 0.42, r: r * 0.42 })],
21
+ walker: r => [el('path', { class: 'counters-legs', d: `M ${-r * 0.2} ${-r} L ${-r * 0.3} 0 M ${r * 0.2} ${-r} L ${r * 0.35} 0` }),
22
+ el('rect', { class: 'counters-body', x: -r * 0.45, y: -r * 2.05, width: r * 0.9, height: r * 1.2, rx: r * 0.35 }),
23
+ el('circle', { class: 'counters-skin', cy: -r * 2.5, r: r * 0.42 })],
24
+ };
25
+
7
26
  function glyph(kind, r) {
27
+ if (OBJECTS[kind]) return OBJECTS[kind](r);
8
28
  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
29
  if (kind === 'car') {
10
30
  const w = r * 1.5, l = r * 2.5;
@@ -22,7 +42,7 @@ const PAINTS = 6;
22
42
  // CSS transform on an element would override its transform attribute. n is the counter's number among its kind.
23
43
  export function counter(kind, colour, r = R, n = 0) {
24
44
  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}` : '';
45
+ const paint = kind === 'car' || kind === 'person' ? ` counters-paint-${n % PAINTS}` : '';
26
46
  const g = el('g', { class: `counters-counter counters-${colour} counters-${kind}${paint}` }, [pop]);
27
47
  return { g, pop, at: { x: 0, y: 0 }, colour };
28
48
  }
@@ -1,4 +1,4 @@
1
- counters_lead: "Drag the counters, tap the cells and watch the two parts make the whole."
1
+ counters_lead: "Tap and drag the counters, and watch the numbers follow them."
2
2
  counters_whole: Whole
3
3
  counters_first: First part
4
4
  counters_second: Second part
@@ -50,3 +50,37 @@ counters_note-more: The tray holds more counters than the cup.
50
50
  counters_note-fewer: The tray holds fewer counters than the cup.
51
51
  counters_hint-make-whole: "Count on from {part} to {whole}. Each number you say after {part} is one blue counter."
52
52
  counters_hint-hidden-part: "Count on from {part} to {whole}. Each number you say after {part} is one counter under the cup."
53
+ counters_total: How many
54
+ counters_tag-count: Last number said
55
+ counters_take-count: Left
56
+ counters_place-count: Number
57
+ counters_marker-count: Marker
58
+ counters_bus-count: Passengers
59
+ counters_stairs-count: Step
60
+ counters_clear: Clear
61
+ counters_ctl-box: In the box
62
+ counters_ctl-marker: Marker
63
+ counters_ctl-step: Step
64
+ counters_kind-disc: Counter
65
+ counters_kind-apple: Apple
66
+ counters_kind-bird: Bird
67
+ counters_kind-walker: Walker
68
+ counters_kind-shell: Shell
69
+ counters_kind-person: Person
70
+ counters_gap: Empty place
71
+ counters_basket: Basket
72
+ counters_stop-sign: Bus
73
+ counters_goal-fill-basket: "Put {target} apples in the basket, then press Check."
74
+ counters_goal-count-on: "The box holds {box}. Put counters beside it until there are {target} in all, then press Check."
75
+ counters_goal-count-back: "Take counters away until {target} are left, then press Check."
76
+ counters_note-fill-basket-more: The basket holds more apples than that.
77
+ counters_note-fill-basket-fewer: The basket holds fewer apples than that.
78
+ counters_note-count-on-more: The box and the counters make more than that.
79
+ counters_note-count-on-fewer: The box and the counters make fewer than that.
80
+ counters_note-count-back-more: More counters are left than that.
81
+ counters_note-count-back-fewer: Fewer counters are left than that.
82
+ counters_hint-fill-basket: "Say one number for each apple you put in, and stop at {target}."
83
+ counters_hint-count-on: "Start from {box} and say the next number for each counter you put beside the box. Stop at {target}."
84
+ counters_hint-count-back: "Start from {start} and say the number before for each counter you take away. Stop at {target}."
85
+ counters_roll: Roll the ball
86
+ counters_set-up: Set up the pins
@@ -1,4 +1,4 @@
1
- counters_lead: "Sayaçları sürükleyin, hücrelere dokunun ve iki parçanın bütünü nasıl oluşturduğunu izleyin."
1
+ counters_lead: "Sayaçlara dokunun, onları sürükleyin ve sayıların onları nasıl izlediğine bakın."
2
2
  counters_whole: Bütün
3
3
  counters_first: Birinci parça
4
4
  counters_second: İkinci parça
@@ -50,3 +50,37 @@ counters_note-more: Tepside bardaktakinden çok sayaç var.
50
50
  counters_note-fewer: Tepside bardaktakinden az sayaç var.
51
51
  counters_hint-make-whole: "{part} sayısından {whole} sayısına kadar ileri sayın. {part} sayısından sonra söylediğiniz her sayı bir mavi sayaçtır."
52
52
  counters_hint-hidden-part: "{part} sayısından {whole} sayısına kadar ileri sayın. {part} sayısından sonra söylediğiniz her sayı bardağın altındaki bir sayaçtır."
53
+ counters_total: Kaç tane
54
+ counters_tag-count: Son söylenen sayı
55
+ counters_take-count: Kalan
56
+ counters_place-count: Sayı
57
+ counters_marker-count: İşaret
58
+ counters_bus-count: Yolcular
59
+ counters_stairs-count: Basamak
60
+ counters_clear: Temizle
61
+ counters_ctl-box: Kutuda
62
+ counters_ctl-marker: İşaret
63
+ counters_ctl-step: Basamak
64
+ counters_kind-disc: Sayaç
65
+ counters_kind-apple: Elma
66
+ counters_kind-bird: Kuş
67
+ counters_kind-walker: Yürüyen kişi
68
+ counters_kind-shell: Deniz kabuğu
69
+ counters_kind-person: Kişi
70
+ counters_gap: Boş yer
71
+ counters_basket: Sepet
72
+ counters_stop-sign: Durak
73
+ counters_goal-fill-basket: "Sepete {target} elma koyun, sonra Kontrol et düğmesine basın."
74
+ counters_goal-count-on: "Kutuda {box} tane var. Hepsi {target} olana kadar yanına sayaç koyun, sonra Kontrol et düğmesine basın."
75
+ counters_goal-count-back: "{target} sayaç kalana kadar sayaç alın, sonra Kontrol et düğmesine basın."
76
+ counters_note-fill-basket-more: Sepette bundan çok elma var.
77
+ counters_note-fill-basket-fewer: Sepette bundan az elma var.
78
+ counters_note-count-on-more: Kutu ve sayaçlar bundan çok ediyor.
79
+ counters_note-count-on-fewer: Kutu ve sayaçlar bundan az ediyor.
80
+ counters_note-count-back-more: Bundan çok sayaç kaldı.
81
+ counters_note-count-back-fewer: Bundan az sayaç kaldı.
82
+ counters_hint-fill-basket: "Koyduğunuz her elma için bir sayı söyleyin ve {target} sayısında durun."
83
+ counters_hint-count-on: "{box} sayısından başlayın ve kutunun yanına koyduğunuz her sayaç için bir sonraki sayıyı söyleyin. {target} sayısında durun."
84
+ counters_hint-count-back: "{start} sayısından başlayın ve aldığınız her sayaç için bir önceki sayıyı söyleyin. {target} sayısında durun."
85
+ counters_roll: Topu yuvarla
86
+ counters_set-up: Lobutları diz
@@ -1,18 +1,19 @@
1
- // The Node half of the counters family: counters a reader moves between parts, cells of ten frames, and the skins of
2
- // the same figure for the world pages. It checks a page's fields against its scene and says what each link shows
1
+ // The Node half of the counters family. The bonds scene moves counters between parts and fills ten frames, and the
2
+ // count scene counts objects one by one. It checks a page's fields against its scene and says what each link shows
3
3
  // when the page opens.
4
4
  import { schema } from '@openbooknetwork/kitap';
5
5
  import { LOOKS, modeOf, capOf, opening, counts, measuresOf } from './model.js';
6
6
  import { GOALS, challengeStart } from './goals.js';
7
+ import count from './count.mjs';
7
8
  import { numbers } from '../../kit/format.js';
8
- import { list, challenge, drawn } from '../../node.mjs';
9
+ import { list, challenge, drawn, value } from '../../node.mjs';
9
10
 
10
- const { z } = schema;
11
+ const { z, check } = schema;
11
12
  const Int = z.number().int();
12
13
  const Range = z.tuple([Int, Int]);
13
14
  const Slider = z.object({ slider: Range, start: Int.optional() }).strict();
14
15
  const Stepper = z.object({ stepper: Range, start: Int.optional() }).strict();
15
- const Fields = z.object({
16
+ const BondsFields = z.object({
16
17
  look: z.enum(LOOKS).default('diagram'), // The diagram, ten frames alone, or the skin of a world page.
17
18
  whole: z.union([Int, Stepper]).optional(), // The whole as a number, or on a stepper.
18
19
  first: z.union([Int, Slider, Stepper]).optional(), // The first part, or the red counters, as the page opens.
@@ -23,21 +24,15 @@ const Fields = z.object({
23
24
  fill: z.boolean().default(false), // A button fills the second frame with red counters and empties it again.
24
25
  cup: z.boolean().default(false), // A cup hides the second part until the reader lifts it.
25
26
  list: z.boolean().default(false), // A list logs each split the reader finds.
27
+ still: z.boolean().default(false), // The counters stay where they are, for a page that sums up.
28
+ roll: z.boolean().default(false), // A ball knocks down pins at random, and the pins take no taps.
26
29
  readout: z.array(z.string()).default([]),
27
30
  // A challenge names a goal of goals.js and the ranges it draws its targets from.
28
31
  challenge: z.object({ goal: z.string(), whole: z.union([Int, Range]), part: Range.optional() }).strict().optional(),
29
32
  }).strict();
30
33
 
31
- // value reads a number, a slider or a stepper as its starting value and its range.
32
- function value(v) {
33
- if (v == null) return { n: null, ctl: null };
34
- if (typeof v === 'number') return { n: v, ctl: null };
35
- const kind = v.slider ? 'slider' : 'stepper', [lo, hi] = v[kind];
36
- return { n: v.start ?? lo, ctl: { kind, lo, hi } };
37
- }
38
-
39
- function read(pg, { at }, ctx) {
40
- const fail = words => ctx.fail(at, words);
34
+ function readBonds(fields, { at }, ctx) {
35
+ const pg = { scene: 'bonds', ...check(BondsFields, fields, at) }, fail = words => ctx.fail(at, words);
41
36
  const look = pg.look, whole = value(pg.whole), first = value(pg.first);
42
37
  if (pg.frames !== undefined && !['diagram', 'frames'].includes(look)) fail(`frames belongs to the diagram and frames looks, the ${look} look has its own places`);
43
38
  const frames = look === 'frames' ? pg.frames ?? 1 : look === 'diagram' ? pg.frames ?? 0 : 0;
@@ -58,6 +53,7 @@ function read(pg, { at }, ctx) {
58
53
  if (pg.swap && look === 'hands') fail('swap belongs to the diagram, leave it out of the hands');
59
54
  } else {
60
55
  if (pg.swap) fail('swap belongs to the diagram without frames, where the parts hold the counters');
56
+ if (pg.roll && look !== 'pins') fail('roll belongs to the pins look, where a ball knocks pins down');
61
57
  if (spec.second != null && (whole.n != null || pg.cup)) fail('second is set by the whole on this page, leave it out');
62
58
  const red = first.ctl?.hi ?? spec.first, blue = spec.second ?? 0;
63
59
  if (red + blue > cap || (whole.ctl?.hi ?? spec.whole ?? 0) > cap) fail(`the counters reach ${Math.max(red + blue, whole.ctl?.hi ?? spec.whole ?? 0)}, and the ${look === 'frames' || look === 'diagram' ? `${frames} frame${frames > 1 ? 's hold' : ' holds'}` : `${look} hold`} ${cap}`);
@@ -91,13 +87,18 @@ function readChallenge(pg, spec, mode, at, ctx) {
91
87
  }
92
88
 
93
89
  // A link shows a count as the page opens.
94
- function start(spec, lang, id) {
90
+ function startBonds(spec, lang, id) {
95
91
  if (!measuresOf(spec).includes(id)) return null;
96
92
  return numbers(lang).int(counts(spec, opening(spec))[id]);
97
93
  }
98
94
 
95
+ // Each scene checks its own fields, so the family's schema lets every field through to the scene.
96
+ const Fields = z.object({}).passthrough();
97
+ const read = ({ scene, ...fields }, info, ctx) => scene === 'count' ? count.read(fields, info, ctx) : readBonds(fields, info, ctx);
98
+ const start = (spec, lang, id) => spec.scene === 'count' ? count.start(spec, lang, id) : startBonds(spec, lang, id);
99
+
99
100
  // The two colours of the counters, a red and a blue that readers with any colour vision tell apart, each with a step
100
101
  // for the dark themes.
101
102
  const bundle = () => ({ families: { 'counters-red': { color: '#d1453b', color_dark: '#f0776d' }, 'counters-blue': { color: '#2a6bd1', color_dark: '#6fa4f5' } } });
102
103
 
103
- export default { id: 'counters', scenes: ['bonds'], schema: Fields, read, start, bundle };
104
+ export default { id: 'counters', scenes: ['bonds', 'count'], schema: Fields, read, start, bundle };
@@ -5,9 +5,11 @@ import { drag } from '../../kit/drag.js';
5
5
  // A pointer that travels less than this many pixels makes a tap.
6
6
  const STILL = 6;
7
7
  // A touch sends its click after the counter it carried has moved, so the click lands on whatever lies under the
8
- // finger then. A click this soon after a carry belongs to the carry and is dropped.
8
+ // finger then. A click this soon after a carry belongs to the carry and is dropped. A new press starts a new
9
+ // gesture, so its click counts however soon it follows.
9
10
  const AFTER = 500;
10
11
  let carried = 0;
12
+ addEventListener('pointerdown', () => { carried = 0; }, true);
11
13
 
12
14
  // carry lets the reader drag node. start may refuse with false. drop gets the point where the counter was let go,
13
15
  // or null when the drag was cancelled, and tap runs for a press that did not move.
package/src/i18n/en.yaml CHANGED
@@ -13,7 +13,7 @@ hesap_hint: Hint
13
13
  hesap_another: Another one
14
14
  hesap_solved: Solved
15
15
  hesap_not-yet: Not solved yet.
16
- counters_lead: "Drag the counters, tap the cells and watch the two parts make the whole."
16
+ counters_lead: "Tap and drag the counters, and watch the numbers follow them."
17
17
  counters_whole: Whole
18
18
  counters_first: First part
19
19
  counters_second: Second part
@@ -65,3 +65,37 @@ counters_note-more: The tray holds more counters than the cup.
65
65
  counters_note-fewer: The tray holds fewer counters than the cup.
66
66
  counters_hint-make-whole: "Count on from {part} to {whole}. Each number you say after {part} is one blue counter."
67
67
  counters_hint-hidden-part: "Count on from {part} to {whole}. Each number you say after {part} is one counter under the cup."
68
+ counters_total: How many
69
+ counters_tag-count: Last number said
70
+ counters_take-count: Left
71
+ counters_place-count: Number
72
+ counters_marker-count: Marker
73
+ counters_bus-count: Passengers
74
+ counters_stairs-count: Step
75
+ counters_clear: Clear
76
+ counters_ctl-box: In the box
77
+ counters_ctl-marker: Marker
78
+ counters_ctl-step: Step
79
+ counters_kind-disc: Counter
80
+ counters_kind-apple: Apple
81
+ counters_kind-bird: Bird
82
+ counters_kind-walker: Walker
83
+ counters_kind-shell: Shell
84
+ counters_kind-person: Person
85
+ counters_gap: Empty place
86
+ counters_basket: Basket
87
+ counters_stop-sign: Bus
88
+ counters_goal-fill-basket: "Put {target} apples in the basket, then press Check."
89
+ counters_goal-count-on: "The box holds {box}. Put counters beside it until there are {target} in all, then press Check."
90
+ counters_goal-count-back: "Take counters away until {target} are left, then press Check."
91
+ counters_note-fill-basket-more: The basket holds more apples than that.
92
+ counters_note-fill-basket-fewer: The basket holds fewer apples than that.
93
+ counters_note-count-on-more: The box and the counters make more than that.
94
+ counters_note-count-on-fewer: The box and the counters make fewer than that.
95
+ counters_note-count-back-more: More counters are left than that.
96
+ counters_note-count-back-fewer: Fewer counters are left than that.
97
+ counters_hint-fill-basket: "Say one number for each apple you put in, and stop at {target}."
98
+ counters_hint-count-on: "Start from {box} and say the next number for each counter you put beside the box. Stop at {target}."
99
+ counters_hint-count-back: "Start from {start} and say the number before for each counter you take away. Stop at {target}."
100
+ counters_roll: Roll the ball
101
+ counters_set-up: Set up the pins
package/src/i18n/tr.yaml CHANGED
@@ -13,7 +13,7 @@ hesap_hint: İpucu
13
13
  hesap_another: Bir tane daha
14
14
  hesap_solved: Çözüldü
15
15
  hesap_not-yet: Henüz çözülmedi.
16
- counters_lead: "Sayaçları sürükleyin, hücrelere dokunun ve iki parçanın bütünü nasıl oluşturduğunu izleyin."
16
+ counters_lead: "Sayaçlara dokunun, onları sürükleyin ve sayıların onları nasıl izlediğine bakın."
17
17
  counters_whole: Bütün
18
18
  counters_first: Birinci parça
19
19
  counters_second: İkinci parça
@@ -65,3 +65,37 @@ counters_note-more: Tepside bardaktakinden çok sayaç var.
65
65
  counters_note-fewer: Tepside bardaktakinden az sayaç var.
66
66
  counters_hint-make-whole: "{part} sayısından {whole} sayısına kadar ileri sayın. {part} sayısından sonra söylediğiniz her sayı bir mavi sayaçtır."
67
67
  counters_hint-hidden-part: "{part} sayısından {whole} sayısına kadar ileri sayın. {part} sayısından sonra söylediğiniz her sayı bardağın altındaki bir sayaçtır."
68
+ counters_total: Kaç tane
69
+ counters_tag-count: Son söylenen sayı
70
+ counters_take-count: Kalan
71
+ counters_place-count: Sayı
72
+ counters_marker-count: İşaret
73
+ counters_bus-count: Yolcular
74
+ counters_stairs-count: Basamak
75
+ counters_clear: Temizle
76
+ counters_ctl-box: Kutuda
77
+ counters_ctl-marker: İşaret
78
+ counters_ctl-step: Basamak
79
+ counters_kind-disc: Sayaç
80
+ counters_kind-apple: Elma
81
+ counters_kind-bird: Kuş
82
+ counters_kind-walker: Yürüyen kişi
83
+ counters_kind-shell: Deniz kabuğu
84
+ counters_kind-person: Kişi
85
+ counters_gap: Boş yer
86
+ counters_basket: Sepet
87
+ counters_stop-sign: Durak
88
+ counters_goal-fill-basket: "Sepete {target} elma koyun, sonra Kontrol et düğmesine basın."
89
+ counters_goal-count-on: "Kutuda {box} tane var. Hepsi {target} olana kadar yanına sayaç koyun, sonra Kontrol et düğmesine basın."
90
+ counters_goal-count-back: "{target} sayaç kalana kadar sayaç alın, sonra Kontrol et düğmesine basın."
91
+ counters_note-fill-basket-more: Sepette bundan çok elma var.
92
+ counters_note-fill-basket-fewer: Sepette bundan az elma var.
93
+ counters_note-count-on-more: Kutu ve sayaçlar bundan çok ediyor.
94
+ counters_note-count-on-fewer: Kutu ve sayaçlar bundan az ediyor.
95
+ counters_note-count-back-more: Bundan çok sayaç kaldı.
96
+ counters_note-count-back-fewer: Bundan az sayaç kaldı.
97
+ counters_hint-fill-basket: "Koyduğunuz her elma için bir sayı söyleyin ve {target} sayısında durun."
98
+ counters_hint-count-on: "{box} sayısından başlayın ve kutunun yanına koyduğunuz her sayaç için bir sonraki sayıyı söyleyin. {target} sayısında durun."
99
+ counters_hint-count-back: "{start} sayısından başlayın ve aldığınız her sayaç için bir önceki sayıyı söyleyin. {target} sayısında durun."
100
+ counters_roll: Topu yuvarla
101
+ counters_set-up: Lobutları diz
package/src/node.mjs CHANGED
@@ -41,3 +41,10 @@ export function drawn(goal, c, spec, { at, ctx, starts }) {
41
41
  export function hidden(readout, hides, at, ctx) {
42
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
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
+ }