{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"compass","type":"registry:block","title":"Compass","description":"Object. A liquid-damped compass. The card swings past the mark and settles while a lit display reads the bearing. Your hand turns the knurled bezel, one click a degree.","registryDependencies":[],"files":[{"path":"tactile/compass/compass.mjs","type":"registry:file","target":"tactile/compass/compass.mjs","content":"/**\n * Compass — Tactile UI.\n *\n * A heading instrument: a printed card floating in liquid turns under a\n * fixed lubber line, inside a turned bezel with a knurled grip. A fixed hub\n * over the pivot carries a small lit display with the bearing (\"274° W\").\n * Turn the bezel — or drag anywhere on the dial — and the card swings after\n * it through the liquid, passes the mark and settles back, the way a real\n * liquid-damped compass does.\n *\n * Mechanisms:\n *   1. The card is a damped rotational spring toward the target bearing,\n *      always the short way round (359° → 1° goes through 0°, never through\n *      180°), clamped to 1/30 s and sub-stepped at 1/240 s. Damping is the\n *      liquid: 0.1 rings for seconds, 1 arrives without passing.\n *   2. The bezel is the hand: it turns in 1° detents, directly under the\n *      pointer, and its index marks the bearing; the card catches up and\n *      \"boxes\" its N under the index.\n *   3. Light fixed in the room. The turning print is split from everything\n *      the lamp decides. The card and the bezel's printing are sprites that\n *      turn; the housing, the bezel's face, the glass sheen, the lip's shadow\n *      across the card and the hub's shadow are baked once and never turn.\n *      The knurl is lit tooth by tooth by where each tooth IS, not where it\n *      was cut: three phases of the knurl, one per degree of its 3° pitch,\n *      are baked and chosen by the bezel's angle.\n *\n * Cost at rest: nothing. The loop runs only while the card moves, sleeps\n * when it settles, pauses off screen and in a hidden tab; a 2.5 s frame gap\n * advances one clamped frame. A frame is five drawImage calls.\n *\n * Accessibility: the root is `role=\"slider\"` (0–359 degrees) with\n * aria-valuenow and aria-valuetext (\"274 degrees, west\"); arrows step 1°,\n * Shift or Page keys 10°, Home is north. It fires `input` as the value\n * changes and `change` when a drag or key commits it. The canvas and the\n * display are aria-hidden. `readonly` makes it a wind or heading readout.\n *\n * Reduced motion: it points instantly; no frame is requested.\n *\n * A device's own compass can drive it (`useSensor()`, which asks for\n * permission; off by default).\n *\n * No dependencies. The exported helpers are pure and tested in Node.\n */\n\nexport const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));\nconst smooth = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };\n\n// ---------------------------------------------------------------- angles\n\n/** Any angle into [0, 360). */\nexport const wrap360 = (a) => ((a % 360) + 360) % 360;\n\n/** Any angle into (−180, 180]: the short way round. */\nexport function wrap180(a) {\n  const w = wrap360(a + 180) - 180;\n  return w === -180 ? 180 : w;\n}\n\n/** The pointer's angle around a centre, degrees clockwise from straight up (screen y down). */\nexport const angleAt = (cx, cy, x, y) => wrap360((Math.atan2(x - cx, cy - y) * 180) / Math.PI);\n\n/** The sixteen winds. */\nexport const WINDS = Object.freeze([\n  ['N', 'north'], ['NNE', 'north-northeast'], ['NE', 'northeast'], ['ENE', 'east-northeast'],\n  ['E', 'east'], ['ESE', 'east-southeast'], ['SE', 'southeast'], ['SSE', 'south-southeast'],\n  ['S', 'south'], ['SSW', 'south-southwest'], ['SW', 'southwest'], ['WSW', 'west-southwest'],\n  ['W', 'west'], ['WNW', 'west-northwest'], ['NW', 'northwest'], ['NNW', 'north-northwest'],\n]);\n\n/** The wind a bearing falls in: { short: 'W', long: 'west' }. */\nexport function windOf(deg) {\n  const [short, long] = WINDS[Math.round(wrap360(deg) / 22.5) % 16];\n  return { short, long };\n}\n\n/** Whole degrees, 0–359. */\nexport const whole = (deg) => Math.round(wrap360(deg)) % 360;\n\n/** What a screen reader says: \"274 degrees, west\". */\nexport const valueText = (deg) => `${whole(deg)} degrees, ${windOf(whole(deg)).long}`;\n\n/** What the display shows: \"274°\", three digits like an instrument (\"004°\"). */\nexport const readout = (deg) => `${String(whole(deg)).padStart(3, '0')}°`;\n\n/** The step a key makes, or null: arrows ±1 (Shift ±10), Page keys ±10, Home to north. */\nexport function keyStep(key, shift = false) {\n  const n = shift ? 10 : 1;\n  switch (key) {\n    case 'ArrowUp': case 'ArrowRight': return { by: n };\n    case 'ArrowDown': case 'ArrowLeft': return { by: -n };\n    case 'PageUp': return { by: 10 };\n    case 'PageDown': return { by: -10 };\n    case 'Home': return { to: 0 };\n    default: return null;\n  }\n}\n\n// ---------------------------------------------------------------- the card\n\n/**\n * The card's natural frequency (Hz) and default damping ratio: a liquid\n * compass card swings about once a second and settles in two or three.\n */\nexport const CARD = Object.freeze({ freq: 1, zeta: 0.6, subStep: 1 / 240, maxStep: 1 / 30 });\n\n/**\n * Advance the card: θ̈ = ω₀²·wrap180(target − θ) − 2ζω₀·θ̇, in degrees. The\n * heading θ is continuous (it may run past 360); the error is always the\n * short way round. Clamped to 1/30 s and sub-stepped: a tab that returns\n * after 2.5 s advances one frame.\n */\nexport function stepCard(s, target, dt, zeta = CARD.zeta, freq = CARD.freq) {\n  const w0 = 2 * Math.PI * freq;\n  const k = w0 * w0;\n  const c = 2 * clamp(zeta, 0.02, 3) * w0;\n  let left = clamp(Number.isFinite(dt) ? dt : 0, 0, CARD.maxStep);\n  while (left > 1e-9) {\n    const h = Math.min(left, CARD.subStep);\n    s.v += (k * wrap180(target - s.h) - c * s.v) * h;\n    s.h += s.v * h;\n    left -= h;\n  }\n  return s;\n}\n\n/** Settled: within a fiftieth of a degree and nearly still. */\nexport const cardSettled = (s, target, eps = 0.02) => Math.abs(wrap180(target - s.h)) < eps && Math.abs(s.v) < eps * 4;\n\n// ---------------------------------------------------------------- the print\n\nexport const STYLES = Object.freeze(['degrees', 'cardinal', 'aviation']);\n\n/**\n * What a card style prints, in fractions of the card's radius. `ticks`:\n * { deg, len, w } from the outer edge inward; `labels`: { deg, text, r, size,\n * bold }. `fine` adds the 1° ticks a card only prints when it is big enough.\n */\nexport function cardMarks(style = 'degrees', fine = true) {\n  const ticks = [];\n  const labels = [];\n  const every = fine && style !== 'aviation' ? 1 : 5;\n  for (let d = 0; d < 360; d += every) {\n    if (d % 10 === 0) ticks.push({ deg: d, len: 0.13, w: 0.011 });\n    else if (d % 5 === 0) ticks.push({ deg: d, len: 0.085, w: 0.008 });\n    else ticks.push({ deg: d, len: 0.05, w: 0.005 });\n  }\n  const cardinals = { 0: 'N', 90: 'E', 180: 'S', 270: 'W' };\n  if (style === 'degrees') {\n    for (let d = 30; d < 360; d += 30) labels.push({ deg: d, text: String(d), r: 0.72, size: 0.105, bold: false });\n    labels.push({ deg: 0, text: 'N', r: 0.72, size: 0.13, bold: true });\n  } else if (style === 'cardinal') {\n    for (const [d, t] of Object.entries(cardinals)) labels.push({ deg: +d, text: t, r: 0.62, size: 0.2, bold: true });\n    for (const [d, t] of [[45, 'NE'], [135, 'SE'], [225, 'SW'], [315, 'NW']]) labels.push({ deg: d, text: t, r: 0.64, size: 0.1, bold: false });\n    for (let d = 30; d < 360; d += 30) if (d % 90) labels.push({ deg: d, text: String(d), r: 0.78, size: 0.068, bold: false });\n  } else {\n    for (let d = 30; d < 360; d += 30) if (d % 90) labels.push({ deg: d, text: String(d / 10), r: 0.7, size: 0.15, bold: false });\n    for (const [d, t] of Object.entries(cardinals)) labels.push({ deg: +d, text: t, r: 0.7, size: 0.17, bold: true });\n  }\n  return { ticks, labels };\n}\n\n// ---------------------------------------------------------------- the instrument\n\n/** Radii, as fractions of the dial's radius. */\nexport const RINGS = Object.freeze({\n  knurl: 0.945, bezelIn: 0.835, lipIn: 0.79, window: 0.79, card: 0.755, hub: 0.27,\n});\n\n/** The knurl's pitch in degrees; the bezel turns in 1° detents, so three phases cover it. */\nexport const KNURL = 3;\n\nexport const FINISHES = Object.freeze(['auto', 'aluminium', 'graphite']);\n\n/**\n * Materials: `bezel` the turned grip, `lip` the fixed ring the glass sits\n * in, `card` and `ink` the print. Aluminium wears a warm-white card and a\n * reflective LCD; graphite a black card and a VFD.\n */\nexport const MATERIALS = Object.freeze({\n  aluminium: Object.freeze({\n    key: 'aluminium', dark: false, glow: 0,\n    bezel: '#c4c6c3', lip: '#2c2d30', hub: '#c9cbc8', card: '#eeebe3', ink: '#17181a', bezelInk: '#1d1e20',\n    amb: 0.26, kd: 0.72, ks: 0.14, gloss: 10, grain: 0.035, shadow: 0.34, display: 'lcd',\n  }),\n  graphite: Object.freeze({\n    key: 'graphite', dark: true, glow: 0,\n    bezel: '#2f3034', lip: '#161719', hub: '#2c2d31', card: '#141517', ink: '#e8e5de', bezelInk: '#d9d6cf',\n    amb: 0.3, kd: 0.8, ks: 0.12, gloss: 9, grain: 0.05, shadow: 0.5, display: 'vfd',\n  }),\n});\n\n/**\n * `finish: 'auto'` follows the page. Aluminium, Porcelain and Daylight have\n * the aluminium dial and AMOLED the graphite one, pixel for pixel; Graphite,\n * Black, Phosphor, Night, Paper and E-paper (`page`) are drawn from the page's\n * object tokens, in each finish's own language: anodised metal with bright cut\n * edges, black glass traced in the display's light, dim metal with its print\n * lit from inside, a matte printed dial. A finish not listed goes by the\n * page's tone.\n */\nexport const AUTO = Object.freeze({\n  aluminium: 'aluminium', graphite: 'page', porcelain: 'aluminium', black: 'page', paper: 'page', phosphor: 'page',\n  daylight: 'aluminium', night: 'page', 'e-paper': 'page', amoled: 'graphite',\n});\n\n/** The finishes whose page is dark, for a page that names its finish and no tone. */\nconst DARK = Object.freeze(['graphite', 'black', 'phosphor', 'night', 'amoled']);\n\n/** The dial drawn: the finish asked for, or on `auto` the page's finish's, then its tone, then the system's. */\nexport function resolveMaterial(own, around, prefersDark, tone) {\n  if (own !== 'auto') return own;\n  if (AUTO[around]) return AUTO[around];\n  return (tone === 'light' || tone === 'dark' ? tone === 'dark' : prefersDark) ? 'graphite' : 'aluminium';\n}\n\n/** The page's object tokens a `page` dial is made from (--tui-obj-plate ... --tui-obj-mark). */\nexport const LOOK = Object.freeze(['plate', 'dark', 'body', 'lite', 'spec', 'env', 'frame', 'edge', 'mark']);\n\n/** Two #rrggbb colours mixed, as #rrggbb. */\nexport const blend = (a, b, t) => {\n  const pa = hexRgb(a);\n  const pb = hexRgb(b);\n  return `#${((1 << 24) | pa.map((v, i) => Math.round(v + (pb[i] - v) * t)).reduce((n, v) => (n << 8) | v, 0)).toString(16).slice(1)}`;\n};\n\n/**\n * The dial in a page's own material, from its object tokens. On a dark\n * finish the bezel is the finish's frame lifted a third toward its body, the\n * glass its plate, the print its mark; on a light one the bezel is the frame,\n * the card the finish's body and edge, the lip its dark side shaded. A matte\n * finish (chalk) takes no sheen. A finish that glows lights its print from\n * within and traces the bezel's rim and the glass's lip in its edge colour.\n */\nexport function materialFrom(t, dark) {\n  const matte = !!t.matte;\n  return Object.freeze({\n    key: ['page', dark ? 'dark' : 'light', ...LOOK.map((k) => t[k]), t.shadow, matte ? 1 : 0, t.glow].join('|'),\n    dark, glow: t.glow, edge: t.edge,\n    bezel: dark ? blend(t.frame, t.body, 0.33) : t.frame,\n    lip: dark ? blend(t.plate, t.frame, 0.5) : blend(t.dark, '#000000', 0.6),\n    hub: dark ? blend(t.frame, t.body, 0.25) : t.plate,\n    card: dark ? blend(t.plate, t.frame, 0.55) : blend(t.body, t.edge, 0.5),\n    ink: t.mark, bezelInk: t.mark,\n    amb: dark ? 0.3 : 0.26, kd: dark ? 0.8 : 0.72, ks: matte ? 0 : dark ? 0.12 : 0.14, gloss: dark ? 9 : 10, grain: dark ? 0.05 : 0.035,\n    shadow: t.shadow, display: dark ? 'vfd' : 'lcd',\n  });\n}\n\n/** Screen direction toward the lamp: 0° is from above, clockwise, y down. */\nexport function lampOf(light) {\n  const t = (light * Math.PI) / 180;\n  return { lx: Math.sin(t), ly: -Math.cos(t) };\n}\n\n/** The lamp as a 3D unit vector for a dial facing the viewer, `off` degrees off the line of sight. */\nexport function lampVector(light, off = 48) {\n  const { lx, ly } = lampOf(light);\n  const e = (off * Math.PI) / 180;\n  return [lx * Math.sin(e), ly * Math.sin(e), Math.cos(e)];\n}\n\n/**\n * The height of the fixed metal (units of the dial radius) at radius r: the\n * bezel's flat face and rounded edge, the step down to the lip ring, the lip\n * ring and its chamfer into the window. The knurl adds its teeth on top.\n */\nexport function housingHeight(r) {\n  if (r > 1) return 0;\n  const edge = 0.055;\n  if (r > 1 - edge) { const t = (r - (1 - edge)) / edge; return 0.06 * Math.sqrt(Math.max(0, 1 - t * t)); }\n  if (r > RINGS.bezelIn + 0.012) return 0.06;\n  if (r > RINGS.bezelIn) return 0.045 + 0.015 * smooth(RINGS.bezelIn, RINGS.bezelIn + 0.012, r);\n  if (r > RINGS.lipIn + 0.008) return 0.045;\n  if (r > RINGS.lipIn) return 0.02 + 0.025 * smooth(RINGS.lipIn, RINGS.lipIn + 0.008, r);\n  return 0;\n}\n\n// ================================================================ drawing\n// Everything below runs only in a browser.\n\nconst SRGB = (() => {\n  const t = new Uint8ClampedArray(4097);\n  for (let i = 0; i <= 4096; i += 1) {\n    const v = i / 4096;\n    t[i] = Math.round(255 * (v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055));\n  }\n  return t;\n})();\nconst toLin = (c) => { const v = c / 255; return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; };\nconst hexRgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));\nconst hexLin = (h) => hexRgb(h).map(toLin);\nconst rgba = (hex, a) => `rgba(${hexRgb(hex).join(', ')}, ${clamp(a, 0, 1).toFixed(3)})`;\nconst canvasOf = (w, h) => { const c = document.createElement('canvas'); c.width = Math.max(1, Math.ceil(w)); c.height = Math.max(1, Math.ceil(h)); return c; };\nlet hexProbe = null;\n/** Any opaque CSS colour (hex, rgb(), oklch() ...) as #rrggbb, the form the maths here reads: painted as one pixel and read back. */\nconst cssHex = (value) => {\n  hexProbe ??= canvasOf(1, 1);\n  const g = hexProbe.getContext('2d', { willReadFrequently: true });\n  g.clearRect(0, 0, 1, 1);\n  g.fillStyle = '#000000';\n  g.fillStyle = value;\n  g.fillRect(0, 0, 1, 1);\n  const [r, gg, b] = g.getImageData(0, 0, 1, 1).data;\n  return `#${((1 << 24) | (r << 16) | (gg << 8) | b).toString(16).slice(1)}`;\n};\n\n/** The page's object tokens as hex colours and numbers, or null on a page without them. */\nexport function readLook(el) {\n  const s = getComputedStyle(el);\n  const v = (k) => s.getPropertyValue(`--tui-obj-${k}`).trim();\n  if (!v('frame')) return null;\n  const t = Object.fromEntries(LOOK.map((k) => [k, cssHex(v(k) || v('frame'))]));\n  t.shadow = clamp(parseFloat(v('shadow')) || 0.4, 0, 1);\n  t.glow = clamp(parseFloat(v('glow')) || 0, 0, 1);\n  t.matte = v('matte') === '1';\n  return t;\n}\nconst hashXY = (x, y) => {\n  let h = (Math.floor(x) * 374761393 + Math.floor(y) * 668265263) | 0;\n  h = Math.imul(h ^ (h >>> 13), 1274126177);\n  return ((h ^ (h >>> 16)) >>> 0) / 4294967296;\n};\n\n/**\n * Paint a heightfield of turned metal, pixel by pixel, into ImageData.\n * `z(r, a)` in units of the dial radius; `albedo(r)` picks the material. The\n * normal comes from finite differences, so the knurl's teeth light by their\n * own flanks.\n */\nfunction paintMetal(img, W, H, cx, cy, R, dpr, { z, material, r0 = 0, r1 = 1, grain = 0.04, L, mats }) {\n  const d = img.data;\n  const H3 = (() => { const v = [L[0], L[1], L[2] + 1]; const l = Math.hypot(...v); return v.map((x) => x / l); })();\n  const px = 1 / (R * dpr); // one device pixel, in dial radii\n  const j0 = Math.max(0, Math.floor(cy - r1 * R * dpr) - 1);\n  const j1 = Math.min(H - 1, Math.ceil(cy + r1 * R * dpr) + 1);\n  const i0 = Math.max(0, Math.floor(cx - r1 * R * dpr) - 1);\n  const i1 = Math.min(W - 1, Math.ceil(cx + r1 * R * dpr) + 1);\n  const at = (x, y) => { const r = Math.hypot(x, y); return z(r, (Math.atan2(x, -y) * 180) / Math.PI); };\n  for (let j = j0; j <= j1; j += 1) {\n    const y = (j + 0.5 - cy) / (R * dpr);\n    for (let i = i0; i <= i1; i += 1) {\n      const x = (i + 0.5 - cx) / (R * dpr);\n      const r = Math.hypot(x, y);\n      const cov = clamp((r1 - r) / px + 0.5, 0, 1) * clamp((r - r0) / px + 0.5, 0, 1);\n      if (cov <= 0) continue;\n      const dzx = (at(x + px, y) - at(x - px, y)) / (2 * px);\n      const dzy = (at(x, y + px) - at(x, y - px)) / (2 * px);\n      const nl = Math.hypot(dzx, dzy, 1);\n      const nx = -dzx / nl;\n      const ny = -dzy / nl;\n      const nz = 1 / nl;\n      const m = mats[material(r)];\n      const ndl = Math.max(0, nx * L[0] + ny * L[1] + nz * L[2]);\n      const ndh = Math.max(0, nx * H3[0] + ny * H3[1] + nz * H3[2]);\n      const bead = 1 + grain * (hashXY(i * 7.3, j * 3.1) - 0.5);\n      const lit = (m.amb * (0.7 + 0.3 * nz) + m.kd * ndl) * bead + m.ks * ndh ** m.gloss;\n      const k = (j * W + i) * 4;\n      const a = cov * 255;\n      const ia = 1 - cov;\n      d[k] = SRGB[Math.round(clamp(m.lin[0] * lit, 0, 1) * 4096)] * cov + d[k] * ia;\n      d[k + 1] = SRGB[Math.round(clamp(m.lin[1] * lit, 0, 1) * 4096)] * cov + d[k + 1] * ia;\n      d[k + 2] = SRGB[Math.round(clamp(m.lin[2] * lit, 0, 1) * 4096)] * cov + d[k + 2] * ia;\n      d[k + 3] = Math.max(d[k + 3], a);\n    }\n  }\n}\n\n/** The knurl's teeth: rounded ridges every KNURL degrees on the bezel's outer edge. */\nconst knurlHeight = (r, a, phase) => {\n  const base = housingHeight(r);\n  if (r < RINGS.knurl - 0.004 || r > 1) return base;\n  const t = (((a - phase) / KNURL) % 1 + 1) % 1;\n  const ridge = 0.5 - 0.5 * Math.cos(t * Math.PI * 2);\n  return base - 0.011 * (1 - ridge) * smooth(RINGS.knurl - 0.004, RINGS.knurl + 0.01, r);\n};\n\n/**\n * The dome bends the card seen through it. The bend is radial, so it commutes\n * with the card's turning: bake it into the card sprite once and the card\n * turns under it for free. Through the body of the dome the print is lifted a\n * little toward the lip; through the shoulder (the outer 3% of the window) it\n * is compressed hard, so the card's edge and the dark bowl beyond are squeezed\n * into a few pixels. `DOME` is where the shoulder begins, as a fraction of the window.\n */\nconst DOME = 0.968;\nfunction refractCard(canvas, Rpx) {\n  const S = canvas.width;\n  const c = S / 2;\n  const gx = canvas.getContext('2d');\n  const src = gx.getImageData(0, 0, S, S).data;\n  const out = new ImageData(new Uint8ClampedArray(src), S, S);\n  const o = out.data;\n  const win = RINGS.window;\n  const sh = win * DOME;\n  const lift = 0.018;\n  const k = (win - sh) > 0 ? ((RINGS.card + 0.06 - (sh - lift)) / (win - sh) - 1) : 0; // the shoulder's end lands 0.06 past the card\n  const bend = (p) => {\n    if (p <= sh) return p - lift * smooth(0.5, sh, p);\n    const u = (p - sh) / (win - sh);\n    return sh - lift + (win - sh) * (u + k * u * u * u);\n  };\n  const acc = [0, 0, 0, 0];\n  const tap = (x, y, w) => {\n    const x0 = Math.floor(x);\n    const y0 = Math.floor(y);\n    const fx = x - x0;\n    const fy = y - y0;\n    for (let q = 0; q < 4; q += 1) {\n      const xi = x0 + (q & 1);\n      const yi = y0 + (q >> 1);\n      if (xi < 0 || yi < 0 || xi >= S || yi >= S) continue;\n      const wq = w * ((q & 1 ? fx : 1 - fx) * (q >> 1 ? fy : 1 - fy));\n      const j = (yi * S + xi) * 4;\n      const a = (src[j + 3] / 255) * wq;\n      acc[0] += src[j] * a; acc[1] += src[j + 1] * a; acc[2] += src[j + 2] * a; acc[3] += a;\n    }\n  };\n  const lo = Math.max(0, Math.floor(c - win * Rpx) - 1);\n  const hi = Math.min(S - 1, Math.ceil(c + win * Rpx) + 1);\n  for (let j = lo; j <= hi; j += 1) {\n    const dy = j + 0.5 - c;\n    for (let i = lo; i <= hi; i += 1) {\n      const dx = i + 0.5 - c;\n      const r = Math.hypot(dx, dy);\n      const p = r / Rpx;\n      if (p < 0.5 || p > win) continue;\n      acc[0] = acc[1] = acc[2] = acc[3] = 0;\n      const n = p > sh - 0.01 ? 4 : 1; // squeezed hard, so look along the pixel a few times\n      for (let t = 0; t < n; t += 1) {\n        const pt = clamp(p + ((t + 0.5) / n - 0.5) / Rpx, 0.001, win);\n        const s = (bend(pt) * Rpx) / r;\n        tap(c + dx * s - 0.5, c + dy * s - 0.5, 1 / n);\n      }\n      const q = (j * S + i) * 4;\n      const a = acc[3];\n      if (a <= 1e-4) { o[q] = o[q + 1] = o[q + 2] = o[q + 3] = 0; continue; }\n      o[q] = acc[0] / a; o[q + 1] = acc[1] / a; o[q + 2] = acc[2] / a; o[q + 3] = a * 255;\n    }\n  }\n  gx.putImageData(out, 0, 0);\n}\n\n/**\n * Everything baked for one size and finish. `D` is the dial's diameter\n * (CSS px), `pad` the margin around it for its shadow.\n */\nfunction bake(o, D, pad, dpr, m) {\n  const finish = m.key;\n  const gr = m.dark;\n  const glow = m.glow;\n  const R = D / 2;\n  const size = D + pad * 2;\n  const W = Math.ceil(size * dpr);\n  const cx = (pad + R) * dpr;\n  const cy = (pad + R) * dpr;\n  const L = lampVector(o.light);\n  const { lx, ly } = lampOf(o.light);\n  const mats = {\n    bezel: { ...m, lin: hexLin(m.bezel) },\n    lip: { ...m, lin: hexLin(m.lip), ks: m.ks * 1.4, gloss: m.gloss * 1.6 },\n    hub: { ...m, lin: hexLin(m.hub) },\n  };\n  const out = { finish, D, pad, dpr, size };\n\n  // ---- the base: the shadow on the page, the housing, the bowl\n  const base = canvasOf(W, W);\n  const g = base.getContext('2d');\n  g.save();\n  g.filter = `blur(${(R * 0.07 * dpr).toFixed(1)}px)`;\n  g.fillStyle = `rgba(0, 0, 0, ${m.shadow})`;\n  g.beginPath(); g.arc(cx - lx * R * 0.05 * dpr, cy - ly * R * 0.05 * dpr, R * dpr * 0.99, 0, Math.PI * 2); g.fill();\n  g.filter = `blur(${(R * 0.015 * dpr).toFixed(1)}px)`;\n  g.fillStyle = `rgba(0, 0, 0, ${m.shadow * 0.9})`;\n  g.beginPath(); g.arc(cx - lx * R * 0.012 * dpr, cy - ly * R * 0.012 * dpr, R * dpr, 0, Math.PI * 2); g.fill();\n  g.restore();\n  // The bowl under the glass, and the card's own shadow on it.\n  g.fillStyle = gr ? '#070708' : '#0d0e10';\n  g.beginPath(); g.arc(cx, cy, RINGS.window * R * dpr, 0, Math.PI * 2); g.fill();\n  const img = g.getImageData(0, 0, W, W);\n  const material = (r) => (r > RINGS.bezelIn ? 'bezel' : 'lip');\n  paintMetal(img, W, W, cx, cy, R, dpr, { z: (r) => housingHeight(r), material, r0: RINGS.window, r1: 1, grain: m.grain, L, mats });\n  g.putImageData(img, 0, 0);\n  out.base = base;\n\n  // ---- the knurl, lit where each tooth is: one sprite per degree of its pitch\n  out.knurl = [];\n  for (let p = 0; p < KNURL; p += 1) {\n    const c = canvasOf(W, W);\n    const cg = c.getContext('2d');\n    const im = cg.createImageData(W, W);\n    paintMetal(im, W, W, cx, cy, R, dpr, { z: (r, a) => knurlHeight(r, a, p), material: () => 'bezel', r0: RINGS.knurl - 0.006, r1: 1, grain: m.grain, L, mats });\n    cg.putImageData(im, 0, 0);\n    out.knurl.push(c);\n  }\n\n  // ---- the bezel's printing, which turns\n  const bp = canvasOf(W, W);\n  const bg = bp.getContext('2d');\n  bg.setTransform(dpr, 0, 0, dpr, cx, cy);\n  bg.fillStyle = m.bezelInk;\n  // A finish that glows lights its printing from within.\n  if (glow) { bg.shadowColor = m.bezelInk; bg.shadowBlur = glow * R * dpr * 0.05; }\n  const face = (RINGS.bezelIn + RINGS.knurl) / 2;\n  // The course index: a solid triangle pointing in at the card.\n  bg.beginPath();\n  bg.moveTo(0, -R * (RINGS.bezelIn + 0.012));\n  bg.lineTo(-R * 0.034, -R * (RINGS.knurl - 0.018));\n  bg.lineTo(R * 0.034, -R * (RINGS.knurl - 0.018));\n  bg.closePath();\n  bg.fill();\n  for (let d = 0; d < 360; d += 10) {\n    if (d === 0) continue;\n    const a = (d * Math.PI) / 180;\n    const big = d % 90 === 0;\n    bg.save();\n    bg.rotate(a);\n    if (big) { bg.beginPath(); bg.arc(0, -R * face, R * 0.013, 0, Math.PI * 2); bg.fill(); } else { bg.fillRect(-R * 0.0035, -R * (face + 0.012), R * 0.007, R * 0.024); }\n    bg.restore();\n  }\n  out.bezelPrint = bp;\n\n  // ---- the card, which turns\n  const Rc = RINGS.card * R;\n  const cs = Math.ceil(2 * RINGS.window * R * dpr) + 2; // to the window: the dome shows a little beyond the card's own edge\n  const card = canvasOf(cs, cs);\n  const kg = card.getContext('2d');\n  kg.setTransform(dpr, 0, 0, dpr, cs / 2, cs / 2);\n  kg.fillStyle = m.card;\n  kg.beginPath(); kg.arc(0, 0, Rc, 0, Math.PI * 2); kg.fill();\n  // A printed card is not flat white: a faint grain of the stock.\n  kg.fillStyle = gr ? 'rgba(255, 255, 255, 0.025)' : 'rgba(0, 0, 0, 0.03)';\n  kg.beginPath(); kg.arc(0, 0, Rc * 0.985, 0, Math.PI * 2); kg.lineWidth = Rc * 0.012; kg.strokeStyle = kg.fillStyle; kg.stroke();\n  const { ticks, labels } = cardMarks(o.card, Rc > 90);\n  kg.fillStyle = m.ink;\n  if (glow) { kg.shadowColor = m.ink; kg.shadowBlur = glow * R * dpr * 0.05; }\n  for (const t of ticks) {\n    kg.save();\n    kg.rotate((t.deg * Math.PI) / 180);\n    const w = Math.max(0.6 / dpr * 1.5, t.w * Rc);\n    kg.fillRect(-w / 2, -Rc * 0.965, w, t.len * Rc);\n    kg.restore();\n  }\n  // North: a solid triangle at the rim.\n  kg.beginPath();\n  kg.moveTo(0, -Rc * 0.965);\n  kg.lineTo(-Rc * 0.05, -Rc * 0.83);\n  kg.lineTo(Rc * 0.05, -Rc * 0.83);\n  kg.closePath();\n  kg.fill();\n  const family = o.font;\n  // A small card does not print what nobody could read: under 6.5 px, a label is left off.\n  for (const l of labels.filter((x) => x.size * Rc >= 6.5)) {\n    kg.save();\n    kg.rotate((l.deg * Math.PI) / 180);\n    kg.translate(0, -l.r * Rc);\n    kg.font = `${l.bold ? 700 : 500} ${(l.size * Rc).toFixed(2)}px ${family}`;\n    kg.textAlign = 'center';\n    kg.textBaseline = 'middle';\n    if ('letterSpacing' in kg) kg.letterSpacing = `${(l.size * Rc * 0.02).toFixed(2)}px`;\n    kg.fillText(l.text, 0, 0);\n    kg.restore();\n  }\n  refractCard(card, R * dpr);\n  out.card = card;\n  out.cardSize = cs;\n\n  // ---- everything fixed above the card: shadows on it, the hub, the lubber, the glass\n  const over = canvasOf(W, W);\n  const og = over.getContext('2d');\n  og.setTransform(dpr, 0, 0, dpr, cx, cy);\n  const win = RINGS.window * R;\n  og.save();\n  og.beginPath(); og.arc(0, 0, win, 0, Math.PI * 2); og.clip();\n  // The lip stands above the card: its shadow across the card on the lamp's side.\n  const lip = og.createRadialGradient(lx * R * 0.05, ly * R * 0.05, win * 0.82, lx * R * 0.05, ly * R * 0.05, win * 1.04);\n  lip.addColorStop(0, 'rgba(0, 0, 0, 0)');\n  lip.addColorStop(0.6, `rgba(0, 0, 0, ${gr ? 0.35 : 0.22})`);\n  lip.addColorStop(1, `rgba(0, 0, 0, ${gr ? 0.7 : 0.5})`);\n  og.fillStyle = lip;\n  og.fillRect(-win, -win, win * 2, win * 2);\n  // The hub's shadow on the card, away from the lamp.\n  og.save();\n  og.filter = `blur(${(R * 0.03 * dpr).toFixed(1)}px)`;\n  og.fillStyle = `rgba(0, 0, 0, ${gr ? 0.6 : 0.34})`;\n  og.beginPath(); og.arc(-lx * R * 0.04, -ly * R * 0.04, RINGS.hub * R, 0, Math.PI * 2); og.fill();\n  og.restore();\n  // The glass: a thick dome over the card. Its shoulder (where the card is\n  // compressed, see `refractCard`) is lit on the lamp's side and dark on the\n  // other; the lamp's softbox is caught in the dome, crisp; a thread of light\n  // runs through the glass to the far edge, where it meets the lip.\n  {\n    const shoulder = win * DOME;\n    const hair = Math.max(0.8, R * 0.005);\n    const la = Math.atan2(ly, lx);\n    const along = (r0, r1) => og.createLinearGradient(lx * r0, ly * r0, lx * r1, ly * r1);\n    const stops = (grad, list) => { for (const [t, a, c = '255, 255, 255'] of list) grad.addColorStop(t, `rgba(${c}, ${a})`); return grad; };\n    og.save();\n    og.beginPath(); og.arc(0, 0, win, 0, Math.PI * 2); og.clip();\n    // The body: never perfectly clear. A neutral veil, and the dome's shading along the lamp's axis.\n    og.fillStyle = gr ? 'rgba(168, 182, 182, 0.035)' : 'rgba(110, 128, 126, 0.075)';\n    og.fillRect(-win, -win, win * 2, win * 2);\n    og.fillStyle = stops(along(win, -win), [[0, gr ? 0.06 : 0.09], [0.5, 0], [1, gr ? 0 : 0.12, '8, 14, 14']]);\n    og.fillRect(-win, -win, win * 2, win * 2);\n    // Thickness: the edge of the glass bends and darkens what is behind it.\n    og.fillStyle = stops(og.createRadialGradient(0, 0, win * 0.84, 0, 0, win), [\n      [0, 0, '8, 14, 14'], [0.5, 0.05, '8, 14, 14'], [0.8, gr ? 0.2 : 0.16, '8, 14, 14'], [1, gr ? 0.5 : 0.44, '8, 14, 14'],\n    ]);\n    og.fillRect(-win, -win, win * 2, win * 2);\n    // The shoulder faces the lamp on its side: a soft band of light in the bevel.\n    og.lineWidth = win - shoulder;\n    og.strokeStyle = stops(along(win, -win), [[0, gr ? 0.3 : 0.4], [0.3, gr ? 0.08 : 0.1], [0.5, 0]]);\n    og.beginPath(); og.arc(0, 0, (win + shoulder) / 2, 0, Math.PI * 2); og.stroke();\n    // Where the flat meets the shoulder: a line of light, brightest toward the lamp.\n    og.lineWidth = hair;\n    og.strokeStyle = stops(along(win, -win), [[0, gr ? 0.5 : 0.7], [0.35, gr ? 0.14 : 0.2], [0.65, 0.05], [1, 0.05]]);\n    og.beginPath(); og.arc(0, 0, shoulder, 0, Math.PI * 2); og.stroke();\n    // The softbox in the dome: a pane curved to it, its outer edge clean, its inner edge held.\n    const a1 = la - 0.55;\n    const a2 = la + 0.55;\n    const P = (a, r) => [Math.cos(a) * r, Math.sin(a) * r];\n    const outer = win * 0.91;\n    const [x1, y1] = P(a1, outer);\n    const [x2, y2] = P(a2, outer);\n    // On a sheet of its own, so its ends can thin away without touching what is under it.\n    const sheet = canvasOf(W, W);\n    const sg = sheet.getContext('2d');\n    sg.setTransform(dpr, 0, 0, dpr, cx, cy);\n    sg.beginPath();\n    sg.arc(0, 0, outer, a1, a2);\n    sg.quadraticCurveTo(Math.cos(la) * win * 0.6, Math.sin(la) * win * 0.6, x1, y1);\n    sg.closePath();\n    const paneG = sg.createLinearGradient(lx * outer, ly * outer, lx * win * 0.66, ly * win * 0.66);\n    stops(paneG, [[0, gr ? 0.17 : 0.24], [1, gr ? 0.03 : 0.05]]);\n    sg.fillStyle = paneG;\n    sg.fill();\n    sg.globalCompositeOperation = 'destination-in';\n    const ends = sg.createLinearGradient(x1, y1, x2, y2);\n    stops(ends, [[0, 0], [0.3, 1], [0.7, 1], [1, 0]]);\n    sg.fillStyle = ends;\n    sg.fillRect(-win, -win, win * 2, win * 2);\n    og.save();\n    og.setTransform(1, 0, 0, 1, 0, 0);\n    og.drawImage(sheet, 0, 0);\n    og.restore();\n    og.lineWidth = hair;\n    const streak = og.createLinearGradient(x1, y1, x2, y2);\n    og.strokeStyle = stops(streak, [[0, 0], [0.5, gr ? 0.36 : 0.55], [1, 0]]);\n    og.beginPath(); og.arc(0, 0, outer - hair / 2, a1, a2); og.stroke();\n    // The lip's contact, and the thread of light that has crossed the glass to the far edge.\n    og.strokeStyle = 'rgba(0, 0, 0, 0.5)';\n    og.beginPath(); og.arc(0, 0, win - hair / 2, 0, Math.PI * 2); og.stroke();\n    og.strokeStyle = stops(along(win, -win), [[0, 0], [0.55, 0], [1, gr ? 0.36 : 0.42]]);\n    og.beginPath(); og.arc(0, 0, win - hair * 1.5, 0, Math.PI * 2); og.stroke();\n    og.restore();\n  }\n  // The lubber: a fine wire across the glass at twelve, above the card, with its shadow on it.\n  const lub0 = -win;\n  const lub1 = -Rc * 0.8; // across the graduations only, clear of the print inside them\n  const wire = Math.max(1.1, R * 0.008);\n  og.lineCap = 'butt';\n  og.strokeStyle = `rgba(0, 0, 0, ${gr ? 0.55 : 0.28})`;\n  og.lineWidth = wire * 1.6;\n  og.beginPath(); og.moveTo(-lx * R * 0.018, lub0 - ly * R * 0.018); og.lineTo(-lx * R * 0.018, lub1 - ly * R * 0.018); og.stroke();\n  og.strokeStyle = gr ? '#d9d6cf' : '#1a1b1d';\n  og.lineWidth = wire;\n  og.beginPath(); og.moveTo(0, lub0); og.lineTo(0, lub1); og.stroke();\n  og.restore();\n  // A finish that glows traces the bezel's outer rim and the glass's lip in its edge colour, lit.\n  if (glow) {\n    og.save();\n    og.shadowColor = m.edge;\n    og.shadowBlur = glow * R * dpr * 0.06;\n    og.strokeStyle = rgba(m.edge, 0.85);\n    og.lineWidth = Math.max(0.8, R * 0.006);\n    og.beginPath(); og.arc(0, 0, R * 0.996, 0, Math.PI * 2); og.stroke();\n    og.beginPath(); og.arc(0, 0, win * 1.006, 0, Math.PI * 2); og.stroke();\n    og.restore();\n  }\n\n  // The hub: a turned boss over the pivot, fixed to the glass.\n  const hubImg = og.getImageData(0, 0, W, W);\n  paintMetal(hubImg, W, W, cx, cy, R, dpr, {\n    z: (r) => (r > RINGS.hub ? 0 : 0.04 * Math.sqrt(Math.max(0, 1 - Math.max(0, (r - (RINGS.hub - 0.03)) / 0.03) ** 2))),\n    material: () => 'hub', r0: 0, r1: RINGS.hub, grain: m.grain, L, mats,\n  });\n  og.putImageData(hubImg, 0, 0);\n  og.setTransform(dpr, 0, 0, dpr, cx, cy);\n  // The display window cut into the hub, and its lip.\n  const dw = RINGS.hub * R * 1.36;\n  const dh = RINGS.hub * R * 0.92;\n  out.display = { w: dw, h: dh };\n  og.fillStyle = 'rgba(0, 0, 0, 0.5)';\n  roundRect(og, -dw / 2 - 1, -dh / 2 - 1, dw + 2, dh + 2, Math.min(dh * 0.18, 6) + 1);\n  og.fill();\n\n  out.over = over;\n  return out;\n}\n\nfunction roundRect(g, x, y, w, h, r) {\n  const k = Math.max(0, Math.min(r, w / 2, h / 2));\n  g.beginPath();\n  g.moveTo(x + k, y);\n  g.arcTo(x + w, y, x + w, y + h, k);\n  g.arcTo(x + w, y + h, x, y + h, k);\n  g.arcTo(x, y + h, x, y, k);\n  g.arcTo(x, y, x + w, y, k);\n  g.closePath();\n}\n\n// ================================================================ the object\n\nexport const DEFAULTS = Object.freeze({\n  bearing: 0,\n  damping: CARD.zeta,\n  card: 'cardinal',\n  finish: 'auto',\n  size: 'fit',\n  light: 315,\n  label: 'Heading',\n  readonly: false,\n  display: true,\n  font: '\"Instrument Sans\", ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif',\n});\n\nfunction normalise(opts, previous) {\n  const o = { ...DEFAULTS, ...previous, ...opts };\n  o.bearing = whole(Number.isFinite(+o.bearing) ? +o.bearing : 0);\n  o.damping = clamp(+o.damping || CARD.zeta, 0.1, 1.5);\n  if (!STYLES.includes(o.card)) o.card = 'cardinal';\n  if (!FINISHES.includes(o.finish)) o.finish = 'auto';\n  o.size = +o.size > 0 ? clamp(+o.size, 64, 1200) : 'fit';\n  o.light = ((+o.light || 0) % 360 + 360) % 360;\n  o.label = String(o.label ?? '').slice(0, 40).trim() || 'Heading';\n  o.readonly = o.readonly === true;\n  o.display = o.display !== false;\n  o.font = String(o.font || DEFAULTS.font);\n  return o;\n}\n\nconst STRUCTURE = ['card', 'finish', 'light', 'size', 'font', 'display'];\n\nexport class Compass {\n  constructor(host, opts = {}) {\n    if (!host) throw new Error('Compass needs a host element');\n    this.host = host;\n    this.o = normalise(opts);\n    this.mq = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;\n    this.reduced = !!this.mq?.matches;\n    this.dark = typeof matchMedia === 'function' ? matchMedia('(prefers-color-scheme: dark)') : null;\n    this.target = this.o.bearing;\n    this.s = { h: this.target, v: 0 };\n\n    const root = document.createElement('div');\n    root.className = 'cp';\n    root.dataset.object = 'compass';\n    root.dataset.state = 'asleep';\n    root.setAttribute('role', 'slider');\n    root.setAttribute('aria-valuemin', '0');\n    root.setAttribute('aria-valuemax', '359');\n    root.tabIndex = 0;\n    this.canvas = document.createElement('canvas');\n    this.canvas.setAttribute('aria-hidden', 'true');\n    this.screen = document.createElement('span');\n    this.screen.className = 'cp-display';\n    this.screen.setAttribute('aria-hidden', 'true');\n    this.deg = document.createElement('span');\n    this.deg.className = 'cp-deg';\n    this.wind = document.createElement('span');\n    this.wind.className = 'cp-wind';\n    this.screen.append(this.deg, this.wind);\n    root.append(this.canvas, this.screen);\n    this.root = root;\n    host.append(root);\n\n    this.raf = 0;\n    this.last = 0;\n    this.visible = false;\n    this.drag = null;\n    this.cache = new Map();\n    this.shown = null;\n\n    this.on = {\n      down: (e) => this.#down(e),\n      move: (e) => this.#move(e),\n      up: (e) => this.#up(e),\n      key: (e) => this.#key(e),\n      motion: (e) => { this.reduced = e.matches; if (this.reduced) this.#jump(); this.#wake(); },\n      scheme: () => this.#followFinish(),\n      visibility: () => { if (document.hidden) this.#sleep(); else this.#wake(); },\n      sensor: (e) => this.#sensor(e),\n    };\n    root.addEventListener('pointerdown', this.on.down);\n    root.addEventListener('pointermove', this.on.move);\n    root.addEventListener('pointerup', this.on.up);\n    root.addEventListener('pointercancel', this.on.up);\n    root.addEventListener('keydown', this.on.key);\n    this.mq?.addEventListener?.('change', this.on.motion);\n    this.dark?.addEventListener?.('change', this.on.scheme);\n    document.addEventListener('visibilitychange', this.on.visibility);\n\n    this.#aria();\n    this.#bindFinish();\n    this.ro = new ResizeObserver(() => this.#fit());\n    this.ro.observe(host);\n    this.io = new IntersectionObserver(([entry]) => {\n      this.visible = entry.isIntersecting;\n      if (this.visible) this.#wake(); else this.#sleep();\n    });\n    this.io.observe(root);\n    document.fonts?.ready?.then(() => { if (this.root.isConnected) { this.cache.clear(); this.#fit(true); } });\n    this.#fit(true);\n  }\n\n  /** The bearing the compass is set to, 0–359. */\n  get value() { return this.target; }\n\n  /** Where the card is pointing right now (it lags the value while it swings). */\n  get heading() { return wrap360(this.s.h); }\n\n  /** What the compass is doing now, as its root's data-state. */\n  get state() { return this.root.dataset.state; }\n\n  /** Turn to a bearing. `instant` (or reduced motion) points at once. No events: that is for the visitor's own changes. */\n  setValue(v, { instant = false } = {}) {\n    if (!Number.isFinite(+v)) return this;\n    this.target = whole(+v);\n    this.#aria();\n    if (instant || this.reduced) this.#jump();\n    else this.#wake();\n    return this;\n  }\n\n  update(opts = {}) {\n    const prev = this.o;\n    this.o = normalise(opts, this.o);\n    if (this.o.finish !== prev.finish) this.#bindFinish();\n    if (STRUCTURE.some((k) => prev[k] !== this.o[k])) { this.cache.clear(); this.#fit(true); }\n    this.#aria();\n    if ('bearing' in opts && this.o.bearing !== this.target && !this.drag) this.setValue(this.o.bearing);\n    return this;\n  }\n\n  /**\n   * Let the device's own compass drive it. Asks for permission where the\n   * platform wants a gesture for it (iOS), so call it from a click. Resolves\n   * true when listening. `stopSensor()` lets go.\n   */\n  async useSensor() {\n    const D = globalThis.DeviceOrientationEvent;\n    if (!D) return false;\n    try {\n      if (typeof D.requestPermission === 'function' && (await D.requestPermission()) !== 'granted') return false;\n    } catch { return false; }\n    this.stopSensor();\n    this.sensorEvent = 'ondeviceorientationabsolute' in globalThis ? 'deviceorientationabsolute' : 'deviceorientation';\n    addEventListener(this.sensorEvent, this.on.sensor);\n    return true;\n  }\n\n  /** Stop following the device’s own compass. */\n  stopSensor() {\n    if (this.sensorEvent) removeEventListener(this.sensorEvent, this.on.sensor);\n    this.sensorEvent = null;\n  }\n\n  destroy() {\n    cancelAnimationFrame(this.raf);\n    this.raf = 0;\n    this.stopSensor();\n    this.ro.disconnect();\n    this.io.disconnect();\n    this.finishObs?.disconnect();\n    this.mq?.removeEventListener?.('change', this.on.motion);\n    this.dark?.removeEventListener?.('change', this.on.scheme);\n    document.removeEventListener('visibilitychange', this.on.visibility);\n    const r = this.root;\n    r.removeEventListener('pointerdown', this.on.down);\n    r.removeEventListener('pointermove', this.on.move);\n    r.removeEventListener('pointerup', this.on.up);\n    r.removeEventListener('pointercancel', this.on.up);\n    r.removeEventListener('keydown', this.on.key);\n    this.cache.clear();\n    r.remove();\n  }\n\n  // ---------------------------------------------------------------- finish\n\n  /**\n   * The material drawn: the one asked for, or on `auto` the page's finish\n   * around the host: a named dial, or `page`, made from its object tokens\n   * (a page without them gets graphite when it is dark, aluminium when light).\n   */\n  #material() {\n    const name = resolveMaterial(this.o.finish, this.host.closest('[data-finish]')?.dataset.finish, this.dark?.matches,\n      this.host.closest('[data-tone=\"light\"], [data-tone=\"dark\"]')?.dataset.tone);\n    if (name !== 'page') return MATERIALS[name];\n    const t = readLook(this.host);\n    const tone = this.host.closest('[data-tone=\"light\"], [data-tone=\"dark\"]')?.dataset.tone;\n    const around = this.host.closest('[data-finish]')?.dataset.finish;\n    const dark = AUTO[around] ? DARK.includes(around) : (tone ?? (this.dark?.matches ? 'dark' : 'light')) === 'dark';\n    return t ? materialFrom(t, dark) : dark ? MATERIALS.graphite : MATERIALS.aluminium;\n  }\n\n  #bindFinish() {\n    this.finishObs?.disconnect();\n    this.finishObs = null;\n    if (this.o.finish !== 'auto') return;\n    // The page's finish, wherever on the page it is set: the dial is drawn again when it changes.\n    this.finishObs = new MutationObserver(() => this.#followFinish());\n    this.finishObs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-finish', 'data-tone'], subtree: true });\n  }\n\n  #followFinish() {\n    if (!this.sprites || this.o.finish !== 'auto') return;\n    if (this.sprites.finish !== this.#material().key) { this.#sprites(); this.#draw(); }\n  }\n\n  // ---------------------------------------------------------------- layout\n\n  /** The dial fills the host's box (fit) or takes its size, shrinking only to fit. */\n  #fit(force = false) {\n    if (!this.root.isConnected) return;\n    const cs = getComputedStyle(this.host);\n    const pad = (k) => parseFloat(cs[k]) || 0;\n    const shown = this.root.style.display;\n    this.root.style.display = 'none';\n    const w = this.host.clientWidth - pad('paddingLeft') - pad('paddingRight');\n    const h = this.host.clientHeight - pad('paddingTop') - pad('paddingBottom');\n    this.root.style.display = shown;\n    let D;\n    if (this.o.size === 'fit') D = Math.min(w > 0 ? w : Infinity, h > 0 ? h : Infinity) * 0.9;\n    else D = Math.min(this.o.size, w > 0 ? w * 0.96 : Infinity);\n    if (!Number.isFinite(D) || D <= 0) D = 240;\n    D = Math.max(64, Math.floor(D));\n    const dpr = Math.min(globalThis.devicePixelRatio || 1, 2);\n    if (!force && D === this.D && dpr === this.dpr) return;\n    this.D = D;\n    this.dpr = dpr;\n    this.pad = Math.ceil(D * 0.09);\n    this.root.style.width = `${D}px`;\n    this.root.style.height = `${D}px`;\n    this.root.style.setProperty('--cp-d', `${D}px`);\n    const size = D + this.pad * 2;\n    this.canvas.style.inset = `${-this.pad}px`;\n    this.canvas.style.width = `${size}px`;\n    this.canvas.style.height = `${size}px`;\n    const px = Math.ceil(size * dpr);\n    if (this.canvas.width !== px) { this.canvas.width = px; this.canvas.height = px; }\n    this.#sprites();\n    this.#draw();\n    this.#wake();\n  }\n\n  #sprites() {\n    const mat = this.#material();\n    const key = `${mat.key}|${this.o.card}|${this.o.light}|${this.D}|${this.dpr}|${this.o.font}`;\n    if (!this.cache.has(key)) this.cache.set(key, bake(this.o, this.D, this.pad, this.dpr, mat));\n    this.sprites = this.cache.get(key);\n    const disp = this.sprites.display;\n    // The material drawn, never `auto`; `page` for a dial made from the page's tokens.\n    this.root.dataset.finish = mat.key.split('|')[0];\n    this.screen.dataset.kind = mat.display;\n    this.screen.style.width = `${disp.w.toFixed(1)}px`;\n    this.screen.style.height = `${disp.h.toFixed(1)}px`;\n    this.screen.hidden = !this.o.display || this.D < 96;\n  }\n\n  // ---------------------------------------------------------------- values\n\n  #aria() {\n    this.root.setAttribute('aria-valuenow', String(this.target));\n    this.root.setAttribute('aria-valuetext', valueText(this.target));\n    this.root.setAttribute('aria-label', this.o.label);\n    this.root.setAttribute('aria-readonly', String(this.o.readonly));\n    this.root.classList.toggle('cp-readonly', this.o.readonly);\n  }\n\n  #jump() {\n    this.s.h = this.target;\n    this.s.v = 0;\n    this.#draw();\n  }\n\n  /** The visitor changed it: input now, change when committed. */\n  #set(v, commit) {\n    const t = whole(v);\n    if (t !== this.target) {\n      this.target = t;\n      this.#aria();\n      this.root.dispatchEvent(new Event('input', { bubbles: true }));\n      if (this.reduced) this.#jump(); else this.#wake();\n    }\n    if (commit && this.committed !== this.target) {\n      this.committed = this.target;\n      this.root.dispatchEvent(new Event('change', { bubbles: true }));\n    }\n  }\n\n  #sensor(e) {\n    let h = null;\n    if (Number.isFinite(e.webkitCompassHeading)) h = e.webkitCompassHeading;\n    else if ((e.absolute || e.type === 'deviceorientationabsolute') && Number.isFinite(e.alpha)) h = 360 - e.alpha;\n    if (h !== null) this.setValue(h);\n  }\n\n  // ---------------------------------------------------------------- input\n\n  #centre() {\n    const r = this.root.getBoundingClientRect();\n    return { x: r.left + r.width / 2, y: r.top + r.height / 2, R: r.width / 2 };\n  }\n\n  #down(e) {\n    if (e.button !== 0 || this.o.readonly) return;\n    const c = this.#centre();\n    const d = Math.hypot(e.clientX - c.x, e.clientY - c.y);\n    if (d > c.R || d < c.R * 0.08) return;\n    this.committed = this.target;\n    this.drag = { id: e.pointerId, a: angleAt(c.x, c.y, e.clientX, e.clientY), t: this.target, turned: 0 };\n    try { this.root.setPointerCapture(e.pointerId); } catch { /* synthetic */ }\n    this.root.classList.add('cp-held');\n  }\n\n  #move(e) {\n    if (!this.drag || e.pointerId !== this.drag.id) return;\n    const c = this.#centre();\n    const a = angleAt(c.x, c.y, e.clientX, e.clientY);\n    // Accumulate the turn the short way round each move, so whole turns count.\n    this.drag.turned += wrap180(a - this.drag.a);\n    this.drag.a = a;\n    this.#set(this.drag.t - this.drag.turned, false);\n  }\n\n  #up(e) {\n    if (!this.drag || e.pointerId !== this.drag.id) return;\n    this.drag = null;\n    this.root.classList.remove('cp-held');\n    this.#set(this.target, true);\n  }\n\n  #key(e) {\n    if (this.o.readonly) return;\n    const k = keyStep(e.key, e.shiftKey);\n    if (!k) return;\n    e.preventDefault();\n    this.committed = this.target;\n    this.#set('to' in k ? k.to : this.target + k.by, true);\n  }\n\n  // ---------------------------------------------------------------- the loop\n\n  #frame = (t) => {\n    this.raf = 0;\n    const dt = this.last ? (t - this.last) / 1000 : 1 / 60;\n    this.last = t;\n    stepCard(this.s, this.target, dt, this.o.damping);\n    const done = cardSettled(this.s, this.target);\n    if (done) { this.s.h = this.target; this.s.v = 0; }\n    this.#draw();\n    if (done || !this.visible || document.hidden) this.#sleep();\n    else this.raf = requestAnimationFrame(this.#frame);\n  };\n\n  #wake() {\n    if (this.reduced) { this.#jump(); return; }\n    if (this.raf || !this.visible || document.hidden || !this.sprites) return;\n    if (cardSettled(this.s, this.target)) return;\n    this.root.dataset.state = 'running';\n    this.last = 0;\n    this.raf = requestAnimationFrame(this.#frame);\n  }\n\n  #sleep() {\n    cancelAnimationFrame(this.raf);\n    this.raf = 0;\n    this.root.dataset.state = 'asleep';\n  }\n\n  // ---------------------------------------------------------------- drawing\n\n  #draw() {\n    const sp = this.sprites;\n    if (!sp) return;\n    const g = this.canvas.getContext('2d');\n    const d = this.dpr;\n    const W = this.canvas.width;\n    const c = (this.pad + this.D / 2) * d;\n    g.setTransform(1, 0, 0, 1, 0, 0);\n    g.clearRect(0, 0, W, W);\n    g.drawImage(sp.base, 0, 0);\n    // The bezel: its knurl lit where each tooth is, its printing turning with it.\n    const rho = wrap360(-this.target);\n    g.drawImage(sp.knurl[Math.round(rho) % KNURL], 0, 0);\n    g.setTransform(1, 0, 0, 1, c, c);\n    g.rotate((rho * Math.PI) / 180);\n    g.drawImage(sp.bezelPrint, -c, -c);\n    // The card, turning under everything fixed.\n    g.setTransform(1, 0, 0, 1, c, c);\n    g.rotate((-this.s.h * Math.PI) / 180);\n    g.imageSmoothingQuality = 'high';\n    g.drawImage(sp.card, -sp.cardSize / 2, -sp.cardSize / 2);\n    g.setTransform(1, 0, 0, 1, 0, 0);\n    g.drawImage(sp.over, 0, 0);\n    // The display reads the card as it swings, not the value it is going to.\n    const h = whole(this.s.h);\n    if (h !== this.shown) {\n      this.shown = h;\n      this.deg.textContent = readout(h);\n      this.wind.textContent = windOf(h).short;\n    }\n  }\n}\n\nexport default Compass;\n"},{"path":"tactile/compass/compass.css","type":"registry:file","target":"tactile/compass/compass.css","content":"/* Compass — Tactile UI.\n   The dial fills its host's box (or takes the size it is given) and centres\n   in it. Its shadow falls outside the dial, on the page. */\n\n.cp {\n  position: relative;\n  flex: none;\n  margin: auto;\n  border-radius: 50%;\n  /* The dial is turned in any direction, so it takes the drag; the page\n     around it still scrolls. */\n  touch-action: none;\n  cursor: grab;\n  outline: none;\n  user-select: none;\n  -webkit-tap-highlight-color: transparent;\n}\n.cp.cp-held { cursor: grabbing; }\n.cp.cp-readonly { cursor: default; }\n\n.cp canvas {\n  position: absolute;\n  display: block;\n  pointer-events: none;\n  /* Host resets (img, svg, canvas { max-width: 100% }, as in Tailwind's) would squeeze\n     the canvas's width and not its height. It sizes itself: leave it alone. */\n  max-width: none;\n  max-height: none;\n}\n\n/* Focus rings the whole instrument, not one edge of it. */\n.cp:focus-visible { outline: 2px solid var(--tui-focus, currentColor); outline-offset: 4px; }\n\n/* The display in the hub: a reflective LCD on aluminium, a VFD on graphite. */\n.cp-display {\n  position: absolute;\n  left: 50%;\n  top: 50%;\n  transform: translate(-50%, -50%);\n  display: grid;\n  place-content: center;\n  justify-items: center;\n  gap: 0.12em;\n  box-sizing: border-box;\n  border-radius: calc(var(--cp-d, 240px) * 0.022);\n  font: 500 calc(var(--cp-d, 240px) * 0.064) / 1 var(--tui-mono, 'Geist Mono', ui-monospace, 'SFMono-Regular', Menlo, Consolas, monospace);\n  font-variant-numeric: tabular-nums;\n  letter-spacing: -0.02em;\n  pointer-events: none;\n}\n.cp-display[hidden] { display: none; }\n.cp-display[data-kind=\"lcd\"] {\n  color: var(--tui-lcd-ink, #1d2318);\n  background: linear-gradient(170deg, rgb(255 255 255 / 0.2), transparent 45%), var(--tui-lcd, #b8bea9);\n  box-shadow: inset 0 2px 4px rgb(0 0 0 / 0.3), inset 0 0 0 1px rgb(0 0 0 / 0.2);\n  text-shadow: 0.06em 0.08em 0 rgb(0 0 0 / 0.12);\n}\n.cp-display[data-kind=\"vfd\"] {\n  color: var(--tui-vfd, #c6f3ea);\n  background: repeating-linear-gradient(0deg, rgb(255 255 255 / 0.025) 0 1px, transparent 1px 3px), var(--tui-vfd-bg, #080b0b);\n  box-shadow: inset 0 2px 6px rgb(0 0 0 / 0.8), inset 0 0 0 1px rgb(255 255 255 / 0.05);\n  text-shadow: 0 0 0.25em color-mix(in oklab, var(--tui-vfd, #c6f3ea) 55%, transparent), 0 0 0.7em color-mix(in oklab, var(--tui-vfd, #c6f3ea) 18%, transparent);\n}\n.cp-wind {\n  font: 600 0.46em/1 var(--tui-sans, ui-sans-serif, system-ui, sans-serif);\n  letter-spacing: 0.14em;\n  margin-right: -0.14em;\n  opacity: 0.8;\n}\n\n@media (forced-colors: active) {\n  .cp:focus-visible { outline-color: Highlight; }\n  .cp-display { forced-color-adjust: none; }\n}\n"},{"path":"tactile/compass-example.html","type":"registry:file","target":"tactile/compass-example.html","content":"<!doctype html>\n<html lang=\"en\">\n<!-- Compass v0.1.0: Tactile UI\n     Put this file beside ./compass/ holding compass.mjs and compass.css.\n     Serve over HTTP (any static server, e.g. `npx serve .`). No framework,\n     no build step, no image, no other dependency. -->\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>Compass</title>\n<link rel=\"stylesheet\" href=\"./compass/compass.css\">\n<style>\n  html { background: #d8d7d2; color: #1b1c1e; }\n  @media (prefers-color-scheme: dark) { html:not([data-finish]) { background: #0e0f10; color: #e8e6e1; } }\n  html[data-finish=\"graphite\"] { background: #0e0f10; color: #e8e6e1; }\n  body { margin: 0; min-height: 100vh; display: grid; place-items: center; font: 15px/1.4 ui-sans-serif, system-ui, sans-serif; }\n  /* With size \"fit\" the dial fills this box and follows it; a number is its diameter. */\n  #compass { width: min(90vw, 520px); height: min(80vh, 520px); display: grid; }\n</style>\n</head>\n<body>\n<div id=\"compass\"></div>\n<script type=\"module\">\nimport { Compass } from './compass/compass.mjs';\n\nconst compass = new Compass(document.getElementById('compass'), {\n  bearing: 274,\n  damping: 0.6,\n  card: \"cardinal\",\n  finish: \"auto\",\n  size: \"fit\",\n  light: 315,\n  readonly: false,\n  display: true,\n  label: \"Heading\",\n});\n\ncompass.root.addEventListener('input', () => { /* compass.value: 0–359, while the bezel turns */ });\ncompass.root.addEventListener('change', () => { /* committed: the drag ended or a key was pressed */ });\n\n// compass.setValue(90)                  swing to a bearing (a wind vane, a heading feed)\n// compass.setValue(90, { instant: true })\n// compass.heading                      where the card points right now, mid-swing\n// button.onclick = () => compass.useSensor()   the device's own compass (asks permission)\n// compass.update({ card: 'aviation' }), compass.destroy()\n</script>\n</body>\n</html>"},{"path":"tactile/compass/LICENSE","type":"registry:file","target":"tactile/compass/LICENSE","content":"MIT License\n\nCopyright (c) 2026 Ciprian Titire\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"}],"docs":"Compass is in tactile/compass/. Open tactile/compass-example.html to see it run; compass.mjs is the class, compass.css its look.\nLoad both or it renders unstyled: in a bundler such as Vite, import './tactile/compass/compass.css' next to the .mjs import (or link it in plain HTML), then construct it on an element as the example does.\nDocs: https://tactileui.dev/objects/compass","meta":{"id":"cmp.compass","version":"0.1.0","access":"free","licence":"MIT"}}