In this section
- Lesson render · kuiper-belt / learn-the-kuiper/202610050609/lesson.js lines 1–700
Lesson
A JavaScript file in the learn the kuiper folder of Kuiper Belt that wraps deg (`wrapDeg`), parses typed (`parseTyped`), finds target (`findTarget`) and calculates planar distances and angles (units: kV).
renderkuiper-belt / learn-the-kuiper/202610050609/lesson.js · lines 1–700 of 1285 · version 2026-10-05 06:09 · Entry point · pattern exportState (shared by 2 files)
- What it does
- It draws its content. Defines 124 functions or classes, including LAW, SCALE, G32, newRule, lawPath. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: browser storage (getItem). Out: browser storage (setItem); canvas drawing; SVG drawing.
- Downstream impact
- Used directly by 1 file: Lesson (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html). Reached from 3 other entry points, including Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html); Play (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html); Solid (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html).
- What it achieves
- It places one (`placeOne`), solves key (`solveKey`) and turns deg (`turnDeg`). `lesson.js` LEARN THE KUIPER, rung KUIPER: the four formulas, opened up and played with. It responds to click, pointerdown and pointermove events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html.
- Application
- kuiper-belt · learn-the-kuiper/202610050609 · script
- Uses
- none found
- Used by
- loaded by Lesson (script src)
- Produces
- LAW, SCALE, G32, newRule, lawPath, isLive, isExercise, power, offset, params, prep, placeOne
- Defines here
- LAW, SCALE, G32, newRule, lawPath, isLive, isExercise, power, offset, params, prep, placeOne, fill, radiusAt, squareFor, solveKey, turnDeg, commas, fmtBig, fmtScaled, fmtNum, fmtDist, fmtShort, angleForm, decimalPair, rootSign, wrapDeg, circDiff, bandEdge, ringOf
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610050609/lesson.js:1-700 · blob 1c14cd3923030bb98dba60e43ca70bbf4f02103d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
// lesson.js LEARN THE KUIPER, rung KUIPER: the four formulas, opened up and played with.
// r = SQRT( k )
// theta = 2 x PI x MOD( k x [2654435769] , [4294967296] ) / [4294967296]
// X = r x COS( theta ) Y = r x SIN( theta )
// One diagram. Every bracket is an input, and the drawing is an input too. One strip (k -> r, theta -> X, Y) is
// always on screen; tapping a part of it opens that formula large. Every position comes from window.KuiperLaw.place
// (the live preset) or window.KuiperScale.place (any other numbers). The law is never copied here.
// Plain script: works from file://, no network, no build step. Also loads in Node (the MATHS block only), so the
// truth tests run the same functions the drawing uses.
(function (root) {
'use strict';
var TWO53 = 9007199254740992, TWO32 = 4294967296, TAU = Math.PI * 2, D2R = Math.PI / 180;
var hasBig = typeof BigInt === 'function';
var CAP = 1200; // most sampled stars drawn at once
var CH = 24; // ghost wedges kept behind the selected key
var MAXS = CAP + CH + 8; // hard size of every star array
var LIMIT_LINE = 'THAT NUMBER IS TOO LARGE FOR THIS COMPUTER TO SHOW. THE REAL LIMIT HERE IS 9,007,199,254,740,992.';
function LAW() { return root.KuiperLaw; }
function SCALE() { return root.KuiperScale; }
function G32() { return LAW().constants.G32; }
// =====================================================================================================
// MATHS (pure; no DOM). rule = { start, G, W, rad: 'sqrt' | 'lin' | 'cbrt', off: 0 | 0.5 }
// EXERCISE: keys from 1, r = SQRT(k). LIVE: keys from 0, r = SQRT(k + 0.5). The angle is the same in both.
// =====================================================================================================
function newRule() { return { start: 1, G: G32(), W: TWO32, rad: 'sqrt', off: 0, _p: null }; }
function lawPath(R) { return R.G === G32() && R.W === TWO32 && R.rad === 'sqrt' && R.off === 0.5; }
function isLive(R) { return lawPath(R) && R.start === 0; }
function isExercise(R) { return R.G === G32() && R.W === TWO32 && R.rad === 'sqrt' && R.off === 0 && R.start === 1; }
function power(R) { return R.rad === 'sqrt' ? 0.5 : R.rad === 'lin' ? 1 : 1 / 3; }
function offset(R) { return R.rad === 'sqrt' ? R.off : 0; }
function params(R, extra) { return { first: 0, count: TWO53, turnNumber: R.G, wrap: R.W, power: power(R), offset: offset(R) + (extra || 0) }; }
function prep(R) { if (!R._p) R._p = SCALE().prepare(params(R)); return R._p; }
// THE placement every star on screen goes through. out = {x, y, r, turns, m}
function placeOne(R, k, out) {
var p = lawPath(R) ? LAW().place(k) : SCALE().place(k, prep(R));
out.x = p.x; out.y = p.y; out.r = p.r; out.turns = p.turns; out.m = p.m;
return out;
}
function fill(R, keys, n, X, Y) { // n is capped by the arrays
var t = { x: 0, y: 0, r: 0, turns: 0, m: 0 }, i, lim = Math.min(n, keys.length, X.length, Y.length), rmax = 0;
for (i = 0; i < lim; i++) { placeOne(R, keys[i], t); X[i] = t.x; Y[i] = t.y; if (t.r > rmax) rmax = t.r; }
return rmax;
}
// the distance for a number between two keys (the square-root piece lets a decimal be typed)
function radiusAt(R, x) {
var f = Math.floor(x), fr = x - f;
if (fr === 0 && lawPath(R)) return LAW().place(f).r;
return SCALE().place(f, fr === 0 ? prep(R) : SCALE().prepare(params(R, fr))).r;
}
// the number under the root for a distance (any point has one; only whole numbers from start are keys)
function squareFor(R, r) { var v = SCALE().keyAtRadius(r, prep(R)); return v === v ? v + offset(R) : 0; }
// the smallest key whose remainder is m (or the nearest remainder below m that any key can reach)
function solveKey(R, m) {
if (!hasBig) return null;
var W = BigInt(R.W), G = BigInt(R.G) % W, a = G, b = W, x0 = BigInt(1), x1 = BigInt(0), q, t, i;
if (G === BigInt(0)) return 0;
for (i = 0; i < 400 && b !== BigInt(0); i++) { q = a / b; t = a - q * b; a = b; b = t; t = x0 - q * x1; x0 = x1; x1 = t; }
var g = a, Wg = W / g, mm = BigInt(Math.floor(m)) % W; if (mm < BigInt(0)) mm += W; mm = mm - (mm % g);
var inv = ((x0 % Wg) + Wg) % Wg;
return Number(((mm / g) * inv) % Wg);
}
// the turn one key makes, in degrees (for drawing the wedge; never used to compute a position)
function turnDeg(R) { return 360 * (R.G % R.W) / R.W; }
function commas(s) { // s = string of digits, optional leading '-'
var neg = s.charAt(0) === '-'; if (neg) s = s.slice(1);
var out = '', n = s.length, i;
for (i = 0; i < n; i++) { out += s.charAt(i); var left = n - 1 - i; if (left > 0 && left % 3 === 0) out += ','; }
return (neg ? '−' : '') + out;
}
function fmtBig(b) { return commas(b.toString()); }
function fmtScaled(b, d) { // b: non-negative BigInt holding value x 10^d
var s = b.toString(); if (d === 0) return commas(s);
while (s.length <= d) s = '0' + s;
return commas(s.slice(0, s.length - d)) + '.' + s.slice(s.length - d);
}
function fmtNum(v, d) { // a float, cut (not rounded) to d decimals, with commas
if (!isFinite(v)) return String(v);
var p = Math.pow(10, d), c = Math.floor(Math.abs(v) * p + 1e-7) / p, s = c.toFixed(d), dot = s.indexOf('.');
return (v < 0 && c > 0 ? '−' : '') + (dot < 0 ? commas(s) : commas(s.slice(0, dot)) + s.slice(dot));
}
function fmtDist(v) { // rounded to 2 decimals, with commas
if (!isFinite(v)) return String(v);
var s = Math.abs(v).toFixed(2), dot = s.indexOf('.'), neg = v < 0 && Number(s) > 0;
return (neg ? '−' : '') + commas(s.slice(0, dot)) + s.slice(dot);
}
function fmtShort(v) { // as few decimals as it needs (up to 4)
if (!isFinite(v)) return String(v);
if (Math.abs(v) >= 1e15) return commas(hasBig ? BigInt(Math.round(v)).toString() : String(Math.round(v)));
var s = (Math.round(v * 10000) / 10000).toString(), dot = s.indexOf('.');
return dot < 0 ? commas(s) : commas(s.slice(0, dot)) + s.slice(dot);
}
// MOD, exact for every key up to 2^53: k x G = product; product = n whole circles of W + remainder m.
function angleForm(R, k) {
var o = { G: R.G, W: R.W };
if (!hasBig) { // approximate fallback for a runtime without BigInt
var t = { x: 0, y: 0, r: 0, turns: 0, m: 0 }; placeOne(R, k, t);
o.m = t.m; o.turns = t.turns; o.nNum = Math.floor(k * R.G / R.W); o.nStr = fmtNum(o.nNum, 0); o.prodStr = fmtNum(k * R.G, 0); o.mStr = fmtNum(t.m, 0);
o.degStr = fmtNum(t.turns * 360, 2);
} else {
var Gb = BigInt(R.G), Wb = BigInt(R.W), prod = BigInt(k) * Gb, n = prod / Wb, m = prod - n * Wb;
o.m = Number(m); o.turns = o.m / R.W; o.n = n; o.prod = prod;
o.nNum = Number(n); o.nStr = fmtBig(n); o.prodStr = fmtBig(prod); o.mStr = fmtBig(m);
o.degStr = fmtScaled((m * BigInt(36000) + Wb / BigInt(2)) / Wb, 2);
}
o.remDeg = o.turns * 360; o.theta = 2 * Math.PI * o.m / R.W;
o.GStr = commas(String(R.G)); o.WStr = commas(String(R.W));
o.fracStr = fmtNum(o.turns, 5); o.thetaStr = fmtNum(o.theta, 4);
return o;
}
function decimalPair(v) {
var a=String(v).replace(/,/g,'').split(/[eE]/), p=a[0].split('.'), d=(p[1]||'').length-(+(a[1]||0));
var n=BigInt(p.join('')); return d<0 ? [n*BigInt(10)**BigInt(-d),BigInt(1)] : [n,BigInt(10)**BigInt(d)];
}
function rootSign(shown, value, off) {
if (!hasBig) return '≈';
var r=decimalPair(shown), a=decimalPair(value), b=decimalPair(off||0);
return r[0]*r[0]*a[1]*b[1] === (a[0]*b[1]+b[0]*a[1])*r[1]*r[1] ? '=' : '≈';
}
function wrapDeg(v) { var w = v % 360; if (w < 0) w += 360; return w === 360 ? 0 : w; } // MOD( v , 360 ): never negative
function circDiff(a, b) { var d = Math.abs(a - b); return d > 0.5 ? 1 - d : d; }
// the band a key owns: between the distances of key - 1/2 and key + 1/2 (overlay geometry, not a star position)
function bandEdge(R, kReal) { var v = Math.max(0, kReal + offset(R)); return R.rad === 'sqrt' ? Math.sqrt(v) : R.rad === 'lin' ? v : Math.pow(v, 1 / 3); }
// rings of whole-number distance under a square-root rule: ring n begins at key n x n and holds 2n + 1 keys.
// True for SQRT(k) and for SQRT(k + 0.5) alike: no whole number plus a half is a square.
function ringOf(k) { var n = Math.floor(Math.sqrt(k)); while (n * n > k) n--; while ((n + 1) * (n + 1) <= k) n++; return n; }
function isSquare(k) { var n = ringOf(k); return n * n === k; }
// the four formulas as the document writes them, with these numbers, ready for a spreadsheet (row 2, key in A2).
// When a product would pass 2^53 the angle uses the split form, so the spreadsheet stays exact.
function sheet(R, lastKey) {
var G = R.G, W = R.W, rad = R.rad === 'sqrt' ? (R.off ? '=SQRT(A2+' + R.off + ')' : '=SQRT(A2)') : R.rad === 'lin' ? '=A2' : '=A2^(1/3)';
// a spreadsheet holds a product exactly up to 2^53, and one key further when that product is even
var fits = lastKey * G < TWO53, ang;
if (hasBig) { var lim = G > 0 ? BigInt(TWO53) / BigInt(G) : BigInt(TWO53); if (((lim + BigInt(1)) * BigInt(G)) % BigInt(2) === BigInt(0)) lim += BigInt(1); fits = BigInt(Math.max(1, lastKey)) <= lim; }
if (fits) ang = '=2*PI()*MOD(A2*' + G + ',' + W + ')/' + W;
else if (W === TWO32 && G < TWO32) ang = '=2*PI()*MOD(MOD(MOD(A2,4294967296)*' + Math.floor(G / 65536) + ',65536)*65536+MOD(A2,4294967296)*' + (G % 65536) + ',4294967296)/4294967296';
else if (hasBig && BigInt(Math.min(lastKey, W - 1)) * BigInt(G % W) <= BigInt(Number.MAX_SAFE_INTEGER)) ang = '=2*PI()*MOD(MOD(A2,' + W + ')*' + (G % W) + ',' + W + ')/' + W;
else return null; // No proven exact spreadsheet product for this custom domain.
return [rad, ang, '=B2*COS(C2)', '=B2*SIN(C2)'];
}
function parseTyped(str, intOnly) {
var s = String(str == null ? '' : str).trim().replace(/\s+/g, '').replace(/°/g, '').replace(/−/g, '-');
if (!s) return { ok: false };
if (intOnly) s = s.replace(/,/g, '');
else if (s.indexOf('.') < 0 && /^[^,]*,\d{1,2}$/.test(s)) s = s.replace(',', '.');
else s = s.replace(/,/g, '');
var v, fr = s.split('/');
if (fr.length === 2 && fr[0] !== '' && fr[1] !== '') v = Number(fr[0]) / Number(fr[1]); else v = Number(s);
if (/^[+-]?\d+$/.test(s) && hasBig) { var b = BigInt(s); return { ok: true, v: v, big: b > BigInt(TWO53) || b < -BigInt(TWO53) }; }
if (v !== v) return { ok: false };
if (hasBig && isFinite(v) && /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(s) && Math.abs(v)<=TWO53) {
var typed=decimalPair(s), represented=decimalPair(v);
if (typed[0]*represented[1]!==represented[0]*typed[1]) return {ok:true,v:v,big:true};
}
return { ok: true, v: v, big: !(Math.abs(v) <= TWO53) };
}
// things to find in the square-root piece: a distance, and how close counts. Whole rings first, then one more digit.
var FINDS = [[3, 0.1], [5, 0.1], [2.5, 0.05], [7.5, 0.01], [1.5, 0.002], [9.9, 0.0005]];
function findTarget(i) {
if (i < FINDS.length) return { r: FINDS[i][0], w: FINDS[i][1] };
var h = Math.imul(i + 11, 2654435761) >>> 0; return { r: 2 + (h % 1100) / 100, w: 0.0005 };
}
var M = {
newRule: newRule, squareFor: squareFor, solveKey: solveKey, lawPath: lawPath, isLive: isLive, isExercise: isExercise, placeOne: placeOne, fill: fill, radiusAt: radiusAt,
turnDeg: turnDeg, wrapDeg: wrapDeg, angleForm: angleForm, circDiff: circDiff, bandEdge: bandEdge, ringOf: ringOf, isSquare: isSquare, sheet: sheet,
rootSign: rootSign, parseTyped: parseTyped, findTarget: findTarget, fmtNum: fmtNum, fmtScaled: fmtScaled, fmtDist: fmtDist, commas: commas, LIMIT_LINE: LIMIT_LINE, CAP: CAP
};
// =====================================================================================================
// THE SCREEN
// =====================================================================================================
var S = null;
var PIPS = ['1 DOT', '2 DOTS', 'RING', 'TIME', 'KUIPER'];
var LABELS = []; (function () { for (var i = 0; i < 100; i++) LABELS.push(String(i)); })();
var FONT = '"Segoe UI", Arial, sans-serif';
var CSS = '.kgl-root{position:absolute;left:0;top:0;right:0;bottom:0;background:#000;overflow:hidden;font-family:' + FONT + ';font-weight:400;color:#fff;user-select:none;-webkit-user-select:none;touch-action:none;-webkit-tap-highlight-color:transparent}' +
'.kgl-root canvas{position:absolute;left:0;top:0;width:100%;height:100%;touch-action:none;display:block}' +
'.kgl-panel{position:absolute;left:0;right:0;bottom:0;padding:4px 10px calc(8px + env(safe-area-inset-bottom,0px));box-sizing:border-box;font-variant-numeric:tabular-nums;pointer-events:none;display:flex;flex-direction:column;justify-content:center}' +
'.kgl-strip{display:flex;flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none;justify-content:flex-start;align-items:flex-end;column-gap:2px;font-size:24px;line-height:1.12;padding-bottom:5px;pointer-events:auto;touch-action:pan-x}.kgl-strip::-webkit-scrollbar{display:none}.kgl-strip>:first-child{margin-left:auto}.kgl-strip>:last-child{margin-right:auto}' +
'.kgl-cell{display:inline-flex;flex-direction:column;align-items:center;padding:1px 2px 2px;border-bottom:3px solid rgba(255,255,255,.14);cursor:pointer;pointer-events:auto;touch-action:manipulation;min-width:1.3em;flex:none;white-space:nowrap}' +
'.kgl-cell.big{font-size:28px}.kgl-cell.on{border-bottom-color:#ffb000}.kgl-cell i{font-style:normal;color:rgba(255,255,255,.55)}.kgl-arrow{color:rgba(255,255,255,.4);align-self:center;flex:none;font-size:24px;margin:0 -3px}' +
'.kgl-line{display:flex;flex-wrap:wrap;justify-content:center;align-items:baseline;column-gap:.26em;line-height:1.24}' +
'.kgl-g{display:inline-flex;align-items:baseline;white-space:nowrap;gap:.2em;flex:none;pointer-events:auto}' +
'.kgl-scroll{flex-wrap:nowrap;overflow-x:auto;justify-content:flex-start;pointer-events:auto;touch-action:pan-x;scrollbar-width:none;-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 26px),transparent);mask-image:linear-gradient(90deg,#000 calc(100% - 26px),transparent)}.kgl-scroll::-webkit-scrollbar{display:none}.kgl-scroll>:first-child{margin-left:auto}.kgl-scroll>:last-child{margin- … [line shortened here: 452 characters; full line on GitHub]
'.kgl-tagset{display:inline-flex;gap:6px 8px;flex-wrap:wrap;justify-content:center}' +
'.kgl-wrap .kgl-g{white-space:normal;flex-wrap:wrap;overflow-wrap:anywhere;word-break:break-all;max-width:100%;flex:0 1 auto}.kgl-wrap .kgl-f{white-space:normal}' +
'.kgl-lab,.kgl-op{color:rgba(255,255,255,.6)}' +
'.kgl-f{cursor:ns-resize;touch-action:none;white-space:nowrap;padding:2px 0}' +
'.kgl-b{color:rgba(255,255,255,.45)}' +
'.kgl-f.kgl-ed{background:rgba(255,255,255,.12);border-radius:6px}.kgl-f.kgl-ed .kgl-v::after{content:"";display:inline-block;width:2px;height:.9em;background:currentColor;margin-left:2px;vertical-align:-0.08em;animation:kglc 1s steps(1) infinite}' +
'@keyframes kglc{50%{opacity:0}}' +
'.kgl-pill{display:inline-flex;align-items:center;justify-content:center;min-width:1.4em;height:1.16em;border:2px solid rgba(0,255,255,.55);border-radius:.4em;color:#00ffff;cursor:pointer;box-sizing:border-box;align-self:center;line-height:1;padding:0 .2em;touch-action:manipulation}' +
'.kgl-tag{font-size:24px;line-height:1.2;border:2px solid rgba(255,255,255,.3);color:rgba(255,255,255,.5);border-radius:8px;padding:0 7px;cursor:pointer;align-self:center;touch-action:manipulation;pointer-events:auto;white-space:nowrap}' +
'.kgl-tag.on{border-color:#00ffff;color:#00ffff;box-shadow:0 0 12px rgba(0,255,255,.55)}' +
'.kgl-tags{display:flex;flex-wrap:wrap;justify-content:center;align-items:center;gap:6px 8px;padding-top:5px}' +
'.kgl-meter{display:inline-flex;gap:4px;align-items:center}.kgl-meter i{width:9px;height:9px;border-radius:50%;background:rgba(255,255,255,.2)}.kgl-meter i.on{background:#00ffff}' +
'.kgl-ring{display:inline-block;width:.72em;height:.72em;border:3px solid #00ffff;border-radius:50%;box-sizing:border-box;align-self:center;flex:none}' +
'.kgl-tap{cursor:pointer}' +
'.kgl-msg{font-size:24px;color:#ffb000;text-align:center;line-height:1.2;display:none;padding-top:4px;pointer-events:none}' +
'.kgl-bad{color:#ff5050}' +
'@keyframes kglp{0%,100%{text-shadow:none}50%{text-shadow:0 0 16px currentColor,0 0 5px currentColor}}' +
'.kgl-pulse{animation:kglp 1.3s ease-in-out 2}' +
'.kgl-pad{position:absolute;left:0;right:0;bottom:0;display:none;grid-template-columns:repeat(5,1fr);gap:4px;padding:4px 6px calc(6px + env(safe-area-inset-bottom,0px));box-sizing:border-box;max-width:520px;margin:0 auto;background:#000}' +
'.kgl-pad button{height:46px;font:400 26px ' + FONT + ';color:#fff;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.22);border-radius:8px;padding:0;margin:0;cursor:pointer;touch-action:manipulation}' +
'.kgl-pad button.fn{color:#00ffff}' +
'.kgl-side.kgl-editing .kgl-strip,.kgl-side.kgl-editing .kgl-tags,.kgl-side.kgl-editing .kgl-live{display:none}' +
'.kgl-pips{position:absolute;left:6px;top:calc(4px + env(safe-area-inset-top,0px));display:flex;align-items:center;height:44px}' +
'.kgl-pip{height:44px;min-width:26px;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;font-size:24px;color:rgba(0,255,255,.8);touch-action:manipulation}' +
'.kgl-pip i{width:12px;height:12px;border-radius:50%;border:2px solid rgba(0,255,255,.85);box-sizing:border-box;flex:none}' +
'.kgl-pip b{margin:0 10px 0 6px;font-weight:400}' +
'.kgl-pip.on{color:#ffb000;cursor:default}.kgl-pip.on i{background:#ffb000;border-color:#ffb000}' +
'.kgl-pip.dim{opacity:.3;cursor:default}' +
'.kgl-icons{position:absolute;right:4px;top:calc(4px + env(safe-area-inset-top,0px));display:flex}' +
'.kgl-ic{width:44px;height:44px;background:none;border:0;padding:0;margin:0;cursor:pointer;color:rgba(255,255,255,.72);display:inline-flex;align-items:center;justify-content:center;touch-action:manipulation}' +
'.kgl-ic svg{width:28px;height:28px;display:block}.kgl-ic.off{color:rgba(255,255,255,.3)}.kgl-ic.lit{color:#ffb000}';
CSS += '.kgl-root *{font-weight:400;text-shadow:none!important}.kgl-panel{max-height:46%;overflow-y:auto;overflow-x:hidden;justify-content:flex-start;pointer-events:auto;touch-action:pan-y}.kgl-panel,.kgl-panel *{color:#fff!important}.kgl-g{min-width:0;max-width:100%;flex-wrap:wrap;white-space:normal;overflow-wrap:anywhere;flex:0 1 auto}.kgl-working{font-size:24px!important;line-height:1.5;margi … [line shortened here: 1,412 characters; full line on GitHub]
CSS += '.kgl-invalid .kgl-strip,.kgl-invalid .kgl-live,.kgl-invalid-root .kgl-root-result{visibility:hidden}';
CSS += '.kgl-tags,.kgl-tags *{color:#fff!important;font-weight:400;text-shadow:none!important}';
// Short landscape footer; optional tags open over the drawing, never over the working line.
CSS += '.kgl-extra{display:contents}.kgl-more-button{display:none;font:inherit;color:inherit}.kgl-side .kgl-panel{padding-bottom:4px}.kgl-side .kgl-strip{padding-bottom:2px}.kgl-side .kgl-tags{flex-wrap:nowrap}.kgl-side .kgl-tags>.kgl-tag{flex:none}.kgl-side .kgl-more-button{display:inline-block;font-size:24px}.kgl-side .kgl-extra{display:none;position:absolute;right:calc(100% + 8px);bottom:0;bo … [line shortened here: 596 characters; full line on GitHub]
var SVG_NOTE = '<svg viewBox="0 0 28 28" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round"><path d="M11 21V6l11-2v14"/><ellipse cx="8" cy="21" rx="3.4" ry="2.6" fill="currentColor"/><ellipse cx="19" cy="18" rx="3.4" ry="2.6" fill="currentColor"/><path class="s" d="M4 4l20 20" stroke-width="3" style="display:none"/></svg>';
var SVG_PLAY = '<svg viewBox="0 0 28 28" fill="currentColor"><path class="p" d="M8 5l15 9-15 9z"/><path class="q" d="M7 5h5v18H7zM16 5h5v18h-5z" style="display:none"/></svg>';
var SVG_STAR = '<svg viewBox="0 0 28 28" fill="currentColor"><path d="M14 2l3.2 8.2 8.8.6-6.8 5.6 2.2 8.6L14 20.2 6.6 25l2.2-8.6L2 10.8l8.8-.6z"/></svg>';
var SVG_X = '<svg viewBox="0 0 28 28" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><path d="M6 6l16 16M22 6L6 22"/></svg>';
function E(tag, cls, text, parent) { var e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; if (parent) parent.appendChild(e); return e; }
function clamp(v, a, b) { return v < a ? a : v > b ? b : v; }
function easeIO(u) { return u < 0.5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2; }
function easeO(u) { return 1 - (1 - u) * (1 - u); }
function seen(name) { try { return root.localStorage.getItem('kgl-' + name) === '1'; } catch (e) { return false; } }
function markSeen(name) { try { root.localStorage.setItem('kgl-' + name, '1'); } catch (e) { } }
function show(el, v) { var d = v ? '' : 'none'; if (el.style.display !== d) el.style.display = d; }
function setT(el, t) { if (el.textContent !== t) el.textContent = t; }
function sprite(r, g, b) { // a star: soft halo, solid disc, white core. Drawn once; stars are blitted from it.
var c = document.createElement('canvas'); c.width = c.height = 96; var x = c.getContext('2d'), m = 48, rd = m / 2.6;
var gr = x.createRadialGradient(m, m, rd * 0.5, m, m, m);
gr.addColorStop(0, 'rgba(' + r + ',' + g + ',' + b + ',0.42)'); gr.addColorStop(1, 'rgba(' + r + ',' + g + ',' + b + ',0)');
x.fillStyle = gr; x.beginPath(); x.arc(m, m, m, 0, TAU); x.fill();
x.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')'; x.beginPath(); x.arc(m, m, rd, 0, TAU); x.fill();
x.fillStyle = 'rgba(255,255,255,0.92)'; x.beginPath(); x.arc(m, m, rd * 0.5, 0, TAU); x.fill();
return c;
}
// ------------------------------------------------------------------ open, close
function open(host, opts) {
if (S) close(true);
opts = opts || {};
host = host || document.body;
var s = S = {
host: host, opts: opts, on: [], raf: 0, timers: [],
rule: newRule(), K: 1, kx: 1, N: 1, dragRule: false, chTop: 0, chN: 0, piece: 't',
KS: new Float64Array(MAXS), SX: new Float64Array(MAXS), SY: new Float64Array(MAXS), PX: new Float64Array(MAXS), PY: new Float64Array(MAXS),
CT: new Float64Array(CH + 2), CR: new Float64Array(CH + 2), cnt: 0, selIdx: -1, rFit: 1, rLast: 0, nextX: 0, nextY: 0, selTh: 0, selR: 0, sig: '', prevSig: '',
T: { x: 0, y: 0, r: 0, turns: 0, m: 0 }, Tdeg: 0,
W: 0, H: 0, dpr: 1, cx: 0, cy: 0, Rp: 100, cxT: 0, cyT: 0, RpT: 100, vs: 1, vsT: 1, zoomK: 1, stackX: 20, stackY: 20, first: true, holdUntil: 0, padH: 0,
A: { on: false, type: '', dir: 1, t0: 0, dur: 0, newStar: false, FL: null, FH: null, lastText: 0, ec: Infinity, rLo: 0, rHi: 0, auto: false },
D: { has: false, e: 1, cross: false }, J: 1, wedgeA: 1, wedgeT0: 0,
queue: 0, playing: false, band: false, edit: null, userN: 0, liveUser: null, probe: { on: false, dirty: false, x: 0, y: 0, idx: -1, gap: '', keyStr: '', ring: -1 },
morph: 1, morphT0: 0, pourOn: false, pourFrom: 0, pourT0: 0, t0: 0, fade: 0, landT0: -1e9,
fly: [], userLands: 0, gest: false, ac: null, lastNote: 0, mutedLocal: false,
find: true, findIdx: 0, tgt: findTarget(0), tries: new Float64Array(16), nTries: 0, marks: 0, score: 0, scoreStr: '', burstT0: -1e9, burstX: 0, burstY: 0, glowT0: -1e9, ringEvT0: -1e9, ringEvN: 0,
F: null, form: null, lblRem: '', lblDist: '', lblArea: '', lblX: '', lblY: '', stackStr: '', stackNum: 0, msgTimer: 0, hashTimer: 0,
ptr: {}, nptr: 0, drag: null, pinch: null
};
var i; for (i = 0; i < 6; i++) s.fly.push({ on: false, t0: 0 });
var fr = opts.from || null;
var fromHash = !fr && opts.hash !== false && readHash();
if (fr) { // carried over from the earlier rungs: their TURN becomes the multiplier of a 360 circle, HOW MANY the count
var ft = fr.turn != null ? fr.turn : fr.TURN, fn = fr.howMany != null ? fr.howMany : (fr.HOW_MANY != null ? fr.HOW_MANY : (fr['HOW MANY'] != null ? fr['HOW MANY'] : fr.count));
if (opts.carryRule === true && typeof ft === 'number' && isFinite(ft)) { var w = ((ft % 360) + 360) % 360, sc = 1; while (sc < 10000 && Math.abs(w * sc - Math.round(w * sc)) > 1e-9) sc *= 10; s.rule.W = 360 * sc; s.rule.G = Math.round(w * sc); }
if (typeof fn === 'number' && isFinite(fn) && fn >= 1) { s.N = Math.min(TWO53 - 1, Math.floor(fn)); s.K = s.rule.start + s.N - 1; }
}
if (fr && opts.carryRule === true && Number.isSafeInteger(fr.multiplier) && fr.multiplier >= 0 && Number.isSafeInteger(fr.circle) && fr.circle >= 1) { s.rule.G=fr.multiplier; s.rule.W=fr.circle; }
if (fr && Number.isSafeInteger(fr.key) && fr.key >= s.rule.start) { s.K=fr.key; s.N=Math.max(s.N,s.K-s.rule.start+1); }
var cinematic = false;
if (cinematic && s.rule.start === 0) s.N = 1;
s.kx = s.K; s.userN = s.N;
var rootEl = s.root = E('div', 'kgl-root', null, host);
E('style', null, CSS, rootEl);
s.canvas = E('canvas', null, null, rootEl); s.ctx = s.canvas.getContext('2d');
s.sprC = sprite(0, 255, 255); s.sprA = sprite(255, 176, 0);
buildTop(); buildPanel(); buildPad();
bind();
setPiece(s.piece, true);
layout(); s.cx = s.cxT; s.cy = s.cyT; s.Rp = s.RpT;
recompute(); restD(); if (cinematic) s.rFit = 2; s.vsT = s.vs = fitScale(); updateFormula();
s.t0 = performance.now(); s.last = s.t0;
if (cinematic) s.timers.push(setTimeout(function () { if (S === s && !s.A.on && s.K === 0) startStep(1, 1700, true); }, 380));
else { s.A.on = true; s.A.type = 'jump'; s.A.t0 = s.t0 + 300; s.A.dur = 700; s.J = 0; s.wedgeA = 0; }
need();
return api;
}
function close(silent) {
if (!S) return;
var s = S; S = null;
if (s.raf) cancelAnimationFrame(s.raf);
s.timers.forEach(function (t) { clearTimeout(t); }); clearTimeout(s.msgTimer); clearTimeout(s.hashTimer);
s.on.forEach(function (o) { o[0].removeEventListener(o[1], o[2], o[3]); });
if (s.ro) { try { s.ro.disconnect(); } catch (e) { } }
try { if (s.ac) s.ac.close(); } catch (e) { }
if (s.root && s.root.parentNode) s.root.parentNode.removeChild(s.root);
if (silent !== true) { try { s.host.dispatchEvent(new CustomEvent('kgclose', { bubbles: true, detail: { id: 'lesson' } })); } catch (e) { } }
}
function on(el, type, fn, opt) { el.addEventListener(type, fn, opt || false); S.on.push([el, type, fn, opt || false]); }
function need() { if (S && !S.raf) S.raf = requestAnimationFrame(tick); }
function lastKey() { return S.rule.start + S.N - 1; }
// one link carries an experiment: the numbers live in the page address
function readHash() {
var s = S, h = ''; try { h = String(root.location.hash || '').replace(/^#/, ''); } catch (e) { }
if (!h || h.indexOf('=') < 0) return false;
var o = {}, parts = h.split('&'), i; for (i = 0; i < parts.length && i < 16; i++) { var kv = parts[i].split('='); o[kv[0]] = kv[1]; }
function int(v, lo, hi, d) { var p = parseTyped(v, true); if (!p.ok || p.big) return d; var n = Math.floor(p.v); return n >= lo && n <= hi ? n : d; }
var R = s.rule;
R.start = int(o.s, 0, TWO53 - 1, R.start); R.G = int(o.g, 0, TWO53, R.G); R.W = int(o.w, 1, TWO53, R.W);
if (o.r === 'sqrt' || o.r === 'lin' || o.r === 'cbrt') R.rad = o.r;
R.off = o.o === '0.5' ? 0.5 : (o.o === '0' ? 0 : R.off);
s.N = int(o.n, 0, TWO53 - R.start, 1); s.K = int(o.k, 0, TWO53, R.start + Math.max(0, s.N - 1));
if (s.K >= R.start && s.K - R.start + 1 > s.N) s.N = s.K - R.start + 1;
if (o.p === 'k' || o.p === 'r' || o.p === 't' || o.p === 'x') s.piece = o.p;
return true;
}
function hashText() { var s = S, R = s.rule; return 'k=' + s.K + '&n=' + s.N + '&s=' + R.start + '&g=' + R.G + '&w=' + R.W + '&r=' + R.rad + '&o=' + R.off + '&p=' + s.piece; }
function writeHash() {
var s = S; if (s.opts.hash === false) return; clearTimeout(s.hashTimer);
s.hashTimer = setTimeout(function () { if (S !== s) return; try { root.history.replaceState(null, '', '#' + hashText()); } catch (e) { try { root.location.hash = hashText(); } catch (e2) { } } }, 400);
}
// ------------------------------------------------------------------ the top edge: pips, play, find, sound, close
function buildTop() {
var s = S, pips = s.pipsEl = E('div', 'kgl-pips', null, s.root), i;
for (i = 0; i < 5; i++) (function (i) {
var p = E('span', 'kgl-pip' + (i === 4 ? ' on' : ''), null, pips); E('i', null, null, p);
p._name = E('b', null, PIPS[i], p);
if (i < 4) p.addEventListener('click', function () {
var KP = root.KGPlay; if (!KP || typeof KP.open !== 'function') return;
var h = s.host, st = exportState(); close(true); KP.open(h, { rung: i + 1, from: st });
});
})(i);
var ic = s.iconsEl = E('div', 'kgl-icons', null, s.root);
s.playBtn = E('button', 'kgl-ic', null, ic); s.playBtn.innerHTML = SVG_PLAY; s.playBtn.setAttribute('aria-label', 'play');
s.playBtn.addEventListener('click', function () { gesture(); endEdit(true); setPlaying(!s.playing); });
s.findBtn = E('button', 'kgl-ic lit', null, ic); s.findBtn.innerHTML = SVG_STAR; s.findBtn.setAttribute('aria-label', 'find');
s.findBtn.addEventListener('click', function () { gesture(); s.find = !s.find; s.findBtn.className = 'kgl-ic' + (s.find ? ' lit' : ' off'); if (s.find && s.piece !== 'r') setPiece('r'); refit(); need(); });
s.muteBtn = E('button', 'kgl-ic', null, ic); s.muteBtn.innerHTML = SVG_NOTE; s.muteBtn.setAttribute('aria-label', 'sound');
s.muteBtn.addEventListener('click', function () {
var m = !muted(); if (root.KGAudio && typeof root.KGAudio.setMuted === 'function') root.KGAudio.setMuted(m); else s.mutedLocal = m;
showMute(); if (!m) { gesture(); note(220 * Math.pow(2, s.selTh / 180)); }
});
if (s.opts.standalone !== true && s.opts.close !== false) {
s.closeBtn = E('button', 'kgl-ic', null, ic); s.closeBtn.innerHTML = SVG_X; s.closeBtn.setAttribute('aria-label', 'close');
s.closeBtn.addEventListener('click', function () { close(); });
}
showMute();
}
function muted() { return root.KGAudio ? !!root.KGAudio.muted : S.mutedLocal; }
function showMute() { var m = muted(); S.muteBtn.className = 'kgl-ic' + (m ? ' off' : ''); S.muteBtn.querySelector('.s').style.display = m ? '' : 'none'; }
function setPlaying(v) {
var s = S; v = !!v; if (s.playing === v) return; s.playing = v;
s.playBtn.querySelector('.p').style.display = v ? 'none' : ''; s.playBtn.querySelector('.q').style.display = v ? '' : 'none';
if (v && !s.A.on) stepKey(1);
}
function exportState() { var R = S.rule; return { turn: turnDeg(R), howMany: S.N, key: S.K, start: R.start, multiplier: R.G, circle: R.W, live: isLive(R) }; }
// ------------------------------------------------------------------ numbers that are controls
// tap: the keypad opens and the dots move with every digit. drag up or down, or wheel: step it (exploring).
function field(parent, o) {
var s = S, el = E('span', 'kgl-f', null, parent); el.style.color = '#fff';
E('span', 'kgl-b', '[', el); var tx = E('span', 'kgl-v', '', el); E('span', 'kgl-b', ']', el);
var st = { down: false, id: -1, y0: 0, moved: false };
var F = { el: el, tx: tx, o: o, buf: '', start: '', fresh: true, set: function (t) { if (s.edit !== F) setT(tx, t); } };
el.addEventListener('pointerdown', function (e) {
gesture(); st.down = true; st.id = e.pointerId; st.y0 = e.clientY; st.moved = false; if (o.begin) o.begin();
try { el.setPointerCapture(e.pointerId); } catch (x) { }
});
el.addEventListener('pointermove', function (e) {
if (!st.down || e.pointerId !== st.id || !o.drag) return; var dy = st.y0 - e.clientY;
if (!st.moved && Math.abs(dy) < 7) return; if (!st.moved && s.edit) endEdit(true);
st.moved = true; setPlaying(false); o.drag(dy > 0 ? dy - 7 : dy + 7);
});
el.addEventListener('pointerup', function () { if (!st.down) return; st.down = false; if (st.moved) releaseHold(); });
el.addEventListener('pointercancel', function () { st.down = false; });
el.addEventListener('click', function () { if (st.moved) { st.moved = false; return; } startEdit(F); });
el.addEventListener('wheel', function (e) { e.preventDefault(); e.stopPropagation(); if (!o.wheel) return; endEdit(true); setPlaying(false); o.wheel(e.deltaY < 0 ? 1 : -1); releaseHold(); }, { passive: false });
return F;
}
function startEdit(F) {
var s = S; if (s.edit === F) return; if (s.edit) endEdit(true);
setPlaying(false); snapRest();
s.edit = F; F.start = F.o.raw(); F.buf = F.start; F.fresh = true; F.accepted = false; F.trusted = false; F.el.classList.add('kgl-ed'); F.tx.textContent = F.buf;
showPad(true);
var sc = F.el.parentNode; while (sc && sc !== s.panel && !(sc.classList && (sc.classList.contains('kgl-scroll') || sc.classList.contains('kgl-strip')))) sc = sc.parentNode;
if (sc && sc !== s.panel) { var er = F.el.getBoundingClientRect(), sr2 = sc.getBoundingClientRect(); sc.scrollLeft += (er.left + er.width / 2) - (sr2.left + sr2.width / 2); }
}
function typeCh(ch, trusted) { // one key of the keypad or the keyboard
var s = S, F = s.edit; if (!F) return;
var b = F.fresh ? '' : F.buf;
if (ch === 'back') b = F.fresh ? F.start.slice(0, -1) : b.slice(0, -1);
else if (ch === 'clear') b = '';
else if (ch === '-') b = b.charAt(0) === '-' ? b.slice(1) : '-' + b;
else if (ch === '.') { if (b.indexOf('.') < 0) b += (b === '' || b === '-') ? '0.' : '.'; }
else if (b.length < 40) b += ch;
F.fresh = false; F.buf = b; F.accepted = false; F.trusted = trusted === true; F.tx.textContent = b === '' ? ' ' : b;
if (b !== '' && b !== '-') F.accepted = F.o.apply(b) === true; // C empties the number; the dot waits where it was
s.root.classList.toggle('kgl-invalid', !F.accepted); s.root.classList.toggle('kgl-invalid-root', !F.accepted && F === s.F.keyR);
fitLines(); need();
}
function endEdit(commit, trusted) {
var s = S, F = s && s.edit; if (!F) return; s.edit = null; F.el.classList.remove('kgl-ed');
if (!commit && !F.fresh) F.o.apply(F.start);
s.root.classList.remove('kgl-invalid','kgl-invalid-root'); showPad(false); updateFormula();
if (commit && trusted !== false && F.accepted && F.trusted && !F.fresh && F.o.commit) F.o.commit(); // only a typed, committed number is answered
need();
}
function buildPad() {
var s = S, pad = s.pad = E('div', 'kgl-pad', null, s.root), keys = ['7', '8', '9', 'back', 'clear', '4', '5', '6', '-', 'ok', '1', '2', '3', '0', '.'];
var face = { back: '⌫', clear: 'C', '-': '−', ok: 'OK' };
keys.forEach(function (k) {
var b = E('button', face[k] && k !== '-' ? 'fn' : null, face[k] || k, pad); b.setAttribute('data-k', k);
b.addEventListener('click', function (e) { gesture(); if (k === 'ok') endEdit(true, e.isTrusted === true); else typeCh(k, e.isTrusted === true); });
});
}
function showPad(v) {
var s = S; s.pad.style.display = v ? 'grid' : 'none'; s.root.classList.toggle('kgl-editing', !!v);
if (v && s.F.moreTag) { s.root.classList.remove('kgl-more'); s.F.moreTag.setAttribute('aria-expanded', 'false'); }
s.padH = v ? s.pad.offsetHeight : 0; applyPanelPos(); fitLines(); placeCircle(); need();
}
function grp(line, cls) { return E('span', 'kgl-g' + (cls ? ' ' + cls : ''), null, line); }
function txt(g, cls, t, color) { var e = E('span', cls, t, g); if (color) e.style.color = '#fff'; return e; }
function intField(parent, color, get, set, lo) { // a whole number: multiplier, circle, count, start
var v0 = 0;
return field(parent, {
color: color,
raw: function () { return String(get()); },
apply: function (v) {
var p = parseTyped(v, true); if (!p.ok) return; var n = p.v;
if (p.big || n > TWO53) { showMsg(LIMIT_LINE); return; }
if (n < lo || n !== Math.floor(n)) return; // the last good value stays
set(n); return true;
},
begin: function () { v0 = get(); },
drag: function (d) { var a = Math.abs(d), stp = Math.max(1, Math.pow(10, Math.floor(Math.log(Math.max(10, v0)) / Math.LN10) - 2)); set(clamp(v0 + (d < 0 ? -1 : 1) * Math.round(a / 6) * stp, lo, TWO53)); },
wheel: function (dir) { var v = get(), stp = Math.max(1, Math.pow(10, Math.floor(Math.log(Math.max(10, v)) / Math.LN10) - 2)); set(clamp(v + dir * stp, lo, TWO53)); }
});
}
function keyField(parent) { // the key: a whole-number address. In the square-root piece the same bracket takes any number.
var k0 = 0;
return field(parent, {
color: '#ffffff',
raw: function () { return String(S.piece === 'r' ? S.kx : S.K); },
apply: function (v) {
var dec = S.piece === 'r', p = parseTyped(v, !dec); if (!p.ok) return; var k = p.v;
if (p.big || k > TWO53) { showMsg(LIMIT_LINE); return; }
if (k < (dec ? 0 : S.rule.start) || (!dec && k !== Math.floor(k))) return; // the last good value stays
S.F.msg.style.display='none'; typeKey(k); return true;
},
commit: function () { if (S.piece === 'r' && S.find) tryFind(true); },
begin: function () { k0 = S.K; },
drag: function (d) { var a = Math.abs(d), f = a / 8 + Math.pow(a / 40, 3); scrubKey(k0 + (d < 0 ? -1 : 1) * Math.round(f)); },
wheel: function (dir) { stepKey(dir); }
});
}
function toDistance(r) { // a distance was given: the number under the root follows
var s = S, R = s.rule; if (!(r >= 0) || !isFinite(r)) return;
var kx = squareFor(R, r) - offset(R); if (!(kx >= 0)) kx = 0; if (kx > Number.MAX_SAFE_INTEGER) { showMsg(LIMIT_LINE); return; }
if (s.piece !== 'r') setPiece('r');
typeKey(kx); return true;
}
function toRemainder(m) { // a remainder was given: the smallest key that stops there
var s = S, k = solveKey(s.rule, m); if (k == null) return;
if (s.piece !== 't') setPiece('t');
typeKey(k); return true;
}
function quarterFind() { var s = S, W = s.rule.W, m = s.form.m; if (m > 0 && (m * 4) % W === 0 && W % 4 === 0) reward(s.cx + Math.cos(s.selTh * D2R) * s.Rp, s.cy - Math.sin(s.selTh * D2R) * s.Rp); }
function buildPanel() {
var s = S, F = s.F = {}, panel = s.panel = E('div', 'kgl-panel', null, s.root), g, L;
// ---- the strip: k -> r, theta -> X, Y, with the live number under each. Tapping a part opens it.
var strip = F.strip = E('div', 'kgl-strip', null, panel);
function cell(id, name, color, big) { var c = E('span', 'kgl-cell' + (big ? ' big' : ''), null, strip); E('i', null, name, c); var v = E('span', null, '', c); v.style.color = '#fff'; c._id = id; c.setAttribute('data-c', name); c.addEventListener('click', function () { gesture(); endEdit(true); setPiece(id); }); return v; }
F.sk = cell('k', 'k', '#ffffff', true); E('span', 'kgl-arrow', '→', strip);
F.sr = cell('r', 'r', '#00ffff'); F.st = cell('t', 'θ', '#00ffff'); E('span', 'kgl-arrow', '→', strip);
F.sx = cell('x', 'X', '#ffb000'); F.sy = cell('x', 'Y', '#ffb000');
// ---- k: a key is a whole number; how many; where they start
var pk = F.pk = E('div', null, null, panel);
L = E('div', 'kgl-line', null, pk);
g = grp(L); txt(g, 'kgl-lab', 'k'); txt(g, 'kgl-op', '='); F.key = keyField(g);
g = grp(L); txt(g, 'kgl-lab', 'COUNT');
F.count = intField(g, '#00ffff', function () { return s.N; }, function (n) { setCount(n); }, 0);
F.count.o.commit = function () { // a ring exactly filled: the count ends on the key before the next square
if (s.rule.rad === 'sqrt' && s.N >= 3 && s.K < 1e15 && isSquare(s.K + 1)) { s.ringEvT0 = performance.now(); s.ringEvN = ringOf(s.K); reward(s.cx, s.cy); }
};
g = grp(L); txt(g, 'kgl-lab', 'START'); F.start = intField(g, '#00ffff', function () { return s.rule.start; }, function (n) { if (n > TWO53 - 1) n = TWO53 - 1; setRule(function (R) { R.start = n; }, false); }, 0);
// ---- r: the square root sets the distance
var pr = F.pr = E('div', null, null, panel), d0 = 0;
L = F.lr = E('div', 'kgl-line', null, pr);
function flip() { gesture(); endEdit(true); s.liveUser = !liveOn(); applyLive(); fitLines(); placeCircle(); need(); }
g = grp(L); txt(g, 'kgl-lab', 'r'); F.flipR = txt(g, 'kgl-pill', '='); F.flipR.setAttribute('data-pill', 'r'); F.flipR.addEventListener('click', flip); F.rPre = txt(g, 'kgl-op', 'SQRT('); F.keyR = keyField(g); F.rPost = txt(g, 'kgl-op', ')');
g = grp(L); F.rootEq = txt(g, 'kgl-op', '=');
F.dist = field(g, {
color: '#00ffff', raw: function () { return String(Math.round(s.selR * 10000) / 10000); },
apply: function (v) { var p = parseTyped(v, false); if (!p.ok || p.v < 0) return; if (p.big) { showMsg(LIMIT_LINE); return; } return toDistance(p.v); },
commit: function () {}, // Direct distance is exploration; the radicand earns FIND.
begin: function () { d0 = s.selR; },
drag: function (d) { toDistance(Math.max(0, Math.round((d0 + Math.round(d / 5) * 0.05 * Math.max(1, Math.pow(10, Math.floor(Math.log(Math.max(1, d0)) / Math.LN10)))) * 100) / 100)); },
wheel: function (dir) { toDistance(Math.max(0, Math.round((s.selR + dir * 0.1) * 100) / 100)); }
});
F.dist.el.classList.add('kgl-root-result'); F.rootEq.classList.add('kgl-root-result');
L = F.lrLive = E('div', 'kgl-line kgl-live', null, pr);
g = grp(L, 'kgl-tap'); F.rSq = txt(g, null, '', '#00ffff'); g.addEventListener('click', function () { gesture(); s.band = !s.band; need(); });
g = grp(L); txt(g, 'kgl-lab', 'AREA');
F.area = field(g, {
color: '#00ffff', raw: function () { return String(Math.round(Math.PI * s.selR * s.selR * 10000) / 10000); },
apply: function (v) { var p = parseTyped(v, false); if (!p.ok || p.v < 0) return; if (p.big) { showMsg(LIMIT_LINE); return; } return toDistance(Math.sqrt(p.v / Math.PI)); },
commit: function () {}, // AREA is exploration.
wheel: function (dir) { toDistance(Math.sqrt(Math.max(0, Math.PI * s.selR * s.selR + dir * Math.PI) / Math.PI)); }
});
g = grp(L); F.areaEq = txt(g, 'kgl-op', '');
// ---- theta: multiply, MOD, share of the circle
var pt = F.pt = E('div', null, null, panel);
L = F.lt = E('div', 'kgl-line kgl-mod', null, pt);
g = grp(L); F.flip = txt(g, 'kgl-pill', '='); txt(g, 'kgl-op', 'MOD(');
F.flip.setAttribute('data-pill', 't'); F.flip.addEventListener('click', flip);
F.keyT = keyField(g); txt(g, 'kgl-op', '×'); g = grp(L);
F.G = intField(g, '#ffb000', function () { return s.rule.G; }, function (n) { setRule(function (R) { R.G = n; }, false); }, 0);
F.G.o.commit = function () { if (s.rule.G === G32() && s.rule.W === TWO32 && F.G.start !== String(G32())) reward(s.cx, s.cy); };
txt(g, 'kgl-op', ','); g = grp(L);
function setW(n) { setRule(function (R) { R.W = n; }, false); }
F.W1 = intField(g, '#00ffff', function () { return s.rule.W; }, setW, 1); txt(g, 'kgl-op', ')'); F.W2 = F.W1;
L = F.ltLive = E('div', 'kgl-line kgl-live', null, pt);
L.classList.add('kgl-working'); g = F.gProd = grp(L); F.prod = txt(g, null, '');
g = grp(L); txt(g, 'kgl-op', '−'); F.n = txt(g, null, '', '#00ffff'); txt(g, 'kgl-op', '×'); F.circleWorking = txt(g, null, '');
g = grp(L); txt(g, 'kgl-op', '=');
F.rem = intField(g, '#00ffff', function () { return s.form.m; }, function (n) { toRemainder(n); }, 0);
F.rem.o.commit = quarterFind;
L = F.ltLive2 = E('div', 'kgl-line kgl-live', null, pt);
g = grp(L); txt(g, 'kgl-op', '≈'); F.frac = txt(g, null, '', '#00ffff'); E('span', 'kgl-ring', null, g);
g = grp(L); txt(g, 'kgl-op', '≈');
F.deg = field(g, {
color: '#00ffff', raw: function () { return String(Math.round(s.form.remDeg * 10000) / 10000); },
apply: function (v) { var p = parseTyped(v, false); if (!p.ok) return; if (p.big) { showMsg(LIMIT_LINE); return; } var fr = wrapDeg(p.v) / 360, W = s.rule.W; return toRemainder(Math.round(fr * W) % W); },
commit: quarterFind,
wheel: function (dir) { var W = s.rule.W, fr = ((Math.round(s.form.remDeg) + dir + 360) % 360) / 360; toRemainder(Math.round(fr * W) % W); }
});
txt(g, 'kgl-op', '°');
g = F.gBad = grp(L); F.diff = txt(g, 'kgl-bad', '');
// ---- X, Y: across and up
var px = F.px = E('div', null, null, panel);
L = E('div', 'kgl-line', null, px); g = grp(L); txt(g, 'kgl-lab', 'X'); txt(g, 'kgl-op', '≈'); F.xr = txt(g, null, '', '#00ffff'); txt(g, 'kgl-op', '× COS('); F.xt = txt(g, null, '', '#00ffff'); txt(g, 'kgl-op', ')');
g = grp(L); txt(g, 'kgl-op', '≈'); F.xv = txt(g, null, '', '#ffb000');
L = E('div', 'kgl-line', null, px); g = grp(L); txt(g, 'kgl-lab', 'Y'); txt(g, 'kgl-op', '≈'); F.yr = txt(g, null, '', '#00ffff'); txt(g, 'kgl-op', '× SIN('); F.yt = txt(g, null, '', '#00ffff'); txt(g, 'kgl-op', ')');
g = grp(L); txt(g, 'kgl-op', '≈'); F.yv = txt(g, null, '', '#ffb000');
// ---- one row of one-word taps: the two presets, how near these numbers are to the live Kuiper,
// the experiments of the open part, and the copy for a spreadsheet
var tags = F.tags = E('div', 'kgl-tags', null, s.root);
tags.style.cssText = 'position:absolute;bottom:0;left:0;right:0;background:#000;color:#fff;padding:6px 8px calc(8px + env(safe-area-inset-bottom,0px));box-sizing:border-box;z-index:4';
function tag(parent, text, fn) { var t = E('span', 'kgl-tag', text, parent); t.addEventListener('click', function () { gesture(); endEdit(true); fn(); }); return t; }
F.exTag = tag(tags, 'EXERCISE', function () { preset(1, 0); });
F.liveTag = tag(tags, 'LIVE', function () { preset(0, 0.5); });
F.copyTag = tag(tags, 'COPY', copySheet);
F.moreTag = E('button', 'kgl-tag kgl-more-button', '...', tags);
F.moreTag.setAttribute('type', 'button');
F.moreTag.setAttribute('aria-label', 'More lesson controls');
F.moreTag.setAttribute('aria-expanded', 'false');
F.moreTag.addEventListener('click', function () {
gesture(); endEdit(true);
var open = s.root.classList.toggle('kgl-more');
F.moreTag.setAttribute('aria-expanded', String(open));
});
var extra = F.extra = E('div', 'kgl-extra', null, tags);
extra.addEventListener('click', function () {
s.root.classList.remove('kgl-more'); F.moreTag.setAttribute('aria-expanded', 'false');
});
F.meter = E('span', 'kgl-meter', null, extra); F.mDots = [E('i', null, null, F.meter), E('i', null, null, F.meter), E('i', null, null, F.meter), E('i', null, null, F.meter)];
F.tgK = E('span', 'kgl-tagset', null, extra);
[100, 1000, 10000].forEach(function (n) { tag(F.tgK, commas(String(n)), function () { setCount(n); }); });
F.tgR = E('span', 'kgl-tagset', null, extra); F.radTags = {};
[['sqrt', 'SQRT(k)'], ['lin', 'k'], ['cbrt', 'k^(1/3)']].forEach(function (a) { F.radTags[a[0]] = tag(F.tgR, a[1], function () { setRule(function (R) { R.rad = a[0]; }, true); }); });
F.tgT = E('span', 'kgl-tagset', null, extra);
tag(F.tgT, '12', function () { setRule(function(R){R.G=1;R.W=12;},false); });
tag(F.tgT, '360', function () { setRule(function(R){R.G=1;R.W=360;},false); });
F.dragTag = tag(F.tgT, 'DRAG', function () { s.dragRule=!s.dragRule; F.dragTag.className='kgl-tag'+(s.dragRule?' on':''); F.dragTag.setAttribute('aria-pressed',String(s.dragRule)); });
F.dragTag.setAttribute('aria-label','Allow dot dragging to change multiplier');
F.dragTag.setAttribute('aria-pressed','false');
var bench = Array.isArray(root.KGBenchPresets) && root.KGBenchPresets.length ? root.KGBenchPresets.slice(0, 8) : [{ label: 'MIRROR', mirror: true }, { label: 'SPOKES', half: true }];
bench.forEach(function (b) {
if (!b || typeof b.label !== 'string') return;
tag(F.tgT, b.label.slice(0, 12), function () {
setRule(function (R) {
if (b.mirror) R.G = R.W - (R.G % R.W); else if (b.half) R.G = Math.floor(R.W / 2);
else { var w = Math.floor(+b.circle), m = Math.floor(+b.multiplier); if (w >= 1 && w <= TWO53) R.W = w; if (m >= 0 && m <= TWO53) R.G = m; }
}, true);
});
});
F.offsetTag = E('span', 'kgl-tag', '', extra); F.offsetTag.style.border = '0';
F.msg = E('div', 'kgl-msg', '', panel);
var id; for (id in F) if (F[id] && F[id].el && F[id].o) F[id].el.setAttribute('data-f', id);
}
// one line large; the rest of the working unfolds with "=" (open already where the screen has the room)
function liveOn() { var s = S; return s.liveUser != null ? s.liveUser : (!s.side && s.W >= 700 && s.H >= 640); }
function applyLive() {
var s = S, F = s.F, v = liveOn();
show(F.gProd, true); show(F.ltLive2, v); show(F.lrLive, v);
show(F.lt, true);
}
function setPiece(p, quiet) {
var s = S, F = s.F, i, cells = F.strip.children; s.piece = p; if(p!=='t'){s.dragRule=false; F.dragTag.className='kgl-tag'; F.dragTag.setAttribute('aria-pressed','false');}
show(F.pk, p === 'k'); show(F.pr, p === 'r'); show(F.pt, p === 't'); show(F.px, p === 'x');
show(F.tgK, p === 'k'); show(F.tgR, p === 'r'); show(F.tgT, p === 't');
for (i = 0; i < cells.length && i < 12; i++) if (cells[i]._id) cells[i].className = 'kgl-cell' + (cells[i]._id === 'k' ? ' big' : '') + (cells[i]._id === p ? ' on' : '');
if (p !== 'r' && s.kx !== s.K) s.kx = s.K;
applyLive();
if (quiet) return;
recompute(); restD(); updateFormula(); fitLines(); placeCircle(); writeHash(); need();
}
function sheetText() { var rows = sheet(S.rule, Math.max(lastKey(), S.K)); return rows ? rows.join('\t') : ''; }
function copySheet() {
if (!sheetText()) return;
var s = S, t = sheetText(), done = function () { s.F.copyTag.className = 'kgl-tag on'; s.timers.push(setTimeout(function () { if (S === s) s.F.copyTag.className = 'kgl-tag'; }, 1200)); };
s.copied = t;
function fallback() { try { var ta = E('textarea', null, null, s.root); ta.value = t; ta.style.cssText = 'position:absolute;left:-9999px;top:0'; ta.select(); document.execCommand('copy'); s.root.removeChild(ta); } catch (e) { } done(); }
try { if (root.navigator && root.navigator.clipboard && root.navigator.clipboard.writeText) { root.navigator.clipboard.writeText(t).then(done, fallback); return; } } catch (e) { }
fallback();
}
function showMsg(t) {
var s = S; s.F.msg.textContent = t; s.F.msg.style.display = 'block'; clearTimeout(s.msgTimer);
s.msgTimer = setTimeout(function () { if (S === s) { s.F.msg.style.display = 'none'; fitLines(); placeCircle(); need(); } }, 7000);
fitLines(); placeCircle(); need();
}
function updateFormula() {
var s = S, F = s.F, R = s.rule, k = s.K, f = s.form = angleForm(R, k), T = s.T;
var ks = commas(String(k)); // keys are whole numbers up to 2^53: String() is exact
placeOne(R, k, T);
var between = s.kx !== k, r = between ? radiusAt(R, s.kx) : T.r, x = between ? r * Math.cos(2 * Math.PI * T.m / R.W) : T.x, y = between ? r * Math.sin(2 * Math.PI * T.m / R.W) : T.y;
// the two paths agree: the exact product above, and the wrapped whole numbers the law itself uses
var diff = circDiff(f.turns, T.turns); s.diff = diff;
if (diff > 1e-9) { show(F.gBad, true); setT(F.diff, '≠ ' + diff.toExponential(2)); } else show(F.gBad, false);
var rs = fmtDist(r), xs = fmtDist(x), ys = fmtDist(y), kxs = between ? String(s.kx) : ks;
setT(F.sk, between ? '-' : ks); setT(F.sr, rs); setT(F.st, fmtNum(f.theta, 3)); setT(F.sx, xs); setT(F.sy, ys);
F.key.set(ks); F.keyT.set(ks); F.keyR.set(kxs);
F.count.set(commas(String(s.N))); F.start.set(commas(String(R.start)));
F.G.set(f.GStr); F.W1.set(f.WStr); F.W2.set(f.WStr);
setT(F.circleWorking, f.WStr); setT(F.prod, f.prodStr); setT(F.n, f.nStr); F.rem.set(f.mStr); setT(F.frac, f.fracStr); F.deg.set(f.degStr);
setT(F.rPre, R.rad === 'sqrt' ? 'SQRT(' : ''); setT(F.rPost, R.rad === 'sqrt' ? (R.off ? '+ ' + R.off + ' )' : ')') : R.rad === 'lin' ? '' : '^ (1/3)');
F.dist.set(rs);
var sq = R.rad === 'sqrt' ? s.kx + R.off : r*r, sqs = String(sq), area = Math.PI * r * r;
var sign = R.rad === 'sqrt' ? rootSign(rs, s.kx, R.off) : '≈'; setT(F.rootEq, sign);
setT(F.rSq, rs + ' × ' + rs + ' ' + sign + ' ' + sqs); F.area.set(fmtDist(area)); setT(F.areaEq, '≈ PI × ' + sqs);
setT(F.xr, rs); setT(F.yr, rs); setT(F.xt, f.thetaStr); setT(F.yt, f.thetaStr); setT(F.xv, xs); setT(F.yv, ys);
var id; for (id in F.radTags) { var onn = id === R.rad; if (F.radTags[id]._on !== onn) { F.radTags[id]._on = onn; F.radTags[id].className = 'kgl-tag' + (onn ? ' on' : ''); } }
var ex = isExercise(R), lv = isLive(R);
if (F.exTag._on !== ex) { F.exTag._on = ex; F.exTag.className = 'kgl-tag' + (ex ? ' on' : ''); }
if (F.liveTag._on !== lv) { F.liveTag._on = lv; F.liveTag.className = 'kgl-tag' + (lv ? ' on' : ''); }
setT(F.offsetTag, 'SQRT(k' + (R.off ? ' + ' + R.off : '') + ')');
var eq = [R.G === G32(), R.W === TWO32, R.rad === 'sqrt' && R.off === 0.5, R.start === 0], i;
for (i = 0; i < 4; i++) { var c = eq[i] ? 'on' : ''; if (F.mDots[i].className !== c) F.mDots[i].className = c; }
s.lblRem = f.degStr + '°'; s.lblDist = rs; s.lblArea = sqs; s.lblX = xs; s.lblY = ys;
s.stackNum = f.nNum; s.stackStr = f.nStr; s.selR = r; s.selTh = T.turns * 360;
applyPanelPos(); fitLines(); writeHash();
}
function liveFormula(now) { // while the arm swings the computed numbers run with it (text only, at most 20 times a second)
var s = S, A = s.A, D = s.D, F = s.F; if (now - A.lastText < 50) return; A.lastText = now;
var rem = A.FL.remDeg + D.e * s.Tdeg - (D.cross && A.FL.remDeg + s.Tdeg >= 360 ? 360 : 0); if (rem < 0) rem = 0;
var ds = fmtNum(rem, 2);
// Keep the committed product, circle count and remainder together during travel.
// The formula shows the selected destination; only the drawn arm travels.
s.lblRem = ds + '°'; s.lblDist = fmtDist(A.rLo + (A.rHi - A.rLo) * D.e);
}
// roaming: the numbers of the place under the mouse roll in the same cells; the nearest drawn key lights
function probeFormula() {
var s = S, F = s.F, R = s.rule, P = s.probe, dx = P.x - s.cx, dy = -(P.y - s.cy), dist = Math.hypot(dx, dy) / s.vs;
var ang = Math.atan2(dy, dx) / D2R; if (ang < 0) ang += 360;
var i, n = s.cnt, best = -1, bd = Infinity;
for (i = 0; i < n; i++) { var ex = s.cx + s.SX[i] * s.vs - P.x, ey = s.cy - s.SY[i] * s.vs - P.y, d = ex * ex + ey * ey; if (d < bd) { bd = d; best = i; } }
P.idx = best; P.gap = best >= 0 ? fmtDist(Math.sqrt(bd) / s.vs) : '';
P.keyStr = best >= 0 ? commas(String(s.KS[best])) : '';
// Hover only highlights the nearest sampled point. It does not rewrite the selected identity.
}
function fitLines() { // 28 px or more; a number too long for the screen drops its line to 24 px, then breaks at any digit
var s = S, lines = s.panel.querySelectorAll('.kgl-line'), i, j;
var avail = s.panel.clientWidth - 20; if (!(avail > 0)) return;
for (i = 0; i < lines.length && i < 12; i++) {
var L = lines[i]; if (L.offsetParent === null || L.classList.contains('kgl-scroll')) continue; L.style.fontSize = ''; L.classList.remove('kgl-wrap');
var widest = 0, ch = L.children; for (j = 0; j < ch.length && j < 40; j++) { var w = ch[j].offsetWidth; if (w > widest) widest = w; }