@openbooknetwork/hesap 0.0.0-stage → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +116 -2
- package/package.json +45 -4
- package/scripts/assemble.mjs +40 -0
- package/src/client.css +240 -0
- package/src/client.js +111 -0
- package/src/families/counters/bonds.js +424 -0
- package/src/families/counters/client.css +150 -0
- package/src/families/counters/client.js +22 -0
- package/src/families/counters/count-figures.js +166 -0
- package/src/families/counters/count-goals.js +57 -0
- package/src/families/counters/count-model.js +57 -0
- package/src/families/counters/count.js +322 -0
- package/src/families/counters/count.mjs +88 -0
- package/src/families/counters/counter.js +52 -0
- package/src/families/counters/driver.js +16 -0
- package/src/families/counters/figures.js +172 -0
- package/src/families/counters/frame.js +28 -0
- package/src/families/counters/goals.js +75 -0
- package/src/families/counters/i18n/en.yaml +86 -0
- package/src/families/counters/i18n/tr.yaml +86 -0
- package/src/families/counters/index.mjs +104 -0
- package/src/families/counters/model.js +86 -0
- package/src/families/counters/move.js +44 -0
- package/src/families/counters/places.js +45 -0
- package/src/families.mjs +5 -0
- package/src/i18n/en.yaml +101 -0
- package/src/i18n/tr.yaml +101 -0
- package/src/index.mjs +82 -0
- package/src/kit/dom.js +32 -0
- package/src/kit/drag.js +40 -0
- package/src/kit/format.js +34 -0
- package/src/kit/goal.js +49 -0
- package/src/kit/i18n/en.yaml +15 -0
- package/src/kit/i18n/tr.yaml +15 -0
- package/src/kit/kit.css +89 -0
- package/src/kit/motion.js +44 -0
- package/src/kit/panel.js +70 -0
- package/src/kit/play.js +26 -0
- package/src/kit/random.js +35 -0
- package/src/kit/text.js +25 -0
- package/src/node.mjs +50 -0
|
@@ -0,0 +1,104 @@
|
|
|
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
|
+
// when the page opens.
|
|
4
|
+
import { schema } from '@openbooknetwork/kitap';
|
|
5
|
+
import { LOOKS, modeOf, capOf, opening, counts, measuresOf } from './model.js';
|
|
6
|
+
import { GOALS, challengeStart } from './goals.js';
|
|
7
|
+
import count from './count.mjs';
|
|
8
|
+
import { numbers } from '../../kit/format.js';
|
|
9
|
+
import { list, challenge, drawn, value } from '../../node.mjs';
|
|
10
|
+
|
|
11
|
+
const { z, check } = schema;
|
|
12
|
+
const Int = z.number().int();
|
|
13
|
+
const Range = z.tuple([Int, Int]);
|
|
14
|
+
const Slider = z.object({ slider: Range, start: Int.optional() }).strict();
|
|
15
|
+
const Stepper = z.object({ stepper: Range, start: Int.optional() }).strict();
|
|
16
|
+
const BondsFields = z.object({
|
|
17
|
+
look: z.enum(LOOKS).default('diagram'), // The diagram, ten frames alone, or the skin of a world page.
|
|
18
|
+
whole: z.union([Int, Stepper]).optional(), // The whole as a number, or on a stepper.
|
|
19
|
+
first: z.union([Int, Slider, Stepper]).optional(), // The first part, or the red counters, as the page opens.
|
|
20
|
+
second: Int.optional(), // The blue counters of the frames as the page opens.
|
|
21
|
+
frames: Int.min(0).max(2).optional(), // The ten frames under the diagram, or of the frames look.
|
|
22
|
+
tap: z.enum(['first', 'second']).optional(), // A tap on a cell adds or takes away a counter of this part.
|
|
23
|
+
swap: z.boolean().default(false), // A Swap button trades the two parts.
|
|
24
|
+
fill: z.boolean().default(false), // A button fills the second frame with red counters and empties it again.
|
|
25
|
+
cup: z.boolean().default(false), // A cup hides the second part until the reader lifts it.
|
|
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.
|
|
29
|
+
readout: z.array(z.string()).default([]),
|
|
30
|
+
// A challenge names a goal of goals.js and the ranges it draws its targets from.
|
|
31
|
+
challenge: z.object({ goal: z.string(), whole: z.union([Int, Range]), part: Range.optional() }).strict().optional(),
|
|
32
|
+
}).strict();
|
|
33
|
+
|
|
34
|
+
function readBonds(fields, { at }, ctx) {
|
|
35
|
+
const pg = { scene: 'bonds', ...check(BondsFields, fields, at) }, fail = words => ctx.fail(at, words);
|
|
36
|
+
const look = pg.look, whole = value(pg.whole), first = value(pg.first);
|
|
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`);
|
|
38
|
+
const frames = look === 'frames' ? pg.frames ?? 1 : look === 'diagram' ? pg.frames ?? 0 : 0;
|
|
39
|
+
if (look === 'frames' && !frames) fail('frames is 0, the frames look shows 1 or 2 ten frames');
|
|
40
|
+
const spec = { ...pg, frames, whole: whole.n, wholeCtl: whole.ctl, first: first.n ?? 0, firstCtl: first.ctl, second: pg.second ?? null };
|
|
41
|
+
const mode = modeOf(spec), cap = capOf(spec);
|
|
42
|
+
for (const [ctl, name] of [[whole.ctl, 'whole'], [first.ctl, 'first']]) if (ctl && (ctl.lo > ctl.hi || spec[name] < ctl.lo || spec[name] > ctl.hi)) fail(`${name} has the range [${ctl.lo}, ${ctl.hi}] and starts at ${spec[name]}, write [low, high] and a start between them`);
|
|
43
|
+
|
|
44
|
+
if (pg.challenge) readChallenge(pg, spec, mode, at, ctx);
|
|
45
|
+
else if (mode === 'parts') {
|
|
46
|
+
if (spec.whole == null) fail('whole is missing, write the number the two parts make, such as 7, or { stepper: [2, 10], start: 7 }');
|
|
47
|
+
const hi = whole.ctl?.hi ?? spec.whole ?? 0;
|
|
48
|
+
if ((whole.ctl?.lo ?? spec.whole) < 1 || hi > 20) fail(`whole reaches ${whole.ctl ? `[${whole.ctl.lo}, ${hi}]` : hi}, the parts hold a whole from 1 to 20`);
|
|
49
|
+
if (first.ctl) fail('first is a number on this page, the reader moves the counters between the parts');
|
|
50
|
+
if (spec.first > (spec.whole ?? 0)) fail(`first is ${spec.first}, more than the whole ${spec.whole}`);
|
|
51
|
+
for (const f of ['second', 'tap']) if (pg[f] !== undefined) fail(`${f} belongs to pages with frames, pins or cars, this page moves counters between parts`);
|
|
52
|
+
for (const f of ['fill', 'cup']) if (pg[f]) fail(`${f} belongs to pages with frames, this page moves counters between parts`);
|
|
53
|
+
if (pg.swap && look === 'hands') fail('swap belongs to the diagram, leave it out of the hands');
|
|
54
|
+
} else {
|
|
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');
|
|
57
|
+
if (spec.second != null && (whole.n != null || pg.cup)) fail('second is set by the whole on this page, leave it out');
|
|
58
|
+
const red = first.ctl?.hi ?? spec.first, blue = spec.second ?? 0;
|
|
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}`);
|
|
60
|
+
if (spec.whole != null && (first.ctl?.hi ?? spec.first) > spec.whole && !whole.ctl) fail(`first reaches ${first.ctl?.hi ?? spec.first}, more than the whole ${spec.whole}`);
|
|
61
|
+
if (whole.ctl && whole.ctl.lo < spec.first) fail(`whole starts its range at ${whole.ctl.lo}, below the ${spec.first} red counters`);
|
|
62
|
+
if (whole.ctl && first.ctl) fail('whole and first both have a control, give one of them a number');
|
|
63
|
+
if (pg.cup && (spec.whole == null || whole.ctl || pg.tap !== 'second' || !frames)) fail('cup hides the second part of a declared whole, write whole as a number, tap: second and frames: 1 or 2 with look: diagram');
|
|
64
|
+
if (pg.fill && (frames !== 2 || spec.first + (spec.second ?? 0) > 10)) fail('fill fills the second of two frames, write frames: 2 and keep the first counters in the first frame');
|
|
65
|
+
if (pg.list && (pg.tap !== 'first')) fail('list logs the counters and the empty cells, write tap: first');
|
|
66
|
+
if (pg.tap && first.ctl) fail('tap and a control on first both change the red counters, keep one');
|
|
67
|
+
}
|
|
68
|
+
// A page with blue counters, a whole or a fill button shows two colours, and its readouts name red and blue.
|
|
69
|
+
spec.two = mode === 'cells' && (spec.second != null || spec.whole != null || !!pg.fill || pg.tap === 'second');
|
|
70
|
+
const ids = measuresOf(spec);
|
|
71
|
+
for (const id of pg.readout) if (!ids.includes(id)) fail(`readout names "${id}", this page reads out ${list(ids) || 'nothing'}`);
|
|
72
|
+
return { data: spec, has: id => ids.includes(id), offers: ids.length ? `one of ${list(ids)}` : 'nothing, a challenge page draws its numbers as it opens' };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// A challenge page names its goal, which draws from the page's ranges. Every target it can draw must be open as the
|
|
76
|
+
// page starts and in reach of the page's controls.
|
|
77
|
+
function readChallenge(pg, spec, mode, at, ctx) {
|
|
78
|
+
const c = pg.challenge, goal = challenge(c, GOALS, { scene: pg.scene, at, ctx });
|
|
79
|
+
if (!goal) return;
|
|
80
|
+
if (!goal.looks.includes(pg.look)) return ctx.fail(at, `challenge.goal ${c.goal} works on the ${list(goal.looks)} look, this page shows ${pg.look}`);
|
|
81
|
+
for (const f of ['whole', 'first', 'second', 'tap']) if (pg[f] !== undefined) ctx.fail(at, `${f} is drawn by challenge.goal ${c.goal}, leave it out`);
|
|
82
|
+
for (const f of ['swap', 'fill', 'cup', 'list']) if (pg[f]) ctx.fail(at, `${f} belongs to pages without a challenge, leave it out`);
|
|
83
|
+
if (c.goal === 'hidden-part' && spec.frames) ctx.fail(at, 'frames would show the empty cells of the hidden part, leave frames out');
|
|
84
|
+
const problem = goal.problem(c, spec);
|
|
85
|
+
if (problem) return ctx.fail(at, `challenge.${problem}`);
|
|
86
|
+
drawn(goal, c, spec, { at, ctx, starts: () => challengeStart() });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// A link shows a count as the page opens.
|
|
90
|
+
function startBonds(spec, lang, id) {
|
|
91
|
+
if (!measuresOf(spec).includes(id)) return null;
|
|
92
|
+
return numbers(lang).int(counts(spec, opening(spec))[id]);
|
|
93
|
+
}
|
|
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
|
+
|
|
100
|
+
// The two colours of the counters, a red and a blue that readers with any colour vision tell apart, each with a step
|
|
101
|
+
// for the dark themes.
|
|
102
|
+
const bundle = () => ({ families: { 'counters-red': { color: '#d1453b', color_dark: '#f0776d' }, 'counters-blue': { color: '#2a6bd1', color_dark: '#6fa4f5' } } });
|
|
103
|
+
|
|
104
|
+
export default { id: 'counters', scenes: ['bonds', 'count'], schema: Fields, read, start, bundle };
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// What a counters page holds and what it counts. The build and the browser both use this file, so a page's text
|
|
2
|
+
// and its live values agree.
|
|
3
|
+
|
|
4
|
+
// A page shows its counters in one of these looks. hands, pins and cars are skins for the world pages.
|
|
5
|
+
export const LOOKS = ['diagram', 'frames', 'hands', 'pins', 'cars'];
|
|
6
|
+
// The pins of a lane and the spaces of the car park.
|
|
7
|
+
const CAP = { pins: 10, cars: 20 };
|
|
8
|
+
// The cars fill the car park in this order as a page opens, so the parked cars look spread out.
|
|
9
|
+
const CAR_ORDER = [2, 13, 7, 16, 0, 10, 5, 18, 11, 3, 8, 15, 19, 1, 12, 6, 17, 4, 9, 14];
|
|
10
|
+
|
|
11
|
+
// A page in the parts mode moves counters between two parts, in hands or in the diagram's circles. A page in the
|
|
12
|
+
// cells mode fills the cells of ten frames, the pins of a lane or the spaces of a car park.
|
|
13
|
+
export const modeOf = spec => spec.look === 'hands' || (spec.look === 'diagram' && !spec.frames) ? 'parts' : 'cells';
|
|
14
|
+
export const capOf = spec => CAP[spec.look] ?? spec.frames * 10;
|
|
15
|
+
|
|
16
|
+
// blueOf gives the blue counters that go with red ones: the rest of a declared whole, or the page's own number.
|
|
17
|
+
export function blueOf(spec, red, whole) {
|
|
18
|
+
if (spec.cup) return 0;
|
|
19
|
+
if (whole != null) return Math.max(0, whole - red);
|
|
20
|
+
return spec.second ?? 0;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// lay puts red counters in the first cells and blue ones after them. keep gives the counter that already sits in a
|
|
24
|
+
// cell, so a counter that stays where it was keeps its id.
|
|
25
|
+
export function lay(spec, red, blue, keep = () => null, fresh = () => null) {
|
|
26
|
+
const cap = capOf(spec), order = spec.look === 'cars' ? CAR_ORDER : [...Array(cap).keys()], cells = Array(cap).fill(null);
|
|
27
|
+
order.forEach((cell, i) => {
|
|
28
|
+
const colour = i < red ? 'a' : i < red + blue ? 'b' : null;
|
|
29
|
+
if (!colour) return;
|
|
30
|
+
const was = keep(cell);
|
|
31
|
+
cells[cell] = was?.colour === colour ? was : { id: fresh() ?? `${colour}${cell}`, colour };
|
|
32
|
+
});
|
|
33
|
+
return cells;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// opening gives the counters as the page opens. A parts page holds the ids of each part, and a cells page holds
|
|
37
|
+
// each cell's counter or null. found lists the first parts of the splits the list has logged.
|
|
38
|
+
export function opening(spec) {
|
|
39
|
+
const whole = spec.whole;
|
|
40
|
+
if (modeOf(spec) === 'parts') {
|
|
41
|
+
const ids = [...Array(whole ?? 0).keys()].map(i => `p${i}`), first = Math.min(spec.first, whole ?? 0);
|
|
42
|
+
const colour = Object.fromEntries(ids.map((id, i) => [id, spec.look === 'hands' || i < first ? 'a' : 'b']));
|
|
43
|
+
const s = { left: ids.slice(0, first), right: ids.slice(first), colour, found: [], lifted: false, extra: false };
|
|
44
|
+
if (spec.list) s.found = [first];
|
|
45
|
+
return s;
|
|
46
|
+
}
|
|
47
|
+
const s = { cells: lay(spec, spec.first, blueOf(spec, spec.first, whole)), found: [], lifted: false, extra: false };
|
|
48
|
+
if (spec.list) s.found = [spec.first];
|
|
49
|
+
return s;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// counts gives every number a page can show for its counters.
|
|
53
|
+
export function counts(spec, s) {
|
|
54
|
+
if (modeOf(spec) === 'parts') {
|
|
55
|
+
const first = s.left.length, second = s.right.length;
|
|
56
|
+
return { first, second, whole: first + second, found: s.found.length, ways: first + second + 1 };
|
|
57
|
+
}
|
|
58
|
+
const cap = capOf(spec), red = s.cells.filter(c => c?.colour === 'a').length, blue = s.cells.filter(c => c?.colour === 'b').length;
|
|
59
|
+
const whole = spec.cup ? spec.whole : red + blue;
|
|
60
|
+
return { first: red, second: spec.cup ? whole - red : blue, whole, empty: cap - red - blue, added: blue, found: s.found.length, ways: cap + 1 };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// The list logs a split as its first part. Its partner is the second part, or the empty cells of a frame.
|
|
64
|
+
export const partnerOf = (spec, st) => modeOf(spec) === 'parts' ? st.second : st.empty;
|
|
65
|
+
|
|
66
|
+
// The context of a page picks the words of its readouts, such as "Left hand" for the first part of the hands.
|
|
67
|
+
export function contextOf(spec) {
|
|
68
|
+
if (['hands', 'pins', 'cars'].includes(spec.look)) return spec.look;
|
|
69
|
+
if (modeOf(spec) === 'parts') return 'parts';
|
|
70
|
+
if (spec.cup) return 'cup';
|
|
71
|
+
return spec.two ? 'two' : 'one';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The measures a page can read out and link in its text.
|
|
75
|
+
export function measuresOf(spec) {
|
|
76
|
+
if (spec.challenge) return [];
|
|
77
|
+
const ids = ['first'];
|
|
78
|
+
if (modeOf(spec) === 'parts') ids.push('second', 'whole');
|
|
79
|
+
else {
|
|
80
|
+
ids.push('empty');
|
|
81
|
+
if (spec.two || spec.cup) ids.push('second', 'whole');
|
|
82
|
+
if (spec.cup) ids.push('added');
|
|
83
|
+
}
|
|
84
|
+
if (spec.list) ids.push('found', 'ways');
|
|
85
|
+
return ids;
|
|
86
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Carrying a counter from one place to another. A press that hardly moves is a tap, and Enter or Space on a focused
|
|
2
|
+
// counter is a tap too, so every move works by touch, by mouse and by keys.
|
|
3
|
+
import { drag } from '../../kit/drag.js';
|
|
4
|
+
|
|
5
|
+
// A pointer that travels less than this many pixels makes a tap.
|
|
6
|
+
const STILL = 6;
|
|
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. A new press starts a new
|
|
9
|
+
// gesture, so its click counts however soon it follows.
|
|
10
|
+
const AFTER = 500;
|
|
11
|
+
let carried = 0;
|
|
12
|
+
addEventListener('pointerdown', () => { carried = 0; }, true);
|
|
13
|
+
|
|
14
|
+
// carry lets the reader drag node. start may refuse with false. drop gets the point where the counter was let go,
|
|
15
|
+
// or null when the drag was cancelled, and tap runs for a press that did not move.
|
|
16
|
+
export function carry(node, { point, start, move, drop, tap, raise }) {
|
|
17
|
+
let from = null, far = false;
|
|
18
|
+
drag(node, {
|
|
19
|
+
point, raise,
|
|
20
|
+
start(p, e) { from = { x: e.clientX, y: e.clientY }; far = false; return start?.(p, e); },
|
|
21
|
+
move(p, e) {
|
|
22
|
+
if (!far && Math.hypot(e.clientX - from.x, e.clientY - from.y) < STILL) return;
|
|
23
|
+
far = true; move?.(p, e);
|
|
24
|
+
},
|
|
25
|
+
drop(e) {
|
|
26
|
+
carried = performance.now();
|
|
27
|
+
if (!far) return e?.type === 'pointercancel' ? drop?.(null) : tap ? tap() : drop?.(null);
|
|
28
|
+
drop?.(e?.type === 'pointercancel' ? null : point(e));
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
node.addEventListener('keydown', e => {
|
|
32
|
+
if (e.key !== 'Enter' && e.key !== ' ') return;
|
|
33
|
+
e.preventDefault(); e.stopPropagation(); tap?.();
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// press makes node a button in the figure: a click, a tap, Enter or Space runs act.
|
|
38
|
+
export function press(node, act) {
|
|
39
|
+
node.addEventListener('click', () => { if (performance.now() - carried > AFTER) act(); });
|
|
40
|
+
node.addEventListener('keydown', e => {
|
|
41
|
+
if (e.key !== 'Enter' && e.key !== ' ') return;
|
|
42
|
+
e.preventDefault(); e.stopPropagation(); act();
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Where counters sit inside a place, and how the blocks of a figure are set out on the stage.
|
|
2
|
+
|
|
3
|
+
// cluster sets n counters in short centred rows round the point 0, 0, so a part reads at a glance.
|
|
4
|
+
export function cluster(n, gap) {
|
|
5
|
+
const cols = n <= 3 ? n : n === 4 ? 2 : n <= 9 ? 3 : n <= 16 ? 4 : 5, rows = Math.ceil(n / cols);
|
|
6
|
+
return Array.from({ length: n }, (_, i) => {
|
|
7
|
+
const r = Math.floor(i / cols), inRow = r === rows - 1 ? n - r * cols : cols, c = i % cols;
|
|
8
|
+
return { x: (c - (inRow - 1) / 2) * gap, y: (r - (rows - 1) / 2) * gap };
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
// reach gives how far from the middle the counters of a cluster of up to max counters go.
|
|
12
|
+
export const reach = (max, gap) => Math.max(0, ...Array.from({ length: max }, (_, n) => Math.max(...cluster(n + 1, gap).map(p => Math.hypot(p.x, p.y)))));
|
|
13
|
+
|
|
14
|
+
// grid sets counters in rows of cols from the top left, the way a tray holds them.
|
|
15
|
+
export const grid = (i, cols, gap) => ({ x: (i % cols + 0.5) * gap, y: (Math.floor(i / cols) + 0.5) * gap });
|
|
16
|
+
|
|
17
|
+
// heap sets counters in a pile that narrows to the top, with these rows from the bottom.
|
|
18
|
+
export const HEAP = [5, 5, 4, 3, 2, 1];
|
|
19
|
+
export function heap(i, gap) {
|
|
20
|
+
let row = 0, left = i;
|
|
21
|
+
while (row < HEAP.length - 1 && left >= HEAP[row]) { left -= HEAP[row]; row++; }
|
|
22
|
+
const n = HEAP[row] ?? 1, shift = row % 2 && n === HEAP[row - 1] ? 0.5 : 0;
|
|
23
|
+
return { x: (left - (n - 1) / 2 + shift) * gap * 0.86, y: -row * gap * 0.64 };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The gap between two blocks of a figure.
|
|
27
|
+
const SPACE = 28;
|
|
28
|
+
// arrange tries each way to set out the blocks, one under another, side by side, or the last block beside the
|
|
29
|
+
// others, with each block's own ways, and keeps the one that fits the box w by h at the largest scale.
|
|
30
|
+
export function arrange(blocks, w, h) {
|
|
31
|
+
const combos = blocks.reduce((all, ways) => all.flatMap(c => ways.map(v => [...c, v])), [[]]);
|
|
32
|
+
let best = null;
|
|
33
|
+
const offer = (cw, ch, items) => { const scale = Math.min(w / cw, h / ch); if (!best || scale > best.scale + 1e-6) best = { scale, w: cw, h: ch, items }; };
|
|
34
|
+
const column = vs => { const cw = Math.max(...vs.map(v => v.w)); let y = 0; return { w: cw, h: vs.reduce((s, v) => s + v.h, 0) + SPACE * (vs.length - 1), items: vs.map(v => { const it = { v, x: (cw - v.w) / 2, y }; y += v.h + SPACE; return it; }) }; };
|
|
35
|
+
for (const vs of combos) {
|
|
36
|
+
const col = column(vs); offer(col.w, col.h, col.items);
|
|
37
|
+
if (vs.length < 2) continue;
|
|
38
|
+
const rh = Math.max(...vs.map(v => v.h)); let x = 0;
|
|
39
|
+
offer(vs.reduce((s, v) => s + v.w, 0) + SPACE * (vs.length - 1), rh, vs.map(v => { const it = { v, x, y: (rh - v.h) / 2 }; x += v.w + SPACE; return it; }));
|
|
40
|
+
if (vs.length < 3) continue;
|
|
41
|
+
const main = column(vs.slice(0, -1)), side = vs.at(-1), sh = Math.max(main.h, side.h);
|
|
42
|
+
offer(main.w + SPACE + side.w, sh, [...main.items.map(it => ({ ...it, y: it.y + (sh - main.h) / 2 })), { v: side, x: main.w + SPACE, y: (sh - side.h) / 2 }]);
|
|
43
|
+
}
|
|
44
|
+
return best;
|
|
45
|
+
}
|
package/src/families.mjs
ADDED
package/src/i18n/en.yaml
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
hint: Move the figure and watch the numbers follow it.
|
|
2
|
+
tab_map: Figure
|
|
3
|
+
map_data: Data
|
|
4
|
+
map_view: View
|
|
5
|
+
chronology: Contents
|
|
6
|
+
layout_center: Figure in the middle
|
|
7
|
+
view_reset: Reset
|
|
8
|
+
hesap_start: Start
|
|
9
|
+
hesap_time: Time
|
|
10
|
+
hesap_reset: Start again
|
|
11
|
+
hesap_undo: Undo
|
|
12
|
+
hesap_hint: Hint
|
|
13
|
+
hesap_another: Another one
|
|
14
|
+
hesap_solved: Solved
|
|
15
|
+
hesap_not-yet: Not solved yet.
|
|
16
|
+
counters_lead: "Tap and drag the counters, and watch the numbers follow them."
|
|
17
|
+
counters_whole: Whole
|
|
18
|
+
counters_first: First part
|
|
19
|
+
counters_second: Second part
|
|
20
|
+
counters_empty: Empty cells
|
|
21
|
+
counters_added: Blue added
|
|
22
|
+
counters_found: Splits found
|
|
23
|
+
counters_ways: Splits in all
|
|
24
|
+
counters_hands-first: Left hand
|
|
25
|
+
counters_hands-second: Right hand
|
|
26
|
+
counters_hands-whole: Beads
|
|
27
|
+
counters_one-first: Counters
|
|
28
|
+
counters_one-found: Pairs found
|
|
29
|
+
counters_one-ways: Pairs in all
|
|
30
|
+
counters_two-first: Red
|
|
31
|
+
counters_two-second: Blue
|
|
32
|
+
counters_cup-first: Part in sight
|
|
33
|
+
counters_cup-second: Hidden part
|
|
34
|
+
counters_cup-added: Blue added
|
|
35
|
+
counters_pins-first: Standing
|
|
36
|
+
counters_pins-empty: Knocked down
|
|
37
|
+
counters_cars-first: Parked
|
|
38
|
+
counters_cars-empty: Free spaces
|
|
39
|
+
counters_ctl-whole: Whole
|
|
40
|
+
counters_swap: Swap
|
|
41
|
+
counters_fill: Fill the second frame
|
|
42
|
+
counters_unfill: Empty the second frame
|
|
43
|
+
counters_lift: Lift the cup
|
|
44
|
+
counters_lower: Put the cup back
|
|
45
|
+
counters_check: Check
|
|
46
|
+
counters_blue: Blue counters
|
|
47
|
+
counters_tray: Tray
|
|
48
|
+
counters_pile: Pile
|
|
49
|
+
counters_cup: Cup
|
|
50
|
+
counters_counter: Counter
|
|
51
|
+
counters_car: Car
|
|
52
|
+
counters_cell: "Cell {x}"
|
|
53
|
+
counters_pin-up: "Pin {x}, standing"
|
|
54
|
+
counters_pin-down: "Pin {x}, knocked down"
|
|
55
|
+
counters_free: Free
|
|
56
|
+
counters_pair: "{a} and {b}"
|
|
57
|
+
counters_list-splits: "Splits of {x}"
|
|
58
|
+
counters_list-pairs: "Pairs that make {x}"
|
|
59
|
+
counters_goal-make-whole: "The red tray holds {part}. Set the blue counters so that the frame holds {whole}, then press Check."
|
|
60
|
+
counters_goal-make-whole-two: "The red tray holds {part}. Set the blue counters so that the two frames hold {whole}, then press Check."
|
|
61
|
+
counters_goal-hidden-part: "The whole is {whole}, and the part in sight is {part}. Build the part under the cup in the tray, then lift the cup."
|
|
62
|
+
counters_note-short: Some cells are still empty.
|
|
63
|
+
counters_note-over: Some counters found no cell.
|
|
64
|
+
counters_note-more: The tray holds more counters than the cup.
|
|
65
|
+
counters_note-fewer: The tray holds fewer counters than the cup.
|
|
66
|
+
counters_hint-make-whole: "Count on from {part} to {whole}. Each number you say after {part} is one blue counter."
|
|
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
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
hint: Şekli hareket ettirin ve sayıların onu izleyişine bakın.
|
|
2
|
+
tab_map: Şekil
|
|
3
|
+
map_data: Veri
|
|
4
|
+
map_view: Görünüm
|
|
5
|
+
chronology: İçindekiler
|
|
6
|
+
layout_center: Şekil ortada
|
|
7
|
+
view_reset: Sıfırla
|
|
8
|
+
hesap_start: Başlat
|
|
9
|
+
hesap_time: Zaman
|
|
10
|
+
hesap_reset: Baştan başla
|
|
11
|
+
hesap_undo: Geri al
|
|
12
|
+
hesap_hint: İpucu
|
|
13
|
+
hesap_another: Bir tane daha
|
|
14
|
+
hesap_solved: Çözüldü
|
|
15
|
+
hesap_not-yet: Henüz çözülmedi.
|
|
16
|
+
counters_lead: "Sayaçlara dokunun, onları sürükleyin ve sayıların onları nasıl izlediğine bakın."
|
|
17
|
+
counters_whole: Bütün
|
|
18
|
+
counters_first: Birinci parça
|
|
19
|
+
counters_second: İkinci parça
|
|
20
|
+
counters_empty: Boş hücreler
|
|
21
|
+
counters_added: Eklenen mavi
|
|
22
|
+
counters_found: Bulunan ayrımlar
|
|
23
|
+
counters_ways: Tüm ayrımlar
|
|
24
|
+
counters_hands-first: Sol el
|
|
25
|
+
counters_hands-second: Sağ el
|
|
26
|
+
counters_hands-whole: Boncuklar
|
|
27
|
+
counters_one-first: Sayaçlar
|
|
28
|
+
counters_one-found: Bulunan ikililer
|
|
29
|
+
counters_one-ways: Tüm ikililer
|
|
30
|
+
counters_two-first: Kırmızı
|
|
31
|
+
counters_two-second: Mavi
|
|
32
|
+
counters_cup-first: Görünen parça
|
|
33
|
+
counters_cup-second: Gizli parça
|
|
34
|
+
counters_cup-added: Eklenen mavi
|
|
35
|
+
counters_pins-first: Ayakta
|
|
36
|
+
counters_pins-empty: Devrilen
|
|
37
|
+
counters_cars-first: Park eden
|
|
38
|
+
counters_cars-empty: Boş yerler
|
|
39
|
+
counters_ctl-whole: Bütün
|
|
40
|
+
counters_swap: Yer değiştir
|
|
41
|
+
counters_fill: İkinci çerçeveyi doldur
|
|
42
|
+
counters_unfill: İkinci çerçeveyi boşalt
|
|
43
|
+
counters_lift: Bardağı kaldır
|
|
44
|
+
counters_lower: Bardağı geri koy
|
|
45
|
+
counters_check: Kontrol et
|
|
46
|
+
counters_blue: Mavi sayaçlar
|
|
47
|
+
counters_tray: Tepsi
|
|
48
|
+
counters_pile: Yığın
|
|
49
|
+
counters_cup: Bardak
|
|
50
|
+
counters_counter: Sayaç
|
|
51
|
+
counters_car: Araba
|
|
52
|
+
counters_cell: "Hücre {x}"
|
|
53
|
+
counters_pin-up: "Lobut {x}, ayakta"
|
|
54
|
+
counters_pin-down: "Lobut {x}, devrik"
|
|
55
|
+
counters_free: Boş
|
|
56
|
+
counters_pair: "{a} ve {b}"
|
|
57
|
+
counters_list-splits: "{x} sayısının ayrımları"
|
|
58
|
+
counters_list-pairs: "{x} yapan ikililer"
|
|
59
|
+
counters_goal-make-whole: "Kırmızı tepside {part} sayaç var. Çerçeve {whole} sayaç tutacak biçimde mavi sayaçları ayarlayın, sonra Kontrol et düğmesine basın."
|
|
60
|
+
counters_goal-make-whole-two: "Kırmızı tepside {part} sayaç var. İki çerçeve {whole} sayaç tutacak biçimde mavi sayaçları ayarlayın, sonra Kontrol et düğmesine basın."
|
|
61
|
+
counters_goal-hidden-part: "Bütün {whole}, görünen parça {part}. Bardağın altındaki parçayı tepside kurun, sonra bardağı kaldırın."
|
|
62
|
+
counters_note-short: Bazı hücreler hâlâ boş.
|
|
63
|
+
counters_note-over: Bazı sayaçlara hücre kalmadı.
|
|
64
|
+
counters_note-more: Tepside bardaktakinden çok sayaç var.
|
|
65
|
+
counters_note-fewer: Tepside bardaktakinden az sayaç var.
|
|
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
|
+
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/index.mjs
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Hesap's Node half, the engine module kitap loads. A page names a scene under the hesap key, and the family that
|
|
2
|
+
// owns the scene reads the rest of the page's fields, checks them and says what each link in the text shows when
|
|
3
|
+
// the page opens.
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { fileURLToPath } from 'url';
|
|
6
|
+
import { schema } from '@openbooknetwork/kitap';
|
|
7
|
+
import FAMILIES from './families.mjs';
|
|
8
|
+
import { LINK, list, links } from './node.mjs';
|
|
9
|
+
|
|
10
|
+
const { z, check } = schema;
|
|
11
|
+
const PKG = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
12
|
+
const family = id => FAMILIES.find(f => f.id === id);
|
|
13
|
+
// A page names a scene as <family>/<scene>, such as counters/bonds. A family whose one scene has the family's name is
|
|
14
|
+
// named alone.
|
|
15
|
+
const nameOf = (fam, scene) => scene === fam.id ? scene : `${fam.id}/${scene}`;
|
|
16
|
+
const SCENES = FAMILIES.flatMap(f => f.scenes.map(s => nameOf(f, s)));
|
|
17
|
+
function owner(name) {
|
|
18
|
+
const [id, scene, more] = name.split('/'), fam = family(id), own = scene ?? id;
|
|
19
|
+
return fam && more === undefined && fam.scenes.includes(own) ? { fam, scene: own } : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const PageHesap = z.object({ scene: z.string() }).passthrough();
|
|
23
|
+
|
|
24
|
+
// has remembers which links each page holds, so finish checks only those.
|
|
25
|
+
const HAS = new Map(), keyOf = (ctx, pid) => `${ctx.where}/${pid}`;
|
|
26
|
+
|
|
27
|
+
function readPage(fields, info, ctx) {
|
|
28
|
+
const { scene: name, ...rest } = check(PageHesap, fields, info.at), own = owner(name);
|
|
29
|
+
if (!own) { ctx.fail(info.at, `scene is "${name}", the scenes are ${list(SCENES)}`); return { data: {} }; }
|
|
30
|
+
const { fam, scene } = own, r = fam.read({ scene, ...check(fam.schema, rest, info.at) }, info, ctx);
|
|
31
|
+
HAS.set(keyOf(ctx, info.pid), r.has);
|
|
32
|
+
return { data: { ...r.data, scene, family: fam.id }, links: links(r.has, r.offers) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// A text types into each link what the page shows when it opens, and a text that differs is told what to write.
|
|
36
|
+
function finish({ pages, texts }, ctx) {
|
|
37
|
+
// A page whose page.yaml failed has no family, and its problem is printed already.
|
|
38
|
+
for (const pg of pages.filter(p => p.hesap?.family)) {
|
|
39
|
+
const fam = family(pg.hesap.family), has = HAS.get(keyOf(ctx, pg.id));
|
|
40
|
+
for (const [lang, text] of Object.entries(texts[pg.id] ?? {})) for (const [, name, id] of text.matchAll(LINK)) {
|
|
41
|
+
// Kitap reports a link the page does not hold, so the family is asked only about its own.
|
|
42
|
+
if (has && !has(id)) continue;
|
|
43
|
+
ctx.attempt(path.join(ctx.root, pg.dir), () => {
|
|
44
|
+
const want = fam.start(pg.hesap, lang, id);
|
|
45
|
+
if (want !== null && want !== undefined && name !== want) ctx.fail(`${pg.dir}/text/${lang}.md`, `[${name}](@${id}) differs from what the page shows at the start, write [${want}](@${id})`);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return {};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// A story's bundle holds the data and the colour families of the families its pages use. A story with no cover
|
|
53
|
+
// opens on the overview scene of its first page's family, or on its first page's figure.
|
|
54
|
+
function bundle(content) {
|
|
55
|
+
const data = {}, families = {}, from = {}, pages = (content.pages ?? []).filter(p => p.hesap?.family);
|
|
56
|
+
for (const id of new Set(pages.map(p => p.hesap.family))) {
|
|
57
|
+
const b = family(id).bundle?.(content) ?? {};
|
|
58
|
+
if (b.data) data[id] = b.data;
|
|
59
|
+
for (const [name, colour] of Object.entries(b.families ?? {})) {
|
|
60
|
+
if (from[name]) throw new Error(`hesap: the families ${from[name]} and ${id} both define the colour "${name}", rename one`);
|
|
61
|
+
from[name] = id; families[name] = colour;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const first = pages[0]?.hesap;
|
|
65
|
+
if (first) data.overview = data[first.family]?.overview ? { ...data[first.family].overview, family: first.family } : first;
|
|
66
|
+
return { data, families, credits: [] };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export default {
|
|
70
|
+
id: 'hesap',
|
|
71
|
+
dir: PKG,
|
|
72
|
+
schemas: { page: PageHesap },
|
|
73
|
+
ui: new URL('./i18n/', import.meta.url),
|
|
74
|
+
// The browser imports hesap's own modules and KaTeX's stylesheet through kitap's import map, from folders named
|
|
75
|
+
// after each package's version. A family that draws with a library of its own adds it here, so the library
|
|
76
|
+
// loads with that family alone.
|
|
77
|
+
client: { script: new URL('./client.js', import.meta.url), styles: new URL('./client.css', import.meta.url), module: true,
|
|
78
|
+
libraries: [['animejs', 'dist/bundles/anime.umd.min.js'], ['katex', 'dist/katex.min.js']],
|
|
79
|
+
imports: { 'hesap/': ['@openbooknetwork/hesap', 'src'], 'katex-dist/': ['katex', 'dist'] } },
|
|
80
|
+
read: { page: readPage, finish },
|
|
81
|
+
bundle,
|
|
82
|
+
};
|
package/src/kit/dom.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Small helpers for building the page: SVG and HTML elements, escaping and the icons the panel uses.
|
|
2
|
+
const NS = 'http://www.w3.org/2000/svg';
|
|
3
|
+
export const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
4
|
+
// svg makes an SVG element with its attributes and children.
|
|
5
|
+
export function svg(tag, attrs = {}, kids = []) {
|
|
6
|
+
const n = document.createElementNS(NS, tag);
|
|
7
|
+
for (const [k, v] of Object.entries(attrs)) if (v !== undefined && v !== null) n.setAttribute(k, v);
|
|
8
|
+
n.append(...kids);
|
|
9
|
+
return n;
|
|
10
|
+
}
|
|
11
|
+
// h makes an HTML element. A text child is written as text, so it needs no escaping.
|
|
12
|
+
export function h(tag, attrs = {}, kids = []) {
|
|
13
|
+
const n = document.createElement(tag);
|
|
14
|
+
for (const [k, v] of Object.entries(attrs)) if (v !== undefined && v !== null && v !== false) n.setAttribute(k, v === true ? '' : v);
|
|
15
|
+
n.append(...[kids].flat());
|
|
16
|
+
return n;
|
|
17
|
+
}
|
|
18
|
+
const ICONS = {
|
|
19
|
+
reset: '<path d="M5.6 9.5A7 7 0 1 1 5 13.5" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/><path d="M3.5 4.5v6.5h6.5z"/>',
|
|
20
|
+
tick: '<path d="M4.5 12.5l5 5 10-11" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/>',
|
|
21
|
+
undo: '<path d="M9 7H15a5 5 0 0 1 0 10H8" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/><path d="M10 2.5v9L4 7z"/>',
|
|
22
|
+
};
|
|
23
|
+
export function icon(id) {
|
|
24
|
+
const s = svg('svg', { viewBox: '0 0 24 24', 'aria-hidden': 'true', fill: 'currentColor', class: 'hesap-icon' });
|
|
25
|
+
s.innerHTML = ICONS[id];
|
|
26
|
+
return s;
|
|
27
|
+
}
|
|
28
|
+
// svgPoint gives a pointer event's place in the coordinates of an SVG element.
|
|
29
|
+
export function svgPoint(node, e) {
|
|
30
|
+
const p = new DOMPoint(e.clientX, e.clientY).matrixTransform(node.getScreenCTM().inverse());
|
|
31
|
+
return { x: p.x, y: p.y };
|
|
32
|
+
}
|
package/src/kit/drag.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Dragging with pointer events, the same by mouse and by touch.
|
|
2
|
+
// drag lets the reader drag node. point turns an event into the family's coordinates. start may return false to
|
|
3
|
+
// refuse the drag, and raise moves the node in the page before the pointer is captured, because moving an element
|
|
4
|
+
// releases its capture.
|
|
5
|
+
export function drag(node, { point, start, move, drop, raise }) {
|
|
6
|
+
let held = null;
|
|
7
|
+
// drop gets the event that ended the drag, so a family can tell a release from a cancel.
|
|
8
|
+
const end = e => { if (held === null) return; held = null; node.classList.remove('drag'); drop?.(e); };
|
|
9
|
+
node.addEventListener('pointerdown', e => {
|
|
10
|
+
if (e.button) return;
|
|
11
|
+
const p = point(e);
|
|
12
|
+
if (start?.(p, e) === false) return;
|
|
13
|
+
e.preventDefault(); e.stopPropagation();
|
|
14
|
+
raise?.();
|
|
15
|
+
try { node.setPointerCapture(e.pointerId); } catch {} // A pointer that a script made has nothing to capture.
|
|
16
|
+
held = e.pointerId; node.classList.add('drag');
|
|
17
|
+
});
|
|
18
|
+
node.addEventListener('pointermove', e => {
|
|
19
|
+
if (held !== e.pointerId) return;
|
|
20
|
+
if (e.pointerType === 'mouse' && !e.buttons) return end(e); // The button came up where the page could not see it.
|
|
21
|
+
move(point(e), e);
|
|
22
|
+
});
|
|
23
|
+
for (const ev of ['pointerup', 'pointercancel', 'lostpointercapture']) node.addEventListener(ev, end);
|
|
24
|
+
return { held: () => held !== null, end };
|
|
25
|
+
}
|
|
26
|
+
const ARROWS = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] };
|
|
27
|
+
// nudge moves a focused node with the arrow keys. The keys stop at the node, because the book turns the page on
|
|
28
|
+
// Left and Right. rest runs once the keys go quiet.
|
|
29
|
+
export function nudge(node, { step, rest, idle = 800 }) {
|
|
30
|
+
let timer = 0;
|
|
31
|
+
node.addEventListener('keydown', e => {
|
|
32
|
+
const d = ARROWS[e.key];
|
|
33
|
+
if (!d) return;
|
|
34
|
+
e.preventDefault(); e.stopPropagation();
|
|
35
|
+
step(d[0], d[1], e);
|
|
36
|
+
if (rest) { clearTimeout(timer); timer = setTimeout(rest, idle); }
|
|
37
|
+
});
|
|
38
|
+
node.addEventListener('blur', () => { if (timer) { clearTimeout(timer); timer = 0; rest?.(); } });
|
|
39
|
+
return { cancel: () => { clearTimeout(timer); timer = 0; } };
|
|
40
|
+
}
|