# #113 — Tactile Rotary Dial / Precision Ruler Scrubber

> Camera-grade horizontal tick-ruler scrubber for fine-grained Exposure, White Balance, and ISO adjustments.

## Metadata

- **Index**: #113
- **Slug**: `tactile-ruler-scrubber`
- **Kind**: `ui`
- **Family**: Precision Controls
- **Theme**: `dark`
- **Mobile Strength**: `native-first`
- **Tags**: `ruler-scrubber`, `rotary-dial`, `precision-control`, `camera-ui`, `tactile-ux`
- **Best For**: Photo & video editing apps, Audio synth & EQ interfaces, Smart-home thermostat & lighting dials, Scientific instrument controls
- **Real-World Inspiration**: [Halide](https://halide.cam)
- **Detail Page**: https://templates.michaelpitts.net/t/tactile-ruler-scrubber
- **Live Demo**: https://templates.michaelpitts.net/demos/tactile-ruler-scrubber.html
- **JSON API**: https://templates.michaelpitts.net/api/templates/tactile-ruler-scrubber

## Why This Aesthetic Is Unique

Replaces clumsy native range sliders with a high-precision, tactile instrument dial that offers fine sub-step control and immediate visual feedback.

## Color Palette

| Role | Name | Hex |
|------|------|-----|
| `canvas` | Camera Matte | `#0D0E10` |
| `surface` | Anodized Alloy | `#191B1F` |
| `ink` | Reticle White | `#F4F4F5` |
| `accent` | Leica Yellow | `#FACC15` |
| `muted` | Dial Pewter | `#8E929B` |

## Typography

- **Display**: `Space Grotesk`
- **Body**: `Inter`
- **Mono**: `JetBrains Mono`
- **Scale Notes**: High-legibility monospace numeric readouts (+0.7 EV, 5600K, ISO 400) anchored directly above the center reticle needle.
- **Google Fonts**: https://fonts.googleapis.com/css2?family=Inter:wght@400;600&family=JetBrains+Mono:wght@600;700&family=Space+Grotesk:wght@600;700&display=swap
  ```html
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&family=JetBrains+Mono:wght@600;700&family=Space+Grotesk:wght@600;700&display=swap">
  ```

## Layout Architecture

Live responsive viewfinder stage above a dedicated dark instrument console with parameter tabs (EV, Kelvin, ISO) and a full-width precision tick ruler.

## Interaction & Micro-Motion Rules

Horizontal pointer drag scrubs smoothly across calibrated tick marks with real-time live canvas color/exposure rendering, wheel support, arrow keys, and double-tap/button reset.

## Mobile & Responsive Rules

Wide drag zone (>=64px tall) with touch-action: none lets thumbs scrub finely without lifting or triggering browser back swipes.

## Agent Guardrails

### DO
- Display a fixed center reticle needle with live numeric readout directly above the moving tick track
- Offer one-tap or double-tap reset back to neutral/auto value for every parameter
- Support mouse wheel and keyboard ArrowLeft/ArrowRight nudging on desktop

### DON'T
- Do not obscure the live preview canvas behind opaque modal controls while scrubbing
- Do not omit visual major/minor tick hierarchy that communicates step scale

## Complete Standalone Starter Code

File: `demos/tactile-ruler-scrubber.html`

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Aperture Manual — Tactile Ruler Scrubber</title>
<style>
  :root {
    --canvas: #0D0E10;
    --surface: #191B1F;
    --surface-2: #23262C;
    --ink: #F4F4F5;
    --accent: #FACC15;
    --accent-dim: rgba(250, 204, 21, 0.16);
    --muted: #8E929B;
    --border: rgba(255, 255, 255, 0.08);
    --danger: #F87171;
    --mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
    --sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Inter", system-ui, sans-serif;
  }

  * { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }

  html, body {
    height: 100%;
    background: var(--canvas);
    color: var(--ink);
    font-family: var(--sans);
    overflow-x: hidden;
    user-select: none;
    -webkit-user-select: none;
  }

  .app {
    min-height: 100dvh;
    max-width: 1120px;
    margin: 0 auto;
    padding: 12px 14px 20px;
    display: grid;
    grid-template-rows: auto 1fr auto;
    gap: 12px;
  }

  /* Top status telemetry bar */
  .topbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    padding: 8px 12px;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 14px;
  }

  .brand {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    font-size: 13px;
    letter-spacing: 0.06em;
    text-transform: uppercase;
  }

  .brand-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--accent);
    box-shadow: 0 0 10px var(--accent);
  }

  .telemetry-pills {
    display: flex;
    align-items: center;
    gap: 6px;
    flex-wrap: wrap;
    justify-content: flex-end;
  }

  .icon-btn {
    min-width: 44px;
    min-height: 44px;
    padding: 0 12px;
    border-radius: 10px;
    border: 1px solid var(--border);
    background: var(--surface-2);
    color: var(--muted);
    font-family: var(--mono);
    font-size: 11px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    cursor: pointer;
    transition: background 0.15s, color 0.15s, border-color 0.15s;
  }

  .icon-btn:hover { color: var(--ink); border-color: rgba(255,255,255,0.18); }
  .icon-btn[aria-pressed="true"] {
    background: var(--accent-dim);
    color: var(--accent);
    border-color: rgba(250, 204, 21, 0.45);
  }

  /* Main layout: mobile stacked, desktop 2-column */
  .workspace {
    display: grid;
    grid-template-columns: 1fr;
    gap: 14px;
    align-items: start;
  }

  @media (min-width: 900px) {
    .app { padding: 20px 28px 28px; gap: 16px; }
    .workspace {
      grid-template-columns: minmax(0, 1.35fr) minmax(320px, 0.85fr);
      gap: 20px;
      align-items: stretch;
    }
  }

  /* Viewfinder */
  .viewfinder-shell {
    position: relative;
    background: #050607;
    border: 1px solid var(--border);
    border-radius: 18px;
    overflow: hidden;
    aspect-ratio: 4 / 3;
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.55);
  }

  #viewfinder {
    width: 100%;
    height: 100%;
    display: block;
  }

  .vf-overlay {
    position: absolute;
    inset: 0;
    pointer-events: none;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 12px 14px;
  }

  .vf-grid {
    position: absolute;
    inset: 0;
    opacity: 0;
    transition: opacity 0.2s;
    background-image:
      linear-gradient(to right, rgba(255,255,255,0.18) 1px, transparent 1px),
      linear-gradient(to bottom, rgba(255,255,255,0.18) 1px, transparent 1px);
    background-size: 33.333% 33.333%;
    background-position: -1px -1px;
  }
  .vf-grid.visible { opacity: 1; }

  .vf-corners::before, .vf-corners::after {
    content: "";
    position: absolute;
    width: 18px;
    height: 18px;
    border: 1.5px solid rgba(255,255,255,0.4);
  }
  .vf-corners::before { top: 10px; left: 10px; border-right: 0; border-bottom: 0; }
  .vf-corners::after { bottom: 10px; right: 10px; border-left: 0; border-top: 0; }

  .vf-top-hud {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 10px;
    z-index: 2;
  }

  .hud-badge {
    background: rgba(13, 14, 16, 0.72);
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    border: 1px solid rgba(255,255,255,0.12);
    border-radius: 8px;
    padding: 5px 9px;
    font-family: var(--mono);
    font-size: 11px;
    letter-spacing: 0.04em;
    color: var(--ink);
    display: inline-flex;
    align-items: center;
    gap: 8px;
  }

  .hud-badge .accent { color: var(--accent); font-weight: 700; }

  #histCanvas {
    width: 96px;
    height: 36px;
    border-radius: 6px;
    background: rgba(13, 14, 16, 0.72);
    border: 1px solid rgba(255,255,255,0.12);
    display: block;
  }

  .vf-reticle {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 54px;
    height: 54px;
    transform: translate(-50%, -50%);
    border: 1px solid rgba(250, 204, 21, 0.65);
    border-radius: 4px;
    transition: transform 0.12s ease-out;
  }
  .vf-reticle::before, .vf-reticle::after {
    content: "";
    position: absolute;
    background: var(--accent);
  }
  .vf-reticle::before { width: 8px; height: 1px; top: 50%; left: -4px; }
  .vf-reticle::after { width: 1px; height: 8px; left: 50%; top: -4px; }

  .vf-bottom-hud {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    z-index: 2;
  }

  .meter-readout {
    display: flex;
    gap: 12px;
    font-family: var(--mono);
    font-size: 12px;
    background: rgba(13, 14, 16, 0.78);
    backdrop-filter: blur(8px);
    padding: 6px 10px;
    border-radius: 8px;
    border: 1px solid rgba(255,255,255,0.1);
  }

  .meter-readout span b { color: var(--accent); font-weight: 700; }
  .meter-readout .dim { color: var(--muted); font-size: 10px; margin-right: 3px; }

  .shutter-flash {
    position: absolute;
    inset: 0;
    background: #fff;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.18s ease-out;
    z-index: 5;
  }
  .shutter-flash.fire { opacity: 0.85; transition: none; }

  /* Control Deck */
  .deck {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 18px;
    padding: 14px;
    display: flex;
    flex-direction: column;
    gap: 14px;
  }

  .param-tabs {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
  }

  .param-tab {
    min-height: 54px;
    border-radius: 12px;
    border: 1px solid var(--border);
    background: var(--surface-2);
    color: var(--muted);
    padding: 8px 10px;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    gap: 2px;
    transition: border-color 0.15s, background 0.15s, transform 0.1s;
    text-align: left;
  }

  .param-tab:active { transform: scale(0.98); }

  .param-tab[aria-selected="true"] {
    background: var(--accent-dim);
    border-color: var(--accent);
    color: var(--ink);
  }

  .param-tab .p-label {
    font-size: 10px;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: var(--muted);
  }
  .param-tab[aria-selected="true"] .p-label { color: var(--accent); }

  .param-tab .p-val {
    font-family: var(--mono);
    font-size: 15px;
    font-weight: 700;
    color: var(--ink);
  }

  /* Active readout header */
  .scrubber-header {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    padding: 0 2px;
  }

  .active-value {
    font-family: var(--mono);
    font-size: 28px;
    font-weight: 700;
    letter-spacing: -0.02em;
    color: var(--accent);
  }

  .active-hint {
    font-size: 11px;
    color: var(--muted);
    font-family: var(--mono);
  }

  /* Precision Tactile Ruler Scrubber */
  .ruler-wrap {
    position: relative;
    height: 86px;
    border-radius: 14px;
    background: #101216;
    border: 1px solid var(--border);
    overflow: hidden;
    touch-action: none;
    cursor: ew-resize;
    outline: none;
  }

  .ruler-wrap:focus-visible {
    border-color: var(--accent);
    box-shadow: 0 0 0 2px rgba(250, 204, 21, 0.25);
  }

  #rulerCanvas {
    width: 100%;
    height: 100%;
    display: block;
  }

  .ruler-needle {
    position: absolute;
    top: 8px;
    bottom: 8px;
    left: 50%;
    width: 2px;
    transform: translateX(-50%);
    background: var(--accent);
    box-shadow: 0 0 10px rgba(250, 204, 21, 0.8);
    pointer-events: none;
  }

  .ruler-needle::before {
    content: "";
    position: absolute;
    top: -4px;
    left: 50%;
    transform: translateX(-50%);
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 6px solid var(--accent);
  }

  .ruler-fade-l, .ruler-fade-r {
    position: absolute;
    top: 0; bottom: 0; width: 44px;
    pointer-events: none;
  }
  .ruler-fade-l { left: 0; background: linear-gradient(to right, #101216, transparent); }
  .ruler-fade-r { right: 0; background: linear-gradient(to left, #101216, transparent); }

  /* Rotary Dial + Actions Row */
  .dial-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding-top: 4px;
  }

  .rotary-wrap {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .rotary-dial {
    width: 72px;
    height: 72px;
    border-radius: 50%;
    background: radial-gradient(circle at 35% 30%, #2d3139, #15171c 75%);
    border: 2px solid rgba(255,255,255,0.12);
    box-shadow: inset 0 2px 6px rgba(255,255,255,0.08), 0 8px 18px rgba(0,0,0,0.45);
    position: relative;
    cursor: grab;
    touch-action: none;
    flex-shrink: 0;
  }

  .rotary-dial:active { cursor: grabbing; border-color: rgba(250,204,21,0.5); }

  .rotary-knurl {
    position: absolute;
    inset: 5px;
    border-radius: 50%;
    border: 2px dashed rgba(255,255,255,0.14);
    pointer-events: none;
  }

  .rotary-pip {
    position: absolute;
    top: 8px;
    left: 50%;
    width: 4px;
    height: 12px;
    margin-left: -2px;
    border-radius: 2px;
    background: var(--accent);
    box-shadow: 0 0 8px var(--accent);
    pointer-events: none;
  }

  .dial-meta {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  .dial-meta strong { font-size: 12px; font-weight: 600; color: var(--ink); }
  .dial-meta span { font-size: 11px; color: var(--muted); line-height: 1.35; }

  .shutter-cluster {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .reset-btn {
    min-width: 44px;
    min-height: 44px;
    padding: 0 12px;
    border-radius: 12px;
    border: 1px solid var(--border);
    background: var(--surface-2);
    color: var(--ink);
    font-family: var(--mono);
    font-size: 11px;
    font-weight: 600;
    cursor: pointer;
  }
  .reset-btn:hover { border-color: var(--accent); color: var(--accent); }

  .shutter-btn {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    border: 3px solid var(--ink);
    background: transparent;
    padding: 4px;
    cursor: pointer;
    flex-shrink: 0;
    transition: transform 0.1s;
  }
  .shutter-btn:active { transform: scale(0.92); }
  .shutter-btn-inner {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: var(--ink);
    display: block;
    transition: background 0.15s;
  }
  .shutter-btn:hover .shutter-btn-inner { background: var(--accent); }

  /* Preset quick strip */
  .preset-strip {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    border-top: 1px solid var(--border);
    padding-top: 12px;
  }

  .preset-chip {
    min-height: 36px;
    padding: 0 10px;
    border-radius: 8px;
    border: 1px solid var(--border);
    background: #121418;
    color: var(--muted);
    font-family: var(--mono);
    font-size: 11px;
    cursor: pointer;
    transition: all 0.15s;
  }
  .preset-chip:hover { color: var(--ink); border-color: rgba(255,255,255,0.22); }

  .footer-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 11px;
    color: var(--muted);
    font-family: var(--mono);
    padding: 0 4px;
    flex-wrap: wrap;
    gap: 8px;
  }
</style>
</head>
<body>
<div class="app">
  <header class="topbar">
    <div class="brand">
      <span class="brand-dot"></span>
      <span>HALIDE // MANUAL</span>
    </div>
    <div class="telemetry-pills">
      <button class="icon-btn" id="gridBtn" aria-pressed="true" title="Toggle Rule of Thirds Grid">GRID</button>
      <button class="icon-btn" id="zebraBtn" aria-pressed="false" title="Toggle Highlight Zebras">ZEBRA</button>
      <button class="icon-btn" id="soundBtn" aria-pressed="false" title="Toggle Tactile Detent Audio">
        <span id="soundLabel">TICK OFF</span>
      </button>
    </div>
  </header>

  <main class="workspace">
    <section class="viewfinder-shell" aria-label="Live Camera Viewfinder">
      <canvas id="viewfinder" width="960" height="720"></canvas>
      <div class="vf-grid visible" id="vfGrid"></div>
      <div class="vf-corners"></div>
      <div class="vf-reticle" id="vfReticle"></div>
      <div class="shutter-flash" id="shutterFlash"></div>
      <div class="vf-overlay">
        <div class="vf-top-hud">
          <div class="hud-badge">
            <span>RAW 14-BIT</span>
            <span class="accent" id="shotCounter">001</span>
          </div>
          <canvas id="histCanvas" width="96" height="36" aria-label="Live Luminance Histogram"></canvas>
        </div>
        <div class="vf-bottom-hud">
          <div class="meter-readout">
            <span><span class="dim">EV</span><b id="hudEv">+0.0</b></span>
            <span><span class="dim">WB</span><b id="hudWb">5200K</b></span>
            <span><span class="dim">ISO</span><b id="hudIso">200</b></span>
          </div>
          <div class="hud-badge">
            <span>28mm</span>
            <span>f/1.8</span>
          </div>
        </div>
      </div>
    </section>

    <section class="deck" aria-label="Manual Exposure Controls">
      <div class="param-tabs" role="tablist" aria-label="Camera Parameter">
        <button class="param-tab" role="tab" data-param="ev" aria-selected="true">
          <span class="p-label">Exposure</span>
          <span class="p-val" id="tabEv">+0.0 EV</span>
        </button>
        <button class="param-tab" role="tab" data-param="wb" aria-selected="false">
          <span class="p-label">White Bal</span>
          <span class="p-val" id="tabWb">5200K</span>
        </button>
        <button class="param-tab" role="tab" data-param="iso" aria-selected="false">
          <span class="p-label">ISO</span>
          <span class="p-val" id="tabIso">200</span>
        </button>
      </div>

      <div class="scrubber-header">
        <div class="active-value" id="activeReadout">+0.0 EV</div>
        <div class="active-hint">DRAG OR DOUBLE-TAP RESET</div>
      </div>

      <div class="ruler-wrap" id="rulerWrap" tabindex="0" role="slider" aria-label="Precision Ruler Scrubber" aria-valuemin="-3" aria-valuemax="3" aria-valuenow="0">
        <canvas id="rulerCanvas"></canvas>
        <div class="ruler-fade-l"></div>
        <div class="ruler-fade-r"></div>
        <div class="ruler-needle"></div>
      </div>

      <div class="dial-row">
        <div class="rotary-wrap">
          <div class="rotary-dial" id="rotaryDial" title="Drag circularly to fine-tune">
            <div class="rotary-knurl"></div>
            <div class="rotary-pip"></div>
          </div>
          <div class="dial-meta">
            <strong>Rotary Fine Dial</strong>
            <span>Twist ring or use ← / → keys for detent steps</span>
          </div>
        </div>

        <div class="shutter-cluster">
          <button class="reset-btn" id="resetAllBtn" title="Reset all parameters">RESET</button>
          <button class="shutter-btn" id="shutterBtn" aria-label="Capture Frame">
            <span class="shutter-btn-inner"></span>
          </button>
        </div>
      </div>

      <div class="preset-strip" aria-label="Lighting Presets">
        <button class="preset-chip" data-preset="neutral">Daylight 5200K</button>
        <button class="preset-chip" data-preset="golden">Golden Dusk</button>
        <button class="preset-chip" data-preset="tungsten">Tungsten Alley</button>
        <button class="preset-chip" data-preset="night">High-ISO Night</button>
      </div>
    </section>
  </main>

  <footer class="footer-bar">
    <span>DOUBLE-TAP RULER TO ZERO ACTIVE CHANNEL</span>
    <span id="statusText">READY · MANUAL METERING</span>
  </footer>
</div>

<script>
(() => {
  const PARAMS = {
    ev: {
      label: 'Exposure',
      min: -3.0, max: 3.0, step: 0.1, defaultVal: 0.0,
      majorEvery: 10, // every 1.0 EV
      format: v => `${v >= 0 ? '+' : ''}${v.toFixed(1)} EV`,
      short: v => `${v >= 0 ? '+' : ''}${v.toFixed(1)}`,
      tickLabel: v => `${v > 0 ? '+' : ''}${v.toFixed(0)}`
    },
    wb: {
      label: 'White Balance',
      min: 2800, max: 7500, step: 100, defaultVal: 5200,
      majorEvery: 5, // every 500K
      format: v => `${Math.round(v)}K`,
      short: v => `${Math.round(v)}K`,
      tickLabel: v => `${(v/1000).toFixed(1)}k`
    },
    iso: {
      label: 'ISO Sensitivity',
      min: 0, max: 18, step: 1, defaultVal: 6, // maps to realistic 1/3-stop ISO table
      values: [50,64,80,100,125,160,200,250,320,400,500,640,800,1000,1250,1600,2000,2500,3200],
      majorEvery: 3,
      format: idx => `ISO ${PARAMS.iso.values[Math.round(idx)]}`,
      short: idx => `${PARAMS.iso.values[Math.round(idx)]}`,
      tickLabel: idx => `${PARAMS.iso.values[Math.round(idx)]}`
    }
  };

  const state = {
    active: 'ev',
    ev: 0.0,
    wb: 5200,
    iso: 6, // index into PARAMS.iso.values -> 200
    grid: true,
    zebra: false,
    sound: false,
    shots: 1,
    dialAngle: 0
  };

  // Web Audio subtle mechanical detent click
  let audioCtx = null;
  function playTick(isMajor) {
    if (!state.sound) return;
    try {
      if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
      if (audioCtx.state === 'suspended') audioCtx.resume();
      const now = audioCtx.currentTime;
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      osc.type = 'triangle';
      osc.frequency.setValueAtTime(isMajor ? 1450 : 920, now);
      osc.frequency.exponentialRampToValueAtTime(220, now + 0.018);
      gain.gain.setValueAtTime(isMajor ? 0.07 : 0.035, now);
      gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.02);
      osc.connect(gain);
      gain.connect(audioCtx.destination);
      osc.start(now);
      osc.stop(now + 0.022);
    } catch (_) {}
  }

  // DOM refs
  const vfCanvas = document.getElementById('viewfinder');
  const vfCtx = vfCanvas.getContext('2d', { willReadFrequently: true });
  const histCanvas = document.getElementById('histCanvas');
  const histCtx = histCanvas.getContext('2d');
  const rulerCanvas = document.getElementById('rulerCanvas');
  const rulerCtx = rulerCanvas.getContext('2d');
  const rulerWrap = document.getElementById('rulerWrap');
  const rotaryDial = document.getElementById('rotaryDial');
  const activeReadout = document.getElementById('activeReadout');
  const hudEv = document.getElementById('hudEv');
  const hudWb = document.getElementById('hudWb');
  const hudIso = document.getElementById('hudIso');
  const tabEv = document.getElementById('tabEv');
  const tabWb = document.getElementById('tabWb');
  const tabIso = document.getElementById('tabIso');
  const statusText = document.getElementById('statusText');
  const vfReticle = document.getElementById('vfReticle');

  // Offscreen base architectural dusk scene (rendered once, graded in real time)
  const baseCanvas = document.createElement('canvas');
  baseCanvas.width = 480;
  baseCanvas.height = 360;
  const bCtx = baseCanvas.getContext('2d');

  function buildBaseScene() {
    const w = baseCanvas.width, h = baseCanvas.height;
    // Deep twilight sky gradient
    const sky = bCtx.createLinearGradient(0, 0, 0, h * 0.72);
    sky.addColorStop(0, '#101b33');
    sky.addColorStop(0.42, '#2b3a5c');
    sky.addColorStop(0.75, '#b86852');
    sky.addColorStop(1, '#f4b56a');
    bCtx.fillStyle = sky;
    bCtx.fillRect(0, 0, w, h);

    // Sun glow low on horizon
    const sun = bCtx.createRadialGradient(w * 0.66, h * 0.57, 4, w * 0.66, h * 0.57, 130);
    sun.addColorStop(0, 'rgba(255, 245, 210, 0.95)');
    sun.addColorStop(0.25, 'rgba(255, 198, 120, 0.55)');
    sun.addColorStop(1, 'rgba(255, 140, 80, 0)');
    bCtx.fillStyle = sun;
    bCtx.fillRect(0, 0, w, h);

    // Distant mountain ridge
    bCtx.fillStyle = '#23283c';
    bCtx.beginPath();
    bCtx.moveTo(0, h * 0.66);
    bCtx.lineTo(w * 0.18, h * 0.53);
    bCtx.lineTo(w * 0.36, h * 0.61);
    bCtx.lineTo(w * 0.54, h * 0.50);
    bCtx.lineTo(w * 0.78, h * 0.59);
    bCtx.lineTo(w, h * 0.52);
    bCtx.lineTo(w, h);
    bCtx.lineTo(0, h);
    bCtx.closePath();
    bCtx.fill();

    // Water reflection plane
    const water = bCtx.createLinearGradient(0, h * 0.66, 0, h);
    water.addColorStop(0, '#363b52');
    water.addColorStop(0.45, '#1e2436');
    water.addColorStop(1, '#0d111a');
    bCtx.fillStyle = water;
    bCtx.fillRect(0, h * 0.66, w, h * 0.34);

    // Shimmering water highlights
    for (let i = 0; i < 42; i++) {
      const y = h * 0.67 + i * 2.7;
      const spread = 16 + i * 1.6;
      const alpha = Math.max(0.05, 0.55 - i * 0.012);
      bCtx.fillStyle = `rgba(255, 210, 140, ${alpha})`;
      bCtx.fillRect(w * 0.66 - spread / 2 + Math.sin(i * 1.9) * 8, y, spread, 1.4);
    }

    // Modernist concrete bridge / pier silhouette & architectural towers
    bCtx.fillStyle = '#141720';
    // Left modernist tower
    bCtx.fillRect(36, 98, 72, 168);
    bCtx.fillStyle = '#1d2230';
    bCtx.fillRect(88, 98, 20, 168);
    // Warm lit architectural windows
    for (let r = 0; r < 8; r++) {
      for (let c = 0; c < 3; c++) {
        if ((r + c) % 3 === 0) continue;
        bCtx.fillStyle = (r * 3 + c) % 4 === 0 ? '#ffd89b' : 'rgba(245, 195, 130, 0.65)';
        bCtx.fillRect(46 + c * 14, 112 + r * 17, 8, 10);
      }
    }

    // Mid-left midrise
    bCtx.fillStyle = '#181c28';
    bCtx.fillRect(118, 152, 54, 114);
    for (let r = 0; r < 5; r++) {
      bCtx.fillStyle = 'rgba(180, 215, 255, 0.35)';
      bCtx.fillRect(126, 164 + r * 16, 38, 4);
    }

    // Foreground seawall & lamp post
    bCtx.fillStyle = '#0e1017';
    bCtx.fillRect(0, h * 0.78, w * 0.42, h * 0.22);
    bCtx.fillRect(w * 0.34, h * 0.55, 4, h * 0.25);
    // Lamp glow
    const lamp = bCtx.createRadialGradient(w * 0.34 + 2, h * 0.55, 1, w * 0.34 + 2, h * 0.55, 34);
    lamp.addColorStop(0, 'rgba(255, 240, 195, 1)');
    lamp.addColorStop(0.3, 'rgba(255, 200, 115, 0.45)');
    lamp.addColorStop(1, 'rgba(255, 180, 90, 0)');
    bCtx.fillStyle = lamp;
    bCtx.beginPath();
    bCtx.arc(w * 0.34 + 2, h * 0.55, 34, 0, Math.PI * 2);
    bCtx.fill();
  }

  buildBaseScene();
  const baseImageData = bCtx.getImageData(0, 0, baseCanvas.width, baseCanvas.height);

  // Render live graded viewfinder + histogram
  function renderViewfinder() {
    const w = baseCanvas.width, h = baseCanvas.height;
    const out = bCtx.createImageData(w, h);
    const src = baseImageData.data;
    const dst = out.data;

    // Exposure multiplier
    const isoVal = PARAMS.iso.values[Math.round(state.iso)];
    const isoGain = Math.pow(isoVal / 200, 0.22); // subtle exposure lift with higher ISO
    const evMult = Math.pow(2, state.ev * 0.62) * isoGain;

    // White Balance Kelvin shift relative to 5200K neutral
    const kNorm = (state.wb - 5200) / 2300; // -1.04 (cool) to +1.0 (warm)
    const rMult = 1 + kNorm * 0.28;
    const gMult = 1 + (kNorm > 0 ? kNorm * 0.04 : -kNorm * 0.03);
    const bMult = 1 - kNorm * 0.30;

    // Sensor grain scaled by ISO
    const noiseAmp = Math.max(0, (isoVal - 160) / 3200) * 38;

    const hist = new Uint32Array(32);
    let seed = 1337;

    for (let i = 0; i < src.length; i += 4) {
      let r = src[i] * evMult * rMult;
      let g = src[i + 1] * evMult * gMult;
      let b = src[i + 2] * evMult * bMult;

      if (noiseAmp > 0.5) {
        seed = (seed * 1664525 + 1013904223) | 0;
        const n = ((seed >>> 24) / 255 - 0.5) * noiseAmp;
        r += n; g += n; b += n;
      }

      // Filmic soft shoulder highlight roll-off
      r = r > 255 ? 255 : (r < 0 ? 0 : r);
      g = g > 255 ? 255 : (g < 0 ? 0 : g);
      b = b > 255 ? 255 : (b < 0 ? 0 : b);

      const lum = (0.299 * r + 0.587 * g + 0.114 * b);
      hist[Math.min(31, (lum / 8) | 0)]++;

      // Zebra highlight warning overlay
      if (state.zebra && lum > 238) {
        const px = (i >> 2) % w;
        const py = ((i >> 2) / w) | 0;
        if (((px + py) & 7) < 3) {
          r = 250; g = 204; b = 21;
        }
      }

      dst[i] = r;
      dst[i + 1] = g;
      dst[i + 2] = b;
      dst[i + 3] = 255;
    }

    const tempCanvas = document.createElement('canvas');
    tempCanvas.width = w;
    tempCanvas.height = h;
    tempCanvas.getContext('2d').putImageData(out, 0, 0);

    vfCtx.imageSmoothingEnabled = true;
    vfCtx.drawImage(tempCanvas, 0, 0, vfCanvas.width, vfCanvas.height);

    // Draw mini histogram
    histCtx.clearRect(0, 0, histCanvas.width, histCanvas.height);
    let maxBin = 1;
    for (let i = 0; i < 32; i++) if (hist[i] > maxBin) maxBin = hist[i];
    histCtx.fillStyle = 'rgba(250, 204, 21, 0.85)';
    const bw = histCanvas.width / 32;
    for (let i = 0; i < 32; i++) {
      const bh = (hist[i] / maxBin) * (histCanvas.height - 4);
      histCtx.fillRect(i * bw, histCanvas.height - bh, Math.max(1, bw - 0.8), bh);
    }
  }

  // Draw tactile ruler canvas
  const PX_PER_STEP = 14;
  function renderRuler() {
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const rect = rulerWrap.getBoundingClientRect();
    const w = Math.max(200, Math.round(rect.width));
    const h = Math.max(70, Math.round(rect.height));
    if (rulerCanvas.width !== w * dpr || rulerCanvas.height !== h * dpr) {
      rulerCanvas.width = w * dpr;
      rulerCanvas.height = h * dpr;
    }
    rulerCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
    rulerCtx.clearRect(0, 0, w, h);

    const cfg = PARAMS[state.active];
    const current = state[state.active];
    const totalSteps = Math.round((cfg.max - cfg.min) / cfg.step);
    const currentStep = (current - cfg.min) / cfg.step;
    const centerX = w / 2;

    rulerCtx.font = '600 10px ui-monospace, SFMono-Regular, Menlo, monospace';
    rulerCtx.textAlign = 'center';

    for (let s = 0; s <= totalSteps; s++) {
      const x = centerX + (s - currentStep) * PX_PER_STEP;
      if (x < -20 || x > w + 20) continue;

      const isMajor = s % cfg.majorEvery === 0;
      const isDefault = Math.abs((cfg.min + s * cfg.step) - cfg.defaultVal) < cfg.step * 0.25;
      const dist = Math.abs(x - centerX);
      const nearCenter = dist < PX_PER_STEP * 0.6;

      rulerCtx.strokeStyle = nearCenter
        ? '#FACC15'
        : isMajor
          ? 'rgba(244, 244, 245, 0.72)'
          : 'rgba(142, 146, 155, 0.38)';
      rulerCtx.lineWidth = isMajor ? 1.6 : 1;

      const tickH = isMajor ? 28 : 14;
      const yTop = h - 14 - tickH;
      rulerCtx.beginPath();
      rulerCtx.moveTo(Math.round(x) + 0.5, h - 14);
      rulerCtx.lineTo(Math.round(x) + 0.5, yTop);
      rulerCtx.stroke();

      if (isDefault) {
        rulerCtx.fillStyle = '#FACC15';
        rulerCtx.beginPath();
        rulerCtx.arc(x, h - 7, 2.2, 0, Math.PI * 2);
        rulerCtx.fill();
      }

      if (isMajor) {
        const val = cfg.min + s * cfg.step;
        rulerCtx.fillStyle = nearCenter ? '#FACC15' : '#8E929B';
        rulerCtx.fillText(cfg.tickLabel(val), x, 22);
      }
    }
  }

  function updateUI(silent = false) {
    const cfg = PARAMS[state.active];
    const val = state[state.active];

    activeReadout.textContent = cfg.format(val);
    hudEv.textContent = PARAMS.ev.short(state.ev);
    hudWb.textContent = PARAMS.wb.short(state.wb);
    hudIso.textContent = PARAMS.iso.short(state.iso);

    tabEv.textContent = PARAMS.ev.format(state.ev);
    tabWb.textContent = PARAMS.wb.format(state.wb);
    tabIso.textContent = PARAMS.iso.short(state.iso);

    rulerWrap.setAttribute('aria-valuemin', cfg.min);
    rulerWrap.setAttribute('aria-valuemax', cfg.max);
    rulerWrap.setAttribute('aria-valuenow', val);

    rotaryDial.style.transform = `rotate(${state.dialAngle}deg)`;

    renderRuler();
    renderViewfinder();
    if (!silent) {
      statusText.textContent = `${cfg.label.toUpperCase()} · ${cfg.format(val)}`;
    }
  }

  function stepValue(deltaSteps) {
    const cfg = PARAMS[state.active];
    const prevStep = Math.round((state[state.active] - cfg.min) / cfg.step);
    const totalSteps = Math.round((cfg.max - cfg.min) / cfg.step);
    const nextStep = Math.max(0, Math.min(totalSteps, prevStep + deltaSteps));
    if (nextStep !== prevStep) {
      state[state.active] = Number((cfg.min + nextStep * cfg.step).toFixed(4));
      state.dialAngle += deltaSteps * 15;
      playTick(nextStep % cfg.majorEvery === 0);
      updateUI();
    }
  }

  // Ruler pointer drag + double-tap reset
  let dragging = false;
  let dragStartX = 0;
  let dragStartVal = 0;
  let lastNotch = 0;
  let lastTapTime = 0;

  rulerWrap.addEventListener('pointerdown', e => {
    const now = performance.now();
    if (now - lastTapTime < 280) {
      // Double-tap reset active parameter
      const cfg = PARAMS[state.active];
      state[state.active] = cfg.defaultVal;
      state.dialAngle = 0;
      playTick(true);
      updateUI();
      statusText.textContent = `RESET ${cfg.label.toUpperCase()} TO NEUTRAL`;
      lastTapTime = 0;
      return;
    }
    lastTapTime = now;

    dragging = true;
    dragStartX = e.clientX;
    dragStartVal = state[state.active];
    const cfg = PARAMS[state.active];
    lastNotch = Math.round((dragStartVal - cfg.min) / cfg.step);
    rulerWrap.setPointerCapture(e.pointerId);
    vfReticle.style.transform = 'translate(-50%, -50%) scale(0.92)';
  });

  rulerWrap.addEventListener('pointermove', e => {
    if (!dragging) return;
    const cfg = PARAMS[state.active];
    const dx = dragStartX - e.clientX; // pull left increases value like moving a physical scale
    const stepsMoved = Math.round(dx / PX_PER_STEP);
    const totalSteps = Math.round((cfg.max - cfg.min) / cfg.step);
    const startStep = Math.round((dragStartVal - cfg.min) / cfg.step);
    const targetStep = Math.max(0, Math.min(totalSteps, startStep + stepsMoved));

    if (targetStep !== lastNotch) {
      const diff = targetStep - lastNotch;
      lastNotch = targetStep;
      state[state.active] = Number((cfg.min + targetStep * cfg.step).toFixed(4));
      state.dialAngle += diff * 14;
      playTick(targetStep % cfg.majorEvery === 0);
      updateUI();
    }
  });

  const endRulerDrag = () => {
    if (!dragging) return;
    dragging = false;
    vfReticle.style.transform = 'translate(-50%, -50%) scale(1)';
  };
  rulerWrap.addEventListener('pointerup', endRulerDrag);
  rulerWrap.addEventListener('pointercancel', endRulerDrag);

  // Wheel support on ruler
  rulerWrap.addEventListener('wheel', e => {
    e.preventDefault();
    const dir = (Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY) > 0 ? 1 : -1;
    stepValue(dir);
  }, { passive: false });

  // Keyboard support on ruler
  rulerWrap.addEventListener('keydown', e => {
    if (e.key === 'ArrowRight' || e.key === 'ArrowUp') { e.preventDefault(); stepValue(1); }
    else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') { e.preventDefault(); stepValue(-1); }
    else if (e.key === '0' || e.key === 'Home') {
      e.preventDefault();
      state[state.active] = PARAMS[state.active].defaultVal;
      playTick(true);
      updateUI();
    }
  });

  // Rotary dial circular drag
  let dialDragging = false;
  let lastAngle = 0;
  let accumAngle = 0;

  function getAngle(el, cx, cy) {
    const r = el.getBoundingClientRect();
    return Math.atan2(cy - (r.top + r.height / 2), cx - (r.left + r.width / 2)) * 180 / Math.PI;
  }

  rotaryDial.addEventListener('pointerdown', e => {
    dialDragging = true;
    lastAngle = getAngle(rotaryDial, e.clientX, e.clientY);
    accumAngle = 0;
    rotaryDial.setPointerCapture(e.pointerId);
  });

  rotaryDial.addEventListener('pointermove', e => {
    if (!dialDragging) return;
    const cur = getAngle(rotaryDial, e.clientX, e.clientY);
    let delta = cur - lastAngle;
    if (delta > 180) delta -= 360;
    if (delta < -180) delta += 360;
    lastAngle = cur;
    accumAngle += delta;

    const STEP_DEG = 16;
    if (Math.abs(accumAngle) >= STEP_DEG) {
      const steps = Math.trunc(accumAngle / STEP_DEG);
      accumAngle -= steps * STEP_DEG;
      stepValue(steps);
    }
  });

  rotaryDial.addEventListener('pointerup', () => { dialDragging = false; });
  rotaryDial.addEventListener('pointercancel', () => { dialDragging = false; });

  // Tabs
  document.querySelectorAll('.param-tab').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.param-tab').forEach(b => b.setAttribute('aria-selected', 'false'));
      btn.setAttribute('aria-selected', 'true');
      state.active = btn.dataset.param;
      playTick(true);
      updateUI();
    });
  });

  // Toggles
  document.getElementById('gridBtn').addEventListener('click', e => {
    state.grid = !state.grid;
    e.currentTarget.setAttribute('aria-pressed', String(state.grid));
    document.getElementById('vfGrid').classList.toggle('visible', state.grid);
  });

  document.getElementById('zebraBtn').addEventListener('click', e => {
    state.zebra = !state.zebra;
    e.currentTarget.setAttribute('aria-pressed', String(state.zebra));
    renderViewfinder();
  });

  document.getElementById('soundBtn').addEventListener('click', e => {
    state.sound = !state.sound;
    e.currentTarget.setAttribute('aria-pressed', String(state.sound));
    document.getElementById('soundLabel').textContent = state.sound ? 'TICK ON' : 'TICK OFF';
    if (state.sound) playTick(true);
  });

  // Reset All
  document.getElementById('resetAllBtn').addEventListener('click', () => {
    state.ev = PARAMS.ev.defaultVal;
    state.wb = PARAMS.wb.defaultVal;
    state.iso = PARAMS.iso.defaultVal;
    state.dialAngle = 0;
    playTick(true);
    updateUI();
    statusText.textContent = 'ALL CHANNELS ZEROED';
  });

  // Shutter capture
  document.getElementById('shutterBtn').addEventListener('click', () => {
    const flash = document.getElementById('shutterFlash');
    flash.classList.add('fire');
    requestAnimationFrame(() => requestAnimationFrame(() => flash.classList.remove('fire')));
    state.shots++;
    document.getElementById('shotCounter').textContent = String(state.shots).padStart(3, '0');
    playTick(true);
    statusText.textContent = `CAPTURED DNG #${String(state.shots).padStart(3, '0')} · ${PARAMS.ev.short(state.ev)}EV ${state.wb}K`;
  });

  // Presets
  const PRESETS = {
    neutral: { ev: 0.0, wb: 5200, iso: 6, label: 'DAYLIGHT NEUTRAL' },
    golden: { ev: 0.4, wb: 6800, iso: 4, label: 'GOLDEN DUSK' },
    tungsten: { ev: -0.5, wb: 3300, iso: 11, label: 'TUNGSTEN ALLEY' },
    night: { ev: -1.1, wb: 4100, iso: 17, label: 'HIGH-ISO NIGHT' }
  };

  document.querySelectorAll('.preset-chip').forEach(chip => {
    chip.addEventListener('click', () => {
      const p = PRESETS[chip.dataset.preset];
      state.ev = p.ev;
      state.wb = p.wb;
      state.iso = p.iso;
      playTick(true);
      updateUI(true);
      statusText.textContent = `PRESET APPLIED · ${p.label}`;
    });
  });

  window.addEventListener('resize', renderRuler);
  updateUI(true);
})();
</script>
</body>
</html>
```
