The complete HTML program, including its combinatorial model and animation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#0b1017" />
<meta name="description" content="Klein quartic: animated hyperbolic tiling and the 168 automorphisms of PSL(2,F7)." />
<title>The Klein quartic — a hyperbolic atlas</title>
<style>
:root {
--paper: #0b1017;
--canvas: #080f17;
--ink: #e0e7e8;
--quiet: #90a1a9;
--rule: #34434d;
--fine: #202e37;
--orbit: #75bdc8;
--warm: #e5c188;
}
*,*::before,*::after {box-sizing:border-box}
html {scroll-behavior:smooth;background:var(--paper);color-scheme:dark}
body {margin:0;min-width:320px;background:var(--paper);color:var(--ink);font:14px/1.5 Arial,Helvetica,sans-serif;-webkit-font-smoothing:antialiased}
button,select,input {font:inherit}
button {cursor:pointer}
button:focus-visible,select:focus-visible,input:focus-visible,summary:focus-visible {outline:2px solid #dddddd;outline-offset:3px}
button:disabled {opacity:.4;cursor:default}
.page {width:min(100%,940px);margin:0 auto;padding:40px 40px 52px}
.mast {display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid #cbcbcb;padding-bottom:12px}
.mast span {font:11px/1.4 'Courier New',monospace;letter-spacing:.02em;color:#a6a6a6}
.mast .folio {color:#79797e}
.hero {padding:38px 0 28px}
h1 {font:normal clamp(39px,5.8vw,58px)/1.08 Georgia,'Times New Roman',serif;letter-spacing:-.043em;margin:0 0 12px}
.mathline {display:flex;align-items:baseline;gap:16px;justify-content:space-between;flex-wrap:wrap;color:#aaaaaa}
.mathline .equation {font:italic 18px/1.4 Georgia,'Times New Roman',serif;letter-spacing:.025em;color:#cbcbcb}
.mathline .invariant {font:12px/1.4 'Courier New',monospace;color:#8e8e92}
.figure-heading {width:min(100%,760px);margin:0 auto 10px;display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap}
.fig-label {font-size:12px;color:#aaaaaa}
.fig-label strong {font-weight:600;color:#dadada}
.canvas-toolbar {display:flex;align-items:center;gap:18px}
.tool-toggle {display:flex;align-items:center;gap:6px;color:#979797;font-size:11px;white-space:nowrap;cursor:pointer;user-select:none}
.tool-toggle input {width:13px;height:13px;margin:0;accent-color:#9ac2c3;cursor:pointer}
.canvas-container {width:min(100%,760px);aspect-ratio:1.08;position:relative;background:var(--canvas);border:1px solid #354650;overflow:hidden;margin:auto}
canvas {width:100%;height:100%;display:block;cursor:crosshair;touch-action:manipulation}
.tooltip {position:absolute;display:none;left:0;top:0;z-index:10;pointer-events:none;white-space:nowrap;background:#101b25;color:#e2e9e9;border:1px solid #5f7e89;padding:7px 9px;font:11px 'Courier New',monospace;box-shadow:0 3px 14px #0007}
.figure-caption {width:min(100%,760px);margin:10px auto 14px;display:flex;align-items:start;justify-content:space-between;gap:18px;font:11px/1.65 Georgia,'Times New Roman',serif;color:#9baab0}
.figure-caption .caps-left {flex:1}
.figure-caption .fig-number {font-style:italic;color:#cfcfcf}
.figure-actions {display:flex;align-items:center;gap:13px;flex-shrink:0}
#fpsLabel {font:10px/1.4 'Courier New',monospace;color:#6d6d72;white-space:nowrap}
.download {padding:0;border:0;background:transparent;color:#a9a9ac;text-decoration:underline;text-underline-offset:3px;font:11px/1.4 Arial,Helvetica,sans-serif;white-space:nowrap}
.download:hover {color:#ffffff}
.figure-key {max-width:760px;margin:12px auto 0;display:flex;gap:10px 22px;flex-wrap:wrap;color:#a9bac1;font:10px/1.5 'Courier New',monospace}
.figure-key span {display:inline-flex;align-items:center;gap:7px}
.figure-key i {width:13px;height:8px;background:var(--orbit);display:inline-block;border:1px solid #ffffff35}
.figure-key .current-key {background:var(--warm)}
.figure-key .fixed-key {width:8px;height:8px;margin:0 3px;border:1px solid #aec1c8;border-radius:50%;background:transparent}
.orbit-sequence {max-width:760px;margin:0 auto 28px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;color:#8296a1;font:10px/1.5 'Courier New',monospace}
#orbitSequence {display:flex;align-items:center;gap:5px;flex-wrap:wrap}
.sequence-face {border:1px solid #33454f;border-radius:0;background:transparent;color:#acc0c6;min-width:29px;padding:3px 5px;font:11px 'Courier New',monospace;transition:background-color .15s,color .15s}
.sequence-face:hover {background:#192d37;color:#eff5f5}
.sequence-face[aria-current="step"] {background:var(--warm);color:#192128;border-color:var(--warm)}
.sequence-arrow {color:#5e7c88;font-size:12px}
.controls {display:grid;grid-template-columns:1fr 1fr;column-gap:36px;align-items:start;border-top:1px solid #c1c1c1;padding:26px 0 22px;margin:0 auto;max-width:800px}
.control-block + .control-block {border-left:1px solid var(--fine);padding-left:35px}
.control-heading {display:flex;align-items:baseline;justify-content:space-between;gap:10px;margin-bottom:18px}
.control-heading .section-title {margin:0;font:600 11px/1.4 Arial,Helvetica,sans-serif;letter-spacing:.11em;text-transform:uppercase}
.control-heading small {font:11px/1.4 'Courier New',monospace;color:#888888}
.preset-grid {display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}
.preset {min-height:55px;display:flex;align-items:center;justify-content:center;gap:10px;padding:8px 5px;text-align:center;border:1px solid #434347;border-radius:0;background:transparent;color:#cccccc;transition:background-color .12s,border-color .12s}
.preset:hover {background:#141417}
.preset.active {background:#d6d6d6;border-color:#d6d6d6;color:#050507}
.preset.active:hover {background:#eeeeee}
.preset-top {font:24px/1 Georgia,'Times New Roman',serif}
.preset-bottom {font:11px/1.15 'Courier New',monospace;color:#8e8e91}
.preset.active .preset-bottom {color:#111111}
.field-label {display:flex;justify-content:space-between;align-items:center;gap:10px;margin:19px 0 8px;color:#bbbbbb;font-size:11px}
.field-label small {font:10px 'Courier New',monospace;color:#75757a}
select {width:100%;min-height:39px;border:1px solid #434347;border-radius:0;padding:8px 10px;background:#030305;color:#dbdbdb;cursor:pointer;font:12px 'Courier New',monospace}
.filters {display:flex;align-items:center;gap:7px;margin-top:8px;flex-wrap:wrap}
.filter {border:0;border-bottom:1px solid transparent;background:transparent;color:#7a7a7f;padding:5px 6px 4px;border-radius:0;font:11px 'Courier New',monospace}
.filter:hover {color:#eeeeee}
.filter.active {color:#e8e8e8;border-bottom-color:#e8e8e8}
.progress-row {display:flex;justify-content:space-between;align-items:baseline;gap:12px;margin:3px 0 15px}
.equation-power {font:normal 35px/1.1 Georgia,'Times New Roman',serif;letter-spacing:-.02em;color:#d9d9d9}
.equation-power sup {font-size:17px;vertical-align:super}
.phase-caption {color:#777777;font:11px/1.4 'Courier New',monospace;text-align:right}
.orbit-line {height:2px;background:#27272b;overflow:hidden}
.orbit-fill {height:100%;width:0;background:var(--orbit);transition:width .15s linear}
.transport {display:grid;grid-template-columns:1fr 1fr 1.2fr;gap:8px;margin-top:21px}
.ctrl-btn {display:flex;align-items:center;justify-content:center;gap:8px;min-height:41px;padding:7px 8px;background:transparent;border:1px solid #454545;color:#cacaca;border-radius:0;font-size:12px;transition:background-color .15s}
.ctrl-btn:hover {background:#161619}
.ctrl-btn.primary {background:#bed4d3;border-color:#bed4d3;color:#101b21}
.ctrl-btn.primary:hover {background:#d6e5e2}
.ctrl-btn svg {height:14px;width:14px}
.speed-row {display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:21px;font-size:11px;color:#929297}
.speed-row label {white-space:nowrap}
input[type=range] {width:100%;height:14px;accent-color:#cccccc;cursor:pointer}
#speedLabel {font:11px 'Courier New',monospace;color:#aaaaaa;min-width:32px;text-align:right}
.selected-box {margin-top:20px;padding-top:11px;border-top:1px solid var(--fine);display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;font-size:11px}
.selected-box small {font-size:11px;color:#76767b}
.selected-box strong {font:12px 'Courier New',monospace;color:#d6d6d6}
.selected-orbit {font:11px 'Courier New',monospace;color:#76767b}
.algebra {max-width:800px;margin:0 auto;border-top:1px solid var(--fine);padding-top:15px;display:flex;flex-wrap:wrap;align-items:baseline;gap:8px 15px;color:#9d9da2;font-size:11px}
#elementId {font:11px 'Courier New',monospace;color:#cccccc}
#elementName {color:#aaaaaa}
#orderPill {font:11px 'Courier New',monospace;color:#cccccc}
.algebra details {flex-basis:100%;margin-top:3px}
.algebra summary {color:#7d7d83;cursor:pointer;display:table;font-size:11px}
.algebra summary:hover {color:#dddddd}
.algebra-expanded {display:flex;flex-wrap:wrap;gap:5px 20px;padding:9px 0 0;font:11px/1.8 'Courier New',monospace;color:#9b9ba0}
.algebra-expanded strong {font-weight:normal;color:#cccccc}
#elementMatrix {white-space:nowrap}
#cycleMeta {line-height:1.6}
.footnote {max-width:800px;margin:27px auto 0;padding-top:11px;border-top:1px solid var(--rule);font:italic 11px/1.65 Georgia,'Times New Roman',serif;color:#7b7b81}
.footer {max-width:800px;margin:25px auto 0;text-align:right;font:10px 'Courier New',monospace;color:#555555}
@media(max-width:730px) {
.page {padding:24px 23px 40px}
.hero {padding:30px 0 24px}
h1 {font-size:clamp(37px,7.7vw,53px)}
.controls {column-gap:24px}
.control-block + .control-block {padding-left:24px}
.preset {gap:3px;flex-direction:column;min-height:62px}
.preset-top {font-size:23px}
.transport {gap:5px}
.ctrl-btn {font-size:11px;padding:6px 3px}
}
@media(max-width:590px) {
.page {padding:21px 17px 34px}
.mast span {font-size:10px}
.hero {padding:29px 0 26px}
h1 {font-size:clamp(37px,10vw,48px)}
.mathline .equation {font-size:16px}
.mathline .invariant {font-size:11px}
.figure-heading {gap:8px;margin-bottom:9px}
.fig-label {font-size:11px}
.canvas-toolbar {gap:10px;flex-wrap:wrap}
.tool-toggle {font-size:10px}
.canvas-container {aspect-ratio:1.02}
.figure-caption {margin-bottom:12px;flex-wrap:wrap;gap:5px 10px;font-size:10.5px}
.figure-key {gap:8px 14px;font-size:9px}
.orbit-sequence {gap:8px;margin-bottom:24px}
.controls {grid-template-columns:1fr;padding-top:22px;gap:27px}
.control-block + .control-block {border-left:0;border-top:1px solid var(--fine);padding-left:0;padding-top:25px}
.preset {flex-direction:row;gap:12px;min-height:47px}
.control-heading {margin-bottom:14px}
.field-label {margin-top:15px}
.progress-row {margin-top:0}
.algebra {padding-top:17px}
}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;scroll-behavior:auto!important}}
</style>
</head>
<body>
<div class="page">
<header class="mast" aria-label="Header">
<span>Riemann surfaces / group actions</span>
<span class="folio">01</span>
</header>
<section class="hero">
<h1>The Klein quartic</h1>
<div class="mathline">
<span class="equation">X³Y + Y³Z + Z³X = 0</span>
<span class="invariant">g = 3 · |Aut(X)| = 168</span>
</div>
</section>
<main>
<section class="figure" aria-label="Interactive hyperbolic tiling">
<div class="figure-heading">
<div class="fig-label"><strong>Fig. 1.</strong> Poincaré disk · {7,3} tiling</div>
<div class="canvas-toolbar">
<label class="tool-toggle"><input type="checkbox" id="showLabels" checked> Labels</label>
<label class="tool-toggle"><input type="checkbox" id="showMesh" checked> Triangle mesh</label>
<label class="tool-toggle"><input type="checkbox" id="showTrails" checked> Trajectories</label>
</div>
</div>
<div class="canvas-container" id="canvasContainer">
<canvas id="disk" aria-label="Interactive Poincaré disc with 24 heptagons, colored by permutation cycle. Click a face to follow its orbit."></canvas>
<div class="tooltip" id="tooltip"></div>
</div>
<div class="figure-key" aria-label="Figure legend"><span><i></i> Selected orbit</span><span><i class="current-key"></i> Current face</span><span><i class="fixed-key"></i> Fixed face</span></div>
<div class="figure-caption">
<span class="caps-left"><span class="fig-number">24 heptagons.</span> Colors group faces into permutation cycles. Click a face to follow its orbit.</span>
<div class="figure-actions"><span id="fpsLabel">— fps</span><button type="button" class="download" id="saveImage">Export PNG</button></div>
</div>
<div class="orbit-sequence"><span>Tracked orbit</span><div id="orbitSequence" aria-label="Faces in the tracked orbit"></div></div>
</section>
<section class="controls" aria-label="Animation controls">
<div class="control-block">
<div class="control-heading"><h2 class="section-title">Automorphism</h2><small>PSL(2, 𝔽₇)</small></div>
<div class="preset-grid" aria-label="Distinguished automorphisms">
<button type="button" class="preset active" data-preset="7" aria-label="Order-7 automorphism" aria-pressed="true"><span class="preset-top">7</span><span class="preset-bottom">face</span></button>
<button type="button" class="preset" data-preset="3" aria-label="Order-3 automorphism" aria-pressed="false"><span class="preset-top">3</span><span class="preset-bottom">vertex</span></button>
<button type="button" class="preset" data-preset="2" aria-label="Order-2 automorphism" aria-pressed="false"><span class="preset-top">2</span><span class="preset-bottom">edge</span></button>
</div>
<label class="field-label" for="elementSelect">Element <small id="elementCount">168 / 168</small></label>
<select id="elementSelect" aria-label="Select one of the 168 automorphisms"></select>
<div class="filters" id="filters" aria-label="Filter by order">
<button type="button" class="filter active" data-order="all">All</button>
<button type="button" class="filter" data-order="2">2</button>
<button type="button" class="filter" data-order="3">3</button>
<button type="button" class="filter" data-order="4">4</button>
<button type="button" class="filter" data-order="7">7</button>
</div>
</div>
<div class="control-block">
<div class="control-heading"><h2 class="section-title">Animation</h2><small id="playStatus">Paused</small></div>
<div class="progress-row"><div class="equation-power" id="powerLabel">g<sup>0</sup></div><div class="phase-caption" id="phaseCaption">0 / 7</div></div>
<div class="orbit-line" aria-hidden="true"><div class="orbit-fill" id="orbitFill"></div></div>
<div class="transport">
<button type="button" class="ctrl-btn" id="resetBtn" title="Return to the starting face"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M3 11a9 9 0 1 1 3 7M3 4v7h7"/></svg> Reset</button>
<button type="button" class="ctrl-btn" id="stepBtn" title="Apply once"><svg viewBox="0 0 24 24" fill="currentColor"><path d="m5 4 11 8-11 8V4Zm13 0h2v16h-2z"/></svg> Step</button>
<button type="button" class="ctrl-btn primary" id="playBtn" title="Automatic playback"><svg id="playIcon" viewBox="0 0 24 24" fill="currentColor"><path d="m7 4 14 8-14 8V4Z"/></svg><span id="playText">Play</span></button>
</div>
<div class="speed-row"><label for="speed">Speed</label><input id="speed" type="range" min="0.5" max="2.5" value="1" step="0.1" aria-label="Animation speed"><span id="speedLabel">1.0×</span></div>
<div class="selected-box"><small>Tracked face</small><strong id="trackedLabel">—</strong><span class="selected-orbit" id="orbitLabel">—</span></div>
</div>
</section>
<div class="algebra" aria-label="Automorphism details">
<span id="elementId">No. 003 / 168</span>
<span id="elementName">Rotation about a face</span>
<span id="orderPill">Order 7</span>
<details>
<summary>Matrix and cycles</summary>
<div class="algebra-expanded"><code id="elementMatrix"></code><span id="cycleMeta"></span></div>
</details>
</div>
<p class="footnote">The shaded triangles have angles π/2, π/3 and π/7 in the hyperbolic metric. The disc is a conformal development of the covering surface; trajectories connect exact images of faces under the group action.</p>
</main>
<footer class="footer">24 − 84 + 56 = −4 = 2 − 2g</footer>
</div>
<script>
'use strict';
/*
* KLEIN QUARTIC — Exact combinatorial model.
* G = PSL(2,F7), of order 168.
* S=[[0,-1],[1,0]] (order 2), T=[[1,1],[0,1]] (order 7), ST (order 3).
* The 24 faces are the cosets g<T>, with the left action of G.
* Hyperbolic representation: S is a half-turn about the midpoint of an
* edge of {7,3}; T rotates through 2π/7 about the root heptagon's centre.
* The 24 faces are developed by BFS in the universal cover. Repeated
* tiles outside this domain do not represent additional faces of the
* quotient surface.
*/
const $ = s => document.querySelector(s);
const TAU = Math.PI*2;
const mod = n => ((n % 7) + 7) % 7;
const ID = [1,0,0,1];
const S = [0,6,1,0];
const T = [1,1,0,1];
const Ti = [1,6,0,1];
function multiply(A,B) {
return [mod(A[0]*B[0]+A[1]*B[2]),mod(A[0]*B[1]+A[1]*B[3]),mod(A[2]*B[0]+A[3]*B[2]),mod(A[2]*B[1]+A[3]*B[3])];
}
function matrixKey(M) {
const a=M.map(mod), b=a.map(n=>mod(-n));
for(let i=0;i<4;i++) if(a[i]!==b[i]) return (a[i]<b[i] ? a:b).join(',');
return a.join(',');
}
const idKey=matrixKey(ID);
function enumerateGroup() {
const result=[{m:ID,word:'e',depth:0}]; const keys=new Map([[idKey,0]]);
for(let idx=0;idx<result.length;idx++) {
const parent=result[idx];
for(const [gen,symbol] of [[S,'S'],[T,'T'],[Ti,'t']]) {
const m=multiply(parent.m,gen), key=matrixKey(m);
if(!keys.has(key)) {
keys.set(key,result.length);
result.push({m,word:parent.word==='e'?symbol:parent.word+symbol,depth:parent.depth+1});
}
}
}
if(result.length!==168) throw new Error('Incorrect group size: '+result.length+' elements');
return {elements:result,byKey:keys};
}
const group=enumerateGroup();
const TPowers=[ID];for(let i=1;i<7;i++) TPowers.push(multiply(TPowers[i-1],T));
function faceKey(M) {let best=''; for(const p of TPowers) {const key=matrixKey(multiply(M,p));if(!best||key<best)best=key;}return best;}
const faceKeyToID=new Map();
for(const element of group.elements) {const key=faceKey(element.m);if(!faceKeyToID.has(key))faceKeyToID.set(key,faceKeyToID.size);}
if(faceKeyToID.size!==24)throw new Error('Incorrect number of faces');
const faceID=M=>faceKeyToID.get(faceKey(M));
const rootID=faceID(ID);
// Complex numbers and SU(1,1) isometries of the Poincaré disk.
const C=(x=0,y=0)=>({x,y});
const add=(a,b)=>C(a.x+b.x,a.y+b.y);
const sub=(a,b)=>C(a.x-b.x,a.y-b.y);
const mul=(a,b)=>C(a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x);
const conjugate=a=>C(a.x,-a.y);
const scale=(a,s)=>C(a.x*s,a.y*s);
const magnitude=a=>Math.hypot(a.x,a.y);
const cdiv=(a,b)=>{const d=b.x*b.x+b.y*b.y;return C((a.x*b.x+a.y*b.y)/d,(a.y*b.x-a.x*b.y)/d);};
const unitAngle=th=>C(Math.cos(th),Math.sin(th));
const gIdentity={a:C(1,0),b:C(0,0)};
function gCompose(f,g) {return {a:add(mul(f.a,g.a),mul(f.b,conjugate(g.b))),b:add(mul(f.a,g.b),mul(f.b,conjugate(g.a)))};}
function gApply(f,z) {return cdiv(add(mul(f.a,z),f.b),add(mul(conjugate(f.b),z),conjugate(f.a)));}
function gRot(center,theta) {
const u=unitAngle(theta/2),uBar=conjugate(u),r2=center.x*center.x+center.y*center.y;
return {a:scale(sub(u,scale(uBar,r2)),1/(1-r2)),b:scale(mul(center,sub(uBar,u)),1/(1-r2))};
}
const coshR=(1/Math.tan(Math.PI/7))*(1/Math.tan(Math.PI/3));
const radialVertex=Math.tanh(Math.acosh(coshR)/2);
const radialMid=Math.tanh(Math.acosh(Math.cos(Math.PI/3)/Math.sin(Math.PI/7))/2);
const polygonBase=Array.from({length:7},(_,k)=>scale(unitAngle(-Math.PI/7+TAU*k/7),radialVertex));
const TGeo=gRot(C(0,0),TAU/7), SGeo=gRot(C(radialMid,0),Math.PI);
const TGeoPowers=[gIdentity];for(let k=1;k<7;k++)TGeoPowers.push(gCompose(TGeoPowers[k-1],TGeo));
function geoSegment(p,q,n=8) {
// Exact geodesic via Möbius map taking p to 0, with distance interpolation.
const w=cdiv(sub(q,p),sub(C(1,0),mul(conjugate(p),q)));
const r=magnitude(w),d=Math.atanh(Math.min(.9999999999,r));
const result=[];
for(let j=0;j<=n;j++) {
const v=r>1e-12?scale(w,Math.tanh(d*j/n)/r):C(0,0);
result.push(cdiv(add(v,p),add(C(1,0),mul(conjugate(p),v))));
}
return result;
}
function polygonFromGeo(geo) {
const vertices=polygonBase.map(z=>gApply(geo,z));
const perimeter=[];
for(let i=0;i<7;i++) {
const pts=geoSegment(vertices[i],vertices[(i+1)%7],14);
perimeter.push(...pts.slice(0,-1));
}
return {vertices,perimeter,center:gApply(geo,C(0,0))};
}
// A connected, non-overlapping patch containing one geometric lift of each of the 24 faces.
const faces=new Array(24);
faces[rootID]={id:rootID,finite:ID,geo:gIdentity,depth:0,parent:-1,...polygonFromGeo(gIdentity)};
const queue=[faces[rootID]];
for(let at=0;at<queue.length;at++) {
const f=queue[at];
for(let j=0;j<7;j++) {
const nextFinite=multiply(multiply(f.finite,TPowers[j]),S);
const nextID=faceID(nextFinite);
if(faces[nextID])continue;
const nextGeo=gCompose(gCompose(f.geo,TGeoPowers[j]),SGeo);
const newFace={id:nextID,finite:nextFinite,geo:nextGeo,depth:f.depth+1,parent:f.id,...polygonFromGeo(nextGeo)};
faces[nextID]=newFace;queue.push(newFace);
}
}
if(faces.some(x=>!x))throw new Error('Incomplete development: '+queue.length+' faces');
const transformations=group.elements.map((el,i)=> {
const perm=faces.map(f=>faceID(multiply(el.m,f.finite)));
const imageSet=new Set(perm);
if(imageSet.size!==24)throw new Error('Non-bijective permutation: '+i);
let power=ID,order=0;
do{power=multiply(power,el.m);order++;}while(matrixKey(power)!==idKey&&order<170);
const visited=new Set(),cycles=[];
for(let j=0;j<24;j++) {
if(visited.has(j))continue;
const cyc=[];let next=j;
while(!visited.has(next)) {visited.add(next);cyc.push(next);next=perm[next];}
cycles.push(cyc);
}
const counts={}; for(const cyc of cycles)counts[cyc.length]=(counts[cyc.length]||0)+1;
return {...el,index:i,perm,order,cycles,counts,fixed:counts[1]||0};
});
const findElement=(M)=>group.byKey.get(matrixKey(M));
const PRESETS={7:findElement(T),3:findElement(multiply(S,T)),2:findElement(S)};
const byOrder={};for(const item of transformations){(byOrder[item.order]??=[]).push(item.index);}
if(JSON.stringify(Object.fromEntries(Object.entries(byOrder).map(([k,v])=>[k,v.length]))) !== JSON.stringify({'1':1,'2':21,'3':56,'4':42,'7':48})) {
console.warn('Unexpected distribution of element orders',Object.fromEntries(Object.entries(byOrder).map(([k,v])=>[k,v.length])));
}
// Subtle repeat cells in the universal {7,3} covering (background).
const cover=[];
const coverSeen=new Set();
function centerKey(z) {return `${Math.round(z.x*100000)},${Math.round(z.y*100000)}`;}
const coverQueue=[{geo:gIdentity,depth:0}];coverSeen.add(centerKey(C(0,0)));
for(let i=0;i<coverQueue.length && i<680;i++) {
const f=coverQueue[i]; const poly=polygonFromGeo(f.geo);
if(f.depth>0)cover.push({depth:f.depth,...poly});
if(f.depth>=6||coverQueue.length>=680)continue;
for(let j=0;j<7;j++) {
if(coverQueue.length>=680)break;
const nextGeo=gCompose(gCompose(f.geo,TGeoPowers[j]),SGeo);
const z=gApply(nextGeo,C(0,0)),key=centerKey(z);
if(magnitude(z)>.995||coverSeen.has(key))continue;
coverSeen.add(key);coverQueue.push({geo:nextGeo,depth:f.depth+1});
}
}
const disk=$('#disk'),canvasContainer=$('#canvasContainer'),ctx=disk.getContext('2d',{alpha:false});
const tooltip=$('#tooltip');
let cw=0,ch=0,cr=0,cx=0,cy=0,dpr=1,backgroundCanvas=null,faceCanvas=null;
let faceLayerKey='',routes=[],faceCycle=[],faceColors=[];
const PALETTE=[[107,181,192],[210,158,101],[147,151,210],[117,181,151],
[207,131,150],[113,158,212],[188,184,111],[165,145,187],
[97,170,158],[191,137,110],[151,182,199],[173,174,142]];
const colorMix=(a,b,t)=>a.map((v,i)=>Math.round(v+(b[i]-v)*t));
const rgba=(c,a=1)=>`rgba(${c[0]},${c[1]},${c[2]},${a})`;
const cycleColor=i=>i<PALETTE.length?PALETTE[i]:colorMix(PALETTE[i%PALETTE.length],[226,226,210],.28);
const screen=z=>({x:cx+z.x*cr,y:cy-z.y*cr});
let reducedMotion=window.matchMedia&&window.matchMedia('(prefers-reduced-motion: reduce)').matches;
let nowTime=performance.now();
const state={elementId:PRESETS[7],activeFace:faceID(S),orbitSeed:faceID(S),phase:0,playing:false,anim:null,showLabels:true,showMesh:true,showTrails:true,speed:1,hover:-1,filter:'all',lastStep:nowTime};
let frameSamples=0,frameTime=nowTime,measuredFPS=60;
const activeTransform=()=>transformations[state.elementId];
const ease=t=>t*t*(3-2*t);
function clamp(t,a,b){return Math.max(a,Math.min(b,t));}
function lerp(p,q,t){return C(p.x+(q.x-p.x)*t,p.y+(q.y-p.y)*t);}
function orbitOf(id,t) {
const orbit=[],seen=new Set();let curr=id;
while(!seen.has(curr)) {seen.add(curr);orbit.push(curr);curr=t.perm[curr];}
return orbit;
}
function matrixFormat(m){return `[ ${m[0]} ${m[1]} ] [ ${m[2]} ${m[3]} ] (mod 7)`;}
function prettyCycleCounts(t){return Object.keys(t.counts).sort((a,b)=>Number(b)-Number(a)).map(k=>`${t.counts[k]} cycle${t.counts[k]>1?'s':''} of length ${k}`).join(' · ');}
function applyPresetButtons(){
for(const btn of document.querySelectorAll('.preset')) {
const on=PRESETS[btn.dataset.preset]===state.elementId;
btn.classList.toggle('active',on);btn.setAttribute('aria-pressed',String(on));
}
}
function updateView() {
const t=activeTransform();
$('#elementId').textContent=`No. ${String(t.index+1).padStart(3,'0')} / 168`;
const name=t.index===PRESETS[7]?'Rotation about a face':t.index===PRESETS[3]?'Rotation about a vertex':t.index===PRESETS[2]?'Half-turn about an edge':t.order===1?'Identity':`Automorphism No. ${String(t.index+1).padStart(3,'0')}`;
$('#elementName').textContent=name;
$('#orderPill').textContent=`Order ${t.order}`;
$('#elementMatrix').textContent=matrixFormat(t.m);
$('#cycleMeta').textContent=`${prettyCycleCounts(t)} · ${t.fixed} fixed face${t.fixed!==1?'s':''}`;
$('#powerLabel').innerHTML=`g<sup>${state.phase}</sup>`;
const orbit=orbitOf(state.orbitSeed,t);
const to=state.anim?state.anim.to:state.activeFace;
$('#trackedLabel').textContent=`${String(state.activeFace+1).padStart(2,'0')} → ${String(to+1).padStart(2,'0')}`;
$('#orbitLabel').textContent=`orbit length ${orbit.length}`;
const cycleIndex=t.cycles.findIndex(c=>c.includes(state.orbitSeed));
document.documentElement.style.setProperty('--orbit',rgba(cycleColor(cycleIndex)));
$('#orbitSequence').innerHTML=orbit.map((id,i)=>`${i?'<span class="sequence-arrow" aria-hidden="true">→</span>':''}<button type="button" class="sequence-face" data-orbit-face="${id}" aria-label="Go to face ${id+1}"${id===state.activeFace?' aria-current="step"':''}>${String(id+1).padStart(2,'0')}</button>`).join('')+'<span class="sequence-arrow" aria-hidden="true">↻</span>';
$('#phaseCaption').textContent=`${state.phase} / ${t.order}`;
$('#orbitFill').style.width=`${100*state.phase/t.order}%`;
$('#playText').textContent=state.playing?'Pause':'Play';
$('#playIcon').innerHTML=state.playing?'<path d="M7 4h4v16H7zM15 4h4v16h-4z"/>':'<path d="m7 4 14 8-14 8V4Z"/>';
$('#playStatus').textContent=state.playing?'Playing':'Paused';
$('#stepBtn').disabled=!!state.anim||t.order===1;
$('#playBtn').disabled=t.order===1;
applyPresetButtons();
}
function populateSelect(){
const select=$('#elementSelect');let options='';let cnt=0;
for(const e of transformations) {
if(state.filter!=='all'&&String(e.order)!==state.filter)continue;
options+=`<option value="${e.index}">#${String(e.index+1).padStart(3,'0')} · order ${e.order} · ${e.word}</option>`;cnt++;
}
select.innerHTML=options;
if(!Array.from(select.options).some(o=>Number(o.value)===state.elementId)){
select.insertAdjacentHTML('afterbegin',`<option value="${state.elementId}">#${String(state.elementId+1).padStart(3,'0')} · order ${activeTransform().order} · current selection</option>`);
}
select.value=String(state.elementId);
$('#elementCount').textContent=`${cnt} / 168`;
document.querySelectorAll('.filter').forEach(btn=>btn.classList.toggle('active',btn.dataset.order===state.filter));
}
function stopAndReset(keepFace=true){
state.playing=false;state.anim=null;state.phase=0;
state.activeFace=keepFace?state.activeFace:faceID(S);
state.orbitSeed=state.activeFace;state.lastStep=performance.now();
}
function selectTransform(i){
if(i<0||i>=168)return;
state.elementId=i;stopAndReset();
if(state.filter!=='all'&&String(activeTransform().order)!==state.filter)state.filter='all';
populateSelect();updateView();
}
function beginStep(t=performance.now()) {
if(state.anim||activeTransform().order===1)return;
state.anim={from:state.activeFace,to:activeTransform().perm[state.activeFace],start:t,duration:reducedMotion?35:830/state.speed};
state.lastStep=t;
updateView();
}
function endStep(t) {
if(!state.anim)return;
state.activeFace=state.anim.to;state.anim=null;
state.phase=(state.phase+1)%activeTransform().order;state.lastStep=t;
updateView();
}
function setPlay(on) {
state.playing=on;
state.lastStep=performance.now()-250;
updateView();
}
function precomputedPath(poly,closed=true){
const path=new Path2D();
for(let j=0;j<poly.length;j++){
const p=screen(poly[j]);if(j===0)path.moveTo(p.x,p.y);else path.lineTo(p.x,p.y);
}
if(closed)path.closePath();
return path;
}
function trianglePath(a,b,c){
return precomputedPath([...geoSegment(a,b,9).slice(0,-1),...geoSegment(b,c,9).slice(0,-1),...geoSegment(c,a,9).slice(0,-1)]);
}
function newLayer(opaque=false){
const layer=document.createElement('canvas');layer.width=disk.width;layer.height=disk.height;
const context=layer.getContext('2d',{alpha:!opaque});
context.setTransform(dpr,0,0,dpr,0,0);
return {layer,context};
}
function fillBackground(){
const {layer,context:bc}=newLayer(true);backgroundCanvas=layer;
bc.fillStyle='#080f17';bc.fillRect(0,0,cw,ch);
const light=bc.createRadialGradient(cx-cr*.38,cy-cr*.44,0,cx,cy,cr*1.45);
light.addColorStop(0,'#203b48');light.addColorStop(.52,'#10232f');light.addColorStop(1,'#070e17');
bc.save();bc.beginPath();bc.arc(cx,cy,cr,0,TAU);bc.clip();
bc.fillStyle=light;bc.fillRect(0,0,cw,ch);
for(const cell of cover){
bc.fillStyle=cell.depth%2?'rgba(91,155,174,.024)':'rgba(197,177,127,.018)';
bc.fill(cell.screenPath);
bc.strokeStyle=cell.depth>3?'rgba(112,159,175,.18)':'rgba(132,175,187,.28)';
bc.lineWidth=.62;bc.stroke(cell.screenPath);
}
// Metric circles: Euclidean radius tanh(d/2) corresponds to hyperbolic distance d.
bc.setLineDash([2,6]);
for(const distance of [1,2,3]){
bc.beginPath();bc.arc(cx,cy,cr*Math.tanh(distance/2),0,TAU);
bc.strokeStyle='rgba(183,206,210,.09)';bc.lineWidth=.65;bc.stroke();
}
bc.setLineDash([]);bc.restore();
bc.beginPath();bc.arc(cx,cy,cr+1.5,0,TAU);bc.lineWidth=3;bc.strokeStyle='#040a10';bc.stroke();
bc.beginPath();bc.arc(cx,cy,cr,0,TAU);bc.lineWidth=.95;bc.strokeStyle='#91adb6';bc.stroke();
bc.beginPath();bc.arc(cx,cy,cr+5,0,TAU);bc.lineWidth=.5;bc.strokeStyle='#385362';bc.stroke();
for(let i=0;i<24;i++){
const angle=TAU*i/24,a=cr+5,b=cr+(i%6===0?11:8);
bc.beginPath();bc.moveTo(cx+Math.cos(angle)*a,cy+Math.sin(angle)*a);
bc.lineTo(cx+Math.cos(angle)*b,cy+Math.sin(angle)*b);
bc.strokeStyle=i%6===0?'#7b99a4':'#3a5563';bc.lineWidth=.65;bc.stroke();
}
label(bc,'boundary at infinity',cx,Math.min(ch-13,cy+cr+23),cw<500?8:9,'#819da8','400');
}
function resizeCanvas(){
const r=disk.getBoundingClientRect();cw=Math.max(1,r.width);ch=Math.max(1,r.height);
dpr=Math.min(window.devicePixelRatio||1,cw<600?1.5:2);
disk.width=Math.round(cw*dpr);disk.height=Math.round(ch*dpr);
ctx.setTransform(dpr,0,0,dpr,0,0);
cr=Math.min(cw*.435,ch*.433);cx=cw*.5;cy=ch*.485;
for(const f of faces){
f.screenPath=precomputedPath(f.perimeter);f.screenCenter=screen(f.center);
const points=f.perimeter.map(screen);
f.bounds={left:Math.floor(Math.min(...points.map(p=>p.x)))-3,top:Math.floor(Math.min(...points.map(p=>p.y)))-3,
right:Math.ceil(Math.max(...points.map(p=>p.x)))+3,bottom:Math.ceil(Math.max(...points.map(p=>p.y)))+3};
f.highlight=null;
f.screenRadius=Math.max(...f.vertices.map(v=>{const p=screen(v);return Math.hypot(p.x-f.screenCenter.x,p.y-f.screenCenter.y);}));
f.facets=[];f.edges=[];
for(let j=0;j<7;j++){
const a=f.vertices[j],b=f.vertices[(j+1)%7],mid=geoSegment(a,b,2)[1];
f.edges.push(precomputedPath(geoSegment(a,b,18),false));
for(const [u,v] of [[a,mid],[mid,b]]){
const p=screen(u),q=screen(v);
const angle=Math.atan2((p.y+q.y)*.5-f.screenCenter.y,(p.x+q.x)*.5-f.screenCenter.x);
f.facets.push({path:trianglePath(f.center,u,v),light:(Math.cos(angle+2.2)+1)*.5});
}
}
}
for(const cell of cover)cell.screenPath=precomputedPath(cell.perimeter);
faceCanvas=null;faceLayerKey='';
fillBackground();
}
function label(context,text,x,y,size,color,weight='500'){
context.font=weight+' '+size+'px ui-monospace,SFMono-Regular,Consolas,monospace';
context.textAlign='center';context.textBaseline='middle';context.fillStyle=color;context.fillText(text,x,y);
}
function paintFace(context,f,color,selected=false){
const p=f.screenCenter,r=f.screenRadius;
const shade=context.createLinearGradient(p.x-r*.55,p.y-r*.85,p.x+r*.6,p.y+r);
if(selected){
shade.addColorStop(0,'#f1d59d');shade.addColorStop(.42,'#d3ad73');shade.addColorStop(1,'#8e6d45');
}else{
const emphasis=faceCycle[f.id]===faceCycle[state.orbitSeed];
shade.addColorStop(0,rgba(colorMix([22,39,50],color,emphasis?.55:.38)));
shade.addColorStop(.52,rgba(colorMix([10,24,35],color,emphasis?.35:.23)));
shade.addColorStop(1,rgba(colorMix([8,18,29],color,emphasis?.21:.12)));
}
context.fillStyle=shade;context.fill(f.screenPath);
if(state.showMesh){
for(let j=0;j<f.facets.length;j++){
const facet=f.facets[j];
context.fillStyle=j%2?'rgba(2,9,18,'+(.08-facet.light*.05)+')':'rgba(224,239,233,'+(.015+facet.light*.075)+')';
context.fill(facet.path);
context.strokeStyle=selected?'rgba(73,56,35,.19)':rgba(colorMix(color,[218,235,232],.6),.10);
context.lineWidth=.45;context.stroke(facet.path);
}
}
context.lineJoin='round';
context.lineWidth=2.1;context.strokeStyle='rgba(3,11,19,.9)';context.stroke(f.screenPath);
context.lineWidth=selected?1.15:.8;
context.strokeStyle=selected?'#f2d9a6':rgba(colorMix(color,[214,236,237],.45),.78);
context.stroke(f.screenPath);
for(let j=0;j<7;j++){
const a=screen(f.vertices[j]),b=screen(f.vertices[(j+1)%7]);
const light=clamp(.5-(b.x-a.x+b.y-a.y)/(Math.hypot(b.x-a.x,b.y-a.y)||1)*.3,0,1);
context.strokeStyle='rgba(231,246,241,'+(light*(selected?.55:.22))+')';
context.lineWidth=.55;context.stroke(f.edges[j]);
}
}
function paintFaceLabel(context,f,selected=false){
const p=f.screenCenter,small=f.screenRadius<22,showLabel=state.showLabels&&f.screenRadius>12;
if(showLabel){
const fixed=activeTransform().perm[f.id]===f.id;
const offset=selected?Math.min(15,f.screenRadius*.45):fixed?Math.min(10,f.screenRadius*.36):0;
label(context,String(f.id+1).padStart(2,'0'),p.x,p.y-offset,small?8.5:10.5,
selected?'#26302e':rgba(colorMix(faceColors[f.id],[226,239,237],.63)),selected?'700':'500');
}
if(activeTransform().perm[f.id]===f.id){
context.beginPath();context.arc(p.x,p.y+(showLabel?Math.min(8,f.screenRadius*.3):0),Math.min(3.5,Math.max(2.1,f.screenRadius*.21)),0,TAU);
context.strokeStyle=selected?'#4d4c35':'#b8cfd1';context.lineWidth=.9;context.stroke();
}
}
function highlightedFace(f){
if(f.highlight&&f.highlight.mesh===state.showMesh)return f.highlight;
const b=f.bounds,width=b.right-b.left,height=b.bottom-b.top;
const layer=document.createElement('canvas');layer.width=Math.ceil(width*dpr);layer.height=Math.ceil(height*dpr);
const context=layer.getContext('2d');context.setTransform(dpr,0,0,dpr,-b.left*dpr,-b.top*dpr);
paintFace(context,f,faceColors[f.id],true);
f.highlight={layer,width,height,mesh:state.showMesh};
return f.highlight;
}
function drawSelectedFace(f){
const h=highlightedFace(f);ctx.drawImage(h.layer,f.bounds.left,f.bounds.top,h.width,h.height);
}
function pathPoint(p,q,t){
// The connector interpolates two chosen lifts; it does not define a surface isotopy.
const a=screen(p),b=screen(q),vx=b.x-a.x,vy=b.y-a.y,dist=Math.hypot(vx,vy);
const control={x:cx*.14+(a.x+b.x)*.43+(-vy/(dist||1))*Math.min(25,dist*.1),
y:cy*.14+(a.y+b.y)*.43+(vx/(dist||1))*Math.min(25,dist*.1)};
const nt=1-t;
return {x:nt*nt*a.x+2*nt*t*control.x+t*t*b.x,y:nt*nt*a.y+2*nt*t*control.y+t*t*b.y,control,a,b};
}
function routePoint(route,t){
const nt=1-t,a=route.a,b=route.b,c=route.control;
return {x:nt*nt*a.x+2*nt*t*c.x+t*t*b.x,y:nt*nt*a.y+2*nt*t*c.y+t*t*b.y};
}
function ensureFaceLayer(){
const key=[state.elementId,state.orbitSeed,state.showMesh,state.showLabels,cw,ch].join(':');
if(faceCanvas&&key===faceLayerKey)return;
faceLayerKey=key;
const t=activeTransform();
faceCycle=[];faceColors=[];
t.cycles.forEach((cycle,i)=>cycle.forEach(id=>{faceCycle[id]=i;faceColors[id]=cycleColor(i);}));
const {layer,context}=newLayer();faceCanvas=layer;
for(const f of faces)paintFace(context,f,faceColors[f.id]);
for(const f of faces)highlightedFace(f);
routes=faces.map(f=>{
const dest=faces[t.perm[f.id]],route=pathPoint(f.center,dest.center,.5);
const path=new Path2D();path.moveTo(route.a.x,route.a.y);
path.quadraticCurveTo(route.control.x,route.control.y,route.b.x,route.b.y);
return {...route,path,fixed:f.id===dest.id};
});
}
function drawArrow(route,color){
if(route.fixed)return;
const p=routePoint(route,.59),q=routePoint(route,.62);
const angle=Math.atan2(q.y-p.y,q.x-p.x);
ctx.save();ctx.translate(q.x,q.y);ctx.rotate(angle);
ctx.beginPath();ctx.moveTo(3.5,0);ctx.lineTo(-2.5,-2.2);ctx.lineTo(-2.5,2.2);ctx.closePath();
ctx.fillStyle=color;ctx.fill();ctx.restore();
}
function drawAnchors(){
const anchors=[{z:C(0,0),kind:7},{z:C(radialMid,0),kind:2},{z:polygonBase[0],kind:3}];
const anchor=anchors.find(a=>state.elementId===PRESETS[a.kind]);
if(!anchor)return;
const p=screen(anchor.z);
ctx.beginPath();ctx.moveTo(p.x-6,p.y);ctx.lineTo(p.x+6,p.y);
ctx.moveTo(p.x,p.y-6);ctx.lineTo(p.x,p.y+6);
ctx.strokeStyle='rgba(235,209,157,.8)';ctx.lineWidth=.85;ctx.stroke();
ctx.beginPath();ctx.arc(p.x,p.y,2,0,TAU);ctx.fillStyle='#f0d3a0';ctx.fill();
}
function drawFrame(now){
if(!backgroundCanvas)return;
ensureFaceLayer();
ctx.drawImage(backgroundCanvas,0,0,cw,ch);
ctx.drawImage(faceCanvas,0,0,cw,ch);
ctx.save();ctx.beginPath();ctx.arc(cx,cy,cr,0,TAU);ctx.clip();
const t=activeTransform(),orbit=orbitOf(state.orbitSeed,t),visited=new Set(orbit);
const progress=state.anim?ease(clamp((now-state.anim.start)/state.anim.duration,0,1)):0;
if(state.hover>=0&&state.hover!==state.activeFace){
const face=faces[state.hover];ctx.fillStyle='rgba(209,234,234,.08)';ctx.fill(face.screenPath);
ctx.strokeStyle='#b8d8db';ctx.lineWidth=1.25;ctx.stroke(face.screenPath);
}
const from=faces[state.activeFace],to=state.anim?faces[state.anim.to]:from;
ctx.save();ctx.globalAlpha=from.id===to.id?1:1-progress*.84;drawSelectedFace(from);ctx.restore();
if(from.id!==to.id){
ctx.save();ctx.globalAlpha=.12+.88*progress;drawSelectedFace(to);ctx.restore();
}
if(state.showTrails){
ctx.save();ctx.setLineDash([2,5]);
for(const id of orbit){
if(routes[id].fixed)continue;
ctx.strokeStyle=rgba(faceColors[id],.65);ctx.lineWidth=1;ctx.stroke(routes[id].path);
}
ctx.setLineDash([]);
for(const id of orbit)drawArrow(routes[id],rgba(colorMix(faceColors[id],[226,238,229],.4),.83));
ctx.restore();
}
let highlighted=from.screenCenter;
if(state.anim){
if(state.showTrails){
for(const f of faces){
if(f.id===from.id||routes[f.id].fixed)continue;
if(!visited.has(f.id)){ctx.strokeStyle=rgba(faceColors[f.id],.12);ctx.lineWidth=.65;ctx.stroke(routes[f.id].path);}
const v=routePoint(routes[f.id],progress);
ctx.beginPath();ctx.arc(v.x,v.y,visited.has(f.id)?2.15:1.65,0,TAU);
ctx.fillStyle=rgba(colorMix(faceColors[f.id],[226,240,231],.2),.85);ctx.fill();
}
}
const route=routes[from.id];
if(state.showTrails){ctx.strokeStyle='rgba(243,211,151,.8)';ctx.lineWidth=1.35;ctx.stroke(route.path);}
highlighted=routePoint(route,progress);
if(state.showTrails&&!route.fixed){
for(let j=7;j>=1;j--){
const u=progress-j*.022;if(u<0)continue;
const p=routePoint(route,u);ctx.beginPath();ctx.arc(p.x,p.y,2.8-j*.24,0,TAU);
ctx.fillStyle='rgba(247,218,162,'+(.62-j*.065)+')';ctx.fill();
}
}
ctx.beginPath();ctx.arc(to.screenCenter.x,to.screenCenter.y,9+2*Math.sin(progress*Math.PI),0,TAU);
ctx.strokeStyle='rgba(238,216,172,.65)';ctx.lineWidth=.9;ctx.stroke();
}
for(const f of faces){
const selected=f.id===from.id?(!state.anim||progress<.55):(f.id===to.id&&progress>.4);
paintFaceLabel(ctx,f,selected);
}
drawAnchors();
ctx.beginPath();ctx.arc(highlighted.x,highlighted.y,6,0,TAU);
ctx.fillStyle='#12232c';ctx.fill();ctx.strokeStyle='#f8e2b1';ctx.lineWidth=1.4;ctx.stroke();
ctx.beginPath();ctx.arc(highlighted.x,highlighted.y,2.35,0,TAU);ctx.fillStyle='#f6d696';ctx.fill();
ctx.restore();
if(!state.showLabels||state.anim){
const x=clamp(highlighted.x+23,35,cw-35),y=clamp(highlighted.y-17,17,ch-17);
ctx.fillStyle='rgba(10,24,34,.94)';ctx.fillRect(x-19,y-9,38,18);
ctx.strokeStyle='rgba(178,205,209,.3)';ctx.lineWidth=.5;ctx.strokeRect(x-19,y-9,38,18);
label(ctx,'F'+String(state.activeFace+1).padStart(2,'0'),x,y,9.5,'#e9d5aa');
}
$('#orbitFill').style.width=(100*(state.phase+progress)/t.order)+'%';
}
// Pointer selection + keyboard operation.
function findFaceAt(px,py) {
for(let i=faces.length-1;i>=0;i--){const f=faces[i];
const polygon=f.perimeter;let inside=false;
for(let a=0,b=polygon.length-1;a<polygon.length;b=a++){
const A=screen(polygon[a]),B=screen(polygon[b]);
if(((A.y>py)!==(B.y>py)) && px<(B.x-A.x)*(py-A.y)/(B.y-A.y)+A.x)inside=!inside;
}
if(inside)return f.id;
}
return -1;
}
disk.addEventListener('pointermove',ev=>{
const r=disk.getBoundingClientRect();const x=ev.clientX-r.left,y=ev.clientY-r.top;
const id=findFaceAt(x,y);state.hover=id;
if(id<0){tooltip.style.display='none';return;}
const cycle=activeTransform().cycles.find(c=>c.includes(id));
tooltip.textContent='Face '+String(id+1).padStart(2,'0')+' · '+(cycle.length===1?'fixed':cycle.length+'-cycle');
tooltip.style.display='block';tooltip.style.left=`${clamp(x+12,8,cw-190)}px`;tooltip.style.top=`${clamp(y+12,8,ch-45)}px`;
});
disk.addEventListener('pointerleave',()=>{state.hover=-1;tooltip.style.display='none';});
disk.addEventListener('click',ev=>{
const r=disk.getBoundingClientRect(),id=findFaceAt(ev.clientX-r.left,ev.clientY-r.top);
if(id<0)return;
stopAndReset();state.activeFace=id;state.orbitSeed=id;updateView();
});
for(const b of document.querySelectorAll('.preset'))b.addEventListener('click',()=>selectTransform(PRESETS[b.dataset.preset]));
$('#elementSelect').addEventListener('change',ev=>selectTransform(Number(ev.target.value)));
for(const btn of document.querySelectorAll('.filter'))btn.addEventListener('click',()=>{
state.filter=btn.dataset.order;
const arr=state.filter==='all'?null:byOrder[Number(state.filter)];
if(arr&&!arr.includes(state.elementId))selectTransform(arr[0]);
else populateSelect();
});
$('#resetBtn').addEventListener('click',()=>{state.playing=false;state.anim=null;state.phase=0;state.activeFace=state.orbitSeed;state.lastStep=performance.now();updateView();});
$('#stepBtn').addEventListener('click',()=>{setPlay(false);beginStep(performance.now());});
$('#playBtn').addEventListener('click',()=>setPlay(!state.playing));
$('#speed').addEventListener('input',ev=>{state.speed=Number(ev.target.value);$('#speedLabel').textContent=state.speed.toFixed(1)+'×';});
$('#showLabels').addEventListener('change',ev=>state.showLabels=ev.target.checked);
$('#showMesh').addEventListener('change',ev=>state.showMesh=ev.target.checked);
$('#orbitSequence').addEventListener('click',ev=>{
const button=ev.target.closest('button[data-orbit-face]');if(!button)return;
const id=Number(button.dataset.orbitFace),orbit=orbitOf(state.orbitSeed,activeTransform());
state.playing=false;state.anim=null;state.activeFace=id;state.phase=orbit.indexOf(id);
state.lastStep=performance.now();updateView();
});
$('#showTrails').addEventListener('change',ev=>state.showTrails=ev.target.checked);
$('#saveImage').addEventListener('click',()=>{
const a=document.createElement('a');a.href=disk.toDataURL('image/png');a.download='klein-quartic-tiling.png';document.body.append(a);a.click();a.remove();
});
window.addEventListener('keydown',ev=>{
if(ev.target instanceof HTMLInputElement||ev.target instanceof HTMLSelectElement||ev.target instanceof HTMLButtonElement)return;
if(ev.code==='Space'){ev.preventDefault();setPlay(!state.playing);}
if(ev.key==='ArrowRight'){ev.preventDefault();setPlay(false);beginStep(performance.now());}
});
function frame(ts){
nowTime=ts;
if(state.anim&&ts-state.anim.start>=state.anim.duration)endStep(ts);
if(state.playing&&!state.anim&&ts-state.lastStep>290/state.speed)beginStep(ts);
drawFrame(ts);
frameSamples++;
if(ts-frameTime>900){measuredFPS=Math.round(frameSamples*1000/(ts-frameTime));$('#fpsLabel').textContent=`${measuredFPS} fps`;frameSamples=0;frameTime=ts;}
requestAnimationFrame(frame);
}
populateSelect();updateView();
resizeCanvas();
const observer=new ResizeObserver(()=>resizeCanvas());observer.observe(canvasContainer);
requestAnimationFrame(frame);
// Quick diagnostics, visible from developer console.
window.KleinLab={groupSize:group.elements.length,faceCount:faces.length,orderCounts:Object.fromEntries(Object.entries(byOrder).map(([k,v])=>[k,v.length])),transformations,faces,PRESETS};
console.info('[KleinLab] 168 elements · 24 faces · 84 edges · 56 vertices · element orders:',window.KleinLab.orderCounts);
</script>
</body>
</html>