{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"pull-cord","type":"registry:block","title":"Pull-cord Bulb","description":"Object. A pendant lamp that is a switch. Pull the acorn on its textile cord or ball chain: the detent resists and snaps, and the filament warms from dull red to white while the lamp sways. It can switch the whole page’s finish, the new one opening from the bulb.","registryDependencies":[],"files":[{"path":"tactile/pull-cord/pull-cord.mjs","type":"registry:file","target":"tactile/pull-cord/pull-cord.mjs","content":"/**\n * Pull-cord Bulb — Tactile UI.\n *\n * A pendant lamp that is a switch. A spun-aluminium shade (or a tube, or a\n * bare lamp holder) hangs from a ceiling cup on its cable; beside the bulb\n * hangs a thin textile cord with a turned acorn at its end. Pull it down: the\n * switch resists, then snaps; the filament warms up; let go and the cord\n * springs back and swings, and the lamp sways with it.\n *\n * Mechanisms:\n *   1. The rig. The pull cord is a chain of stiff tension-only springs under\n *      gravity, stepped at 1/16000 s (so a 3 mm cord cannot stretch like\n *      rubber) and hung from a spring-loaded plunger inside the lamp. The\n *      plunger has a detent: its force rises, peaks and snaps down when the\n *      latch trips, and the latch re-arms on the way back with a softer tick.\n *      The visitor's hand is a stiff spring to the acorn, so under load the\n *      acorn visibly lags the pointer and catches up at the snap. The lamp is\n *      a damped pendulum; the cord pulls it at its anchor, so a tug tilts it.\n *   2. The filament. Electrical heating against T⁴ radiation: it heats in\n *      ~130 ms and cools along T ∝ (1 + 3t/τ)^(-1/3) — fast at first, then a\n *      dull red ember that lingers. Its colour is the blackbody colour of its\n *      temperature, so it goes red → orange → warm white on the way up.\n *   3. Light fixed in the room. Every turned part is shaded per pixel from\n *      its profile with the room lamp (upper left by default). The dome and\n *      the glass are split: the body turns with the sway, the sheen does not\n *      (it is drawn unrotated, clipped to the turned silhouette). When the\n *      bulb is on it lights the inside of the shade and throws the scallop a\n *      real downlight throws on the wall behind it, computed from the rim's\n *      cut-off, on its own canvas blended `screen` onto the page — within\n *      the object's box, faded at its edges, never a page overlay.\n *\n * Cost at rest: nothing. The loop sleeps once the rig is still and the\n * filament has settled, pauses off screen and in a hidden tab, and a 2.5 s\n * frame gap advances one clamped frame. Sprites are baked once per size and\n * finish; a frame is a dozen drawImage calls and two short paths.\n *\n * Accessibility: the root is `role=\"switch\"` with `aria-checked` and a label;\n * Space and Enter pull the cord (the same physical pull, animated); a click\n * or tap anywhere on it pulls too. It fires `change`. The canvases are\n * aria-hidden. Touch: the acorn's 44 px grip takes the drag\n * (`touch-action: none`), the rest of the box still scrolls the page.\n *\n * Reduced motion: the switch still works and nothing moves. State changes\n * instantly, the glow steps instead of ramping, and no frame is requested.\n *\n * With `target` it is a finish switch: on is aluminium, off is graphite,\n * written to the target's `data-finish` — and, on the page root, remembered\n * in localStorage['tui-finish'] exactly as the site's own finish key does.\n * With `reveal` too, on the page root, the new finish opens from the bulb as\n * a growing circle (a View Transition; instant without one or under reduced\n * motion). With `reveal` and no target, the `change` event is dispatched\n * inside that transition: a page that switches its own finish in its\n * listener gets the same reveal.\n *\n * `pull: 'chain'` hangs the acorn on a metal ball chain instead of the cord:\n * the same rig with its own numbers (heavier, stiffer, less air drag), its\n * beads threaded at a fixed pitch up the cord's curve, one baked sprite each.\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// ---------------------------------------------------------------- the room lamp\n\n/** Screen direction toward the room 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 room lamp as a 3D unit vector (x right, y down, z toward the viewer), `off` degrees off the line of sight. */\nexport function lampVector(light, off = 55) {\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// ---------------------------------------------------------------- the filament\n\n/** Blackbody colour at T kelvin, 0–255 per channel (Tanner Helland's fit). */\nexport function blackbody(T) {\n  const t = T / 100;\n  const r = t <= 66 ? 255 : 329.698727446 * (t - 60) ** -0.1332047592;\n  const g = t <= 66 ? 99.4708025861 * Math.log(t) - 161.1195681661 : 288.1221695283 * (t - 60) ** -0.0755148492;\n  const b = t >= 66 ? 255 : t <= 19 ? 0 : 138.5177312231 * Math.log(t - 10) - 305.0447927307;\n  return [r, g, b].map((v) => Math.round(clamp(v, 0, 255)));\n}\n\n/**\n * The filament's thermal constants. `tau` is the warm-up time scale: the\n * electrical power heats the coil at warm/tau kelvin per second while it is\n * cold; radiation (∝ T⁴) balances it exactly at the warm temperature.\n * `draper` is where a hot body starts to glow a dull red.\n */\nexport const FILAMENT = Object.freeze({ room: 300, draper: 760, tau: 0.15, subStep: 1 / 600, maxStep: 1 / 30 });\n\n/**\n * Advance the filament temperature. C·dT/dt = P·on − k(T⁴ − T_room⁴), with P\n * and k chosen so it settles at `warm`. Clamped and sub-stepped: a tab that\n * returns after 2.5 s advances one sane frame.\n */\nexport function stepFilament(T, on, dt, warm = 2700, tau = FILAMENT.tau) {\n  const Tr = FILAMENT.room;\n  const rate = warm / tau;\n  const span = warm ** 4 - Tr ** 4;\n  let t = clamp(Number.isFinite(T) ? T : Tr, Tr, warm);\n  let left = clamp(dt, 0, FILAMENT.maxStep);\n  while (left > 1e-9) {\n    const h = Math.min(left, FILAMENT.subStep);\n    t += rate * ((on ? 1 : 0) - (t ** 4 - Tr ** 4) / span) * h;\n    left -= h;\n  }\n  return clamp(t, Tr, warm);\n}\n\n/** How brightly the filament glows, 0–1, as drawn: nothing below the Draper point, full at the warm temperature. */\nexport const glowOf = (T, warm = 2700) => clamp((T - FILAMENT.draper) / (warm - FILAMENT.draper), 0, 1) ** 1.6;\n\n// ---------------------------------------------------------------- the switch\n\n/**\n * The pull switch, in metres and newtons. The plunger travels `travel`; the\n * latch trips at `click` and re-arms below `reset`. While armed the force\n * rises (`preload` + `rate`·e) with a detent bump before the trip; once\n * tripped the over-centre spring lets go and the force drops to `after` of\n * the rate — that drop is the snap.\n */\nexport const SWITCH = Object.freeze({\n  travel: 0.014, click: 0.009, reset: 0.0035, preload: 1.2, rate: 500, bump: 3, bumpAt: 0.78, bumpWidth: 0.3, after: 0.35,\n  mass: 0.004, damping: 1.4,\n});\n\n/** The force the switch pushes back with at extension `e`. */\nexport function switchForce(e, armed, sw = SWITCH) {\n  if (e <= 0) return sw.preload;\n  if (!armed) return sw.preload + sw.rate * sw.after * e;\n  const c = sw.click * sw.bumpAt;\n  const w = sw.click * sw.bumpWidth;\n  return sw.preload + sw.rate * e + sw.bump * Math.exp(-(((e - c) / w) ** 2));\n}\n\n// ---------------------------------------------------------------- the lamp\n\n/**\n * The lamps, in metres, in the pendant's own frame: x right, y down from\n * where the cable enters the top. `bulb` is where the glass meets the cap;\n * `anchor` is where the pull cord leaves the switch; `cord` is the default\n * pull-cord length; `mass` and `cm` make the pendulum.\n */\nexport const STYLES = Object.freeze({\n  dome: Object.freeze({ left: 0.143, right: 0.143, bottom: 0.19, rim: 0.155, R: 0.14, bulb: 0.105, anchor: [0.056, 0.153], cord: 0.26, mass: 1.1, cm: 0.09 }),\n  tube: Object.freeze({ left: 0.075, right: 0.075, bottom: 0.28, rim: 0.25, R: 0.072, bulb: 0.19, anchor: [0.05, 0.248], cord: 0.24, mass: 0.9, cm: 0.13 }),\n  bare: Object.freeze({ left: 0.032, right: 0.056, bottom: 0.17, rim: 0.062, R: 0.0205, bulb: 0.084, anchor: [0.047, 0.042], cord: 0.2, mass: 0.35, cm: 0.05 }),\n});\n\n/** The A60 glass: neck radius, sphere radius, and the sphere centre below the cap. */\nexport const BULB = Object.freeze({ neck: 0.0135, R: 0.03, centre: 0.05 });\nexport const ACORN = Object.freeze({ len: 0.04, r: 0.0088, mass: 0.016 });\nexport const CANOPY = Object.freeze({ r: 0.04, h: 0.02 });\n/** How much of the view is from below: the rim of a shade reads as an ellipse this flat. */\nexport const ELEVATION = 0.18;\n/** Room kept below the acorn for a full pull, and the least cable between ceiling and lamp. */\nconst PULL_ROOM = 0.042;\nconst MIN_DROP = 0.035;\n\n/**\n * Fit the lamp into a box W × H (CSS px). Returns the scale `S` (px per\n * metre), the cable drop `Ls` (m) that fills the height, and where the\n * ceiling pivot sits. A tall narrow box (a toggle hanging from a nav) is\n * width-bound and gets a long cable; a wide hero is height-bound.\n */\nexport function layout(W, H, style = 'dome', cord = 1) {\n  const st = STYLES[style] ?? STYLES.dome;\n  const Lp = st.cord * clamp(+cord || 1, 0.4, 2);\n  const left = st.left;\n  const right = Math.max(st.right, st.anchor[0] + ACORN.r);\n  const span = left + right + 0.05;\n  const below = Math.max(st.bottom, st.anchor[1] + Lp + ACORN.len + PULL_ROOM) + 0.012;\n  const above = CANOPY.h + ELEVATION * CANOPY.r;\n  const byW = W > 0 ? W / span : Infinity;\n  const byH = H > 0 ? H / (above + MIN_DROP + below) : Infinity;\n  let S = Math.min(byW, byH);\n  if (!Number.isFinite(S) || S <= 0) S = 400;\n  const Ls = Math.max(MIN_DROP, (H > 0 ? H / S : 0) - above - below);\n  return {\n    S, Ls, Lp, below, above,\n    axisX: (W > 0 ? W / 2 : 0) + ((left - right) / 2) * S,\n    pivotY: CANOPY.h * S,\n  };\n}\n\n// ---------------------------------------------------------------- the rig\n\nexport const RIG = Object.freeze({\n  segments: 12, nodeMass: 0.0008, ks: 40000, slack: 0.02, kd: 1.2, air: 4, g: 9.81,\n  subStep: 1 / 16000, maxStep: 1 / 30,\n  hand: 800, handMax: 12, handZeta: 0.8,\n  swayZeta: 0.3, minPendulum: 0.6,\n});\n\n/**\n * The ball chain (`pull: 'chain'`): the same rig with its own numbers. More\n * nodes and more of them metal, so it hangs heavier than the cord; stiffer\n * (a chain does not give); almost nothing in compression (it folds at every\n * link); less air drag, so it swings on a little longer. `bead` and `pitch`\n * are the drawn beads (m): a 4.2 mm ball every 5.8 mm, centre to centre.\n */\nexport const CHAIN = Object.freeze({\n  ...RIG,\n  segments: 16, nodeMass: 0.0015, ks: 60000, slack: 0.004, kd: 1.5, air: 2.6,\n  bead: 0.0042, pitch: 0.0058, minBead: 5.5,\n});\n\n/**\n * The beads of a ball chain hung through the points (xs, ys), node 0 at the\n * switch and the last at the pull: the path is smoothed as the cord is drawn\n * (a quadratic through each node's midpoints), and the beads are threaded up\n * it from the pull, each exactly `pitch` (straight-line, centre to centre)\n * from the one before, the way the links hold them. The chain runs out at\n * the switch, so as the plunger pulls more chain out of it, beads come out\n * at the top. Returns [x0, y0, x1, y1, …] from the pull up.\n */\nexport function beadsAlong(xs, ys, pitch, n = xs.length - 1) {\n  // The smoothed path, from the pull up.\n  const px = [xs[n]];\n  const py = [ys[n]];\n  const q = (ax, ay, cx, cy, bx, by) => {\n    for (let s = 1; s <= 6; s += 1) {\n      const t = s / 6;\n      const u = 1 - t;\n      px.push(u * u * ax + 2 * u * t * cx + t * t * bx);\n      py.push(u * u * ay + 2 * u * t * cy + t * t * by);\n    }\n  };\n  let ex = xs[n];\n  let ey = ys[n];\n  if (n >= 2) {\n    const mx = (xs[n - 1] + xs[n]) / 2;\n    const my = (ys[n - 1] + ys[n]) / 2;\n    px.push(mx); py.push(my); ex = mx; ey = my;\n    for (let i = n - 1; i >= 1; i -= 1) {\n      const bx = i > 1 ? (xs[i - 1] + xs[i]) / 2 : xs[0];\n      const by = i > 1 ? (ys[i - 1] + ys[i]) / 2 : ys[0];\n      q(ex, ey, xs[i], ys[i], bx, by);\n      ex = bx; ey = by;\n    }\n  } else { px.push(xs[0]); py.push(ys[0]); }\n  // Thread the beads: the next is where the path first leaves a circle of radius `pitch` round the last.\n  const out = [];\n  let bx = px[0];\n  let by = py[0];\n  let j = 1;\n  const p2 = pitch * pitch;\n  for (;;) {\n    while (j < px.length && (px[j] - bx) ** 2 + (py[j] - by) ** 2 < p2) j += 1;\n    if (j >= px.length) break;\n    // Where segment j-1 → j crosses the circle (its start is inside, its end is not).\n    const ax = px[j - 1] - bx;\n    const ay = py[j - 1] - by;\n    const dx = px[j] - px[j - 1];\n    const dy = py[j] - py[j - 1];\n    const A = dx * dx + dy * dy;\n    const B = 2 * (ax * dx + ay * dy);\n    const C = ax * ax + ay * ay - p2;\n    const t = A > 0 ? (-B + Math.sqrt(Math.max(0, B * B - 4 * A * C))) / (2 * A) : 0;\n    bx = px[j - 1] + dx * t;\n    by = py[j - 1] + dy * t;\n    out.push(bx, by);\n  }\n  return out;\n}\n\n/**\n * A rig at rest: the cord hanging straight from the anchor, the switch\n * seated and armed, the lamp plumb. Positions in metres from the ceiling\n * pivot, y down.\n */\nexport function makeRig({ style = 'dome', Ls = 0.3, Lp, pull = 'cord' } = {}) {\n  const st = STYLES[style] ?? STYLES.dome;\n  const P = pull === 'chain' ? CHAIN : RIG;\n  const N = P.segments;\n  const len = Lp ?? st.cord;\n  const n = N + 1; // node 0 is the anchor (on the lamp), 1…N the cord, N the acorn\n  const r = {\n    style, st, N, Ls, P, seg: len / N,\n    x: new Float64Array(n), y: new Float64Array(n), vx: new Float64Array(n), vy: new Float64Array(n),\n    m: new Float64Array(n), fx: new Float64Array(n), fy: new Float64Array(n),\n    theta: 0, omega: 0, e: 0, ev: 0, armed: true, tension: 0,\n  };\n  for (let i = 1; i <= N; i += 1) r.m[i] = i === N ? ACORN.mass : P.nodeMass;\n  const L = Math.max(RIG.minPendulum, Ls + st.cm);\n  r.L = L;\n  r.I = st.mass * L * L;\n  r.cTheta = 2 * RIG.swayZeta * Math.sqrt(st.mass * RIG.g * L * r.I);\n  const [ax, ay] = anchorOf(r);\n  for (let i = 1; i <= N; i += 1) { r.x[i] = ax; r.y[i] = ay + i * r.seg; }\n  r.x[0] = ax;\n  r.y[0] = ay;\n  return r;\n}\n\n/** Where the cord leaves the lamp, in the room, for the lamp's current angle. */\nexport function anchorOf(r, theta = r.theta) {\n  const [lx, ly] = r.st.anchor;\n  const s = Math.sin(theta);\n  const c = Math.cos(theta);\n  const d = r.Ls + ly;\n  return [d * s + lx * c, d * c - lx * s];\n}\n\n/** A point of the lamp's own frame, in the room. */\nexport function lampPoint(r, lx, ly, theta = r.theta) {\n  const s = Math.sin(theta);\n  const c = Math.cos(theta);\n  const d = r.Ls + ly;\n  return [d * s + lx * c, d * c - lx * s];\n}\n\nfunction substep(r, h, hand, events) {\n  const { N, x, y, vx, vy, m, fx, fy, P } = r;\n  const sw = SWITCH;\n  const s = Math.sin(r.theta);\n  const c = Math.cos(r.theta);\n  const [lax, lay] = r.st.anchor;\n  const d = r.Ls + lay;\n  // The anchor rides on the lamp: position and velocity from the pendulum.\n  const Ax = d * s + lax * c;\n  const Ay = d * c - lax * s;\n  const dAx = d * c - lax * s;\n  const dAy = -d * s - lax * c;\n  x[0] = Ax; y[0] = Ay; vx[0] = dAx * r.omega; vy[0] = dAy * r.omega;\n\n  for (let i = 1; i <= N; i += 1) {\n    fx[i] = -P.air * m[i] * vx[i];\n    fy[i] = m[i] * RIG.g - P.air * m[i] * vy[i];\n  }\n  // A cord pulls hard and barely pushes back: stiff in tension, soft in\n  // compression (a textile cord's own stiffness), damped either way. A spring\n  // that switched off at its rest length would chatter there for ever.\n  let T0 = 0;\n  let t0x = 0;\n  let t0y = 1;\n  for (let k = 0; k < N; k += 1) {\n    const dx = x[k + 1] - x[k];\n    const dy = y[k + 1] - y[k];\n    const L = Math.hypot(dx, dy) || 1e-9;\n    const rest = r.seg + (k === 0 ? r.e : 0);\n    const ux = dx / L;\n    const uy = dy / L;\n    const rv = (vx[k + 1] - vx[k]) * ux + (vy[k + 1] - vy[k]) * uy;\n    const stretch = L - rest;\n    const f = (stretch > 0 ? P.ks : P.ks * P.slack) * stretch + P.kd * rv;\n    if (k > 0) { fx[k] += f * ux; fy[k] += f * uy; }\n    fx[k + 1] -= f * ux;\n    fy[k + 1] -= f * uy;\n    if (k === 0) { T0 = Math.max(0, f); t0x = ux; t0y = uy; }\n  }\n  if (hand && hand.node >= 1 && hand.node <= N) {\n    const j = hand.node;\n    let hx = RIG.hand * (hand.x - x[j]);\n    let hy = RIG.hand * (hand.y - y[j]);\n    const F = Math.hypot(hx, hy);\n    if (F > RIG.handMax) { hx *= RIG.handMax / F; hy *= RIG.handMax / F; }\n    const ch = 2 * RIG.handZeta * Math.sqrt(RIG.hand * m[j]);\n    fx[j] += hx - ch * vx[j];\n    fy[j] += hy - ch * vy[j];\n  }\n  for (let i = 1; i <= N; i += 1) {\n    vx[i] += (fx[i] / m[i]) * h;\n    vy[i] += (fy[i] / m[i]) * h;\n    x[i] += vx[i] * h;\n    y[i] += vy[i] * h;\n  }\n  // The plunger: pulled by the cord's tension, pushed back by the switch.\n  r.ev += ((T0 - switchForce(r.e, r.armed) - sw.damping * r.ev) / sw.mass) * h;\n  r.e += r.ev * h;\n  if (r.e < 0) { r.e = 0; if (r.ev < 0) r.ev = 0; }\n  if (r.e > sw.travel) { r.e = sw.travel; if (r.ev > 0) r.ev = 0; }\n  if (r.armed && r.e >= sw.click) { r.armed = false; events.push('click'); }\n  else if (!r.armed && r.e <= sw.reset) { r.armed = true; events.push('reset'); }\n  // The lamp: a damped pendulum, pulled at the anchor by the cord.\n  const Q = T0 * (t0x * dAx + t0y * dAy);\n  const st = r.st;\n  r.omega += ((-st.mass * RIG.g * r.L * Math.sin(r.theta) - r.cTheta * r.omega + Q) / r.I) * h;\n  r.theta += r.omega * h;\n  r.tension = T0;\n}\n\n/**\n * Advance the rig by `dt` seconds (clamped to 1/30 s, sub-stepped at\n * 1/16000 s). `hand` is null or { node, x, y }: a stiff spring from that node\n * toward a point, capped at 12 N like a hand that stops pulling at the stop.\n * Returns the switch events in order: 'click' when the latch trips (the\n * lamp toggles), 'reset' when it re-arms.\n */\nexport function stepRig(r, dt, hand = null) {\n  const events = [];\n  let left = clamp(Number.isFinite(dt) ? dt : 0, 0, RIG.maxStep);\n  while (left > 1e-9) {\n    const h = Math.min(left, RIG.subStep);\n    substep(r, h, hand, events);\n    left -= h;\n  }\n  return events;\n}\n\n/** Still, to within `eps` m/s everywhere (the caller scales it to a fraction of a pixel). */\nexport function rigSettled(r, eps = 0.002) {\n  for (let i = 1; i <= r.N; i += 1) if (Math.abs(r.vx[i]) > eps || Math.abs(r.vy[i]) > eps) return false;\n  if (Math.abs(r.omega) * (r.Ls + 0.3) > eps) return false;\n  return Math.abs(r.ev) <= eps;\n}\n\n/** Stop dead: what the loop does once motion is below a hundredth of a pixel a frame. */\nexport function freezeRig(r) {\n  r.vx.fill(0);\n  r.vy.fill(0);\n  r.omega = 0;\n  r.ev = 0;\n}\n\n/** Let a new rig hang for a while so it wakes up already still. */\nexport function settleRig(r, seconds = 2) {\n  for (let t = 0; t < seconds; t += 1 / 60) stepRig(r, 1 / 60);\n  freezeRig(r);\n  return r;\n}\n\n/** Where the acorn hangs at rest (the last node), for the programmed pull. */\nexport const acornOf = (r) => [r.x[r.N], r.y[r.N]];\n\n/** The depth of a full programmed pull below rest, in metres: past the stop, with the hand's lag. */\nexport const PULL_DEPTH = SWITCH.travel + 0.014;\n\n// ---------------------------------------------------------------- the light on the wall\n\n/**\n * The downlight on the wall behind the lamp, 0–1, at a wall point (x, y)\n * metres from the bulb's centre (y down), the wall `d` behind it. Inverse\n * square and cosine; light is stopped by the shade (a ray that crosses the\n * rim plane inside the rim) or, for the bare holder, by the holder above.\n * The edge is soft by the bulb's size; the white inside of a shade adds to\n * what goes down.\n */\nexport function wallLight(x, y, style = 'dome', d = 0.2) {\n  const st = STYLES[style] ?? STYLES.dome;\n  const r2 = x * x + y * y + d * d;\n  const bulbY = st.bulb + BULB.centre; // lamp frame\n  const flat = Math.sqrt(x * x + d * d);\n  // The bulb is not a point: sample it top to bottom, so the rim's cut-off\n  // softens by the bulb's own size, as a real shade's does.\n  const n = 7;\n  let seen = 0;\n  for (let k = 0; k < n; k += 1) {\n    const yb = (k / (n - 1) - 0.5) * 1.6 * BULB.R;\n    const ry = y - yb; // the ray, from this part of the bulb\n    const rim = st.rim - (bulbY + yb); // the rim plane, relative to it (negative: above)\n    let v = 1;\n    if (style === 'bare') {\n      if (ry < 0 && rim < 0) v = (rim / ry) * flat > st.R ? 1 : 0;\n    } else if (rim < 0) {\n      if (ry < 0) v = (rim / ry) * flat > st.R ? 1 : 0;\n    } else {\n      v = ry > 0 && (rim / ry) * flat < st.R ? 1 : 0;\n    }\n    seen += v;\n  }\n  const E = ((d * d * d) / r2 ** 1.5) * (seen / n);\n  const down = y / Math.sqrt(r2);\n  return E * (1 + 0.8 * Math.max(0, down));\n}\n\n// ---------------------------------------------------------------- tuning\n\nexport const FINISHES = Object.freeze(['auto', 'aluminium', 'graphite']);\nexport const SHADES = Object.freeze(Object.keys(STYLES));\nexport const BULBS = Object.freeze(['clear', 'frosted']);\n/** What hangs from the switch: the textile cord, or a metal ball chain. */\nexport const PULLS = Object.freeze(['cord', 'chain']);\n\n/**\n * The materials. `metal` is the shade, holder, ceiling cup and acorn;\n * `cord` the textile cable and pull cord; the inside of a shade is white\n * enamel on both finishes, as on the real thing.\n */\nexport const MATERIALS = Object.freeze({\n  aluminium: Object.freeze({\n    key: 'aluminium', metal: '#bdbfbc', amb: 0.22, kd: 0.74, ks: 0.1, gloss: 7, env: 0.04, grain: 0.035,\n    cord: '#c9c8c2', cordDark: '#8e8d88', cordLight: '#f4f3ee', shadow: 0.3, lip: 0.55,\n  }),\n  graphite: Object.freeze({\n    key: 'graphite', metal: '#2b2c30', amb: 0.24, kd: 0.8, ks: 0.1, gloss: 7, env: 0.04, grain: 0.05,\n    cord: '#232426', cordDark: '#0d0d0e', cordLight: '#6a6b6f', shadow: 0.42, lip: 0.28,\n  }),\n});\n\n/** The page's object tokens `auto` reads the lamp's material from (`--tui-obj-frame` …), when a page carries them. */\nexport const LOOK = Object.freeze(['frame', 'edge']);\nconst ENAMEL = '#efebe2';\nconst MILK = '#f2f0ea';\n/** Where tungsten burns to at its hottest: not white, a warm cream. */\nconst HOT = [255, 243, 212];\n\n/** Where the wall is behind the lamp (m), and how far the room lamp's shadow falls on it. */\nexport const WALL = Object.freeze({ distance: 0.12, shadow: 0.03, blur: 0.022 });\n\n// ---------------------------------------------------------------- the reveal\n\n/**\n * The finish changing from the lamp. Lights on: the light page opens out of\n * the bulb (the site's footer lamp, app/home.mjs, as the component's own).\n * Lights off: the reverse, the lit page shrinking back into the bulb over the\n * dark one, so the filament's afterglow is the last light left; darkness\n * never pours out of a lamp. The light's edge is soft: a feather of\n * `feather` of the radius (pull-cord.css draws it with a radial mask).\n */\nexport const REVEAL = Object.freeze({ ms: 700, easing: 'cubic-bezier(0.23, 1, 0.32, 1)', feather: 0.1 });\nlet revealing = 0;\n\n/**\n * Run `apply` (the page-root finish change) as a View Transition about\n * (x, y), viewport px: the new state grows out of that point, or with\n * `closing` the old state shrinks into it. Under reduced motion or without\n * `startViewTransition` it runs `apply` at once and returns null. While it\n * runs the root carries `pc-reveal` (and `pc-closing`) and the point as\n * `--pc-x` / `--pc-y`, which pull-cord.css reads.\n */\nexport function revealFrom(apply, x, y, { doc = globalThis.document, reduced = false, closing = false } = {}) {\n  if (reduced || typeof doc?.startViewTransition !== 'function') { apply(); return null; }\n  const root = doc.documentElement;\n  const w = doc.defaultView?.innerWidth ?? root.clientWidth ?? 0;\n  const h = doc.defaultView?.innerHeight ?? root.clientHeight ?? 0;\n  // Out past the farthest corner by the feather, so the soft edge has left the screen when it opens.\n  const far = Math.ceil(Math.hypot(Math.max(x, w - x), Math.max(y, h - y)) / (1 - REVEAL.feather));\n  revealing += 1;\n  root.classList.add('pc-reveal');\n  if (closing) root.classList.add('pc-closing'); else root.classList.remove('pc-closing');\n  root.style.setProperty('--pc-x', `${x}px`);\n  root.style.setProperty('--pc-y', `${y}px`);\n  const done = () => {\n    revealing -= 1;\n    if (revealing) return;\n    root.classList.remove('pc-reveal');\n    root.classList.remove('pc-closing');\n    root.style.removeProperty('--pc-x');\n    root.style.removeProperty('--pc-y');\n  };\n  let vt;\n  try { vt = doc.startViewTransition(apply); } catch { done(); apply(); return null; }\n  vt.ready.then(() => root.animate(\n    { '--pc-r': closing ? [`${far}px`, '0px'] : ['0px', `${far}px`] },\n    // Held at its end until the transition is torn down: a closing light that let go would flash the whole light page back.\n    { duration: REVEAL.ms, easing: REVEAL.easing, fill: 'forwards', pseudoElement: closing ? '::view-transition-old(root)' : '::view-transition-new(root)' },\n  )).catch(() => {});\n  // A skipped transition (another one started, or the page hidden) rejects: the class still comes off, nothing is thrown.\n  vt.updateCallbackDone?.catch(() => {});\n  vt.finished.catch(() => {}).finally(done);\n  return vt;\n}\n\nexport const TUNING = Object.freeze({\n  rig: RIG, switch: SWITCH, filament: FILAMENT, elevation: ELEVATION, pullDepth: PULL_DEPTH, wall: WALL, maxDpr: 2,\n  glowLevels: 16,\n});\n\n// ================================================================ drawing\n// Everything below runs only in a browser.\n\nconst GLOW_LEVELS = 16;\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 css = (rgb, a = 1) => `rgba(${rgb.map((v) => Math.round(v)).join(', ')}, ${clamp(a, 0, 1).toFixed(3)})`;\nconst mixRgb = (a, b, t) => a.map((v, i) => v + (b[i] - v) * clamp(t, 0, 1));\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 probe = 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 hex = (value) => {\n  probe ??= canvasOf(1, 1).getContext('2d', { willReadFrequently: true });\n  probe.clearRect(0, 0, 1, 1);\n  probe.fillStyle = '#000000';\n  probe.fillStyle = value;\n  probe.fillRect(0, 0, 1, 1);\n  const [r, g, b] = probe.getImageData(0, 0, 1, 1).data;\n  return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;\n};\nconst hexOf = (rgb) => `#${((1 << 24) | (Math.round(rgb[0]) << 16) | (Math.round(rgb[1]) << 8) | Math.round(rgb[2])).toString(16).slice(1)}`;\n\n/**\n * The lamp's material from a page's object tokens: its metal is the finish's\n * `--tui-obj-frame`, its cord the same metal with the finish's edge for the\n * light on it, its shadow the finish's own; a matte finish (chalk) takes no\n * sheen and no reflection. The shading numbers are the two named materials'.\n */\nexport function materialFrom(frame, edge, shadow, matte, glow = 0) {\n  const rgb = hexRgb(frame);\n  const to = (t) => hexOf(mixRgb(rgb, hexRgb(edge), t));\n  return Object.freeze({\n    key: `page|${frame}|${edge}|${shadow}|${matte ? 1 : 0}|${glow}`,\n    metal: frame, amb: 0.23, kd: 0.77, ks: matte ? 0 : 0.1, gloss: 7, env: matte ? 0 : 0.04, grain: matte ? 0.06 : 0.04,\n    // A finish that glows (Phosphor, Night) has a frame as dark as the wall behind it: its cord and its acorn are drawn in its edge colour, so they read.\n    ...(glow > 0 ? { acorn: to(0.5) } : {}),\n    cord: glow > 0 ? to(0.55) : frame, cordDark: glow > 0 ? to(0.25) : hexOf(mixRgb(rgb, [0, 0, 0], 0.45)), cordLight: glow > 0 ? hexOf(hexRgb(edge)) : to(0.35),\n    shadow: clamp(shadow, 0, 1),\n    // A bright metal has a bright rolled lip; a dark one a dim one.\n    lip: (rgb[0] + rgb[1] + rgb[2]) / 765 > 0.45 ? 0.55 : 0.28,\n  });\n}\nconst norm3 = (v) => { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; };\n\n/** A premultiplied, linear-light paint buffer, turned into a canvas at the end. */\nclass Paint {\n  constructor(w, h) { this.w = Math.max(1, Math.ceil(w)); this.h = Math.max(1, Math.ceil(h)); this.d = new Float32Array(this.w * this.h * 4); }\n  over(i, j, r, g, b, a) {\n    if (a <= 0 || i < 0 || j < 0 || i >= this.w || j >= this.h) return;\n    const k = (j * this.w + i) * 4;\n    const d = this.d;\n    const ia = 1 - a;\n    d[k] = r * a + d[k] * ia;\n    d[k + 1] = g * a + d[k + 1] * ia;\n    d[k + 2] = b * a + d[k + 2] * ia;\n    d[k + 3] = a + d[k + 3] * ia;\n  }\n  canvas() {\n    const c = canvasOf(this.w, this.h);\n    const g = c.getContext('2d');\n    const img = g.createImageData(this.w, this.h);\n    const o = img.data;\n    const d = this.d;\n    for (let k = 0; k < d.length; k += 4) {\n      const a = d[k + 3];\n      if (a <= 0.0005) continue;\n      o[k] = SRGB[Math.round(clamp(d[k] / a, 0, 1) * 4096)];\n      o[k + 1] = SRGB[Math.round(clamp(d[k + 1] / a, 0, 1) * 4096)];\n      o[k + 2] = SRGB[Math.round(clamp(d[k + 2] / a, 0, 1) * 4096)];\n      o[k + 3] = Math.round(clamp(a, 0, 1) * 255);\n    }\n    g.putImageData(img, 0, 0);\n    return c;\n  }\n}\n\n/**\n * A turned part — a surface of revolution about the vertical axis — seen a\n * little from below, painted pixel by pixel. `r(y)` is its radius (m) down\n * its height y0…y1 (m, lamp frame). Its top edge is straight (`cut`, as where\n * it meets something) or the front arc of its top circle (`arc`); its bottom\n * edge is the front arc of its bottom circle, below which a `solid` part\n * shows its underside and an open shade shows nothing (its inside is drawn\n * separately). `shade(nx, ny, nz, x, y)` returns linear [r, g, b, a].\n */\nfunction turned(buf, fr, part, shade, under) {\n  const { k, ox, oy } = fr;\n  const s = ELEVATION;\n  const { y0, y1 } = part;\n  const r0 = part.r(y0);\n  const r1 = part.r(y1);\n  let rmax = 0;\n  for (let t = 0; t <= 48; t += 1) rmax = Math.max(rmax, part.r(y0 + ((y1 - y0) * t) / 48));\n  const jTop = Math.max(0, Math.floor(oy + (y0 - s * r0) * k) - 1);\n  const jBot = Math.min(buf.h - 1, Math.ceil(oy + (y1 + s * r1) * k) + 1);\n  const iL = Math.max(0, Math.floor(ox - rmax * k) - 1);\n  const iR = Math.min(buf.w - 1, Math.ceil(ox + rmax * k) + 1);\n  const dy = Math.max((y1 - y0) / 300, 1e-5);\n  for (let j = jTop; j <= jBot; j += 1) {\n    const y = (j + 0.5 - oy) / k;\n    const yc = clamp(y, y0, y1);\n    const r = part.r(yc);\n    const ya = Math.max(y0, yc - dy);\n    const yb = Math.min(y1, yc + dy);\n    const dr = yb > ya ? (part.r(yb) - part.r(ya)) / (yb - ya) : 0;\n    const ca = 1 / Math.sqrt(1 + dr * dr);\n    const sa = dr * ca;\n    for (let i = iL; i <= iR; i += 1) {\n      const x = (i + 0.5 - ox) / k;\n      const ax = Math.abs(x);\n      const bot = y1 - s * r1 * Math.sqrt(Math.max(0, 1 - (x / r1) ** 2));\n      const cb = clamp((bot - y) * k + 0.5, 0, 1);\n      if (r > 0 && ax < r + 1 / k) {\n        const cx = clamp((r - ax) * k + 0.5, 0, 1);\n        const top = part.top === 'arc' ? y0 - s * r0 * Math.sqrt(Math.max(0, 1 - (x / r0) ** 2)) : y0;\n        const ct = clamp((y - top) * k + 0.5, 0, 1);\n        const cov = cx * ct * cb;\n        if (cov > 0) {\n          const q = clamp(x / r, -1, 1);\n          const c = shade(q * ca, -sa, Math.sqrt(1 - q * q) * ca, x, y);\n          buf.over(i, j, c[0], c[1], c[2], c[3] * cov);\n        }\n      }\n      if (under && ax < r1 + 1 / k) {\n        const e = (y - y1) / (s * r1);\n        const d = 1 - Math.hypot(x / r1, e);\n        const cu = clamp(d * s * r1 * k + 0.5, 0, 1) * (1 - cb);\n        if (cu > 0) {\n          const c = under(x / r1, e, x, y);\n          buf.over(i, j, c[0], c[1], c[2], c[3] * cu);\n        }\n      }\n    }\n  }\n}\n\n/** Cheap stable noise in [0, 1) for a 2D point. */\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/** Bead-blasted metal or soft-touch paint under the room lamp: ambient from the ceiling, Lambert, a broad sheen. */\nfunction metalShader(mat, L, V, { spec = true, sheenOnly = false } = {}) {\n  const albedo = hexLin(mat.metal);\n  const H = norm3([L[0] + V[0], L[1] + V[1], L[2] + V[2]]);\n  const grain = mat.grain ?? 0;\n  return (nx, ny, nz, x = 0, y = 0) => {\n    const ndl = nx * L[0] + ny * L[1] + nz * L[2];\n    const ndh = Math.max(0, nx * H[0] + ny * H[1] + nz * H[2]);\n    // Bead-blast: a fine, even grain in the surface, fixed to the part.\n    const bead = grain ? 1 + grain * (hashXY(x * 9000, y * 9000) - 0.5) : 1;\n    const ndv = nx * V[0] + ny * V[1] + nz * V[2];\n    const ry = 2 * ndv * ny - V[1];\n    const sky = smooth(-0.15, 0.85, -ry);\n    const sp = (spec ? mat.ks * ndh ** mat.gloss : 0) + mat.env * (0.25 + 0.75 * sky) * (0.4 + 0.6 * (1 - Math.max(0, ndv)) ** 2);\n    if (sheenOnly) return [1, 1, 1, clamp(sp * 2.4, 0, 0.85)];\n    // A rough surface darkens toward the silhouette, where it is seen at a graze.\n    const graze = 0.62 + 0.38 * Math.max(0, ndv) ** 0.7;\n    const lit = (mat.amb * (0.55 + 0.45 * Math.max(0, -ny) + 0.25 * Math.max(0, nz)) + mat.kd * Math.max(0, ndl)) * graze;\n    const v = bead * lit + sp * 1.4;\n    return [albedo[0] * v, albedo[1] * v, albedo[2] * v, 1];\n  };\n}\n\n/**\n * Polished metal's own light, untinted, to add on top of its colour: the\n * room lamp as a hard white point, a sheen round it, the ceiling along the\n * top and a thin bright limb. The chain's beads have it; so does a dark pull.\n */\nfunction polishLight(L, V, polish) {\n  const H = norm3([L[0] + V[0], L[1] + V[1], L[2] + V[2]]);\n  return (nx, ny, nz) => {\n    const ndh = Math.max(0, nx * H[0] + ny * H[1] + nz * H[2]);\n    const ndv = Math.max(0, nx * V[0] + ny * V[1] + nz * V[2]);\n    const ry = 2 * ndv * ny - V[1];\n    return polish * (0.9 * ndh ** 70 + 0.16 * ndh ** 9) + 0.07 * smooth(-0.1, 0.9, -ry) + 0.05 * (1 - ndv) ** 3;\n  };\n}\n\n/** The underside of a solid turned part: a flat face turned away from the lamp, lit only by the room. */\nconst undersideShader = (mat) => {\n  const albedo = hexLin(mat.metal);\n  return (qx, e) => {\n    const l = mat.amb * (0.32 + 0.12 * e) * (1 - 0.25 * qx * qx);\n    return [albedo[0] * l, albedo[1] * l, albedo[2] * l, 1];\n  };\n};\n\n/** The A60 envelope's radius at y (m) below the cap. */\nexport function bulbRadius(y) {\n  const { neck, R, centre } = BULB;\n  if (y <= 0) return neck;\n  if (y <= centre) return neck + (R - neck) * Math.sin((y / centre) * (Math.PI / 2)) ** 1.35;\n  const t = y - centre;\n  return t >= R ? 0 : Math.sqrt(R * R - t * t);\n}\n\n/** Canvas helpers that draw in metres of the lamp frame. */\nfunction withFrame(g, fr) { g.setTransform(fr.k, 0, 0, fr.k, fr.ox, fr.oy); }\n\n/** The glass outline as a Path2D, in metres, cap at y = top. */\nfunction bulbPath(top) {\n  const p = new Path2D();\n  const steps = 96;\n  const bottom = BULB.centre + BULB.R;\n  // Denser toward the bottom, where the round of the glass turns fastest.\n  const at = (i) => bottom * (1 - (1 - i / steps) ** 2);\n  for (let i = 0; i <= steps; i += 1) {\n    const y = at(i);\n    const x = -bulbRadius(y);\n    if (i === 0) p.moveTo(x, top + y); else p.lineTo(x, top + y);\n  }\n  for (let i = steps; i >= 0; i -= 1) {\n    const y = at(i);\n    p.lineTo(bulbRadius(y), top + y);\n  }\n  p.closePath();\n  return p;\n}\n\n/** A turned outline as a Path2D (m): the profile down one side, the front arc of the bottom, up the other. */\nfunction turnedPath(r, y0, y1, { topArc = false } = {}) {\n  const p = new Path2D();\n  const s = ELEVATION;\n  const n = 40;\n  const r0 = r(y0);\n  const r1 = r(y1);\n  if (topArc) {\n    for (let i = 0; i <= n; i += 1) {\n      const a = Math.PI + (Math.PI * i) / n;\n      const x = r0 * Math.cos(a);\n      const y = y0 + s * r0 * Math.sin(a);\n      if (i === 0) p.moveTo(x, y); else p.lineTo(x, y);\n    }\n  } else {\n    p.moveTo(-r0, y0);\n    p.lineTo(r0, y0);\n  }\n  for (let i = 0; i <= n; i += 1) { const y = y0 + ((y1 - y0) * i) / n; p.lineTo(r(y), y); }\n  for (let i = 0; i <= n; i += 1) {\n    const a = (Math.PI * i) / n;\n    p.lineTo(r1 * Math.cos(a), y1 - s * r1 * Math.sin(a));\n  }\n  for (let i = n; i >= 0; i -= 1) { const y = y0 + ((y1 - y0) * i) / n; p.lineTo(-r(y), y); }\n  p.closePath();\n  return p;\n}\n\n/** The parts of each lamp as profiles, in the lamp frame (m). */\nfunction partsOf(style) {\n  const st = STYLES[style];\n  if (style === 'dome') {\n    const top = 0.02;\n    const skirt = 0.14;\n    return {\n      grip: { r: () => 0.0085, y0: -0.004, y1: 0.028, top: 'cut' },\n      shell: {\n        r: (y) => (y >= skirt ? st.R : Math.max(0.021, st.R * Math.sqrt(Math.max(0, 1 - (1 - (y - top) / (skirt - top)) ** 2)) ** 0.92)),\n        y0: top, y1: st.rim, top: 'cut', world: true,\n      },\n    };\n  }\n  if (style === 'tube') {\n    return {\n      grip: { r: () => 0.0085, y0: -0.004, y1: 0.03, top: 'cut' },\n      shell: { r: () => st.R, y0: 0.024, y1: st.rim, top: 'arc' },\n    };\n  }\n  return {\n    holder: {\n      // Turned aluminium: a shoulder, the body, two cut grooves near the mouth.\n      r: (y) => {\n        if (y < 0.006) return 0.0105 + (0.0205 - 0.0105) * smooth(0, 0.006, y);\n        const g1 = Math.exp(-(((y - 0.046) / 0.0011) ** 2));\n        const g2 = Math.exp(-(((y - 0.051) / 0.0011) ** 2));\n        return 0.0205 - 0.0012 * (g1 + g2);\n      },\n      y0: 0, y1: st.rim, top: 'cut',\n    },\n    base: {\n      r: (y) => 0.0132 + 0.0009 * Math.cos(((y - st.rim) / 0.0036) * Math.PI * 2),\n      y0: st.rim, y1: st.bulb, top: 'cut',\n    },\n    pod: { r: () => 0.0075, x: st.anchor[0], y0: 0.012, y1: st.anchor[1], top: 'arc' },\n  };\n}\n\n/**\n * Everything the frame loop draws that does not move by itself, for one\n * finish at one size: the lamp's body (turning with the sway), the sheen on\n * the dome and the glass (not turning), the inside of the shade dark and\n * lit, the bulb cold and at GLOW_LEVELS temperatures, the ceiling cup, the\n * acorn, the shadows, and the scallop of light on the wall.\n */\nfunction bake(o, lay, dpr, mat) {\n  const st = STYLES[o.shade];\n  const S = lay.S;\n  const k = S * dpr; // device px per metre\n  const L = lampVector(o.light);\n  const V = norm3([0, ELEVATION, Math.sqrt(1 - ELEVATION ** 2)]);\n  const parts = partsOf(o.shade);\n  const out = { mat, dpr, S };\n  const bulbTop = st.bulb;\n  const bc = bulbTop + BULB.centre; // bulb centre, lamp frame\n\n  // The lamp's sprite frame: generous around the lamp, origin at the cable entry.\n  const padX = 0.02;\n  const lampW = Math.max(st.left, st.right, st.anchor[0] + 0.012) + padX;\n  const lampTop = -0.012;\n  const lampBottom = Math.max(st.bottom, st.rim + ELEVATION * st.R) + 0.012;\n  const fr = { k, ox: lampW * k, oy: -lampTop * k, w: 2 * lampW * k, h: (lampBottom - lampTop) * k };\n  out.frame = { ox: lampW * S, oy: -lampTop * S, w: 2 * lampW * S, h: (lampBottom - lampTop) * S };\n\n  // ---- the inside of the shade, cold and lit\n  if (parts.shell) {\n    const R = st.R;\n    const rim = st.rim;\n    const enamel = hexLin(ENAMEL);\n    const warm = blackbody(o.warmth).map((v) => toLin(v));\n    const off = new Paint(fr.w, fr.h);\n    const on = new Paint(fr.w, fr.h);\n    const s = ELEVATION;\n    for (let j = 0; j < fr.h; j += 1) {\n      const y = (j + 0.5 - fr.oy) / k;\n      if (y < rim - s * R - 0.002 || y > rim + s * R + 0.002) continue;\n      for (let i = 0; i < fr.w; i += 1) {\n        const x = (i + 0.5 - fr.ox) / k;\n        if (Math.abs(x) > R + 0.002) continue;\n        const e = (y - rim) / (s * R);\n        const d = 1 - Math.hypot(x / R, e);\n        const cov = clamp(d * s * R * k + 0.5, 0, 1);\n        if (cov <= 0) continue;\n        // v: 0 at the front lip, 1 at the far lip.\n        const front = rim - s * R * Math.sqrt(Math.max(0, 1 - (x / R) ** 2));\n        const back = rim + s * R * Math.sqrt(Math.max(0, 1 - (x / R) ** 2));\n        const v = clamp((y - front) / Math.max(1e-6, back - front), 0, 1);\n        const lipBand = Math.exp(-((((1 - d) * s * R * k) / 1.6) ** 2)); // the far lip, seen edge on\n        const lo = 0.012 + 0.045 * v * v + 0.07 * lipBand;\n        off.over(i, j, enamel[0] * lo, enamel[1] * lo, enamel[2] * lo, cov);\n        // Lit: the enamel near the bulb burns brightest; the far lip catches it edge on.\n        const near = Math.exp(-((x / (R * 0.75)) ** 2)) * (0.55 + 0.45 * v);\n        // The enamel right round the bulb is the brightest thing in the shade, and burns toward white.\n        const hot = Math.exp(-((x * x + (y - rim) ** 2 * 9) / (2 * 0.05 * 0.05)));\n        const hi = 0.3 + 0.75 * near + 0.3 * hot + 0.5 * lipBand;\n        const w = clamp(hi - 0.9, 0, 1) * 0.55;\n        const c = [warm[0] * enamel[0] * hi, warm[1] * enamel[1] * hi, warm[2] * enamel[2] * hi];\n        on.over(i, j, c[0] + (1 - c[0]) * w, c[1] + (1 - c[1]) * w, c[2] + (1 - c[2]) * w, cov);\n      }\n    }\n    // The switch body hangs from the socket beside the bulb, into the opening.\n    out.inside = off.canvas();\n    const pod = canvasOf(fr.w, fr.h);\n    const pg = pod.getContext('2d');\n    withFrame(pg, fr);\n    const ax = st.anchor[0];\n    const ay = st.anchor[1];\n    const podGrad = pg.createLinearGradient(ax - 0.006, 0, ax + 0.006, 0);\n    const pm = hexRgb(mat.metal);\n    podGrad.addColorStop(0, css(mixRgb(pm, [0, 0, 0], 0.55)));\n    podGrad.addColorStop(0.35, css(mixRgb(pm, [255, 255, 255], 0.08)));\n    podGrad.addColorStop(1, css(mixRgb(pm, [0, 0, 0], 0.7)));\n    pg.save();\n    const clipIn = new Path2D();\n    clipIn.ellipse(0, rim, R, s * R, 0, 0, Math.PI * 2);\n    pg.clip(clipIn);\n    pg.fillStyle = podGrad;\n    pg.fillRect(ax - 0.0055, rim - s * R - 0.01, 0.011, ay - (rim - s * R - 0.01));\n    pg.fillStyle = 'rgba(0, 0, 0, 0.55)';\n    pg.beginPath(); pg.ellipse(ax, ay, 0.0055, 0.0055 * s, 0, 0, Math.PI * 2); pg.fill();\n    pg.restore();\n    out.pod = pod;\n    out.insideOn = on.canvas();\n  }\n\n  // ---- the bulb, cold\n  const glass = new Paint(fr.w, fr.h);\n  const glassSheen = new Paint(fr.w, fr.h);\n  const bulbPart = { r: (y) => bulbRadius(y - bulbTop), y0: bulbTop, y1: bulbTop + BULB.centre + BULB.R * 0.999, top: 'cut' };\n  const room = (Rx, Ry, Rz) => {\n    // The room in a reflection: a bright ceiling, a darker floor, and the lamp as a softbox.\n    const ceiling = 0.07 + 0.2 * smooth(-0.2, 0.9, -Ry);\n    const bx = Math.abs(Rx - L[0]);\n    const by = Math.abs(Ry - L[1]);\n    const box = (1 - smooth(0.13, 0.19, bx)) * (1 - smooth(0.08, 0.13, by)) * (Rz > 0 ? 1 : 0);\n    return ceiling + 18 * box;\n  };\n  const Lh = Math.hypot(L[0], L[1]) || 1;\n  if (o.bulb === 'frosted') {\n    // Milk glass: it takes the room's light on the lit side, scatters it to a brighter edge, and lets the dark inside of the shade show through underneath.\n    const milk = hexLin(MILK);\n    const H = norm3([L[0] + V[0], L[1] + V[1], L[2] + V[2]]);\n    turned(glass, fr, { ...bulbPart, bottom: 'none' }, (nx, ny, nz) => {\n      const ndl = Math.max(0, nx * L[0] + ny * L[1] + nz * L[2]);\n      const ndv = Math.max(0, nx * V[0] + ny * V[1] + nz * V[2]);\n      const side = Math.max(0, (nx * L[0] + ny * L[1]) / Lh);\n      const wrap = clamp((nx * L[0] + ny * L[1] + nz * L[2] + 0.35) / 1.35, 0, 1); // light wraps round milk glass\n      const l = 0.05 + 0.6 * wrap ** 1.4 + 0.07 * ndv + 0.04 * Math.max(0, -ny) + 0.24 * (1 - ndv) ** 2.2 * side;\n      return [milk[0] * l, milk[1] * l, milk[2] * l, 0.74 + 0.24 * (1 - ndv) ** 1.3];\n    });\n    turned(glassSheen, fr, { ...bulbPart, bottom: 'none' }, (nx, ny, nz) => {\n      const ndh = Math.max(0, nx * H[0] + ny * H[1] + nz * H[2]);\n      return [1, 1, 1, 0.07 * ndh ** 5 + 0.08 * ndh ** 14];\n    });\n  } else {\n    // Clear glass: nearly nothing where it is seen face on, a dark thick edge where it grazes, a bright hairline where the room lamp catches that edge.\n    turned(glass, fr, { ...bulbPart, bottom: 'none' }, (nx, ny, nz) => {\n      const ndv = Math.max(0, nx * V[0] + ny * V[1] + nz * V[2]);\n      const edge = 1 - ndv;\n      const side = Math.max(0, (nx * L[0] + ny * L[1]) / Lh);\n      const dark = 0.05 + 0.34 * edge ** 2.6;\n      const rim = clamp(0.03 * side + 0.5 * edge ** 3 * side ** 1.4, 0, 0.9);\n      const a = rim + dark * (1 - rim);\n      return [rim / a, rim / a * 0.98, rim / a * 0.95, a];\n    });\n    turned(glassSheen, fr, { ...bulbPart, bottom: 'none' }, (nx, ny, nz) => {\n      const ndv = Math.max(0, nx * V[0] + ny * V[1] + nz * V[2]);\n      const F = 0.04 + 0.96 * (1 - ndv) ** 5;\n      const Rx = 2 * ndv * nx - V[0];\n      const Ry = 2 * ndv * ny - V[1];\n      const Rz = 2 * ndv * nz - V[2];\n      // The back of the envelope reflects the room again, smaller and upside down.\n      const Rbx = 2 * ndv * -nx - V[0];\n      const Rby = 2 * ndv * -ny - V[1];\n      const v = F * room(Rx, Ry, Rz) + 0.35 * F * room(Rbx, Rby, Rz);\n      return [1, 1, 1, clamp(v, 0, 1)];\n    });\n  }\n  const bulbCold = glass.canvas();\n  if (o.bulb === 'clear') drawColdMount(bulbCold.getContext('2d'), fr, bulbTop, bc, L);\n  if (o.shade === 'bare') drawThreadsShadow(bulbCold.getContext('2d'), fr, bulbTop);\n  out.bulb = bulbCold;\n  out.bulbSheen = glassSheen.canvas();\n  out.glassPath = bulbPath(bulbTop);\n\n  // ---- the lamp body: turns with the sway\n  const body = new Paint(fr.w, fr.h);\n  const sheen = new Paint(fr.w, fr.h);\n  const shadeBody = metalShader(mat, L, V);\n  const under = undersideShader(mat);\n  if (o.shade === 'bare') {\n    turned(body, fr, { ...parts.holder, bottom: 'solid' }, shadeBody, under);\n    turned(body, fr, { ...parts.base, bottom: 'cut' }, metalShader({ ...MATERIALS.aluminium, metal: '#b9bab6', ks: 0.5, gloss: 30 }, L, V));\n    // The switch pod on its arm.\n    const pod = parts.pod;\n    turned(body, { ...fr, ox: fr.ox + pod.x * k }, { ...pod, bottom: 'solid' }, shadeBody, under);\n  } else {\n    turned(body, fr, { ...parts.grip, bottom: 'cut' }, shadeBody);\n    if (parts.shell.world) {\n      // The dome: body here, its sheen in a layer that does not turn.\n      turned(body, fr, { ...parts.shell, bottom: 'open' }, metalShader(mat, L, V, { spec: false }));\n      turned(sheen, fr, { ...parts.shell, bottom: 'open', r: (y) => parts.shell.r(y) + 0.004 }, metalShader(mat, L, V, { sheenOnly: true }));\n    } else {\n      turned(body, fr, { ...parts.shell, bottom: 'open' }, shadeBody);\n    }\n  }\n  out.body = body.canvas();\n  const bg = out.body.getContext('2d');\n  withFrame(bg, fr);\n  if (o.shade === 'bare') drawPodArm(bg, st, mat);\n  if (parts.shell) drawLip(bg, st, mat);\n  if (parts.shell?.world) out.sheen = sheen.canvas();\n  if (parts.shell) {\n    out.shellPath = turnedPath(parts.shell.r, parts.shell.y0 - 0.001, st.rim, { topArc: parts.shell.top === 'arc' });\n    const lip = new Path2D();\n    lip.ellipse(0, st.rim, st.R - 0.0015, ELEVATION * (st.R - 0.0015), 0, Math.PI, Math.PI * 2);\n    out.lipPath = lip;\n  }\n\n  // ---- the bulb at temperature. Its own small frame around the bulb, with the\n  // shade already cut out of it, so the loop draws one screen-blended sprite.\n  const gk = BLOOM * 2 * k;\n  const gfr = { k, ox: BLOOM * k, oy: (BLOOM - bc) * k, w: gk, h: gk };\n  const gsx = fr.ox - BLOOM * k;\n  const gsy = fr.oy + (bc - BLOOM) * k;\n  out.glowFrame = { x: -BLOOM * S, y: (bc - BLOOM) * S, w: 2 * BLOOM * S };\n  out.glow = [];\n  for (let lv = 1; lv <= GLOW_LEVELS; lv += 1) {\n    const T = FILAMENT.draper + ((o.warmth - FILAMENT.draper) * lv) / GLOW_LEVELS;\n    const gl = glowOf(T, o.warmth);\n    const col = blackbody(T);\n    let c;\n    if (o.bulb === 'frosted') {\n      const p = new Paint(gfr.w, gfr.h);\n      const lin = mixRgb(col, HOT, 0.2 * gl).map(toLin);\n      const fy = bc - 0.004;\n      turned(p, gfr, { ...bulbPart, bottom: 'none' }, (nx, ny, nz, x, y) => {\n        const ndv = Math.max(0, nx * V[0] + ny * V[1] + nz * V[2]);\n        const hot = Math.exp(-((x * x + (y - fy) ** 2) / 0.00022));\n        const e = gl * (0.7 + 0.3 * ndv) * (0.75 + 1.3 * hot);\n        const w = clamp(e - 0.9, 0, 1) * 0.65; // past full, the core burns toward white\n        return [lin[0] + (1 - lin[0]) * w, lin[1] + (1 - lin[1]) * w, lin[2] + (1 - lin[2]) * w, clamp(e, 0, 1)];\n      });\n      c = p.canvas();\n      drawBloom(c.getContext('2d'), gfr, bc, bc - 0.004, col, gl, 0.32);\n    } else {\n      c = canvasOf(gfr.w, gfr.h);\n      drawHotMount(c.getContext('2d'), gfr, bulbTop, bc, col, gl);\n    }\n    const cg2 = c.getContext('2d');\n    cg2.setTransform(1, 0, 0, 1, 0, 0);\n    cg2.globalCompositeOperation = 'destination-out';\n    cg2.drawImage(out.body, -gsx, -gsy);\n    out.glow.push(c);\n  }\n\n  // ---- the ceiling cup\n  const cupW = CANOPY.r + 0.01;\n  const cfr = { k, ox: cupW * k, oy: (CANOPY.h + 0.004) * k, w: 2 * cupW * k, h: (CANOPY.h + 0.004 + ELEVATION * CANOPY.r + 0.006) * k };\n  const cup = new Paint(cfr.w, cfr.h);\n  turned(cup, cfr, { r: (y) => CANOPY.r - 0.0015 * smooth(-0.004, 0, y), y0: -CANOPY.h - 0.004, y1: 0, top: 'cut', bottom: 'solid' }, shadeBody, under);\n  out.cup = cup.canvas();\n  const cg = out.cup.getContext('2d');\n  withFrame(cg, cfr);\n  cg.fillStyle = 'rgba(0, 0, 0, 0.5)';\n  cg.beginPath(); cg.ellipse(0, 0, 0.0065, 0.0065 * ELEVATION, 0, 0, Math.PI * 2); cg.fill();\n  out.cupFrame = { ox: cupW * S, oy: (CANOPY.h + 0.004) * S, w: 2 * cupW * S, h: cfr.h / dpr };\n\n  // ---- the acorn: turned, hanging from its ferrule\n  const aw = ACORN.r + 0.004;\n  const afr = { k, ox: aw * k, oy: 0.003 * k, w: 2 * aw * k, h: (ACORN.len + 0.008) * k };\n  const acorn = new Paint(afr.w, afr.h);\n  const acornR = (y) => {\n    const t = clamp(y / ACORN.len, 0, 1);\n    const body = ACORN.r * Math.sin(Math.PI * t ** 1.55) ** 0.72;\n    return Math.max(t < 0.2 ? 0.0024 : 0, body);\n  };\n  const pullRgb = hexRgb(mat.acorn ?? mat.metal);\n  const brightPull = (pullRgb[0] + pullRgb[1] + pullRgb[2]) / 765 > 0.45;\n  const polish = polishLight(L, V, mat.ks > 0 ? 1 : 0.3); // a matte finish's metal is satin, not mirror\n  const acornShade = metalShader({ ...mat, metal: mat.acorn ?? mat.metal, ks: mat.ks * 1.4, gloss: mat.gloss * 1.6 }, L, V);\n  // A dark pull (graphite) would be black on a black wall: it takes the beads' own untinted catch-lights, so it reads where the hand goes.\n  const acornLit = brightPull ? acornShade : (nx, ny, nz, x, y) => {\n    const c = acornShade(nx, ny, nz, x, y);\n    const p = polish(nx, ny, nz);\n    return [c[0] + p, c[1] + p, c[2] + p, c[3]];\n  };\n  turned(acorn, afr, { r: acornR, y0: 0, y1: ACORN.len * 0.999, top: 'cut', bottom: 'none' }, acornLit);\n  out.acorn = acorn.canvas();\n  const ag = out.acorn.getContext('2d');\n  withFrame(ag, afr);\n  ag.strokeStyle = 'rgba(0, 0, 0, 0.35)';\n  ag.lineWidth = 0.0006;\n  const ringY = ACORN.len * 0.34;\n  ag.beginPath(); ag.ellipse(0, ringY, acornR(ringY) * 0.98, acornR(ringY) * ELEVATION * 0.98, 0, 0, Math.PI); ag.stroke();\n  out.acornFrame = { ox: aw * S, oy: 0.003 * S, w: 2 * aw * S, h: afr.h / dpr };\n\n  // ---- the ball chain: one polished bead, shaded per pixel in the room's light. A sphere looks\n  // the same however the chain turns, so every bead is this sprite and its highlight stays put.\n  if (o.pull === 'chain') {\n    // Small lamps draw their beads bigger, as they draw their cord heavier: a bead you can count at a thumbnail.\n    const cb = clamp(CHAIN.minBead / (CHAIN.bead * S), 1, 2.6);\n    const D = CHAIN.bead * S * cb; // CSS px\n    const rd = (D * dpr) / 2; // device px\n    const size = Math.ceil(2 * rd + 2);\n    const c0 = size / 2;\n    const bead = new Paint(size, size);\n    const albedo = hexLin(mat.acorn ?? mat.metal);\n    for (let j = 0; j < size; j += 1) {\n      for (let i = 0; i < size; i += 1) {\n        const x = (i + 0.5 - c0) / rd;\n        const y = (j + 0.5 - c0) / rd;\n        const cov = clamp((1 - Math.hypot(x, y)) * rd + 0.5, 0, 1);\n        if (cov <= 0) continue;\n        const nz = Math.sqrt(Math.max(0, 1 - x * x - y * y));\n        const ndl = x * L[0] + y * L[1] + nz * L[2];\n        const ndv = Math.max(0, x * V[0] + y * V[1] + nz * V[2]);\n        const lit = (mat.amb * (0.55 + 0.45 * Math.max(0, -y) + 0.25 * nz) + mat.kd * Math.max(0, ndl)) * (0.5 + 0.5 * ndv ** 0.7);\n        const spec = polish(x, y, nz);\n        bead.over(i, j, albedo[0] * lit + spec, albedo[1] * lit + spec, albedo[2] * lit + spec, cov);\n      }\n    }\n    out.bead = {\n      c: bead.canvas(), w: size / dpr, D, pitch: CHAIN.pitch * cb,\n      // The links between the beads: a short rod, darker than a bright bead and lighter than a dark one, so it reads on either wall.\n      link: css(mixRgb(pullRgb, brightPull ? [0, 0, 0] : [255, 255, 255], brightPull ? 0.4 : 0.3)),\n    };\n  }\n\n  // ---- shadows on the wall: soft silhouettes, blurred once\n  const sd = Math.max(0.5, dpr / 2);\n  const blurPx = WALL.blur * S * sd;\n  const sil = (w, h, ox, oy, paint) => {\n    const pad = Math.ceil(blurPx * 2.5);\n    const c = canvasOf(w * sd + pad * 2, h * sd + pad * 2);\n    const g = c.getContext('2d');\n    g.filter = `blur(${blurPx.toFixed(2)}px)`;\n    g.setTransform(S * sd, 0, 0, S * sd, ox * sd + pad, oy * sd + pad);\n    g.fillStyle = '#000';\n    paint(g);\n    return { c, ox: ox + pad / sd, oy: oy + pad / sd, w: c.width / sd, h: c.height / sd };\n  };\n  out.lampShadow = sil(out.frame.w, out.frame.h, out.frame.ox, out.frame.oy, (g) => {\n    if (out.shellPath) g.fill(out.shellPath);\n    if (out.shellPath) { g.beginPath(); g.ellipse(0, st.rim, st.R, ELEVATION * st.R, 0, 0, Math.PI * 2); g.fill(); }\n    g.fill(out.glassPath);\n    if (o.shade === 'bare') {\n      g.fillRect(-0.0205, 0, 0.041, st.bulb);\n      g.fillRect(st.anchor[0] - 0.0075, 0.012, 0.015, st.anchor[1] - 0.012);\n      g.fillRect(0.015, 0.018, st.anchor[0] - 0.015, 0.008);\n    } else {\n      g.fillRect(-0.0085, 0, 0.017, 0.03);\n    }\n  });\n  out.acornShadow = sil(out.acornFrame.w, out.acornFrame.h, out.acornFrame.ox, out.acornFrame.oy, (g) => {\n    g.beginPath();\n    for (let i = 0; i <= 30; i += 1) { const y = (ACORN.len * i) / 30; g.lineTo(acornR(y), y); }\n    for (let i = 30; i >= 0; i -= 1) { const y = (ACORN.len * i) / 30; g.lineTo(-acornR(y), y); }\n    g.fill();\n  });\n  out.cupShadow = sil(out.cupFrame.w, out.cupFrame.h, out.cupFrame.ox, out.cupFrame.oy, (g) => {\n    g.fillRect(-CANOPY.r, -CANOPY.h, 2 * CANOPY.r, CANOPY.h);\n    g.beginPath(); g.ellipse(0, 0, CANOPY.r, ELEVATION * CANOPY.r, 0, 0, Math.PI * 2); g.fill();\n  });\n  out.shadowScale = sd;\n\n  // ---- the scallop on the wall, at a quarter of the light canvas's resolution\n  const q = 0.3;\n  const reach = 0.9;\n  const pw = Math.ceil(2 * reach * S * q);\n  const ph = Math.ceil(2 * reach * S * q);\n  const pool = canvasOf(pw, ph);\n  const pctx = pool.getContext('2d');\n  const img = pctx.createImageData(pw, ph);\n  const warmRgb = mixRgb(blackbody(o.warmth), [255, 244, 228], 0.15);\n  for (let j = 0; j < ph; j += 1) {\n    const y = (j + 0.5) / (S * q) - reach;\n    for (let i = 0; i < pw; i += 1) {\n      const x = (i + 0.5) / (S * q) - reach;\n      const E = wallLight(x, y, o.shade, WALL.distance);\n      const a = 0.7 * (1 - Math.exp(-1.1 * E));\n      const p = (j * pw + i) * 4;\n      img.data[p] = warmRgb[0];\n      img.data[p + 1] = warmRgb[1];\n      img.data[p + 2] = warmRgb[2];\n      img.data[p + 3] = Math.round(255 * a * smooth(reach, reach * 0.8, Math.hypot(x, y)));\n    }\n  }\n  pctx.putImageData(img, 0, 0);\n  out.pool = { c: pool, w: 2 * reach * S, h: 2 * reach * S, ox: reach * S, oy: reach * S };\n  out.bulbCentre = bc;\n  out.warmRgb = blackbody(o.warmth);\n  return out;\n}\n\n/** The E27 cap's shadow on the neck of the glass (bare holder). */\nfunction drawThreadsShadow(g, fr, top) {\n  withFrame(g, fr);\n  const grad = g.createLinearGradient(0, top, 0, top + 0.01);\n  grad.addColorStop(0, 'rgba(0, 0, 0, 0.35)');\n  grad.addColorStop(1, 'rgba(0, 0, 0, 0)');\n  g.fillStyle = grad;\n  g.save();\n  g.clip(bulbPath(top));\n  g.fillRect(-0.03, top, 0.06, 0.01);\n  g.restore();\n}\n\n/**\n * The mount inside a clear bulb (m, lamp frame): the glass stem's press, two\n * lead-in wires, a support wire and the coil strung between the leads. The\n * coil is a helix seen a little from the side, so its turns lean.\n */\nfunction mountPaths(bc) {\n  const pressY = bc - 0.013;\n  const fy = bc - 0.0045;\n  const fx = 0.0085;\n  const coil = new Path2D();\n  const turns = 13;\n  const steps = turns * 10;\n  for (let i = 0; i <= steps; i += 1) {\n    const t = i / steps;\n    const ph = t * turns * Math.PI * 2;\n    const x = -fx + 2 * fx * t + 0.0004 * (Math.cos(ph) - 1);\n    const y = fy + 0.0012 * Math.sin(Math.PI * t) + 0.00055 * Math.sin(ph);\n    if (i === 0) coil.moveTo(x, y); else coil.lineTo(x, y);\n  }\n  const leads = new Path2D();\n  leads.moveTo(-0.0022, pressY);\n  leads.lineTo(-fx, fy);\n  leads.moveTo(0.0022, pressY);\n  leads.lineTo(fx, fy);\n  leads.moveTo(0, pressY);\n  leads.lineTo(0, fy + 0.001);\n  return { pressY, fy, coil, leads };\n}\n\n/** Half the side of the bulb's light sprite (m): the bloom spreads this far from the filament. */\nconst BLOOM = 0.075;\n\n/** Cold clear bulb: the stem in glass, the wires and the coil in bright metal that the room lamp catches on one side. */\nfunction drawColdMount(g, fr, top, bc, L) {\n  withFrame(g, fr);\n  const { pressY, coil, leads } = mountPaths(bc);\n  const h = Math.hypot(L[0], L[1]) || 1;\n  const tx = (L[0] / h) * 0.00016;\n  const ty = (L[1] / h) * 0.00016;\n  // The stem: a flared glass tube from the cap down to the press, its walls and its foot catching the light.\n  const stem = new Path2D();\n  stem.moveTo(-0.0056, top + 0.002);\n  stem.quadraticCurveTo(-0.0033, top + 0.012, -0.0029, pressY);\n  stem.lineTo(0.0029, pressY);\n  stem.quadraticCurveTo(0.0033, top + 0.012, 0.0056, top + 0.002);\n  stem.closePath();\n  const tube = g.createLinearGradient(-0.0056, 0, 0.0056, 0);\n  tube.addColorStop(0, 'rgba(255, 255, 255, 0.16)');\n  tube.addColorStop(0.5, 'rgba(255, 255, 255, 0.03)');\n  tube.addColorStop(1, 'rgba(255, 255, 255, 0.08)');\n  g.fillStyle = tube;\n  g.fill(stem);\n  g.strokeStyle = 'rgba(240, 244, 248, 0.3)';\n  g.lineWidth = 0.0004;\n  g.stroke(stem);\n  g.fillStyle = 'rgba(255, 255, 255, 0.14)';\n  g.beginPath(); g.ellipse(0, pressY, 0.0034, 0.0013, 0, 0, Math.PI * 2); g.fill();\n  g.strokeStyle = 'rgba(240, 244, 248, 0.34)';\n  g.lineWidth = 0.00035;\n  g.beginPath(); g.ellipse(0, pressY, 0.0034, 0.0013, 0, 0, Math.PI); g.stroke();\n  // Nickel-plated wire: a dark body, a bright thread on the lit side.\n  g.lineCap = 'round';\n  g.strokeStyle = 'rgba(96, 92, 88, 0.95)';\n  g.lineWidth = 0.0007;\n  g.stroke(leads);\n  g.save();\n  g.translate(tx, ty);\n  g.strokeStyle = 'rgba(236, 232, 224, 0.75)';\n  g.lineWidth = 0.00024;\n  g.stroke(leads);\n  g.restore();\n  // The coil: cold tungsten, dull grey with a warm cast, a hard thread of light along its top.\n  g.strokeStyle = 'rgba(88, 80, 72, 1)';\n  g.lineWidth = 0.00115;\n  g.stroke(coil);\n  g.save();\n  g.translate(tx, ty * 1.6);\n  g.strokeStyle = 'rgba(206, 190, 168, 0.8)';\n  g.lineWidth = 0.00036;\n  g.stroke(coil);\n  g.restore();\n}\n\n/**\n * The light a lit bulb puts round itself, drawn under whatever is already on\n * the sprite: a wide, soft bloom that spills past the glass onto the enamel.\n */\nfunction drawBloom(g, fr, bc, fy, col, gl, a0) {\n  withFrame(g, fr);\n  g.globalCompositeOperation = 'destination-over';\n  const R = BLOOM - 0.005;\n  const bloom = g.createRadialGradient(0, fy, 0, 0, fy, R);\n  for (let i = 0; i <= 10; i += 1) {\n    const r = i / 10;\n    bloom.addColorStop(r, css(col, a0 * gl * Math.exp(-((r * 2.5) ** 2)) * (1 - r ** 3)));\n  }\n  g.fillStyle = bloom;\n  g.fillRect(-BLOOM, bc - BLOOM, 2 * BLOOM, 2 * BLOOM);\n  g.globalCompositeOperation = 'source-over';\n}\n\n/**\n * A lit clear bulb: the coil white-hot in the middle and orange at its edges,\n * the leads it lights, the whole envelope full of warm light with a brighter\n * limb where it piped to the edge, and the bloom round it.\n */\nfunction drawHotMount(g, fr, top, bc, col, gl) {\n  withFrame(g, fr);\n  const { fy, coil, leads } = mountPaths(bc);\n  const white = mixRgb(col, HOT, 0.75);\n  g.save();\n  g.clip(bulbPath(top));\n  // The envelope is full of light but still glass: warmest and brightest round the coil,\n  // dimmer toward the thick edge, so the rim reads as a rim and the reflection has a ground.\n  const fill = g.createRadialGradient(0, fy, 0, 0, fy, 0.034);\n  fill.addColorStop(0, css(HOT, 0.7 * gl));\n  fill.addColorStop(0.3, css(mixRgb(col, HOT, 0.7), 0.7 * gl));\n  fill.addColorStop(0.65, css(mixRgb(col, HOT, 0.3), 0.42 * gl));\n  fill.addColorStop(1, css(col, 0.26 * gl));\n  g.fillStyle = fill;\n  g.fillRect(-0.04, top, 0.08, 0.1);\n  // The limb: the glass piped bright at its edge, a soft band and a thin hot line on it.\n  g.lineJoin = 'round';\n  g.strokeStyle = css(mixRgb(col, HOT, 0.25), 0.34 * gl);\n  g.lineWidth = 0.0028;\n  g.stroke(bulbPath(top));\n  g.strokeStyle = css(mixRgb(col, HOT, 0.7), 0.9 * gl);\n  g.lineWidth = 0.00075;\n  g.stroke(bulbPath(top));\n  g.restore();\n  g.lineCap = 'round';\n  g.strokeStyle = css(mixRgb(col, HOT, 0.3), 0.7 * gl);\n  g.lineWidth = 0.0006;\n  g.stroke(leads);\n  // The coil's own halo, then its orange, then its white-hot thread.\n  g.strokeStyle = css(col, 0.14 * gl);\n  g.lineWidth = 0.0052;\n  g.stroke(coil);\n  g.strokeStyle = css(col, 0.26 * gl);\n  g.lineWidth = 0.0032;\n  g.stroke(coil);\n  g.strokeStyle = css(mixRgb(col, HOT, 0.5 * gl), Math.min(1, 0.5 + gl));\n  g.lineWidth = 0.002;\n  g.stroke(coil);\n  g.strokeStyle = css(mixRgb(col, HOT, 0.6 + 0.4 * gl), Math.min(1, 0.3 + gl));\n  g.lineWidth = 0.001;\n  g.stroke(coil);\n  const core = g.createRadialGradient(0, fy, 0, 0, fy, 0.03);\n  core.addColorStop(0, css(HOT, 0.5 * gl ** 1.2));\n  core.addColorStop(0.35, css(mixRgb(col, HOT, 0.7), 0.4 * gl ** 1.2));\n  core.addColorStop(1, css(col, 0));\n  g.fillStyle = core;\n  g.fillRect(-0.031, fy - 0.031, 0.062, 0.062);\n  drawBloom(g, fr, bc, fy, col, gl, 0.6);\n}\n\n/** The bare holder's switch pod hangs on a short turned arm. */\nfunction drawPodArm(g, st, mat) {\n  const m = hexRgb(mat.metal);\n  const y = 0.022;\n  const grad = g.createLinearGradient(0, y - 0.0035, 0, y + 0.0035);\n  grad.addColorStop(0, css(mixRgb(m, [255, 255, 255], 0.35)));\n  grad.addColorStop(0.45, css(m));\n  grad.addColorStop(1, css(mixRgb(m, [0, 0, 0], 0.6)));\n  g.fillStyle = grad;\n  g.fillRect(0.019, y - 0.0033, st.anchor[0] - 0.0075 - 0.019 + 0.0005, 0.0066);\n}\n\n/** The shade's rolled lip: a catch-light along its front edge, a hairline of shadow under it. */\nfunction drawLip(g, st, mat) {\n  const R = st.R;\n  const lit = mat.lip;\n  g.lineWidth = 0.0012;\n  g.strokeStyle = `rgba(255, 255, 255, ${lit})`;\n  g.beginPath(); g.ellipse(0, st.rim - 0.0011, R - 0.0006, ELEVATION * R, 0, Math.PI * 1.02, Math.PI * 1.98); g.stroke();\n  g.lineWidth = 0.0007;\n  g.strokeStyle = 'rgba(0, 0, 0, 0.45)';\n  g.beginPath(); g.ellipse(0, st.rim, R, ELEVATION * R, 0, Math.PI, Math.PI * 2); g.stroke();\n}\n\n// ================================================================ the object\n\nexport const DEFAULTS = Object.freeze({\n  on: true,\n  shade: 'dome',\n  bulb: 'clear',\n  finish: 'auto',\n  warmth: 2700,\n  cord: 1,\n  light: 315,\n  label: 'Light',\n  target: null,\n  sound: false,\n  pull: 'cord',\n  reveal: false,\n});\n\nfunction normalise(opts, previous) {\n  const o = { ...DEFAULTS, ...previous, ...opts };\n  o.on = o.on !== false;\n  if (!STYLES[o.shade]) o.shade = 'dome';\n  if (!BULBS.includes(o.bulb)) o.bulb = 'clear';\n  if (!FINISHES.includes(o.finish)) o.finish = 'auto';\n  o.warmth = clamp(Math.round(+o.warmth || 2700), 1900, 3400);\n  o.cord = clamp(+o.cord || 1, 0.5, 1.6);\n  o.light = ((+o.light || 0) % 360 + 360) % 360;\n  o.label = String(o.label ?? '').slice(0, 40).trim() || 'Light';\n  o.sound = o.sound === true;\n  o.pull = PULLS.includes(o.pull) ? o.pull : 'cord';\n  o.reveal = o.reveal === true;\n  return o;\n}\n\nconst STRUCTURE = ['shade', 'bulb', 'finish', 'warmth', 'cord', 'light', 'pull'];\nconst KEY = 'tui-finish';\n\nexport class PullCord {\n  constructor(host, opts = {}) {\n    if (!host) throw new Error('PullCord 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\n    const root = document.createElement('div');\n    root.className = 'pc';\n    root.dataset.object = 'pull-cord';\n    root.dataset.state = 'asleep';\n    root.setAttribute('role', 'switch');\n    root.tabIndex = 0;\n    const layer = (cls) => { const c = document.createElement('canvas'); c.className = cls; c.setAttribute('aria-hidden', 'true'); return c; };\n    this.cvShadow = layer('pc-shadow');\n    this.cvLight = layer('pc-light');\n    this.cvLamp = layer('pc-lamp');\n    this.cvGlow = layer('pc-glow');\n    // Grain over the light on the wall (pull-cord.css): a smooth light on a pale wall bands into rings in 8 bits.\n    this.grain = document.createElement('span');\n    this.grain.className = 'pc-grain';\n    this.grain.setAttribute('aria-hidden', 'true');\n    this.grip = document.createElement('span');\n    this.grip.className = 'pc-grip';\n    this.grip.setAttribute('aria-hidden', 'true');\n    root.append(this.cvShadow, this.cvLight, this.grain, this.cvLamp, this.cvGlow, this.grip);\n    this.root = root;\n    host.append(root);\n\n    this.raf = 0;\n    this.last = 0;\n    this.visible = false;\n    this.hand = null;\n    this.drag = null;\n    this.pullRun = null;\n    this.cache = new Map();\n    this.drawn = {};\n\n    this.on = {\n      down: (e) => this.#down(e),\n      move: (e) => this.#move(e),\n      up: (e) => this.#up(e),\n      click: (e) => this.#click(e),\n      key: (e) => this.#key(e),\n      motion: (e) => { this.reduced = e.matches; this.#rest(); this.#draw(true); this.#wake(); },\n      scheme: () => { this.#followFinish(); this.#followSystem(); },\n      visibility: () => { if (document.hidden) this.#sleep(); else this.#wake(); },\n      gesture: () => this.#armAudio(),\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('click', this.on.click);\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.#bindTarget();\n    this.lit = this.target ? this.#targetOn() : this.o.on;\n    this.T = this.lit ? this.o.warmth : FILAMENT.room;\n    this.#aria();\n    if (this.target) this.#applyTarget(false);\n    this.#bindFinish();\n    if (this.o.sound) this.#listenForGesture();\n\n    this.ro = new ResizeObserver(() => this.#build());\n    this.ro.observe(root);\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    this.#build();\n  }\n\n  /** Whether the lamp is lit. */\n  get checked() { return this.lit; }\n\n  /** What the bulb is doing now, as its root's data-state. */\n  get state() { return this.root.dataset.state; }\n\n  /** Pull the cord: the same physical pull a hand makes, animated. Toggles when the switch clicks. */\n  pull() {\n    if (this.reduced || !this.rig) { this.#toggle(true); return this; }\n    if (this.drag) return this;\n    // A press while the last pull is still going is the next pull: it goes as soon as this one lets go.\n    if (this.pullRun) { this.pullRun.again = true; return this; }\n    this.#startPull();\n    return this;\n  }\n\n  /**\n   * The hand goes to where the pull hangs at rest and pulls from there, not\n   * from wherever the bounce has it: a pull while the chain still swings or\n   * springs back up must reach the trip like any other.\n   */\n  #startPull() {\n    const [ax, ay] = anchorOf(this.rig);\n    this.pullRun = { t0: -1, x: ax + this.hang[0], y: ay + this.hang[1] };\n    this.#wake(true);\n  }\n\n  /** Pull the cord from outside, as a hand would. */\n  toggle() { return this.pull(); }\n\n  /** Set the lamp without a pull (no `change` event). `instant` skips the filament's warm-up. */\n  set(on, { instant = false } = {}) {\n    const next = !!on;\n    if (next !== this.lit) {\n      this.lit = next;\n      this.#aria();\n      if (this.target) this.#applyTarget(false);\n    }\n    if (instant || this.reduced) { this.T = this.lit ? this.o.warmth : FILAMENT.room; this.#draw(true); }\n    this.#wake(true);\n    return this;\n  }\n\n  update(opts = {}) {\n    const prev = this.o;\n    this.o = normalise(opts, this.o);\n    this.#aria();\n    if (opts.target !== undefined && opts.target !== prev.target) { this.#bindTarget(); if (this.target) this.set(this.#targetOn(), { instant: true }); }\n    if (this.o.sound && !prev.sound) this.#listenForGesture();\n    if (this.o.finish !== prev.finish) this.#bindFinish();\n    if (STRUCTURE.some((k) => prev[k] !== this.o[k])) {\n      if (prev.warmth !== this.o.warmth && this.lit) this.T = this.o.warmth;\n      this.cache.clear();\n      this.#build();\n    }\n    if ('on' in opts && !this.target && this.o.on !== this.lit) this.set(this.o.on);\n    return this;\n  }\n\n  destroy() {\n    cancelAnimationFrame(this.raf);\n    this.raf = 0;\n    this.ro.disconnect();\n    this.io.disconnect();\n    this.finishObs?.disconnect();\n    this.targetObs?.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('click', this.on.click);\n    r.removeEventListener('keydown', this.on.key);\n    this.#stopListening();\n    this.audio?.close?.();\n    this.cache.clear();\n    r.remove();\n  }\n\n  // ---------------------------------------------------------------- finish and target\n\n  /**\n   * The material the lamp is made in: the one asked for, or on `auto` the\n   * page's object tokens (`--tui-obj-frame`, `-edge`, `-shadow`, `-matte`), so\n   * it is made in whatever finish the page is in. A page without them gets\n   * graphite when it is dark and aluminium when it is light.\n   */\n  #material() {\n    if (this.o.finish !== 'auto') return MATERIALS[this.o.finish];\n    const s = getComputedStyle(this.host);\n    const v = (k) => s.getPropertyValue(`--tui-obj-${k}`).trim();\n    if (v('frame')) return materialFrom(hex(v('frame')), hex(v('edge') || v('frame')), parseFloat(v('shadow')) || 0.34, v('matte') === '1', clamp(parseFloat(v('glow')) || 0, 0, 1));\n    const t = this.host.closest?.('[data-tone=\"light\"], [data-tone=\"dark\"]')?.dataset.tone;\n    return (t ?? (this.dark?.matches ? 'dark' : 'light')) === '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 lamp 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.lay || this.o.finish !== 'auto') return;\n    if (this.sprites?.mat.key !== this.#material().key) { this.#sprites(); this.#draw(true); }\n  }\n\n  #bindTarget() {\n    this.targetObs?.disconnect();\n    this.targetObs = null;\n    const t = this.o.target;\n    this.target = typeof t === 'string' ? document.querySelector(t) : t instanceof Element ? t : null;\n    if (!this.target) return;\n    this.targetObs = new MutationObserver(() => {\n      const on = this.#targetOn();\n      if (on !== this.lit) this.set(on);\n    });\n    this.targetObs.observe(this.target, { attributes: true, attributeFilter: ['data-finish'] });\n  }\n\n  /** On is aluminium (lights on), off is graphite. With nothing set, the visitor's choice, then their system. */\n  #targetOn() {\n    const f = this.target.dataset.finish;\n    if (f === 'aluminium' || f === 'graphite') return f === 'aluminium';\n    let stored = null;\n    if (this.target === document.documentElement) try { stored = localStorage.getItem(KEY); } catch { /* private mode */ }\n    if (stored === 'aluminium' || stored === 'graphite') return stored === 'aluminium';\n    return !this.dark?.matches;\n  }\n\n  #applyTarget(remember) {\n    const f = this.lit ? 'aluminium' : 'graphite';\n    if (this.target.dataset.finish !== f) this.target.dataset.finish = f;\n    if (remember && this.target === document.documentElement) try { localStorage.setItem(KEY, f); } catch { /* the choice lasts the page */ }\n  }\n\n  /** Until the visitor has chosen, the page finish keeps following the system, as the site's own key does. */\n  #followSystem() {\n    if (this.target !== document.documentElement) return;\n    let stored = null;\n    try { stored = localStorage.getItem(KEY); } catch { /* none */ }\n    if (!stored) this.set(!this.dark?.matches);\n  }\n\n  #aria() {\n    this.root.setAttribute('aria-checked', String(this.lit));\n    this.root.setAttribute('aria-label', this.o.label);\n    this.root.dataset.on = String(this.lit);\n  }\n\n  #toggle(user) {\n    this.lit = !this.lit;\n    this.#aria();\n    const change = () => this.root.dispatchEvent(new CustomEvent('change', { bubbles: true, detail: { on: this.lit } }));\n    // Without a target the page's own `change` listener is the finish switch (a site with its own finish\n    // families): with `reveal`, that listener runs inside the reveal, so what it changes opens from the bulb.\n    const revealChange = user && this.o.reveal && !this.target;\n    if (this.target && user && this.o.reveal && this.target === document.documentElement) {\n      const [x, y] = this.#bulbOnPage();\n      revealFrom(() => this.#applyTarget(true), x, y, { reduced: this.reduced, closing: !this.lit });\n    } else if (this.target) this.#applyTarget(user);\n    if (this.reduced) { this.T = this.lit ? this.o.warmth : FILAMENT.room; this.#draw(true); }\n    this.#sound('click');\n    if (revealChange) {\n      const [x, y] = this.#bulbOnPage();\n      revealFrom(change, x, y, { reduced: this.reduced, closing: !this.lit });\n    } else if (user) change();\n    this.#wake(true);\n  }\n\n  // ---------------------------------------------------------------- build\n\n  #build() {\n    if (!this.root.isConnected) return;\n    const rect = this.root.getBoundingClientRect();\n    const W = Math.round(rect.width);\n    const H = Math.round(rect.height);\n    if (!W || !H) return;\n    const dpr = Math.min(globalThis.devicePixelRatio || 1, 2);\n    const same = this.lay && this.W === W && this.H === H && this.dpr === dpr && this.layKey === `${this.o.shade}|${this.o.cord}|${this.o.pull}`;\n    this.W = W;\n    this.H = H;\n    this.dpr = dpr;\n    if (!same) {\n      this.lay = layout(W, H, this.o.shade, this.o.cord);\n      this.layKey = `${this.o.shade}|${this.o.cord}|${this.o.pull}`;\n      this.#newRig();\n      this.cache.clear();\n      this.pullRun = null;\n      this.drag = null;\n      this.hand = null;\n    }\n    const ld = Math.max(0.5, dpr / 2);\n    this.ld = ld;\n    for (const [cv, d] of [[this.cvLamp, dpr], [this.cvGlow, dpr], [this.cvShadow, ld], [this.cvLight, ld]]) {\n      const w = Math.max(1, Math.round(W * d));\n      const h = Math.max(1, Math.round(H * d));\n      if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }\n    }\n    this.#edgeMask();\n    this.#sprites();\n    this.#draw(true);\n    this.#wake();\n  }\n\n  #sprites() {\n    const mat = this.#material();\n    const key = `${mat.key}|${this.o.shade}|${this.o.bulb}|${this.o.warmth}|${this.o.light}|${this.lay.S.toFixed(3)}|${this.dpr}|${this.o.pull}`;\n    if (!this.cache.has(key)) this.cache.set(key, bake(this.o, this.lay, this.dpr, mat));\n    this.sprites = this.cache.get(key);\n  }\n\n  /** The light on the wall dies out well before the edge of the box, whatever its shape: it is the object's, not the page's. */\n  #edgeMask() {\n    const w = this.cvLight.width;\n    const h = this.cvLight.height;\n    const c = canvasOf(w, h);\n    const g = c.getContext('2d');\n    const img = g.createImageData(w, h);\n    for (let j = 0; j < h; j += 1) {\n      const v = ((j + 0.5) / h) * 2 - 1;\n      for (let i = 0; i < w; i += 1) {\n        const u = ((i + 0.5) / w) * 2 - 1;\n        // An elliptical, bell-shaped falloff: no flat sides and no line where it starts, so the light has no edge.\n        const r2 = u * u + v * v;\n        img.data[(j * w + i) * 4 + 3] = Math.round(255 * Math.exp(-2.2 * r2) * (1 - smooth(0.7, 1, Math.sqrt(r2))));\n      }\n    }\n    g.putImageData(img, 0, 0);\n    this.mask = c;\n  }\n\n  /** A rig hung still, and where its pull hangs from the switch at rest: every programmed pull starts from there. */\n  #newRig() {\n    this.rig = settleRig(makeRig({ style: this.o.shade, Ls: this.lay.Ls, Lp: this.lay.Lp, pull: this.o.pull }), 1.2);\n    const [ax, ay] = anchorOf(this.rig);\n    const [x, y] = acornOf(this.rig);\n    this.hang = [x - ax, y - ay];\n  }\n\n  /** Put the rig at rest (reduced motion: the lamp hangs still). */\n  #rest() {\n    if (!this.lay) return;\n    this.#newRig();\n    this.pullRun = null;\n    this.drag = null;\n    this.hand = null;\n    this.T = this.lit ? this.o.warmth : FILAMENT.room;\n  }\n\n  // ---------------------------------------------------------------- input\n\n  #local(e) {\n    const r = this.root.getBoundingClientRect();\n    return { x: e.clientX - r.left, y: e.clientY - r.top };\n  }\n\n  /** The bulb's centre in viewport px (the middle of the box before the first layout). */\n  #bulbOnPage() {\n    const b = this.root.getBoundingClientRect();\n    if (!this.rig || !this.sprites) return [b.left + b.width / 2, b.top + b.height / 2];\n    const [x, y] = this.#px(...lampPoint(this.rig, 0, this.sprites.bulbCentre));\n    return [b.left + x, b.top + y];\n  }\n\n  #world(p) { return [(p.x - this.lay.axisX) / this.lay.S, (p.y - this.lay.pivotY) / this.lay.S]; }\n\n  #px(x, y) { return [this.lay.axisX + x * this.lay.S, this.lay.pivotY + y * this.lay.S]; }\n\n  /** The cord node under the pointer (the acorn first), or 0. */\n  #nearest(p, touch) {\n    const r = this.rig;\n    const [axp, ayp] = this.#px(r.x[r.N], r.y[r.N] + ACORN.len * 0.45);\n    const reach = Math.max(22, ACORN.len * 0.6 * this.lay.S);\n    if (Math.hypot(p.x - axp, p.y - ayp) <= reach) return r.N;\n    if (touch) return 0;\n    let best = 0;\n    let bd = Math.max(10, 0.012 * this.lay.S);\n    for (let i = 2; i < r.N; i += 1) {\n      const [x, y] = this.#px(r.x[i], r.y[i]);\n      const d = Math.hypot(p.x - x, p.y - y);\n      if (d < bd) { bd = d; best = i; }\n    }\n    return best;\n  }\n\n  #down(e) {\n    if (e.button !== 0) return;\n    const p = this.#local(e);\n    this.downAt = { x: p.x, y: p.y, t: performance.now(), moved: false };\n    if (this.reduced || !this.rig || this.pullRun) return;\n    const j = this.#nearest(p, e.pointerType === 'touch' && e.target !== this.grip);\n    if (!j) return;\n    const [wx, wy] = this.#world(p);\n    this.drag = { id: e.pointerId, node: j, dx: this.rig.x[j] - wx, dy: this.rig.y[j] - wy, x0: this.rig.x[j], y0: this.rig.y[j] };\n    this.hand = { node: j, x: this.rig.x[j], y: this.rig.y[j] };\n    try { this.root.setPointerCapture(e.pointerId); } catch { /* synthetic */ }\n    this.root.classList.add('pc-held');\n    this.#armAudioIfWanted();\n    this.#wake(true);\n  }\n\n  #move(e) {\n    if (this.downAt && !this.downAt.moved) {\n      const p = this.#local(e);\n      if (Math.hypot(p.x - this.downAt.x, p.y - this.downAt.y) > 2) this.downAt.moved = true;\n    }\n    if (!this.drag || e.pointerId !== this.drag.id) return;\n    const [wx, wy] = this.#world(this.#local(e));\n    const lp = this.lay.Lp;\n    // A hand cannot pull the cord through the ceiling or out of the room.\n    this.hand.x = clamp(wx + this.drag.dx, this.drag.x0 - 0.55 * lp, this.drag.x0 + 0.55 * lp);\n    this.hand.y = clamp(wy + this.drag.dy, this.drag.y0 - 0.6 * lp, this.drag.y0 + PULL_DEPTH + 0.03);\n    this.#wake(true);\n  }\n\n  #up(e) {\n    if (this.drag && e.pointerId === this.drag.id) {\n      this.drag = null;\n      this.hand = null;\n      this.root.classList.remove('pc-held');\n      // A tug is not a click: a hand that moved the cord, or held it, has already done what it meant to.\n      if (this.downAt?.moved || performance.now() - (this.downAt?.t ?? 0) > 350) this.suppress = true;\n      this.#wake(true);\n    }\n  }\n\n  #click(e) {\n    if (this.suppress) { this.suppress = false; e.preventDefault(); return; }\n    this.#armAudioIfWanted();\n    this.pull();\n  }\n\n  #key(e) {\n    if (e.key !== ' ' && e.key !== 'Enter') return;\n    e.preventDefault();\n    if (e.repeat) return;\n    this.#armAudioIfWanted();\n    this.pull();\n  }\n\n  // ---------------------------------------------------------------- the loop\n\n  #frame = (t) => {\n    this.raf = 0;\n    this.inFrame = true;\n    const dt = this.last ? Math.min((t - this.last) / 1000, 1 / 30) : 1 / 60;\n    this.last = t;\n    const r = this.rig;\n    let hand = this.hand;\n    if (this.pullRun) {\n      const run = this.pullRun;\n      if (run.t0 < 0) run.t0 = t;\n      const el = (t - run.t0) / 1000;\n      const k = clamp(el / 0.17, 0, 1);\n      const depth = PULL_DEPTH * k * k * (3 - 2 * k);\n      hand = { node: r.N, x: run.x, y: run.y + depth };\n      if (el > 0.26) { this.pullRun = null; hand = null; if (run.again) this.#startPull(); }\n    }\n    for (const ev of stepRig(r, dt, hand)) {\n      if (ev === 'click') this.#toggle(true);\n      else this.#sound('reset');\n    }\n    const want = this.lit ? this.o.warmth : FILAMENT.room;\n    this.T = stepFilament(this.T, this.lit, dt, this.o.warmth);\n    this.#draw();\n    const eps = (0.04 * 60) / this.lay.S; // a twenty-fifth of a pixel a frame\n    const still = !hand && !this.pullRun && !this.drag && rigSettled(r, eps);\n    // Settled: lit, within 3 K of its warmth; dark, below the Draper point, where it\n    // no longer glows (radiating T⁴ away, the last few hundred kelvin take minutes).\n    const cool = this.lit ? Math.abs(this.T - want) < 3 : this.T < FILAMENT.draper;\n    if (cool && this.T !== want) { this.T = want; this.#draw(); }\n    if (still) freezeRig(r);\n    this.inFrame = false;\n    if ((still && cool) || (!this.visible && !this.pullRun && !this.drag) || document.hidden) this.#sleep();\n    else this.raf = requestAnimationFrame(this.#frame);\n  };\n\n  #wake(force = false) {\n    // A pull or a drag someone is making runs even before the observer has said the cord is on screen\n    // (it can be late on a busy device); otherwise that press would be lost.\n    const handled = this.pullRun || this.drag;\n    if (this.reduced || this.raf || this.inFrame || (!this.visible && !handled) || document.hidden || !this.rig) return;\n    if (!force && !this.pullRun && !this.drag) {\n      const want = this.lit ? this.o.warmth : FILAMENT.room;\n      if (rigSettled(this.rig, 1e-6) && this.T === want) return;\n    }\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(all = false) {\n    const sp = this.sprites;\n    const r = this.rig;\n    if (!sp || !r) return;\n    const S = this.lay.S;\n    const d = this.dpr;\n    const st = STYLES[this.o.shade];\n    const glow = this.reduced ? (this.lit ? 1 : 0) : glowOf(this.T, this.o.warmth);\n    const theta = r.theta;\n    const [topX, topY] = this.#px(Math.sin(theta) * r.Ls, Math.cos(theta) * r.Ls);\n    const [pvX, pvY] = this.#px(0, 0);\n    const mat = sp.mat;\n    const boost = clamp(26 / (ACORN.len * S), 1, 2.4); // small lamps draw their cord and acorn a little heavier\n\n    // The cord as a smooth path, in CSS px.\n    const pts = [];\n    for (let i = 0; i <= r.N; i += 1) pts.push(this.#px(r.x[i], r.y[i]));\n    const cordPath = (ox = 0, oy = 0) => {\n      const p = new Path2D();\n      p.moveTo(pts[0][0] + ox, pts[0][1] + oy);\n      for (let i = 1; i < pts.length - 1; i += 1) {\n        const mx = (pts[i][0] + pts[i + 1][0]) / 2;\n        const my = (pts[i][1] + pts[i + 1][1]) / 2;\n        p.quadraticCurveTo(pts[i][0] + ox, pts[i][1] + oy, mx + ox, my + oy);\n      }\n      p.lineTo(pts[r.N][0] + ox, pts[r.N][1] + oy);\n      return p;\n    };\n    const last = pts[r.N];\n    const prev = pts[r.N - 1];\n    const acornAng = Math.atan2(last[0] - prev[0], last[1] - prev[1]);\n\n    // ---- shadows (the room lamp, on the wall), only when something moved\n    const moved = all || this.#changed(theta, last, glow);\n    if (moved) {\n      const g = this.cvShadow.getContext('2d');\n      const ld = this.ld;\n      g.setTransform(1, 0, 0, 1, 0, 0);\n      g.clearRect(0, 0, this.cvShadow.width, this.cvShadow.height);\n      const { lx, ly } = lampOf(this.o.light);\n      const ox = -lx * WALL.shadow * S;\n      const oy = -ly * WALL.shadow * S;\n      g.setTransform(ld, 0, 0, ld, 0, 0);\n      g.globalAlpha = mat.shadow;\n      const cs = sp.cupShadow;\n      g.drawImage(sp.cupShadow.c, pvX + ox - cs.ox, pvY + oy - cs.oy, cs.w, cs.h);\n      const blur = WALL.blur * S;\n      // A thin cord's shadow spreads over the blur: as wide as the blur, as dark as the cord is thick.\n      // The same blur as the lamp's own shadow; a 3 mm cord under a soft room\n      // light leaves little more than a smudge, and that is what it gets.\n      const soft = (path, w) => {\n        g.save();\n        g.filter = `blur(${(blur * 0.45 * ld).toFixed(1)}px)`;\n        g.lineCap = 'round';\n        g.strokeStyle = '#000';\n        g.lineWidth = w * 1.6;\n        g.globalAlpha = mat.shadow * 0.9;\n        g.stroke(path);\n        g.restore();\n      };\n      const cable = new Path2D();\n      cable.moveTo(pvX + ox, pvY + oy);\n      cable.lineTo(topX + ox, topY + oy);\n      soft(cable, 0.0055 * S);\n      soft(cordPath(ox, oy), sp.bead ? sp.bead.D * 0.85 : 0.0034 * S * boost);\n      g.globalAlpha = mat.shadow;\n      g.save();\n      g.translate(topX + ox, topY + oy);\n      g.rotate(-theta);\n      const ls = sp.lampShadow;\n      g.drawImage(ls.c, -ls.ox, -ls.oy, ls.w, ls.h);\n      g.restore();\n      g.save();\n      g.translate(last[0] + ox, last[1] + oy);\n      g.rotate(-acornAng);\n      g.scale(boost, boost);\n      const as = sp.acornShadow;\n      g.drawImage(as.c, -as.ox, -as.oy, as.w, as.h);\n      g.restore();\n      g.globalAlpha = 1;\n\n      // ---- the light on the wall\n      const lg = this.cvLight.getContext('2d');\n      lg.setTransform(1, 0, 0, 1, 0, 0);\n      lg.clearRect(0, 0, this.cvLight.width, this.cvLight.height);\n      const grainOn = glow > 0.002 ? glow.toFixed(2) : '0';\n      if (this.grain.style.opacity !== grainOn) this.grain.style.opacity = grainOn;\n      if (glow > 0.002) {\n        const [bx, by] = this.#px(...lampPoint(r, 0, sp.bulbCentre));\n        lg.setTransform(ld, 0, 0, ld, 0, 0);\n        lg.translate(bx, by);\n        lg.rotate(-theta);\n        // A narrow box can only hold a column of it: there, keep it a faint wash, not a stripe.\n        lg.globalAlpha = glow * (0.3 + 0.7 * smooth(60, 240, Math.min(this.W, this.H)));\n        lg.drawImage(sp.pool.c, -sp.pool.ox, -sp.pool.oy, sp.pool.w, sp.pool.h);\n        lg.globalAlpha = 1;\n        lg.setTransform(1, 0, 0, 1, 0, 0);\n        lg.globalCompositeOperation = 'destination-in';\n        lg.drawImage(this.mask, 0, 0);\n        lg.globalCompositeOperation = 'source-over';\n      }\n    }\n\n    // ---- the lamp\n    const g = this.cvLamp.getContext('2d');\n    g.setTransform(1, 0, 0, 1, 0, 0);\n    g.clearRect(0, 0, this.cvLamp.width, this.cvLamp.height);\n    g.setTransform(d, 0, 0, d, 0, 0);\n    // The cable, pivot to lamp.\n    this.#cable(g, [[pvX, pvY], [topX, topY]], 0.0055 * S, mat, 0);\n    const cf = sp.cupFrame;\n    g.drawImage(sp.cup, pvX - cf.ox, pvY - cf.oy, cf.w, cf.h);\n\n    const f = sp.frame;\n    const turn = () => { g.setTransform(d, 0, 0, d, 0, 0); g.translate(topX, topY); g.rotate(-theta); };\n    const still = () => { g.setTransform(d, 0, 0, d, 0, 0); g.translate(topX, topY); };\n    const blit = (c) => g.drawImage(c, -f.ox, -f.oy, f.w, f.h);\n    // Clip to a turned outline (paths are in metres), then draw a layer that does not turn.\n    const clipTurned = (path) => { turn(); g.scale(S, S); g.clip(path); };\n\n    turn();\n    if (sp.inside) {\n      blit(sp.inside);\n      if (glow > 0.002) { g.globalCompositeOperation = 'lighter'; g.globalAlpha = glow; blit(sp.insideOn); g.globalAlpha = 1; g.globalCompositeOperation = 'source-over'; }\n      blit(sp.pod);\n    }\n    blit(sp.bulb);\n    g.save();\n    clipTurned(sp.glassPath);\n    still();\n    blit(sp.bulbSheen);\n    g.restore();\n    turn();\n    blit(sp.body);\n    if (sp.sheen) {\n      g.save();\n      clipTurned(sp.shellPath);\n      still();\n      blit(sp.sheen);\n      g.restore();\n    }\n    // The filament's light is added to whatever is behind the glass, so it\n    // goes on its own screen-blended layer, with the shade cut out of it.\n    const lvl = Math.round(clamp((this.T - FILAMENT.draper) / (this.o.warmth - FILAMENT.draper), 0, 1) * GLOW_LEVELS);\n    const showGlow = this.reduced ? (this.lit ? GLOW_LEVELS : 0) : lvl;\n    const gg = this.cvGlow.getContext('2d');\n    if (showGlow > 0 || this.glowShown) {\n      gg.setTransform(1, 0, 0, 1, 0, 0);\n      gg.clearRect(0, 0, this.cvGlow.width, this.cvGlow.height);\n      this.glowShown = showGlow > 0;\n      if (showGlow > 0) {\n        gg.setTransform(d, 0, 0, d, 0, 0);\n        gg.translate(topX, topY);\n        gg.rotate(-theta);\n        const gf = sp.glowFrame;\n        gg.drawImage(sp.glow[showGlow - 1], gf.x, gf.y, gf.w, gf.w);\n        // The room lamp's reflection stays on the lit glass, fixed to the room as the lamp sways.\n        gg.save();\n        gg.setTransform(d, 0, 0, d, 0, 0);\n        gg.translate(topX, topY);\n        gg.rotate(-theta);\n        gg.scale(S, S);\n        gg.clip(sp.glassPath);\n        gg.setTransform(d, 0, 0, d, 0, 0);\n        gg.translate(topX, topY);\n        gg.globalAlpha = 0.5 + 0.5 * glow;\n        gg.drawImage(sp.bulbSheen, -f.ox, -f.oy, f.w, f.h);\n        gg.rotate(-theta);\n        gg.globalCompositeOperation = 'destination-out'; // the shade stands in front of the part of the glass above its rim\n        gg.drawImage(sp.body, -f.ox, -f.oy, f.w, f.h);\n        gg.restore();\n      }\n    }\n    if (sp.lipPath && glow > 0.002) {\n      turn();\n      g.scale(S, S);\n      g.strokeStyle = css(sp.warmRgb, 0.85 * glow);\n      g.lineWidth = 0.0014;\n      g.stroke(sp.lipPath);\n    }\n\n    // ---- the pull cord and the acorn\n    g.setTransform(d, 0, 0, d, 0, 0);\n    const cw = Math.max(1.1, 0.0034 * S * boost);\n    const [bx, by] = this.#px(...lampPoint(r, 0, sp.bulbCentre));\n    const warm = glow > 0.002 ? { x: bx, y: by, glow, rgb: sp.warmRgb } : null;\n    if (sp.bead) this.#chain(g, pts, sp.bead, warm);\n    else this.#cable(g, pts, cw, mat, r.e * S, warm, cordPath());\n    g.save();\n    g.translate(last[0], last[1]);\n    g.rotate(-acornAng);\n    g.scale(boost, boost);\n    const af = sp.acornFrame;\n    g.drawImage(sp.acorn, -af.ox, -af.oy, af.w, af.h);\n    if (glow > 0.002) {\n      // The bulb's light on the side of the acorn that faces it.\n      const toB = Math.atan2(bx - last[0], by - last[1]) + acornAng;\n      const dist = Math.hypot(bx - last[0], by - last[1]) / S;\n      const a = 0.45 * glow * clamp(0.02 / (dist * dist + 0.004), 0, 1);\n      const hx = Math.sin(toB) * ACORN.r * 0.55 * S;\n      const hy = ACORN.len * 0.62 * S + Math.cos(toB) * ACORN.r * 0.3 * S;\n      g.globalCompositeOperation = 'lighter';\n      g.fillStyle = css(sp.warmRgb, a);\n      g.beginPath();\n      g.ellipse(hx, hy, ACORN.r * 0.28 * S, ACORN.len * 0.22 * S, 0, 0, Math.PI * 2);\n      g.fill();\n      g.globalCompositeOperation = 'source-over';\n    }\n    g.restore();\n\n    // The grip follows the acorn.\n    const gx = last[0] + Math.sin(acornAng) * ACORN.len * 0.45 * S * boost;\n    const gy = last[1] + Math.cos(acornAng) * ACORN.len * 0.45 * S * boost;\n    this.grip.style.transform = `translate(${gx.toFixed(1)}px, ${gy.toFixed(1)}px)`;\n    // The focus ring hugs the acorn; the grip around it stays 44 px.\n    const ring = clamp(ACORN.len * S * boost + 12, 24, 44);\n    if (ring !== this.ring) { this.ring = ring; this.grip.style.setProperty('--pc-ring', `${ring.toFixed(1)}px`); }\n  }\n\n  /** Did anything the shadow or the wall light shows move by a tenth of a pixel? */\n  #changed(theta, last, glow) {\n    const p = this.drawn;\n    const S = this.lay.S;\n    const moved = p.theta === undefined || Math.abs(theta - p.theta) * S * 0.6 > 0.1 || Math.hypot(last[0] - p.ax, last[1] - p.ay) > 0.1 || Math.abs(glow - p.glow) > 0.002;\n    if (moved) { p.theta = theta; p.ax = last[0]; p.ay = last[1]; p.glow = glow; }\n    return moved;\n  }\n\n  /**\n   * A textile cord through `pts` (CSS px): its colour, a braid that travels\n   * with the cord as it is pulled out of the switch, a thread of the room\n   * lamp on the side facing it, and — when the bulb is on — its warm light on\n   * the side facing the bulb.\n   */\n  #cable(g, pts, w, mat, slide, warm, path) {\n    let p = path;\n    if (!p) { p = new Path2D(); p.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i += 1) p.lineTo(pts[i][0], pts[i][1]); }\n    const { lx, ly } = lampOf(this.o.light);\n    g.lineCap = 'round';\n    g.lineJoin = 'round';\n    g.strokeStyle = mat.cordDark;\n    g.lineWidth = w;\n    g.stroke(p);\n    g.strokeStyle = mat.cord;\n    g.lineWidth = w * 0.72;\n    g.stroke(p);\n    if (w > 2.2) {\n      g.setLineDash([w * 0.55, w * 0.55]);\n      g.lineDashOffset = -slide;\n      g.strokeStyle = 'rgba(0, 0, 0, 0.22)';\n      g.lineWidth = w * 0.7;\n      g.stroke(p);\n      g.setLineDash([]);\n    }\n    g.save();\n    g.translate(lx * w * 0.2, ly * w * 0.2);\n    g.strokeStyle = mat.cordLight;\n    g.globalAlpha = 0.55;\n    g.lineWidth = Math.max(0.5, w * 0.26);\n    g.stroke(p);\n    g.restore();\n    if (warm) {\n      const mid = pts[Math.floor(pts.length / 2)];\n      const dx = warm.x - mid[0];\n      const dy = warm.y - mid[1];\n      const dist = Math.hypot(dx, dy) || 1;\n      const a = warm.glow * clamp((0.06 * this.lay.S) / dist, 0, 1) * 0.9;\n      g.save();\n      g.translate((dx / dist) * w * 0.22, (dy / dist) * w * 0.22);\n      g.globalCompositeOperation = 'lighter';\n      g.strokeStyle = css(warm.rgb, a);\n      g.lineWidth = Math.max(0.5, w * 0.3);\n      g.stroke(p);\n      g.restore();\n    }\n  }\n\n  /**\n   * A ball chain through the rig: the beads threaded up the cord's curve at\n   * their fixed pitch (`beadsAlong`), the links between them, every bead the\n   * one baked sprite, and when the bulb is on a warm glint on each bead's side\n   * that faces it.\n   */\n  #chain(g, pts, b, warm) {\n    const r = this.rig;\n    const m = beadsAlong(r.x, r.y, b.pitch, r.N);\n    const xy = [];\n    for (let k = 0; k < m.length; k += 2) xy.push(this.#px(m[k], m[k + 1]));\n    const links = new Path2D();\n    links.moveTo(pts[r.N][0], pts[r.N][1]);\n    for (const [x, y] of xy) links.lineTo(x, y);\n    links.lineTo(pts[0][0], pts[0][1]);\n    g.lineCap = 'round';\n    g.lineJoin = 'round';\n    g.strokeStyle = b.link;\n    g.lineWidth = Math.max(0.7, b.D * 0.22);\n    g.stroke(links);\n    const h = b.w / 2;\n    for (const [x, y] of xy) g.drawImage(b.c, x - h, y - h, b.w, b.w);\n    if (warm && xy.length) {\n      const glints = new Path2D();\n      const gr = b.D * 0.18;\n      for (const [x, y] of xy) {\n        const dx = warm.x - x;\n        const dy = warm.y - y;\n        const d = Math.hypot(dx, dy) || 1;\n        const cx = x + (dx / d) * b.D * 0.28;\n        const cy = y + (dy / d) * b.D * 0.28;\n        glints.moveTo(cx + gr, cy);\n        glints.arc(cx, cy, gr, 0, Math.PI * 2);\n      }\n      const mid = xy[Math.floor(xy.length / 2)];\n      const a = warm.glow * clamp((0.06 * this.lay.S) / (Math.hypot(warm.x - mid[0], warm.y - mid[1]) || 1), 0, 1);\n      g.save();\n      g.globalCompositeOperation = 'lighter';\n      g.fillStyle = css(warm.rgb, a);\n      g.fill(glints);\n      g.restore();\n    }\n  }\n\n  // ---------------------------------------------------------------- sound\n\n  #armAudioIfWanted() { if (this.o.sound) this.#armAudio(); }\n\n  #listenForGesture() {\n    if (this.audio || this.listening) return;\n    this.listening = true;\n    addEventListener('pointerdown', this.on.gesture, true);\n    addEventListener('keydown', this.on.gesture, true);\n  }\n\n  #stopListening() {\n    if (!this.listening) return;\n    this.listening = false;\n    removeEventListener('pointerdown', this.on.gesture, true);\n    removeEventListener('keydown', this.on.gesture, true);\n  }\n\n  #armAudio() {\n    this.#stopListening();\n    try {\n      const Ctx = globalThis.AudioContext ?? globalThis.webkitAudioContext;\n      if (!Ctx || this.audio) return;\n      this.audio = new Ctx();\n      const len = Math.floor(this.audio.sampleRate * 0.02);\n      this.noise = this.audio.createBuffer(1, len, this.audio.sampleRate);\n      const ch = this.noise.getChannelData(0);\n      for (let i = 0; i < len; i += 1) ch[i] = (Math.random() * 2 - 1) * (1 - i / len) ** 6;\n    } catch { /* no audio device: the switch must still switch */ }\n  }\n\n  /** The switch: a hard plastic snap on the pull, a softer tick as it re-arms. */\n  #sound(kind) {\n    if (!this.o.sound || !this.audio || this.audio.state !== 'running') return;\n    try {\n      const ctx = this.audio;\n      const t = ctx.currentTime;\n      const src = ctx.createBufferSource();\n      src.buffer = this.noise;\n      const band = ctx.createBiquadFilter();\n      band.type = 'bandpass';\n      band.frequency.value = kind === 'click' ? 2600 : 4200;\n      band.Q.value = kind === 'click' ? 2.2 : 3.5;\n      const gain = ctx.createGain();\n      gain.gain.value = kind === 'click' ? 0.5 : 0.14;\n      src.connect(band).connect(gain).connect(ctx.destination);\n      src.start(t);\n      if (kind === 'click') {\n        const body = ctx.createOscillator();\n        body.frequency.setValueAtTime(190, t);\n        body.frequency.exponentialRampToValueAtTime(90, t + 0.04);\n        const bg = ctx.createGain();\n        bg.gain.setValueAtTime(0.18, t);\n        bg.gain.exponentialRampToValueAtTime(0.001, t + 0.05);\n        body.connect(bg).connect(ctx.destination);\n        body.start(t);\n        body.stop(t + 0.06);\n      }\n    } catch { /* never let sound break the switch */ }\n  }\n}\n\nexport default PullCord;\n"},{"path":"tactile/pull-cord/pull-cord.css","type":"registry:file","target":"tactile/pull-cord/pull-cord.css","content":"/* Pull-cord Bulb — Tactile UI.\n   The lamp fills its host: give the host a width and a height. A tall narrow\n   host (56 × 150 px under a nav) is a header toggle; a wide one is a hero. */\n\n.pc {\n  position: relative;\n  width: 100%;\n  height: 100%;\n  min-height: 96px;\n  /* A vertical swipe over the empty wall still scrolls the page; only the grip takes the drag. */\n  touch-action: pan-y;\n  cursor: pointer;\n  outline: none;\n  -webkit-tap-highlight-color: transparent;\n  user-select: none;\n}\n\n.pc canvas {\n  position: absolute;\n  inset: 0;\n  width: 100%;\n  height: 100%;\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/* The bulb's light on the wall adds to the page behind it, as light does. */\n.pc-light, .pc-glow { mix-blend-mode: screen; }\n\n/* Grain over that light, the kit's fractal noise as an overlay: a smooth light on a pale wall would\n   band into rings in 8 bits. Overlay on mid grey changes nothing on average, and does most on a pale\n   wall, where the banding is. It is as strong as the light (opacity is set as it draws) and fades\n   with it toward the box's edge. */\n.pc-grain {\n  position: absolute;\n  inset: 0;\n  pointer-events: none;\n  opacity: 0;\n  mix-blend-mode: overlay;\n  background: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='1.1' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0.3 0 0 0 0.35 0.3 0 0 0 0.35 0.3 0 0 0 0.35 0 0 0 0 1'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\");\n  -webkit-mask-image: radial-gradient(closest-side, #000 70%, transparent);\n  mask-image: radial-gradient(closest-side, #000 70%, transparent);\n}\n\n/* The acorn's hit target: 44 px, following it, taking the pull on touch. */\n.pc-grip {\n  position: absolute;\n  left: 0;\n  top: 0;\n  width: 44px;\n  height: 44px;\n  margin: -22px 0 0 -22px;\n  border-radius: 50%;\n  touch-action: none;\n  cursor: grab;\n}\n.pc.pc-held, .pc.pc-held .pc-grip { cursor: grabbing; }\n/* The focus ring hugs the acorn (its size is set as it draws); the grip stays 44 px. */\n.pc-grip::after {\n  content: '';\n  position: absolute;\n  left: 50%;\n  top: 50%;\n  width: var(--pc-ring, 36px);\n  height: var(--pc-ring, 36px);\n  transform: translate(-50%, -50%);\n  border-radius: 50%;\n}\n.pc:focus-visible .pc-grip::after { outline: 2px solid var(--tui-focus, currentColor); outline-offset: 1px; }\n\n/* `reveal`: lights on, the light page opens out of the bulb; lights off, it shrinks back into\n   the bulb over the dark one. --pc-r is the light's radius (animated by the script), --pc-x/y the\n   bulb; the edge is feathered over the outer tenth (REVEAL.feather). Nothing else animates under\n   it (a page's own colour transition would smear inside the light). */\n@property --pc-r { syntax: '<length>'; inherits: false; initial-value: 0px; }\nhtml.pc-reveal::view-transition-old(root), html.pc-reveal::view-transition-new(root) { animation: none; mix-blend-mode: normal; }\nhtml.pc-reveal:not(.pc-closing)::view-transition-new(root),\nhtml.pc-reveal.pc-closing::view-transition-old(root) {\n  -webkit-mask-image: radial-gradient(circle at var(--pc-x) var(--pc-y), #000 calc(var(--pc-r) * 0.9), transparent var(--pc-r));\n  mask-image: radial-gradient(circle at var(--pc-x) var(--pc-y), #000 calc(var(--pc-r) * 0.9), transparent var(--pc-r));\n}\n/* Going dark, the light page stays on top, whole until the script starts shrinking it. */\nhtml.pc-reveal.pc-closing::view-transition-old(root) { z-index: 1; --pc-r: 300vmax; }\nhtml.pc-reveal, html.pc-reveal *, html.pc-reveal *::before, html.pc-reveal *::after { transition: none !important; }\n\n@media (forced-colors: active) {\n  .pc:focus-visible .pc-grip::after { outline-color: Highlight; }\n}\n"},{"path":"tactile/pull-cord-example.html","type":"registry:file","target":"tactile/pull-cord-example.html","content":"<!doctype html>\n<html lang=\"en\">\n<!-- Pull-cord Bulb v0.1.0: Tactile UI\n     Put this file beside ./pull-cord/ holding pull-cord.mjs and\n     pull-cord.css. Serve over HTTP (any static server, e.g. `npx serve .`).\n     No framework, 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>Pull-cord Bulb</title>\n<link rel=\"stylesheet\" href=\"./pull-cord/pull-cord.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  html { transition: background-color 0.3s; }\n  body { margin: 0; min-height: 100vh; display: grid; justify-items: center; font: 15px/1.4 ui-sans-serif, system-ui, sans-serif; }\n  /* The lamp fills its host and hangs from the host's top edge. A 56 × 150 px\n     host under a nav is a header toggle; this one is a hero. */\n  #lamp { width: min(92vw, 760px); height: min(82vh, 620px); }\n</style>\n</head>\n<body>\n<div id=\"lamp\"></div>\n<script type=\"module\">\nimport { PullCord } from './pull-cord/pull-cord.mjs';\n\nconst lamp = new PullCord(document.getElementById('lamp'), {\n  on: true,\n  shade: \"dome\",\n  bulb: \"clear\",\n  finish: \"auto\",\n  warmth: 2700,\n  cord: 1,\n  pull: \"cord\",\n  light: 315,\n  target: null,\n  reveal: false,\n  label: \"Light\",\n  sound: false,\n});\n\nlamp.root.addEventListener('change', (e) => {\n  // e.detail.on: the lamp was pulled on or off.\n});\n\n// lamp.pull()                     pull the cord from code (the same animated pull)\n// lamp.set(false)                 switch without a pull and without a change event\n// lamp.checked                    whether it is lit\n// lamp.update({ shade: 'bare' })  any option, in place\n// lamp.destroy()\n</script>\n</body>\n</html>"},{"path":"tactile/pull-cord/LICENSE","type":"registry:file","target":"tactile/pull-cord/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":"Pull-cord Bulb is in tactile/pull-cord/. Open tactile/pull-cord-example.html to see it run; pull-cord.mjs is the class, pull-cord.css its look.\nLoad both or it renders unstyled: in a bundler such as Vite, import './tactile/pull-cord/pull-cord.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/pull-cord","meta":{"id":"cmp.pull-cord","version":"0.1.0","access":"free","licence":"MIT"}}