An AI skill that turns books into animated, narrated, interactive web experiences
JavaScript ai-agentsai-educationanimationclaudeclaude-codeclaude-skillsedtecheducationinteractive-textbookscormtext-to-video
// A 2 × 2 matrix A carrying the whole plane, drawn from one state: the matrix in brackets (and, when given, a vector x
// and the product Ax beside it) and the plane, where every grid line, the unit square, a small shape and some points are
// moved by A while the original grid stays faint behind. The columns of A are the green and violet arrows: their tips are
// where [1, 0] and [0, 1] land. Drag a tip and the grid and the numbers follow; scrub a number and the grid follows.
// The beat moves it with g.to(); a question turns the reader's hands on with g.live(true). Same shape as linsys.js.
// Loads after engine.js and math.js (it uses plane()).
//
// Inverses (chapters 26–28), all optional, so chapter 10's uses are unchanged:
// pre: M the plane was moved by M first: the grid, square, flag and points show A·M (keys p00 p01 p10 p11 in g.v,
// tweenable like A's), while the arrows and tips stay A's columns. With pre = A0 and A going from I to
// A0⁻¹ the moved plane comes home: that is "A⁻¹ undoes A0". The moved axes are chalk in this mode.
// fracs: true A's numbers show exact fractions (1/2) at rest instead of 0.5.
// name: 'B' the letter under the matrix (and in the inverse panel).
// lost: true when ad − bc = 0 (and A is not all zeros), the line of points A sends to (0, 0) is drawn dashed red on
// the plane: the lost direction (g.parts.lost; fade it in on a word, live it simply shows).
// g.inverse({ at: [x, y], size }) builds a live panel: ad − bc = 2·1 − 1·1 = 1 over A⁻¹ = 1/1 · [d −b; −c a] = [ … ];
// its parts (each a group to show on a word) are in g.inv: det, lhs, scale, adj, eq, res, none,
// plus adjCells and resCells (the four entries of each matrix, row by row, as g2val), xs and mid (layout);
// ("no inverse: ad − bc = 0", shown in place of scale … res when ad − bc = 0). The adjusted matrix keeps
// each number's column colour, so the swap of a and d and the sign change of b and c are visible.
// g.det(), g.inverseOf() (null when ad − bc = 0), g.total() (the plane's matrix A·pre), g.turn(d0, d1, at, dur, ease, 'p')
// turns pre instead of A.
// Labels on the plane (chapters 23–25 asked for these; all optional):
// names: { x: 'column 2 of B', ax: 'column 2 of AB' }, or a function of the state v returning that object: what the
// x and Ax labels call their points ("x = (…)", "Ax = (…)" by default). g.names(n) changes it later.
// avoid: [[x, y], …] in plane units, or a function of v returning them: extra dots the chapter draws (mm's numbered
// dots) that the labels keep clear of, like the tips. g.avoid(a) changes it later.
// Labels never pile up at one spot: a column label hides while its tip is at the origin, the x label hides while x is
// at the origin or on Ax while Ax's label shows (it names the spot), and the Ax label hides while both are at the origin. Hiding uses
// the display attribute, so a chapter's own opacity or visibility on these labels is untouched.
// Exact fractions: g2frac(v) → [n, d] or null; g2parts(v) → math parts (whole, F(n, d), or one decimal while moving).
// g2mid(e): e scales and turns about its own middle (pulse it without it sliding); numbers (g2val, the scrubbable ones) have it.
const G2_COLS = [COL.irr, COL.real], G2_AX = COL.task;
// A small flag: a pole and a pennant pointing right, so a flip or a turn shows at once.
// It stands beside the unit square (x 1.4 … 2.3), not on it, so the square and the flag never hide each other.
const G2_FLAG = [[1.4, .25], [1.55, .25], [1.55, 1.05], [2.3, 1.3], [1.55, 1.55], [1.55, 1.75], [1.4, 1.75]];
const g2frac = v => { if (!isFinite(v)) return null; for (let d = 1; d <= 200; d++) { const n = Math.round(v * d); if (Math.abs(v * d - n) < 1e-7) return [n, d]; } return null; };
const g2fmt = n => { const r = Math.round(n * 10) / 10; return (r < 0 ? '−' : '') + (Number.isInteger(r) ? String(Math.abs(r)) : Math.abs(r).toFixed(1)); };
const g2parts = v => {
const f = g2frac(v);
if (!f) return [Math.abs(v) >= 1000 ? (v < 0 ? '−' : '') + '999+' : g2fmt(v)];
const [n, d] = f;
return d === 1 ? [num(n)] : n < 0 ? ['−', F(-n, d)] : [F(n, d)];
};
const g2key = ps => ps.map(q => typeof q === 'string' ? q : q.f.join('/')).join('');
// A number drawn as math parts, rebuilt only when what it shows changes.
// Scale and turn an element about the middle of its own box (pulse, flash), not about the stage's corner.
const g2mid = e => { e.style.transformBox = 'fill-box'; e.style.transformOrigin = 'center'; return e; };
function g2val(parent, { x = 0, y = 0, size = 40, fill = COL.chalk, anchor = 'middle' } = {}) {
const g = g2mid(G(parent, {}));
let key = null;
return { g, set(v, color = fill, parts = g2parts(v)) { const k = g2key(parts) + color; if (k === key) return; key = k; g.replaceChildren(); M(g, parts, { x, y, size, fill: color, anchor }); } };
}
function grid2(p, { A = [[1, 0], [0, 1]], x = null, mat = [90, 300], size = 54, plane: po = {}, grid = true, square = true, shape = false,
units = true, pts = [], t0 = .1, hidePlane = false, result = true, showMat = true, brackets = false, pre = null, fracs = false, name = 'A', lost = false,
names = null, avoid = null } = {}) {
const Pm = pre || [[1, 0], [0, 1]];
const v = { a00: A[0][0], a01: A[0][1], a10: A[1][0], a11: A[1][1], x0: x ? x[0] : 0, x1: x ? x[1] : 0, p00: Pm[0][0], p01: Pm[0][1], p10: Pm[1][0], p11: Pm[1][1] };
const RANGE = { a00: 9, a01: 9, a10: 9, a11: 9, x0: 9, x1: 9 }, K = 14; // grid lines k = −K … K
const holder = G(p, { o: hidePlane ? 0 : 1 });
const P2 = plane(holder, { cx: 1160, cy: 450, u: 52, x0: -6, x1: 6, y0: -6, y1: 6, t0, ...po });
const { PX, PY } = P2, box = [P2.x0 - .4, P2.x1 + .4, P2.y0 - .4, P2.y1 + .4];
const svg = $('stage'), listeners = [], slots = [], drags = [];
let live = false, plan = { ...v };
const fmt = g2fmt;
const setText = (e, s) => { if (e.textContent !== s) e.textContent = s; };
const setD = (e, d) => { if (e.getAttribute('d') !== d) e.setAttribute('d', d); };
const clamp = (k, n) => Math.max(-RANGE[k], Math.min(RANGE[k], n));
const pt = e => { const q = svg.createSVGPoint(); q.x = e.clientX; q.y = e.clientY; const w = q.matrixTransform(P2.g.getScreenCTM().inverse()); return [(w.x - P2.cx) / P2.u, (P2.cy - w.y) / P2.u]; };
const map = ([a, b]) => [v.a00 * a + v.a01 * b, v.a10 * a + v.a11 * b];
const tmap = ([a, b]) => map([v.p00 * a + v.p01 * b, v.p10 * a + v.p11 * b]); // the plane: pre first, then A
const XY = ([a, b]) => `${PX(a).toFixed(1)} ${PY(b).toFixed(1)}`;
/* ---------- numbers you can scrub ---------- */
function slot(g, key, x, y, fill) {
const bx = mk('rect', { x: x - 44, y: y - size * .85, width: 88, height: size * 1.1, rx: 10, fill: 'transparent' }, g);
const t = g2mid(T(g, '', { x, y, size, fill, font: MATH, anchor: 'middle' }));
t.style.pointerEvents = 'none';
bx.setAttribute('aria-label', key);
const fv = fracs ? g2val(g, { x, y, size: size * .8, fill }) : null;
if (fv) fv.g.style.pointerEvents = 'none';
const s = { key, t, box: bx, set: () => {
const fr = fv && g2frac(v[key]);
if (fr && fr[1] > 1) { t.style.display = 'none'; fv.g.style.display = ''; fv.set(v[key], t.getAttribute('fill')); return; }
if (fv) { fv.g.style.display = 'none'; t.style.display = ''; }
const str = fmt(v[key]); setText(t, str); const fs = String(str.length > 2 ? Math.round(size * .74) : size); if (t.getAttribute('font-size') !== fs) t.setAttribute('font-size', fs); } };
let drag = null;
bx.addEventListener('pointerdown', e => { if (!live || !s.on) return; e.preventDefault(); drag = { x: e.clientX, from: Math.round(v[key]) }; bx.setPointerCapture(e.pointerId); });
bx.addEventListener('pointermove', e => { if (!drag) return; const k = svg.getScreenCTM().a; edit({ [key]: clamp(key, drag.from + Math.round((e.clientX - drag.x) / k / 22)) }); });
const end = () => { drag = null; };
bx.addEventListener('pointerup', end); bx.addEventListener('lostpointercapture', end);
bx.addEventListener('keydown', e => {
if (!live || !s.on) return;
if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); bx.blur(); P.keys?.(e); return; }
const d = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1 }[e.key];
if (!d) return;
e.preventDefault(); e.stopPropagation();
edit({ [key]: clamp(key, Math.round(v[key]) + d) });
});
slots.push(s);
return s;
}
/* ---------- the matrix (and x, Ax) in brackets ---------- */
const Mx = G(p, { o: 0 }), cw = size * 1.7, rh = size * 1.35;
const bracket = (x0, w, color = COL.chalk) => {
const top = mat[1] - size * .95, bot = mat[1] + rh + size * .35;
path(Mx, `M${x0 + 14} ${top}H${x0}V${bot}H${x0 + 14}M${x0 + w - 14} ${top}H${x0 + w}V${bot}H${x0 + w - 14}`, { stroke: color, 'stroke-width': 3, fill: 'none' });
};
const [mx, my] = mat || [0, 0], lay = {};
if (mat) {
bracket(mx, cw * 2 + 20);
lay.A = [[0, 1].map(j => mx + 10 + cw * (j + .5)), [my, my + rh]];
[0, 1].forEach(i => [0, 1].forEach(j => slot(Mx, `a${i}${j}`, lay.A[0][j], my + rh * i, G2_COLS[j])));
T(Mx, name, { x: mx + cw + 10, y: my + rh + size * 1.25, size: 34, fill: COL.dim, font: MATH, anchor: 'middle', weight: 700 });
if (x) {
const xa = mx + cw * 2 + 44, wx = cw * .95;
bracket(xa, wx);
[0, 1].forEach(i => slot(Mx, `x${i}`, xa + wx / 2, my + rh * i, COL.chalk));
T(Mx, 'x', { x: xa + wx / 2, y: my + rh + size * 1.25, size: 34, fill: COL.dim, font: MATH, anchor: 'middle' }).setAttribute('font-style', 'italic');
lay.x = xa + wx / 2;
if (result) {
T(Mx, '=', { x: xa + wx + 40, y: my + rh / 2 + size * .3, size, fill: COL.chalk, font: MATH, anchor: 'middle' });
const xr = xa + wx + 80, wr = cw * 1.25;
bracket(xr, wr);
lay.r = xr + wr / 2;
lay.res = [0, 1].map(i => T(Mx, '', { x: xr + wr / 2, y: my + rh * i, size, fill: G2_AX, font: MATH, anchor: 'middle' }));
const lab = T(Mx, 'Ax', { x: xr + wr / 2, y: my + rh + size * 1.25, size: 34, fill: COL.dim, font: MATH, anchor: 'middle' });
lab.setAttribute('font-style', 'italic');
}
}
}
/* ---------- the plane: the moved grid, square, shape, points; the columns; x and Ax ---------- */
const layer = (o = 1) => G(P2.g, { o });
const gridG = layer(grid ? 1 : 0), sqG = layer(square ? 1 : 0), shG = layer(shape ? 1 : 0), unG = layer(units ? 1 : 0);
const lostG = layer(lost ? 1 : 0), ptG = layer(), colG = layer(), xG = layer(x ? 1 : 0);
const gl = path(gridG, '', { stroke: COL.chalk, 'stroke-opacity': .32, 'stroke-width': 1.6, fill: 'none' });
const axs = G2_COLS.map(c => path(gridG, '', { stroke: pre ? COL.chalk : c, 'stroke-opacity': pre ? .55 : .75, 'stroke-width': 3, fill: 'none' }));
const lostL = path(lostG, '', { stroke: COL.bad, 'stroke-width': 4, 'stroke-dasharray': '12 9', fill: 'none' });
const sq = path(sqG, '', { fill: COL.chalk, 'fill-opacity': .12, stroke: COL.chalk, 'stroke-opacity': .7, 'stroke-width': 2.5 });
const sh = path(shG, '', { fill: COL.chalk, 'fill-opacity': .45, stroke: COL.chalk, 'stroke-width': 2, 'stroke-linejoin': 'round' });
path(unG, `M${PX(0)} ${PY(0)}H${PX(1)}M${PX(0)} ${PY(0)}V${PY(1)}`, { stroke: COL.chalk, 'stroke-opacity': .45, 'stroke-width': 3, 'stroke-dasharray': '5 6' });
[[.5, 0, '(1, 0)', 0, -12, 'middle'], [0, .5, '(0, 1)', -10, 7, 'end']].forEach(([a, b, s, dx, dy, anchor]) => T(unG, s, { x: PX(a) + dx, y: PY(b) + dy, size: 20, fill: COL.dim, font: MATH, anchor })); // beside the dashed arrows, clear of the axis numbers
const arrowD = (a, c, hl0 = 18) => {
const A1 = [PX(a[0]), PY(a[1])], C = [PX(c[0]), PY(c[1])], L = Math.hypot(C[0] - A1[0], C[1] - A1[1]);
if (L < 1) return '';
const ux = (C[0] - A1[0]) / L, uy = (C[1] - A1[1]) / L, hl = Math.min(hl0, L * .45);
return `M${A1[0]} ${A1[1]}L${C[0] - ux * hl * .6} ${C[1] - uy * hl * .6}M${C[0] - hl * ux - 9 * uy} ${C[1] - hl * uy + 9 * ux}L${C[0]} ${C[1]}L${C[0] - hl * ux + 9 * uy} ${C[1] - hl * uy - 9 * ux}Z`;
};
const arrow = (g, color, w = 5, dash) => path(g, '', { stroke: color, fill: color, 'stroke-width': w, 'stroke-linejoin': 'round', ...(dash ? { 'stroke-dasharray': dash, 'fill-opacity': .5 } : {}) });
const ptDots = pts.map(q => {
const g = G(ptG, {});
mk('circle', { r: 8, fill: COL.chalk, stroke: COL.board, 'stroke-width': 2 }, g);
const lab = q.label ? T(g, q.label, { x: 12, y: -12, size: 22, fill: COL.chalk, font: MATH }) : null;
return { g, q, lab };
});
const combo = [arrow(xG, G2_COLS[0], 4, '10 8'), arrow(xG, G2_COLS[1], 4, '10 8')]; // x·col 1, then y·col 2 from its tip
const axArrow = arrow(xG, G2_AX, 6);
const xRing = G(xG, {});
mk('circle', { r: 22, fill: 'transparent' }, xRing);
mk('circle', { r: 9, fill: COL.board, stroke: COL.chalk, 'stroke-width': 3 }, xRing);
const xLab = T(xG, '', { size: 24, fill: COL.chalk, font: MATH, anchor: 'start' });
const axDot = G(xG, {});
mk('circle', { r: 10, fill: G2_AX, stroke: COL.board, 'stroke-width': 3 }, axDot);
const axLab = T(xG, '', { size: 26, fill: G2_AX, font: MATH, weight: 600 });
[...combo, axArrow, axDot, axLab, xLab].forEach(e => { e.style.pointerEvents = 'none'; }); // only the ring under x takes the pointer
const cols = G2_COLS.map(c => arrow(colG, c));
const tips = G2_COLS.map(c => {
const g = G(colG, {});
mk('circle', { r: 24, fill: 'transparent' }, g);
const ring = mk('circle', { r: 14, fill: 'none', stroke: c, 'stroke-width': 3, 'stroke-dasharray': '4 4' }, g);
ring.style.opacity = 0;
g._ring = ring;
return g;
});
const tipLabels = [0, 1].map(() => G(colG, {}));
// Drag in the plane: a column tip or x follows the pointer (to a tenth), and lands on the nearest whole numbers when let go.
const dragIn = (el, keys, what) => {
let on = false;
const to = ([X, Y], snap) => { const r = n => snap ? Math.round(n) : Math.round(n * 10) / 10; edit({ [keys[0]]: clamp(keys[0], r(X)), [keys[1]]: clamp(keys[1], r(Y)) }); };
el.addEventListener('pointerdown', e => { if (!live || !drags.includes(what)) return; e.preventDefault(); on = true; el.setPointerCapture(e.pointerId); to(pt(e), false); });
el.addEventListener('pointermove', e => { if (on) to(pt(e), false); });
const end = () => { if (!on) return; on = false; to([v[keys[0]], v[keys[1]]], true); };
el.addEventListener('pointerup', end); el.addEventListener('lostpointercapture', end);
};
dragIn(tips[0], ['a00', 'a10'], 'cols'); dragIn(tips[1], ['a01', 'a11'], 'cols'); dragIn(xRing, ['x0', 'x1'], 'x');
/* ---------- one state, drawn everywhere ---------- */
// The part of the line P + s·d, s in [s0, s1], inside the box, as a path piece (Liang–Barsky).
const seg = (P0, d, s0, s1) => {
let a = s0, b = s1;
for (const [p0, dd, lo, hi] of [[P0[0], d[0], box[0], box[1]], [P0[1], d[1], box[2], box[3]]]) {
if (Math.abs(dd) < 1e-9) { if (p0 < lo || p0 > hi) return ''; continue; }
let t1 = (lo - p0) / dd, t2 = (hi - p0) / dd;
if (t1 > t2) [t1, t2] = [t2, t1];
a = Math.max(a, t1); b = Math.min(b, t2);
if (a > b) return '';
}
return `M${XY([P0[0] + a * d[0], P0[1] + a * d[1]])}L${XY([P0[0] + b * d[0], P0[1] + b * d[1]])}`;
};
// A polygon cut to the box (Sutherland–Hodgman), so a big stretch never draws past the plane.
const poly = pts => {
for (const [k, lim, keep] of [[0, box[0], 1], [0, box[1], -1], [1, box[2], 1], [1, box[3], -1]]) {
const out = [];
pts.forEach((a, i) => {
const b = pts[(i + 1) % pts.length], fa = (a[k] - lim) * keep, fb = (b[k] - lim) * keep;
if (fa >= 0) out.push(a);
if (fa * fb < 0) { const t = fa / (fa - fb); out.push([a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]); }
});
pts = out;
if (!pts.length) return '';
}
return 'M' + pts.map(XY).join('L') + 'Z';
};
// The labels beside the tips (col 1, col 2, Ax, x) go where they cover least: each tries eight places around its
// point and takes the one over the fewest arrow and axis pixels and clear of the labels already placed, preferring
// the side the arrow points to. A function of the state alone, so seeking and playing give the same frame.
const unitBoxes = units ? [[PX(.5) - 28, PY(0) - 30, 56, 22], [PX(0) - 64, PY(.5) - 10, 56, 22]] : [];
const tickBoxes = po.labels === false ? [] : [[PX(P2.x0) - 10, P2.cy + 8, PX(P2.x1) - PX(P2.x0) + 20, 22], [P2.cx - 36, PY(P2.y1) - 10, 30, PY(P2.y0) - PY(P2.y1) + 20]];
const widthOf = (e, n, size) => { let w = 0; try { w = e.getBBox().width; } catch (_) {} return w || n * size * .55; };
function placeLabels(c0, c1, ax) {
const pts = [], seg = (a, b, wt = 1) => {
const A1 = [PX(a[0]), PY(a[1])], B = [PX(b[0]), PY(b[1])], n = Math.max(1, Math.ceil(Math.hypot(B[0] - A1[0], B[1] - A1[1]) / 10));
for (let i = 0; i <= n; i++) pts.push([A1[0] + (B[0] - A1[0]) * i / n, A1[1] + (B[1] - A1[1]) * i / n, wt]);
};
seg([P2.x0, 0], [P2.x1, 0], .5); seg([0, P2.y0], [0, P2.y1], .5);
seg([0, 0], c0); seg([0, 0], c1);
if (x) { const m1 = [v.x0 * c0[0], v.x0 * c0[1]]; seg([0, 0], m1); seg(m1, ax); seg([0, 0], ax); }
if (shape) { const F = G2_FLAG.map(tmap); F.forEach((q, i) => seg(q, F[(i + 1) % F.length], 1.5)); seg(F[1], F[3], 1.5); seg(F[0], F[5], 1.5); } // the flag, outline and body
// the dots and handles themselves weigh most
const extra = (typeof avoid === 'function' ? avoid(v) : avoid) || [];
for (const q of [...(x ? [c0, c1, ax, [v.x0, v.x1]] : [c0, c1]), ...extra]) for (const [ox, oy] of [[0, 0], [-12, 0], [12, 0], [0, -12], [0, 12]]) pts.push([PX(q[0]) + ox, PY(q[1]) + oy, 4]);
const placed = [...unitBoxes.map(b => [...b, 120]), ...tickBoxes.map(b => [...b, 120])];
const over = (a, b) => Math.max(0, Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0])) * Math.max(0, Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]));
const place = (e, tip, dir, w, hh, baseline) => {
const [X, Y] = [PX(tip[0]), PY(tip[1])], gp = 14, n = Math.hypot(...dir) || 1, d = [dir[0] / n, -dir[1] / n];
const near = [[gp, -hh - 4], [gp, 6], [-w - gp, -hh - 4], [-w - gp, 6], [-w / 2, -hh - gp - 4], [-w / 2, gp + 6], [gp + 6, -hh / 2], [-w - gp - 6, -hh / 2]];
const ring = (k, cost) => near.map(([dx, dy]) => [dx + (dx > 0 ? 26 * k : dx < -w / 2 ? -26 * k : 0), dy + (dy > 0 ? 22 * k : -22 * k), cost]);
const cands = [...near.map(c => [...c, 0]), ...ring(1, 1.5), ...ring(2.2, 4)]; // farther rings, a little dearer: a crowded spot sends a label out
let best = null;
for (const [dx, dy, extra] of cands) {
const b = [X + dx, Y + dy, w, hh], cx = dx + w / 2, cy = dy + hh / 2, cn = Math.hypot(cx, cy) || 1;
let cost = extra + (1 - (cx * d[0] + cy * d[1]) / cn) * .6; // 0 straight ahead of the arrow … 1.2 behind it
for (const [px, py, wt] of pts) if (px > b[0] - 3 && px < b[0] + w + 3 && py > b[1] - 3 && py < b[1] + hh + 3) cost += wt;
for (const q of placed) cost += over(b, q) / (w * hh) * (q[4] || 200);
if (b[0] < 10 || b[0] + w > 1590 || b[1] < 10 || b[1] + hh > 890) cost += 100;
if (!best || cost < best[0] - 1e-9) best = [cost, b];
}
placed.push(best[1]);
put(e, { x: best[1][0], y: best[1][1] + baseline });
};
// one label per spot: a zero column, x = 0, or x sitting on Ax leave their names to what is already there
const near0 = q => Math.hypot(q[0], q[1]) < .12, same = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]) < .3;
const shown = (e, on) => { if (on) e.removeAttribute('display'); else { e.setAttribute('display', 'none'); put(e, { x: 0, y: 0 }); } return on; }; // hidden: an attribute and no place of its own, so a replay leaves the same markup
[c0, c1].forEach((c, j) => { const L = tipLabels[j]; if (shown(L, !near0(c)) && L.firstChild) place(L, c, c, widthOf(L, 5, 28), 32, 23); });
if (x) {
const xv = [v.x0, v.x1];
if (shown(axLab, !(near0(ax) && near0(xv)))) place(axLab, ax, ax, widthOf(axLab, axLab.textContent.length, 26), 30, 22);
const axSeen = axLab.getAttribute('display') !== 'none' && axLab.style.visibility !== 'hidden'; // x hands its name to Ax's label unless a chapter hid it (not its fading: that would make the frame depend on the path)
if (shown(xLab, !near0(xv) && !(axSeen && same(xv, ax)))) place(xLab, xv, xv, widthOf(xLab, xLab.textContent.length, 24), 28, 21);
}
}
/* ---------- the inverse, live: ad − bc and A⁻¹ = 1/(ad − bc) · [d −b; −c a] ---------- */
let inv = null;
function inverse({ at: [ix, iy] = [90, 520], size: s = 40 } = {}) {
const root = G(p, {}), part = () => G(root, {});
const det = part(), lhs = part(), scale = part(), adj = part(), eq = part(), res = part(), none = g2mid(part());
const rh = s * 1.6, mid = iy + s * 2.4 + rh / 2; // matrices: rows at mid ± rh/2
const xL = ix, xS = xL + s * 3.1, xA = xS + s * 1.9, cwA = s * 2, xE = xA + cwA * 2 + 36, xR = xE + s * 1.3, cwR = s * 2.1;
const brk = (g, x0, w) => { const top = mid - rh / 2 - s * .95, bot = mid + rh / 2 + s * .45; path(g, `M${x0 + 12} ${top}H${x0}V${bot}H${x0 + 12}M${x0 + w - 12} ${top}H${x0 + w}V${bot}H${x0 + w - 12}`, { stroke: COL.chalk, 'stroke-width': 2.5, fill: 'none' }); };
M(lhs, [name, E('−1'), ' ='], { x: xL, y: mid + s * .3, size: s, anchor: 'start' });
brk(adj, xA, cwA * 2 + 20); brk(res, xR, cwR * 2 + 20);
M(eq, ['='], { x: xE + s * .45, y: mid + s * .3, size: s, anchor: 'middle' });
const ax = j => xA + 10 + cwA * (j + .5), rx = j => xR + 10 + cwR * (j + .5), ry = i => mid - rh / 2 + i * rh + s * .3;
const A_ = [[0, 0], [0, 1], [1, 0], [1, 1]].map(([i, j]) => g2val(adj, { x: ax(j), y: ry(i), size: s * .9 }));
const R_ = [[0, 0], [0, 1], [1, 0], [1, 1]].map(([i, j]) => g2val(res, { x: rx(j), y: ry(i), size: s * .9 }));
const S_ = g2val(scale, { x: xS + s * .6, y: mid + s * .3, size: s * .9 });
const D_ = g2val(det, { x: ix, y: iy, size: s * .9, anchor: 'start' });
const N_ = T(none, 'no inverse: ad − bc = 0', { x: xS, y: mid + s * .3, size: s * .8, fill: COL.bad, weight: 600 });
const inner = [scale, adj, eq, res].map(g => { const k = G(g, {}); while (g.firstChild !== k) k.append(g.firstChild); return k; });
const draw = () => {
const a = v.a00, b = v.a01, c = v.a10, d = v.a11, dt = a * d - b * c, zero = Math.abs(dt) < 1e-9;
const pp = x => { const q = g2parts(x); return x < 0 ? ['(', ...q, ')'] : q; };
const dk = [...g2parts(a), '·', ...pp(d), ' − ', ...pp(b), '·', ...pp(c), ' = ', ...g2parts(dt)];
D_.set(0, COL.chalk, ['ad − bc = ', ...dk]);
inner.forEach(k => { k.style.display = zero ? 'none' : ''; });
N_.style.display = zero ? '' : 'none';
if (zero) { [...A_, ...R_, S_].forEach(c => c.set(0, COL.chalk, [''])); return; } // hidden, and blank: what shows never depends on the path taken
const fd = g2frac(dt);
S_.set(0, COL.chalk, fd && fd[1] === 1 ? [...(dt < 0 ? ['−'] : []), F(1, Math.abs(fd[0]))] : g2parts(1 / dt));
[[d, G2_COLS[1]], [-b, G2_COLS[1]], [-c, G2_COLS[0]], [a, G2_COLS[0]]].forEach(([x, col], k) => A_[k].set(x, col));
[d / dt, -b / dt, -c / dt, a / dt].forEach((x, k) => R_[k].set(x));
};
inv = { root, det, lhs, scale, adj, eq, res, none, draw, mid, adjCells: A_, resCells: R_, xs: { xL, xS, xA, xE, xR } };
draw();
return inv;
}
function draw() {
slots.forEach(s => s.set());
const c0 = [v.a00, v.a10], c1 = [v.a01, v.a11], ax = map([v.x0, v.x1]);
const t0c = tmap([1, 0]), t1c = tmap([0, 1]); // the plane's own columns (A's, unless pre is set)
if (lay.res) lay.res.forEach((t, i) => setText(t, fmt(ax[i])));
if (grid) {
let d = '';
for (let k = -K; k <= K; k++) {
if (!k) continue;
d += seg([k * t0c[0], k * t0c[1]], t1c, -K, K); // the image of the line x = k
d += seg([k * t1c[0], k * t1c[1]], t0c, -K, K); // the image of the line y = k
}
setD(gl, d);
setD(axs[0], seg([0, 0], t0c, -K, K)); // the x-axis lands along column 1
setD(axs[1], seg([0, 0], t1c, -K, K)); // the y-axis along column 2
}
if (square) setD(sq, poly([[0, 0], t0c, [t0c[0] + t1c[0], t0c[1] + t1c[1]], t1c]));
if (shape) setD(sh, poly(G2_FLAG.map(tmap)));
if (lost) { // the points A sends to (0, 0): a line when ad − bc = 0 and A is not all zeros
const dt = v.a00 * v.a11 - v.a01 * v.a10, r = Math.hypot(v.a00, v.a01) > 1e-9 ? [v.a00, v.a01] : [v.a10, v.a11];
setD(lostL, Math.abs(dt) < 1e-9 && Math.hypot(...r) > 1e-9 ? seg([0, 0], [-r[1], r[0]], -40, 40) : '');
}
if (inv) inv.draw();
ptDots.forEach(({ g, lab }, i) => {
const [a, b] = tmap(ptDots[i].q.p);
put(g, { x: PX(a), y: PY(b) });
});
[c0, c1].forEach((c, j) => {
setD(cols[j], arrowD([0, 0], c));
put(tips[j], { x: PX(c[0]), y: PY(c[1]) });
});
if (x) {
const m1 = [v.x0 * c0[0], v.x0 * c0[1]];
setD(combo[0], arrowD([0, 0], m1, 14));
setD(combo[1], arrowD(m1, ax, 14));
setD(axArrow, arrowD([0, 0], ax));
put(xRing, { x: PX(v.x0), y: PY(v.x1) });
const br = brackets ? ['[', ']'] : ['(', ')']; // brackets: x and Ax read as vectors, else as points
const nm = { x: 'x', ax: 'Ax', ...(typeof names === 'function' ? names(v) : names) };
setText(xLab, `${nm.x} = ${br[0]}${fmt(v.x0)}, ${fmt(v.x1)}${br[1]}`);
put(axDot, { x: PX(ax[0]), y: PY(ax[1]) });
setText(axLab, `${nm.ax} = ${br[0]}${fmt(ax[0])}, ${fmt(ax[1])}${br[1]}`);
}
placeLabels(c0, c1, ax);
listeners.forEach(f => f(v));
}
function edit(to) {
let changed = false;
for (const k in to) if (v[k] !== to[k]) { v[k] = to[k]; changed = true; }
if (changed) draw();
}
draw();
if (mat && showMat) show(Mx, t0 + .3); // showMat: false keeps the matrix hidden (a question that asks for it)
const api = {
v, P: P2, stage: holder, M: Mx, lay, cols, tips, combo, axArrow, axDot, xRing, xLab, axLab,
parts: { grid: gridG, square: sqG, shape: shG, units: unG, pts: ptG, cols: colG, x: xG, lost: lostG },
get inv() { return inv; },
inverse,
det: () => v.a00 * v.a11 - v.a01 * v.a10,
inverseOf() { const dt = v.a00 * v.a11 - v.a01 * v.a10; return Math.abs(dt) < 1e-9 ? null : [[v.a11 / dt, -v.a01 / dt], [-v.a10 / dt, v.a00 / dt]]; },
total: () => { const c0 = tmap([1, 0]), c1 = tmap([0, 1]); return [[c0[0], c1[0]], [c0[1], c1[1]]]; },
// Move the numbers to new values over dur seconds, on the beat clock (deterministic, so seeking replays it).
to(next, at, dur = 1.2, ease = io) {
const from = { ...plan };
plan = { ...plan, ...next };
const goal = { ...plan };
prog(q => edit(Object.fromEntries(Object.keys(goal).map(k => [k, from[k] + (goal[k] - from[k]) * q]))), at, dur, ease);
},
// Turn the plane from deg0 to deg1 degrees (counterclockwise) on the beat clock: a true turn, where a straight blend
// of the numbers would shrink the plane halfway. Later g.to() calls start from where the turn ends.
turn(deg0, deg1, at, dur = 1.6, ease = io, key = 'a') {
const rot = d => { const a = d * Math.PI / 180, k = n => Math.round(n * 1e6) / 1e6; return { [key + '00']: k(Math.cos(a)), [key + '01']: k(-Math.sin(a)), [key + '10']: k(Math.sin(a)), [key + '11']: k(Math.cos(a)) }; };
plan = { ...plan, ...rot(deg1) };
prog(q => edit(rot(deg0 + (deg1 - deg0) * q)), at, dur, ease);
},
// Hands on. what: which parts take the reader's hands: 'A' the matrix numbers, 'cols' the column tips, 'x' the point x and its numbers.
live(on, what = ['A', 'cols', 'x']) {
live = on;
drags.splice(0, drags.length, ...(on ? what : []));
for (const s of slots) {
s.on = on && what.includes(s.key[0] === 'a' ? 'A' : 'x');
s.box.style.cursor = s.on ? 'ew-resize' : '';
s.box.setAttribute('stroke', s.on ? COL.faint : 'none');
s.box.setAttribute('stroke-dasharray', '4 6');
if (s.on) s.box.setAttribute('tabindex', 0); else s.box.removeAttribute('tabindex');
}
const cOn = on && what.includes('cols'), xOn = on && what.includes('x');
tips.forEach(g => { g.style.cursor = cOn ? 'grab' : ''; g._ring.style.opacity = cOn ? 1 : 0; g.style.pointerEvents = cOn ? '' : 'none'; });
xRing.style.cursor = xOn ? 'grab' : ''; xRing.style.pointerEvents = xOn ? '' : 'none'; // a handle not in play never hides one that is
},
set: edit, // at once, for a reader's action or an answer shown
num: key => slots.filter(s => s.key === key).map(s => s.t), // the text that shows this value (to flash it)
res: i => lay.res?.[i],
onChange(f) { listeners.push(f); },
col: j => j ? [v.a01, v.a11] : [v.a00, v.a10],
Ax: () => map([v.x0, v.x1]),
map,
labels(names) { names.forEach((n, i) => { tipLabels[i].replaceChildren(); M(tipLabels[i], [n], { size: 28, fill: G2_COLS[i], anchor: 'start' }); }); draw(); },
tipLabels, // the groups that hold the column names (to show or hide one on its own)
names(n) { names = n; draw(); }, // what the x and Ax labels call their points (see the header)
avoid(a) { avoid = a; draw(); }, // extra dots the labels keep clear of (see the header)
};
return api;
}
// A question that is a task on the moved plane: the reader changes it until test(v) holds, then checks.
// what: the parts the reader may move (see g.live).
const g2Task = (g, test, why, hint, reveal, what) => (body, api) => {
g.live(true, what);
const parts = what || ['A', 'cols', 'x'];
return {
check: () => { const ok = test(g.v); api.grade(ok, ok ? why : hint); },
reveal: () => { reveal?.(); return why; },
lock: () => g.live(false),
hint: parts.includes('A') || parts.includes('x') ? [kbd('Tab'), 'pick a number', kbd('↑'), kbd('↓'), 'change it, or drag in the picture'] : ['drag in the picture'],
};
};