Quantum Visual LabPhysics, made visible
Back to the lab
Source & architecture

The code behind
the laboratory

Every experiment on this site is generated from the physics core below. The excerpts are the real files, not illustrations: read the equations, the sampling loop and the rendering budget that make each canvas run at 60 frames per second.

Curated excerpts
5 files
1633 lines listed
Physics source
137 lines
physics.ts · fully typed
License
MIT
reuse in classrooms
Repository

The lab is maintained in a private Next.js workspace while the public mirror is prepared. This page is the canonical, readable listing of the physics and rendering code until then.

GitHub profile
FrameworkNext.js 15 (App Router)
RenderingCanvas 2D + p5.js 1.11
StylingTailwind CSS 3.4
MotionFramer Motion 12
Runtime deps0 external APIs
BuildFully static output
Next.js 15p5.jsCanvas APITailwind CSSFramer Motion
src/lib/physics.ts137 linesEvery formula used by the three simulations: Fraunhofer intensity, fringe spacing, box eigenstates, exact time evolution, expectation values and the uncertainty relation.View
Physics core
/**
 * Physics core for Quantum Visual Lab.
 *
 * Units:
 *  - Double slit: SI (metres). d, a, lambda and L are metres, y is metres on the screen.
 *  - Schrödinger well: natural units with ħ = 1, 2m = 1 and box width L = 1.
 *  - Uncertainty: natural units with ħ = 1.
 */

export const SCREEN_HALF_WIDTH_M = 0.004; // visible screen window: ±4 mm
export const HBAR = 1;

export type DoubleSlitParams = {
  /** slit separation, metres */
  d: number;
  /** wavelength, metres */
  lambda: number;
  /** slit width, metres */
  a: number;
  /** slit-to-screen distance, metres */
  L: number;
};

/** Fraunhofer double-slit intensity, normalised to 1 at the centre. */
export function doubleSlitIntensity(y: number, p: DoubleSlitParams): number {
  const sinTheta = y / Math.hypot(y, p.L);
  const alpha = (Math.PI * p.d * sinTheta) / p.lambda;
  const beta = (Math.PI * p.a * sinTheta) / p.lambda;
  const envelope = beta === 0 ? 1 : Math.sin(beta) / beta;
  return Math.cos(alpha) ** 2 * envelope ** 2;
}

/** Distance between adjacent bright fringes on the screen, metres. */
export function fringeSpacing(d: number, lambda: number, L: number): number {
  return (lambda * L) / d;
}

/** Order of the outermost visible maximum inside the screen window. */
export function visibleOrders(d: number, lambda: number, L: number): number {
  const sinThetaMax = SCREEN_HALF_WIDTH_M / Math.hypot(SCREEN_HALF_WIDTH_M, L);
  return Math.floor((d * sinThetaMax) / lambda);
}

/** Infinite-square-well eigenfunction (normalised, x in [0, 1]). */
export function boxEigenfunction(n: number, x: number): number {
  return Math.SQRT2 * Math.sin(n * Math.PI * x);
}

/** Energy of level n in units of E1. */
export function boxEnergy(n: number): number {
  return n * n;
}

export type ComplexWave = { re: number; im: number; abs2: number };

/**
 * Exact time evolution of a superposition of the first five box eigenstates,
 * ψ(x,t) = Σ c_k φ_k(x) e^(-i E_k t) / ‖c‖, with E_k = k² (ħ = 2m = L = 1).
 * The slider n sets the centre of the spectral mixture, so higher n means
 * higher energy, more nodes and faster motion.
 */
export function boxWave(
  x: number,
  t: number,
  n: number,
  mixing = 1.05,
): ComplexWave {
  let re = 0;
  let im = 0;
  let norm = 0;
  for (let k = 1; k <= 5; k++) {
    const c = Math.exp(-0.5 * ((k - n) / mixing) ** 2);
    const phi = boxEigenfunction(k, x);
    const phase = -boxEnergy(k) * t;
    re += c * phi * Math.cos(phase);
    im += c * phi * Math.sin(phase);
    norm += c * c;
  }
  norm = Math.sqrt(norm);
  re /= norm;
  im /= norm;
  return { re, im, abs2: re * re + im * im };
}

export function boxCoefficients(n: number, mixing = 1.05) {
  const raw: number[] = [];
  let norm = 0;
  for (let k = 1; k <= 5; k++) {
    const c = Math.exp(-0.5 * ((k - n) / mixing) ** 2);
    raw.push(c);
    norm += c * c;
  }
  norm = Math.sqrt(norm);
  return raw.map((c, i) => ({
    k: i + 1,
    c: c / norm,
    weight: (c * c) / (norm * norm),
  }));
}

/** ⟨E⟩ in units of E1 for the mixture centred on n. */
export function meanEnergy(n: number, mixing = 1.05): number {
  return boxCoefficients(n, mixing).reduce((s, { k, weight }) => s + weight * k * k, 0);
}

/** ⟨x⟩ for a box wavefunction, via Simpson integration on [0,1]. */
export function meanPosition(t: number, n: number, mixing = 1.05): number {
  const steps = 240;
  let sum = 0;
  for (let i = 0; i <= steps; i++) {
    const x = i / steps;
    const { abs2 } = boxWave(x, t, n, mixing);
    const w = i === 0 || i === steps ? 1 : i % 2 === 0 ? 2 : 4;
    sum += w * x * abs2;
  }
  return (sum * (1 / steps)) / 3;
}

/** Minimum-uncertainty momentum spread for a given position spread (ħ = 1). */
export function momentumSpread(dx: number): number {
  return HBAR / (2 * dx);
}

export function clamp(value: number, min: number, max: number): number {
  return Math.min(max, Math.max(min, value));
}

export function formatSI(value: number, digits = 2): string {
  if (value === 0) return "0";
  const abs = Math.abs(value);
  if (abs < 1e-9) return `${(value * 1e12).toFixed(digits)} pm`;
  if (abs < 1e-6) return `${(value * 1e9).toFixed(digits)} nm`;
  if (abs < 1e-3) return `${(value * 1e6).toFixed(digits)} µm`;
  if (abs < 1) return `${(value * 1e3).toFixed(digits)} mm`;
  return `${value.toFixed(digits)} m`;
}
src/lib/use-canvas-animation.ts102 linesDevice-pixel-ratio aware Canvas 2D loop. Pauses off-screen and under prefers-reduced-motion, and repaints when props change.View
Canvas hook
"use client";

import { useEffect, useRef } from "react";

type DrawFn = (
  ctx: CanvasRenderingContext2D,
  width: number,
  height: number,
  time: number,
  dt: number,
) => void;

/**
 * Sets up a DPR-aware canvas with a resize observer, pauses off-screen work,
 * and respects prefers-reduced-motion (still redrawing when props change).
 */
export function useCanvasAnimation(draw: DrawFn, options?: { paused?: boolean }) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const drawRef = useRef<DrawFn>(draw);
  const pausedRef = useRef<boolean>(Boolean(options?.paused));
  const reducedRef = useRef(false);
  const ctxRef = useRef<CanvasRenderingContext2D | null>(null);
  const sizeRef = useRef({ w: 0, h: 0 });
  const timeRef = useRef(0);

  drawRef.current = draw;
  pausedRef.current = Boolean(options?.paused);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    ctxRef.current = ctx;
    reducedRef.current =
      typeof window !== "undefined" &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    let raf = 0;
    let visible = true;
    let last = performance.now();
    const dpr = Math.min(typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1, 2);

    const render = (time: number, dt: number) => {
      const { w, h } = sizeRef.current;
      if (w > 0 && h > 0) drawRef.current(ctx, w, h, time, dt);
    };

    const resize = () => {
      const rect = canvas.getBoundingClientRect();
      const w = Math.max(1, Math.round(rect.width));
      const h = Math.max(1, Math.round(rect.height));
      sizeRef.current = { w, h };
      canvas.width = Math.round(w * dpr);
      canvas.height = Math.round(h * dpr);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      render(timeRef.current, 0);
    };

    const observer = new ResizeObserver(resize);
    observer.observe(canvas);
    resize();

    const intersection = new IntersectionObserver(
      (entries) => {
        visible = entries[0]?.isIntersecting ?? true;
      },
      { rootMargin: "160px" },
    );
    intersection.observe(canvas);

    const loop = (now: number) => {
      raf = requestAnimationFrame(loop);
      const dt = Math.min(0.05, (now - last) / 1000);
      last = now;
      if (!visible || pausedRef.current || reducedRef.current) return;
      timeRef.current += dt;
      render(timeRef.current, dt);
    };
    raf = requestAnimationFrame(loop);

    return () => {
      cancelAnimationFrame(raf);
      observer.disconnect();
      intersection.disconnect();
      ctxRef.current = null;
    };
  }, []);

  // Keep the canvas fresh when a slider changes while paused / reduced motion.
  useEffect(() => {
    const ctx = ctxRef.current;
    const { w, h } = sizeRef.current;
    if (ctx && w > 0 && h > 0) {
      drawRef.current(ctx, w, h, timeRef.current, 0);
    }
  });

  return canvasRef;
}
src/components/simulations/double-slit.tsx425 linesWavefront schematic plus live intensity profile, drawn from doubleSlitIntensity().View
Double slit
"use client";

import { useMemo, useState } from "react";
import { Slider } from "@/components/slider";
import { useCanvasAnimation } from "@/lib/use-canvas-animation";
import {
  SCREEN_HALF_WIDTH_M,
  doubleSlitIntensity,
  formatSI,
  fringeSpacing,
  visibleOrders,
} from "@/lib/physics";

const DEFAULTS = { dUm: 0.35, lambdaNm: 550, L: 0.6 };

function Readout({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-xl border border-white/[0.07] bg-white/[0.025] px-3 py-2">
      <div className="font-mono text-[8.5px] uppercase tracking-[0.16em] text-slate-500">
        {label}
      </div>
      <div className="mt-0.5 font-mono text-[12px] tabular-nums text-slate-200">
        {value}
      </div>
    </div>
  );
}

export function DoubleSlitSim() {
  const [dUm, setDUm] = useState(DEFAULTS.dUm);
  const [lambdaNm, setLambdaNm] = useState(DEFAULTS.lambdaNm);
  const [L, setL] = useState(DEFAULTS.L);

  const d = dUm * 1e-6;
  const lambda = lambdaNm * 1e-9;
  const a = Math.max(2e-8, Math.min(1.2e-7, d * 0.22));

  const params = useMemo(() => ({ d, lambda, a, L }), [d, lambda, a, L]);
  const spacing = fringeSpacing(d, lambda, L);
  const orders = visibleOrders(d, lambda, L);

  const drawSchematic = (
    ctx: CanvasRenderingContext2D,
    w: number,
    h: number,
    t: number,
  ) => {
    ctx.clearRect(0, 0, w, h);

    const cy = h * 0.5;
    const halfRegion = h * 0.41;
    const barrierX = Math.round(w * 0.34);
    const screenX = Math.round(w * 0.9);
    const sepPx = 26 + ((dUm - 0.1) / 0.9) * (h * 0.3);
    const y1 = cy - sepPx / 2;
    const y2 = cy + sepPx / 2;
    const lambdaPx = 7 + ((lambdaNm - 400) / 300) * 11;

    // ---- incoming plane wave ----
    const travel = (t * 26) % lambdaPx;
    for (let x = 10 + travel; x < barrierX - 7; x += lambdaPx) {
      const fade = (x - 10) / Math.max(1, barrierX - 20);
      ctx.strokeStyle = `rgba(56,189,248,${0.05 + 0.22 * fade})`;
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(x, cy - halfRegion);
      ctx.lineTo(x, cy + halfRegion);
      ctx.stroke();
    }

    // coherent source
    ctx.save();
    ctx.shadowColor = "#38BDF8";
    ctx.shadowBlur = 12;
    ctx.fillStyle = "rgba(186,230,253,0.95)";
    ctx.beginPath();
    ctx.arc(8, cy, 2.4, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();

    // ---- wavefronts from each slit ----
    ctx.save();
    ctx.beginPath();
    ctx.rect(barrierX + 1, 6, screenX - barrierX - 4, h - 12);
    ctx.clip();
    ctx.globalCompositeOperation = "lighter";
    const maxR = Math.hypot(screenX - barrierX, h * 0.75) + lambdaPx;
    const sources: Array<[number, string]> = [
      [y1, "56,189,248"],
      [y2, "167,139,250"],
    ];
    for (const [sy, rgb] of sources) {
      const offset = (t * 30) % (lambdaPx * 1.35);
      for (let r = offset; r < maxR; r += lambdaPx * 1.35) {
        if (r < 3) continue;
        const alpha = 0.19 * Math.pow(1 - r / maxR, 1.15);
        ctx.strokeStyle = `rgba(${rgb},${alpha})`;
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.arc(barrierX, sy, r, -Math.PI / 2, Math.PI / 2);
        ctx.stroke();
      }
    }
    ctx.restore();

    // ---- barrier with two slits ----
    const bw = 10;
    const gap = 3.5;
    const segments: Array<[number, number]> = [
      [7, y1 - gap],
      [y1 + gap, y2 - gap],
      [y2 + gap, h - 7],
    ];
    for (const [top, bottom] of segments) {
      if (bottom <= top) continue;
      ctx.fillStyle = "#050b18";
      ctx.strokeStyle = "rgba(148,163,184,0.32)";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.rect(barrierX - bw / 2, top, bw, bottom - top);
      ctx.fill();
      ctx.stroke();
    }

    // slit mouths glow
    ctx.save();
    ctx.shadowColor = "#38BDF8";
    ctx.shadowBlur = 14;
    ctx.strokeStyle = "rgba(186,230,253,0.9)";
    ctx.lineWidth = 1.4;
    for (const sy of [y1, y2]) {
      ctx.beginPath();
      ctx.moveTo(barrierX - bw / 2 - 4, sy);
      ctx.lineTo(barrierX + bw / 2 + 4, sy);
      ctx.stroke();
    }
    ctx.restore();

    // separation indicator
    if (sepPx > 24) {
      const ax = barrierX - 22;
      ctx.strokeStyle = "rgba(167,139,250,0.5)";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(ax, y1);
      ctx.lineTo(ax, y2);
      ctx.moveTo(ax - 3, y1);
      ctx.lineTo(ax + 3, y1);
      ctx.moveTo(ax - 3, y2);
      ctx.lineTo(ax + 3, y2);
      ctx.stroke();
      ctx.fillStyle = "rgba(196,181,253,0.9)";
      ctx.font = "10px ui-monospace, SFMono-Regular, monospace";
      ctx.textAlign = "center";
      ctx.fillText("d", ax - 8, cy + 3.5);
    }

    // ---- screen ----
    const stripW = 7;
    ctx.fillStyle = "rgba(255,255,255,0.045)";
    ctx.fillRect(screenX - 2, 8, stripW + 4, h - 16);

    for (let y = 9; y < h - 8; y += 2) {
      const yM = ((y - cy) / halfRegion) * SCREEN_HALF_WIDTH_M;
      const intensity = doubleSlitIntensity(yM, params);
      if (intensity < 0.0006) continue;
      const alpha = Math.pow(intensity, 0.78);
      ctx.fillStyle = `rgba(125,211,252,${0.08 + 0.88 * alpha})`;
      ctx.fillRect(screenX, y, stripW, 2);
      ctx.fillStyle = `rgba(56,189,248,${0.15 * alpha})`;
      ctx.fillRect(screenX - 8, y, stripW + 16, 2);
    }

    // screen edge
    ctx.strokeStyle = "rgba(148,163,184,0.22)";
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(screenX + stripW + 6, 8);
    ctx.lineTo(screenX + stripW + 6, h - 8);
    ctx.stroke();

    // ---- labels ----
    ctx.font = "9px ui-monospace, SFMono-Regular, monospace";
    ctx.fillStyle = "rgba(148,163,184,0.55)";
    ctx.textAlign = "center";
    ctx.fillText("coherent light", (12 + barrierX) / 2, 16);
    ctx.fillText("double slit", barrierX, h - 5);
    ctx.fillText("screen", screenX + 2, h - 5);
    ctx.textAlign = "left";
    ctx.fillText("I(y)", screenX + stripW + 11, 16);
  };

  const drawGraph = (
    ctx: CanvasRenderingContext2D,
    w: number,
    h: number,
  ) => {
    ctx.clearRect(0, 0, w, h);

    const m = { l: 34, r: 14, t: 20, b: 28 };
    const pw = Math.max(10, w - m.l - m.r);
    const ph = Math.max(10, h - m.t - m.b);
    const left = m.l;
    const top = m.t;
    const bottom = top + ph;
    const right = left + pw;

    // grid
    ctx.strokeStyle = "rgba(255,255,255,0.055)";
    ctx.lineWidth = 1;
    for (let i = 0; i <= 4; i++) {
      const y = top + (i / 4) * ph;
      ctx.beginPath();
      ctx.moveTo(left, y);
      ctx.lineTo(right, y);
      ctx.stroke();
    }
    for (let i = 0; i <= 8; i++) {
      const x = left + (i / 8) * pw;
      ctx.beginPath();
      ctx.moveTo(x, top);
      ctx.lineTo(x, bottom);
      ctx.stroke();
    }

    // axes
    ctx.strokeStyle = "rgba(148,163,184,0.35)";
    ctx.beginPath();
    ctx.moveTo(left, top);
    ctx.lineTo(left, bottom);
    ctx.lineTo(right, bottom);
    ctx.stroke();

    // intensity curve
    const gamma = 0.72;
    const samples = Math.max(260, Math.floor(pw * 2));
    const xs: number[] = [];
    const ys: number[] = [];
    for (let i = 0; i <= samples; i++) {
      const frac = i / samples;
      const yM = -SCREEN_HALF_WIDTH_M + frac * 2 * SCREEN_HALF_WIDTH_M;
      const intensity = Math.pow(doubleSlitIntensity(yM, params), gamma);
      xs.push(left + frac * pw);
      ys.push(bottom - intensity * ph);
    }

    const fill = ctx.createLinearGradient(0, top, 0, bottom);
    fill.addColorStop(0, "rgba(56,189,248,0.34)");
    fill.addColorStop(0.6, "rgba(56,189,248,0.09)");
    fill.addColorStop(1, "rgba(56,189,248,0.01)");
    ctx.beginPath();
    ctx.moveTo(xs[0], bottom);
    for (let i = 0; i < xs.length; i++) ctx.lineTo(xs[i], ys[i]);
    ctx.lineTo(xs[xs.length - 1], bottom);
    ctx.closePath();
    ctx.fillStyle = fill;
    ctx.fill();

    ctx.save();
    ctx.shadowColor = "rgba(56,189,248,0.9)";
    ctx.shadowBlur = 9;
    ctx.strokeStyle = "#7DD3FC";
    ctx.lineWidth = 1.4;
    ctx.beginPath();
    for (let i = 0; i < xs.length; i++) {
      if (i === 0) ctx.moveTo(xs[i], ys[i]);
      else ctx.lineTo(xs[i], ys[i]);
    }
    ctx.stroke();
    ctx.restore();

    // fringe maxima ticks
    const maxOrder = Math.min(30, Math.ceil((d * 0.0067) / lambda));
    for (let order = 1; order <= maxOrder; order++) {
      const ratio = (order * lambda) / d;
      if (ratio >= 1) break;
      const yM = L * Math.tan(Math.asin(ratio));
      if (Math.abs(yM) > SCREEN_HALF_WIDTH_M) break;
      const x = left + ((yM + SCREEN_HALF_WIDTH_M) / (2 * SCREEN_HALF_WIDTH_M)) * pw;
      ctx.strokeStyle = "rgba(167,139,250,0.3)";
      ctx.beginPath();
      ctx.moveTo(x, top);
      ctx.lineTo(x, top + 5);
      ctx.moveTo(left + (( -yM + SCREEN_HALF_WIDTH_M) / (2 * SCREEN_HALF_WIDTH_M)) * pw, top);
      ctx.lineTo(left + ((-yM + SCREEN_HALF_WIDTH_M) / (2 * SCREEN_HALF_WIDTH_M)) * pw, top + 5);
      ctx.stroke();
    }

    // labels
    ctx.font = "9px ui-monospace, SFMono-Regular, monospace";
    ctx.fillStyle = "rgba(148,163,184,0.55)";
    ctx.textAlign = "center";
    for (let mm = -4; mm <= 4; mm += 2) {
      const x = left + ((mm / 1000 + SCREEN_HALF_WIDTH_M) / (2 * SCREEN_HALF_WIDTH_M)) * pw;
      ctx.fillText(`${mm}`, x, bottom + 14);
      ctx.strokeStyle = "rgba(148,163,184,0.25)";
      ctx.beginPath();
      ctx.moveTo(x, bottom);
      ctx.lineTo(x, bottom + 3);
      ctx.stroke();
    }
    ctx.fillText("position on screen y (mm)", left + pw / 2, h - 4);

    ctx.textAlign = "right";
    ctx.fillText("I / Imax", left - 4, top + 3);
    ctx.textAlign = "left";
    ["0", "0.5", "1"].forEach((label, i) => {
      const y = bottom - (i / 2) * ph;
      ctx.fillText(label, left - 17, y + 3);
    });

    // centre marker
    ctx.strokeStyle = "rgba(255,255,255,0.16)";
    ctx.setLineDash([2, 4]);
    ctx.beginPath();
    ctx.moveTo(left + pw / 2, top);
    ctx.lineTo(left + pw / 2, bottom);
    ctx.stroke();
    ctx.setLineDash([]);
  };

  const schematicRef = useCanvasAnimation(drawSchematic);
  const graphRef = useCanvasAnimation(drawGraph);

  const reset = () => {
    setDUm(DEFAULTS.dUm);
    setLambdaNm(DEFAULTS.lambdaNm);
    setL(DEFAULTS.L);
  };

  return (
    <div>
      <div className="grid gap-3 md:grid-cols-2">
        <div className="overflow-hidden rounded-2xl border border-white/[0.07] bg-[#060b16]/70">
          <div className="flex items-center justify-between border-b border-white/[0.06] px-3 py-2">
            <span className="font-mono text-[9px] uppercase tracking-[0.18em] text-slate-500">
              Wavefront model
            </span>
            <span className="chip">not to scale</span>
          </div>
          <canvas
            ref={schematicRef}
            className="block h-[236px] w-full sm:h-[268px]"
            role="img"
            aria-label="Animated double slit schematic. Plane waves strike a barrier with two slits and interfere on a screen."
          />
        </div>

        <div className="overflow-hidden rounded-2xl border border-white/[0.07] bg-[#060b16]/70">
          <div className="flex items-center justify-between border-b border-white/[0.06] px-3 py-2">
            <span className="font-mono text-[9px] uppercase tracking-[0.18em] text-slate-500">
              Intensity on screen
            </span>
            <span className="rounded-md border border-sky-300/20 bg-sky-400/[0.08] px-2 py-0.5 font-mono text-[10px] tabular-nums text-sky-200">
              Δy {formatSI(spacing, 2)}
            </span>
          </div>
          <canvas
            ref={graphRef}
            className="block h-[236px] w-full sm:h-[268px]"
            role="img"
            aria-label="Live interference intensity graph. Fringe spacing updates as the slit distance, wavelength and screen distance change."
          />
        </div>
      </div>

      <div className="mt-5 grid gap-x-6 gap-y-5 sm:grid-cols-3">
        <Slider
          id="slit-distance"
          label="Slit distance"
          symbol="d"
          value={dUm}
          min={0.1}
          max={1}
          step={0.01}
          display={`${dUm.toFixed(2)} µm`}
          onChange={setDUm}
        />
        <Slider
          id="wavelength"
          label="Wavelength"
          symbol="λ"
          value={lambdaNm}
          min={400}
          max={700}
          step={5}
          display={`${lambdaNm} nm`}
          onChange={setLambdaNm}
        />
        <Slider
          id="screen-distance"
          label="Screen distance"
          symbol="L"
          value={L}
          min={0.2}
          max={2}
          step={0.05}
          display={`${L.toFixed(2)} m`}
          onChange={setL}
        />
      </div>

      <div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
        <Readout label="Fringe spacing" value={formatSI(spacing, 2)} />
        <Readout label="Visible orders" value={`±${orders}`} />
        <Readout label="Slit width (model)" value={`${(a * 1e9).toFixed(0)} nm`} />
        <Readout label="Screen window" value="±4.0 mm" />
      </div>

      <div className="mt-4 flex items-center justify-between gap-3">
        <p className="text-[11px] leading-relaxed text-slate-500">
          Fraunhofer model · I(θ) = sinc²(πa sinθ/λ) · cos²(πd sinθ/λ)
        </p>
        <button
          type="button"
          onClick={reset}
          className="shrink-0 rounded-full border border-white/10 px-3 py-1.5 font-mono text-[9px] uppercase tracking-[0.16em] text-slate-400 transition-colors hover:border-white/20 hover:text-slate-200"
        >
          Reset
        </button>
      </div>
    </div>
  );
}
src/components/simulations/wave-function.tsx416 linesp5.js instance-mode sketch that samples boxWave() every frame and draws |psi|^2, Re psi and Im psi.View
Schrödinger (p5.js)
"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { Slider } from "@/components/slider";
import { boxCoefficients, boxWave, meanEnergy, meanPosition } from "@/lib/physics";

const DEFAULTS = { n: 2, speed: 0.9 };

type Sample = { x: number; abs2: number; re: number; im: number };

/**
 * Schrödinger simulation.
 *
 * The drawing is handled by p5.js in instance mode (loaded lazily on the client
 * so nothing touches `window` during SSR). The wave function itself comes from
 * `boxWave`, an exact solution of the time-dependent Schrödinger equation for a
 * superposition of infinite-square-well eigenstates.
 */
export function WaveFunctionSim() {
  const hostRef = useRef<HTMLDivElement | null>(null);
  const xOutRef = useRef<HTMLSpanElement | null>(null);
  const tOutRef = useRef<HTMLSpanElement | null>(null);
  const [n, setN] = useState(DEFAULTS.n);
  const [speed, setSpeed] = useState(DEFAULTS.speed);

  const nRef = useRef(n);
  const speedRef = useRef(speed);
  nRef.current = n;
  speedRef.current = speed;

  const mixture = useMemo(() => boxCoefficients(n), [n]);
  const energy = useMemo(() => meanEnergy(n), [n]);

  useEffect(() => {
    const host = hostRef.current;
    if (!host) return;

    let disposed = false;
    let instance: { remove: () => void } | null = null;
    let ro: ResizeObserver | null = null;
    let io: IntersectionObserver | null = null;
    let t = 0;
    let frame = 0;

    const reduceMotion =
      typeof window !== "undefined" &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    import("p5")
      .then((mod) => {
        if (disposed) return;
        const P5 = mod.default as unknown as new (sketch: (p: any) => void) => {
          remove: () => void;
        };

        const sketch = (p: any) => {
          let W = 0;
          let H = 0;
          let pausedByView = false;

          p.setup = () => {
            const rect = host.getBoundingClientRect();
            W = Math.max(320, Math.round(rect.width));
            H = Math.max(200, Math.round(rect.height));
            p.createCanvas(W, H);
            p.canvas.style.display = "block";
            p.canvas.style.width = "100%";
            p.canvas.style.height = "100%";
            p.pixelDensity(Math.min(2, window.devicePixelRatio || 1));
            p.frameRate(60);

            ro = new ResizeObserver(() => {
              const r = host.getBoundingClientRect();
              if (r.width < 40 || r.height < 40) return;
              W = Math.round(r.width);
              H = Math.round(r.height);
              p.resizeCanvas(W, H);
            });
            ro.observe(host);

            io = new IntersectionObserver(
              (entries) => {
                const visible = entries[0]?.isIntersecting ?? true;
                pausedByView = !visible;
                if (visible && !pausedByView) p.loop();
                else p.noLoop();
              },
              { rootMargin: "120px" },
            );
            io.observe(host);
          };

          p.draw = () => {
            const ctx = p.drawingContext as CanvasRenderingContext2D;
            p.clear();
            if (pausedByView) return;

            const level = nRef.current;
            const dt = Math.min(0.05, p.deltaTime / 1000);
            if (!reduceMotion) t += dt * speedRef.current * 1.7;

            const pad = { l: 44, r: 16, t: 24, b: 28 };
            const plotW = Math.max(20, W - pad.l - pad.r);
            const stackedH = Math.max(20, H - pad.t - pad.b);
            const gap = 20;
            const topH = (stackedH - gap) * 0.6;
            const botH = stackedH - gap - topH;
            const topA = pad.t;
            const bottomA = topA + topH;
            const topB = bottomA + gap;
            const bottomB = topB + botH;

            const samples = Math.min(420, Math.max(140, Math.floor(plotW)));
            const pts: Sample[] = [];
            let maxA = 0;
            let maxB = 0;

            for (let i = 0; i <= samples; i++) {
              const x = i / samples;
              const { re, im, abs2 } = boxWave(x, t, level);
              pts.push({ x, abs2, re, im });
              if (abs2 > maxA) maxA = abs2;
              const amp = Math.max(Math.abs(re), Math.abs(im));
              if (amp > maxB) maxB = amp;
            }
            maxA = Math.max(maxA, 0.4);
            maxB = Math.max(maxB, 0.4);

            // ---------- grid ----------
            ctx.lineWidth = 1;
            ctx.strokeStyle = "rgba(255,255,255,0.05)";
            for (let i = 0; i <= 4; i++) {
              const x = pad.l + (i / 4) * plotW;
              ctx.beginPath();
              ctx.moveTo(x, topA);
              ctx.lineTo(x, bottomB);
              ctx.stroke();
            }
            ctx.strokeStyle = "rgba(148,163,184,0.28)";
            ctx.beginPath();
            ctx.moveTo(pad.l, topA);
            ctx.lineTo(pad.l, bottomB);
            ctx.lineTo(pad.l + plotW, bottomB);
            ctx.stroke();

            // ---------- |psi|^2 ----------
            const base = bottomA - 3;
            const usable = topH - 16;
            const absScale = usable / maxA;

            const grad = ctx.createLinearGradient(0, topA, 0, base);
            grad.addColorStop(0, "rgba(167,139,250,0.42)");
            grad.addColorStop(0.55, "rgba(129,140,248,0.18)");
            grad.addColorStop(1, "rgba(56,189,248,0.03)");

            ctx.beginPath();
            ctx.moveTo(pad.l, base);
            for (let i = 0; i < pts.length; i++) {
              const px = pad.l + pts[i].x * plotW;
              const py = base - pts[i].abs2 * absScale;
              ctx.lineTo(px, py);
            }
            ctx.lineTo(pad.l + plotW, base);
            ctx.closePath();
            ctx.fillStyle = grad;
            ctx.fill();

            ctx.save();
            ctx.shadowColor = "rgba(186,230,253,0.9)";
            ctx.shadowBlur = 12;
            ctx.strokeStyle = "#E0F2FE";
            ctx.lineWidth = 1.7;
            ctx.beginPath();
            for (let i = 0; i < pts.length; i++) {
              const px = pad.l + pts[i].x * plotW;
              const py = base - pts[i].abs2 * absScale;
              if (i === 0) ctx.moveTo(px, py);
              else ctx.lineTo(px, py);
            }
            ctx.stroke();
            ctx.restore();

            // ---------- Re / Im ----------
            const zero = topB + botH / 2;
            const amp = Math.max(6, botH / 2 - 8);
            const reScale = amp / maxB;

            ctx.strokeStyle = "rgba(255,255,255,0.10)";
            ctx.setLineDash([3, 5]);
            ctx.beginPath();
            ctx.moveTo(pad.l, zero);
            ctx.lineTo(pad.l + plotW, zero);
            ctx.stroke();
            ctx.setLineDash([]);

            const drawTrace = (key: "re" | "im", color: string, width: number) => {
              ctx.strokeStyle = color;
              ctx.lineWidth = width;
              ctx.beginPath();
              for (let i = 0; i < pts.length; i++) {
                const px = pad.l + pts[i].x * plotW;
                const py = zero - pts[i][key] * reScale;
                if (i === 0) ctx.moveTo(px, py);
                else ctx.lineTo(px, py);
              }
              ctx.stroke();
            };

            drawTrace("re", "rgba(56,189,248,0.82)", 1.3);
            drawTrace("im", "rgba(167,139,250,0.82)", 1.3);

            // ---------- <x> marker ----------
            const xbar = meanPosition(t, level);
            const mx = pad.l + xbar * plotW;
            ctx.strokeStyle = "rgba(244,114,182,0.5)";
            ctx.setLineDash([2, 4]);
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(mx, topA);
            ctx.lineTo(mx, bottomB);
            ctx.stroke();
            ctx.setLineDash([]);
            ctx.fillStyle = "rgba(249,168,212,0.95)";
            ctx.beginPath();
            ctx.arc(mx, base, 3, 0, Math.PI * 2);
            ctx.fill();

            // ---------- axis ticks ----------
            ctx.font = "9px ui-monospace, SFMono-Regular, monospace";
            ctx.fillStyle = "rgba(148,163,184,0.6)";
            ctx.textAlign = "center";
            ctx.fillText("0", pad.l, bottomB + 13);
            ctx.fillText("L / 2", pad.l + plotW / 2, bottomB + 13);
            ctx.fillText("L", pad.l + plotW, bottomB + 13);
            for (let i = 0; i <= 4; i++) {
              const x = pad.l + (i / 4) * plotW;
              ctx.strokeStyle = "rgba(148,163,184,0.3)";
              ctx.beginPath();
              ctx.moveTo(x, bottomB);
              ctx.lineTo(x, bottomB + 3);
              ctx.stroke();
            }

            // ---------- labels ----------
            ctx.textAlign = "left";
            ctx.fillStyle = "rgba(226,232,240,0.9)";
            ctx.font = "10px ui-monospace, SFMono-Regular, monospace";
            ctx.fillText("|ψ(x, t)|²", pad.l + 2, topA - 8);
            ctx.fillStyle = "rgba(148,163,184,0.55)";
            ctx.fillText("probability density", pad.l + 74, topA - 8);

            ctx.fillStyle = "rgba(226,232,240,0.85)";
            ctx.fillText("Re ψ / Im ψ", pad.l + 2, topB - 6);

            // legend
            const legendX = pad.l + plotW - 96;
            const legendY = topB - 9;
            ctx.strokeStyle = "rgba(56,189,248,0.9)";
            ctx.lineWidth = 1.6;
            ctx.beginPath();
            ctx.moveTo(legendX, legendY);
            ctx.lineTo(legendX + 14, legendY);
            ctx.stroke();
            ctx.fillStyle = "rgba(148,163,184,0.7)";
            ctx.fillText("Re", legendX + 18, legendY + 3);

            ctx.strokeStyle = "rgba(167,139,250,0.9)";
            ctx.beginPath();
            ctx.moveTo(legendX + 44, legendY);
            ctx.lineTo(legendX + 58, legendY);
            ctx.stroke();
            ctx.fillStyle = "rgba(148,163,184,0.7)";
            ctx.fillText("Im", legendX + 62, legendY + 3);

            // node markers for the dominant eigenstate
            ctx.fillStyle = "rgba(148,163,184,0.35)";
            ctx.textAlign = "center";
            for (let k = 1; k < level; k++) {
              const nx = pad.l + (k / level) * plotW;
              ctx.beginPath();
              ctx.arc(nx, bottomA - 1, 1.6, 0, Math.PI * 2);
              ctx.fill();
            }

            // ---------- live readouts ----------
            frame++;
            if (frame % 4 === 0) {
              if (xOutRef.current) xOutRef.current.textContent = xbar.toFixed(3);
              if (tOutRef.current) tOutRef.current.textContent = t.toFixed(1);
            }
          };
        };

        instance = new P5(sketch);
      })
      .catch(() => {
        /* p5 failed to load — the static readouts below still work */
      });

    return () => {
      disposed = true;
      ro?.disconnect();
      io?.disconnect();
      instance?.remove();
    };
  }, []);

  return (
    <div>
      <div className="relative overflow-hidden rounded-2xl border border-white/[0.07] bg-[#060b16]/70">
        <div className="flex items-center justify-between border-b border-white/[0.06] px-3 py-2">
          <span className="font-mono text-[9px] uppercase tracking-[0.18em] text-slate-500">
            p5.js · infinite square well
          </span>
          <span className="flex items-center gap-1.5 rounded-md border border-violet-300/20 bg-violet-400/[0.08] px-2 py-0.5 font-mono text-[10px] tabular-nums text-violet-200">
            <span className="h-1 w-1 rounded-full bg-violet-300" />
            n = {n}
          </span>
        </div>
        <div
          ref={hostRef}
          className="h-[268px] w-full sm:h-[312px]"
          role="img"
          aria-label="Animated Schrödinger wave function. A probability density curve and the real and imaginary parts of psi evolve inside an infinite square well."
        />
        <p className="border-t border-white/[0.06] px-3 py-2 text-[10.5px] leading-relaxed text-slate-500">
          Pink marker: the expectation value ⟨x⟩. Higher n means a higher-energy
          mixture: more nodes and faster phase evolution.
        </p>
      </div>

      <div className="mt-5 grid gap-x-6 gap-y-5 sm:grid-cols-2">
        <Slider
          id="energy-level"
          label="Energy level"
          symbol="n"
          value={n}
          min={1}
          max={5}
          step={1}
          display={`n = ${n}`}
          hint="centres the mixture"
          onChange={(value) => setN(Math.round(value))}
        />
        <Slider
          id="animation-speed"
          label="Animation speed"
          value={speed}
          min={0.2}
          max={2}
          step={0.05}
          display={`${speed.toFixed(2)} ×`}
          onChange={setSpeed}
        />
      </div>

      <div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
        <div className="rounded-xl border border-white/[0.07] bg-white/[0.025] px-3 py-2">
          <div className="font-mono text-[8.5px] uppercase tracking-[0.16em] text-slate-500">
            ⟨E⟩
          </div>
          <div className="mt-0.5 font-mono text-[12px] tabular-nums text-slate-200">
            {energy.toFixed(2)} E₁
          </div>
        </div>
        <div className="rounded-xl border border-white/[0.07] bg-white/[0.025] px-3 py-2">
          <div className="font-mono text-[8.5px] uppercase tracking-[0.16em] text-slate-500">
            Nodes
          </div>
          <div className="mt-0.5 font-mono text-[12px] tabular-nums text-slate-200">
            {n - 1} of {n}
          </div>
        </div>
        <div className="rounded-xl border border-white/[0.07] bg-white/[0.025] px-3 py-2">
          <div className="font-mono text-[8.5px] uppercase tracking-[0.16em] text-slate-500">
            ⟨x⟩ / L
          </div>
          <div className="mt-0.5 font-mono text-[12px] tabular-nums text-slate-200">
            <span ref={xOutRef}>0.500</span>
          </div>
        </div>
        <div className="rounded-xl border border-white/[0.07] bg-white/[0.025] px-3 py-2">
          <div className="font-mono text-[8.5px] uppercase tracking-[0.16em] text-slate-500">
            Time (ħ/E₁)
          </div>
          <div className="mt-0.5 font-mono text-[12px] tabular-nums text-slate-200">
            <span ref={tOutRef}>0.0</span>
          </div>
        </div>
      </div>

      <div className="mt-4 flex flex-wrap gap-1.5">
        {mixture.map(({ k, weight }) => (
          <span
            key={k}
            className="inline-flex items-center gap-1.5 rounded-full border border-white/[0.08] bg-white/[0.03] px-2 py-1 font-mono text-[9.5px] text-slate-400"
          >
            <span className="text-slate-500">k={k}</span>
            <span className="tabular-nums text-slate-300">
              {(weight * 100).toFixed(0)}%
            </span>
          </span>
        ))}
        <span className="ml-auto self-center font-mono text-[9px] uppercase tracking-[0.14em] text-slate-600">
          spectral weights |cₖ|²
        </span>
      </div>

      <p className="mt-4 text-[11px] leading-relaxed text-slate-500">
        Exact evolution ψ(x,t) = Σ cₖ φₖ(x) e<sup>−iEₖt</sup>, with Eₖ = k² in
        units of E₁ (ħ = 2m = L = 1).
      </p>
    </div>
  );
}
src/components/simulations/uncertainty.tsx553 linesDraggable state point on the dx-dp plane with inset Gaussians for both conjugate variables.View
Uncertainty
"use client";

import { useCallback, useRef, useState } from "react";
import { Slider } from "@/components/slider";
import { useCanvasAnimation } from "@/lib/use-canvas-animation";
import { clamp, momentumSpread } from "@/lib/physics";

const DX_MIN = 0.2;
const DX_MAX = 3;
const DP_MAX = 3;

const DEFAULTS = { dx: 1.1, dp: momentumSpread(1.1) };

const MARGIN = { l: 46, r: 16, t: 18, b: 34 };

function plotBox(w: number, h: number) {
  return {
    l: MARGIN.l,
    t: MARGIN.t,
    pw: Math.max(10, w - MARGIN.l - MARGIN.r),
    ph: Math.max(10, h - MARGIN.t - MARGIN.b),
  };
}

function readouts(dx: number, dp: number) {
  return {
    product: dx * dp,
    minimum: momentumSpread(dx),
    isMinimum: Math.abs(dp - momentumSpread(dx)) < 1e-3,
  };
}

export function UncertaintySim() {
  const [dx, setDx] = useState(DEFAULTS.dx);
  const [dp, setDp] = useState(DEFAULTS.dp);
  const draggingRef = useRef(false);

  const stats = readouts(dx, dp);

  const setPosition = useCallback((value: number) => {
    const next = clamp(value, DX_MIN, DX_MAX);
    setDx(next);
    setDp((current) => Math.max(current, momentumSpread(next)));
  }, []);

  const setMomentum = useCallback(
    (value: number) => {
      setDp(clamp(value, momentumSpread(dx), DP_MAX));
    },
    [dx],
  );

  const handlePointer = useCallback(
    (clientX: number, clientY: number, canvas: HTMLCanvasElement) => {
      const rect = canvas.getBoundingClientRect();
      const { l, t, pw, ph } = plotBox(rect.width, rect.height);
      const fx = (clientX - rect.left - l) / pw;
      const fy = 1 - (clientY - rect.top - t) / ph;
      const nextDx = clamp(DX_MIN + fx * (DX_MAX - DX_MIN), DX_MIN, DX_MAX);
      const minDp = momentumSpread(nextDx);
      const nextDp = clamp(fy * DP_MAX, minDp, DP_MAX);
      setDx(nextDx);
      setDp(nextDp);
    },
    [],
  );

  const drawGraph = (
    ctx: CanvasRenderingContext2D,
    w: number,
    h: number,
  ) => {
    ctx.clearRect(0, 0, w, h);
    const { l, t, pw, ph } = plotBox(w, h);
    const right = l + pw;
    const bottom = t + ph;
    const xToPx = (value: number) =>
      l + ((value - DX_MIN) / (DX_MAX - DX_MIN)) * pw;
    const pToPy = (value: number) => bottom - (value / DP_MAX) * ph;

    // grid
    ctx.lineWidth = 1;
    ctx.strokeStyle = "rgba(255,255,255,0.05)";
    for (let v = 0.5; v <= DP_MAX; v += 0.5) {
      const y = pToPy(v);
      ctx.beginPath();
      ctx.moveTo(l, y);
      ctx.lineTo(right, y);
      ctx.stroke();
    }
    for (let v = 0.5; v <= DX_MAX; v += 0.5) {
      const x = xToPx(v);
      ctx.beginPath();
      ctx.moveTo(x, t);
      ctx.lineTo(x, bottom);
      ctx.stroke();
    }

    // forbidden region: Δx·Δp < ħ/2
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(l, bottom);
    const steps = 220;
    for (let i = 0; i <= steps; i++) {
      const value = DX_MIN + (i / steps) * (DX_MAX - DX_MIN);
      ctx.lineTo(xToPx(value), pToPy(momentumSpread(value)));
    }
    ctx.lineTo(right, bottom);
    ctx.closePath();
    ctx.fillStyle = "rgba(244,63,94,0.10)";
    ctx.fill();
    ctx.clip();
    ctx.strokeStyle = "rgba(244,63,94,0.16)";
    for (let i = -h; i < w + h; i += 9) {
      ctx.beginPath();
      ctx.moveTo(i, t);
      ctx.lineTo(i + h, bottom);
      ctx.stroke();
    }
    ctx.restore();

    ctx.save();
    ctx.beginPath();
    ctx.rect(l, t, pw, ph);
    ctx.clip();
    ctx.strokeStyle = "rgba(148,163,184,0.25)";
    ctx.beginPath();
    ctx.moveTo(l, t);
    ctx.lineTo(l, bottom);
    ctx.lineTo(right, bottom);
    ctx.stroke();
    ctx.restore();

    // allowed-region wash
    ctx.beginPath();
    ctx.moveTo(l, t);
    for (let i = 0; i <= steps; i++) {
      const value = DX_MIN + (i / steps) * (DX_MAX - DX_MIN);
      ctx.lineTo(xToPx(value), pToPy(momentumSpread(value)));
    }
    ctx.lineTo(right, t);
    ctx.closePath();
    const wash = ctx.createLinearGradient(0, t, 0, bottom);
    wash.addColorStop(0, "rgba(56,189,248,0.07)");
    wash.addColorStop(1, "rgba(56,189,248,0.0)");
    ctx.fillStyle = wash;
    ctx.fill();

    // boundary curve
    ctx.save();
    ctx.shadowColor = "rgba(56,189,248,0.85)";
    ctx.shadowBlur = 12;
    ctx.strokeStyle = "#7DD3FC";
    ctx.lineWidth = 1.8;
    ctx.beginPath();
    for (let i = 0; i <= steps; i++) {
      const value = DX_MIN + (i / steps) * (DX_MAX - DX_MIN);
      const px = xToPx(value);
      const py = pToPy(momentumSpread(value));
      if (i === 0) ctx.moveTo(px, py);
      else ctx.lineTo(px, py);
    }
    ctx.stroke();
    ctx.restore();

    // state point
    const px = xToPx(dx);
    const py = pToPy(dp);

    ctx.setLineDash([2, 5]);
    ctx.strokeStyle = "rgba(167,139,250,0.45)";
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(l, py);
    ctx.lineTo(px, py);
    ctx.moveTo(px, py);
    ctx.lineTo(px, bottom);
    ctx.stroke();
    ctx.setLineDash([]);

    ctx.save();
    ctx.shadowColor = "rgba(167,139,250,0.95)";
    ctx.shadowBlur = 18;
    ctx.fillStyle = "#F5F3FF";
    ctx.beginPath();
    ctx.arc(px, py, 5.5, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
    ctx.strokeStyle = "rgba(167,139,250,0.9)";
    ctx.lineWidth = 1.2;
    ctx.beginPath();
    ctx.arc(px, py, 10, 0, Math.PI * 2);
    ctx.stroke();

    // point label
    const label = "Δx·Δp = " + (dx * dp).toFixed(2) + " ħ";
    ctx.font = "10px ui-monospace, SFMono-Regular, monospace";
    const tw = ctx.measureText(label).width;
    let bx = px + 14;
    let by = py - 26;
    if (bx + tw + 14 > right) bx = px - tw - 28;
    if (by < t + 2) by = py + 14;
    ctx.fillStyle = "rgba(10,17,32,0.88)";
    ctx.strokeStyle = "rgba(255,255,255,0.12)";
    const rr = 6;
    const bw = tw + 14;
    ctx.beginPath();
    ctx.moveTo(bx + rr, by);
    ctx.lineTo(bx + bw - rr, by);
    ctx.quadraticCurveTo(bx + bw, by, bx + bw, by + rr);
    ctx.lineTo(bx + bw, by + 20 - rr);
    ctx.quadraticCurveTo(bx + bw, by + 20, bx + bw - rr, by + 20);
    ctx.lineTo(bx + rr, by + 20);
    ctx.quadraticCurveTo(bx, by + 20, bx, by + 20 - rr);
    ctx.lineTo(bx, by + rr);
    ctx.quadraticCurveTo(bx, by, bx + rr, by);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    ctx.fillStyle = "rgba(233,238,252,0.92)";
    ctx.textAlign = "left";
    ctx.fillText(label, bx + 7, by + 14);

    // region labels
    ctx.font = "9px ui-monospace, SFMono-Regular, monospace";
    ctx.fillStyle = "rgba(251,113,133,0.7)";
    ctx.textAlign = "left";
    ctx.fillText("forbidden", l + 8, bottom - 10);

    // ticks
    ctx.fillStyle = "rgba(148,163,184,0.65)";
    ctx.textAlign = "center";
    for (let v = 1; v <= DX_MAX; v += 0.5) {
      ctx.fillText(v.toFixed(1), xToPx(v), bottom + 14);
    }
    ctx.textAlign = "right";
    for (let v = 0.5; v <= DP_MAX; v += 0.5) {
      ctx.fillText(v.toFixed(1), l - 8, pToPy(v) + 3);
    }

    ctx.textAlign = "right";
    ctx.fillStyle = "rgba(148,163,184,0.7)";
    ctx.fillText("Δx  (arb. units)", right, h - 3);
    ctx.save();
    ctx.translate(11, t + ph / 2);
    ctx.rotate(-Math.PI / 2);
    ctx.textAlign = "center";
    ctx.fillText("Δp  (arb. units)", 0, 0);
    ctx.restore();
  };

  const drawPosition = (
    ctx: CanvasRenderingContext2D,
    w: number,
    h: number,
  ) => {
    ctx.clearRect(0, 0, w, h);
    const pad = 10;
    const base = h - 10;
    const sigma = (dx / DX_MAX) * (w * 0.42) + 1;
    const cx = w / 2;

    ctx.strokeStyle = "rgba(255,255,255,0.08)";
    ctx.beginPath();
    ctx.moveTo(pad, base);
    ctx.lineTo(w - pad, base);
    ctx.stroke();

    ctx.beginPath();
    for (let x = 0; x <= w; x += 1.5) {
      const value = Math.exp(-((x - cx) ** 2) / (2 * sigma * sigma));
      const y = base - value * (h - 26);
      if (x === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    }
    const grad = ctx.createLinearGradient(0, 0, 0, base);
    grad.addColorStop(0, "rgba(56,189,248,0.5)");
    grad.addColorStop(1, "rgba(56,189,248,0.02)");
    ctx.lineTo(w, base);
    ctx.lineTo(0, base);
    ctx.closePath();
    ctx.fillStyle = grad;
    ctx.fill();

    ctx.strokeStyle = "rgba(186,230,253,0.85)";
    ctx.lineWidth = 1.2;
    ctx.beginPath();
    for (let x = 0; x <= w; x += 1.5) {
      const value = Math.exp(-((x - cx) ** 2) / (2 * sigma * sigma));
      const y = base - value * (h - 26);
      if (x === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    }
    ctx.stroke();

    ctx.setLineDash([2, 5]);
    ctx.strokeStyle = "rgba(255,255,255,0.14)";
    ctx.beginPath();
    ctx.moveTo(cx, 6);
    ctx.lineTo(cx, base);
    ctx.stroke();
    ctx.setLineDash([]);

    // ±sigma band
    ctx.strokeStyle = "rgba(56,189,248,0.5)";
    ctx.beginPath();
    ctx.moveTo(cx - sigma, 8);
    ctx.lineTo(cx - sigma, base);
    ctx.moveTo(cx + sigma, 8);
    ctx.lineTo(cx + sigma, base);
    ctx.stroke();
  };

  const drawMomentum = (
    ctx: CanvasRenderingContext2D,
    w: number,
    h: number,
  ) => {
    ctx.clearRect(0, 0, w, h);
    const pad = 10;
    const base = h - 10;
    const sigma = (dp / DP_MAX) * (w * 0.42) + 1;
    const cx = w / 2;

    ctx.strokeStyle = "rgba(255,255,255,0.08)";
    ctx.beginPath();
    ctx.moveTo(pad, base);
    ctx.lineTo(w - pad, base);
    ctx.stroke();

    ctx.beginPath();
    for (let x = 0; x <= w; x += 1.5) {
      const value = Math.exp(-((x - cx) ** 2) / (2 * sigma * sigma));
      const y = base - value * (h - 26);
      if (x === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    }
    const grad = ctx.createLinearGradient(0, 0, 0, base);
    grad.addColorStop(0, "rgba(167,139,250,0.5)");
    grad.addColorStop(1, "rgba(167,139,250,0.02)");
    ctx.lineTo(w, base);
    ctx.lineTo(0, base);
    ctx.closePath();
    ctx.fillStyle = grad;
    ctx.fill();

    ctx.strokeStyle = "rgba(221,214,254,0.85)";
    ctx.lineWidth = 1.2;
    ctx.beginPath();
    for (let x = 0; x <= w; x += 1.5) {
      const value = Math.exp(-((x - cx) ** 2) / (2 * sigma * sigma));
      const y = base - value * (h - 26);
      if (x === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    }
    ctx.stroke();

    ctx.setLineDash([2, 5]);
    ctx.strokeStyle = "rgba(255,255,255,0.14)";
    ctx.beginPath();
    ctx.moveTo(cx, 6);
    ctx.lineTo(cx, base);
    ctx.stroke();
    ctx.setLineDash([]);

    ctx.strokeStyle = "rgba(167,139,250,0.5)";
    ctx.beginPath();
    ctx.moveTo(cx - sigma, 8);
    ctx.lineTo(cx - sigma, base);
    ctx.moveTo(cx + sigma, 8);
    ctx.lineTo(cx + sigma, base);
    ctx.stroke();
  };

  const graphRef = useCanvasAnimation(drawGraph, { paused: true });
  const positionRef = useCanvasAnimation(drawPosition, { paused: true });
  const momentumRef = useCanvasAnimation(drawMomentum, { paused: true });

  const reset = () => {
    setDx(DEFAULTS.dx);
    setDp(DEFAULTS.dp);
  };

  const snapToMinimum = () => {
    setDp(momentumSpread(dx));
  };

  return (
    <div>
      <div className="overflow-hidden rounded-2xl border border-white/[0.07] bg-[#060b16]/70">
        <div className="flex items-center justify-between border-b border-white/[0.06] px-3 py-2">
          <span className="font-mono text-[9px] uppercase tracking-[0.18em] text-slate-500">
            Allowed states · drag the point
          </span>
          <span
            className={
              stats.isMinimum
                ? "rounded-md border border-sky-300/20 bg-sky-400/[0.08] px-2 py-0.5 font-mono text-[10px] text-sky-200"
                : "rounded-md border border-violet-300/20 bg-violet-400/[0.08] px-2 py-0.5 font-mono text-[10px] text-violet-200"
            }
          >
            {stats.isMinimum ? "minimum uncertainty" : "above the limit"}
          </span>
        </div>
        <canvas
          ref={graphRef}
          className="block h-[280px] w-full cursor-crosshair sm:h-[320px]"
          style={{ touchAction: "pan-y" }}
          role="img"
          aria-label="Graph of momentum uncertainty against position uncertainty. The hyperbola dx dp equals hbar over 2 separates allowed states from the forbidden region."
          onPointerDown={(event) => {
            draggingRef.current = true;
            event.currentTarget.setPointerCapture(event.pointerId);
            handlePointer(event.clientX, event.clientY, event.currentTarget);
          }}
          onPointerMove={(event) => {
            if (!draggingRef.current) return;
            handlePointer(event.clientX, event.clientY, event.currentTarget);
          }}
          onPointerUp={(event) => {
            draggingRef.current = false;
            if (event.currentTarget.hasPointerCapture(event.pointerId)) {
              event.currentTarget.releasePointerCapture(event.pointerId);
            }
          }}
          onPointerCancel={() => {
            draggingRef.current = false;
          }}
        />
      </div>

      <div className="mt-3 grid gap-3 sm:grid-cols-2">
        <div className="overflow-hidden rounded-2xl border border-white/[0.07] bg-[#060b16]/70">
          <div className="flex items-center justify-between border-b border-white/[0.06] px-3 py-1.5">
            <span className="font-mono text-[9px] uppercase tracking-[0.16em] text-slate-500">
              Position space
            </span>
            <span className="font-mono text-[10px] tabular-nums text-sky-200">
              Δx = {dx.toFixed(2)}
            </span>
          </div>
          <canvas
            ref={positionRef}
            className="block h-[86px] w-full"
            role="img"
            aria-label="Gaussian position distribution whose width equals the current position uncertainty."
          />
        </div>
        <div className="overflow-hidden rounded-2xl border border-white/[0.07] bg-[#060b16]/70">
          <div className="flex items-center justify-between border-b border-white/[0.06] px-3 py-1.5">
            <span className="font-mono text-[9px] uppercase tracking-[0.16em] text-slate-500">
              Momentum space
            </span>
            <span className="font-mono text-[10px] tabular-nums text-violet-200">
              Δp = {dp.toFixed(2)}
            </span>
          </div>
          <canvas
            ref={momentumRef}
            className="block h-[86px] w-full"
            role="img"
            aria-label="Gaussian momentum distribution. Narrowing the position distribution broadens this one."
          />
        </div>
      </div>

      <div className="mt-5 grid gap-x-6 gap-y-5 sm:grid-cols-2">
        <Slider
          id="delta-x"
          label="Position uncertainty"
          symbol="Δx"
          value={dx}
          min={DX_MIN}
          max={DX_MAX}
          step={0.01}
          display={dx.toFixed(2)}
          hint="squeeze the packet"
          onChange={setPosition}
        />
        <Slider
          id="delta-p"
          label="Momentum uncertainty"
          symbol="Δp"
          value={dp}
          min={momentumSpread(dx)}
          max={DP_MAX}
          step={0.01}
          display={dp.toFixed(2)}
          hint={`min ${momentumSpread(dx).toFixed(2)}`}
          onChange={setMomentum}
        />
      </div>

      <div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
        <div className="rounded-xl border border-white/[0.07] bg-white/[0.025] px-3 py-2">
          <div className="font-mono text-[8.5px] uppercase tracking-[0.16em] text-slate-500">
            Δx · Δp
          </div>
          <div className="mt-0.5 font-mono text-[12px] tabular-nums text-slate-200">
            {stats.product.toFixed(2)} ħ
          </div>
        </div>
        <div className="rounded-xl border border-white/[0.07] bg-white/[0.025] px-3 py-2">
          <div className="font-mono text-[8.5px] uppercase tracking-[0.16em] text-slate-500">
            Lower bound
          </div>
          <div className="mt-0.5 font-mono text-[12px] tabular-nums text-slate-200">
            0.50 ħ
          </div>
        </div>
        <div className="rounded-xl border border-white/[0.07] bg-white/[0.025] px-3 py-2">
          <div className="font-mono text-[8.5px] uppercase tracking-[0.16em] text-slate-500">
            Δp minimum
          </div>
          <div className="mt-0.5 font-mono text-[12px] tabular-nums text-slate-200">
            {stats.minimum.toFixed(2)}
          </div>
        </div>
        <div className="rounded-xl border border-white/[0.07] bg-white/[0.025] px-3 py-2">
          <div className="font-mono text-[8.5px] uppercase tracking-[0.16em] text-slate-500">
            Margin
          </div>
          <div className="mt-0.5 font-mono text-[12px] tabular-nums text-slate-200">
            {`${((stats.product / 0.5 - 1) * 100).toFixed(0)}%`}
          </div>
        </div>
      </div>

      <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
        <p className="text-[11px] leading-relaxed text-slate-500">
          Drag anywhere in the plot · the rose region is forbidden
        </p>
        <div className="flex gap-2">
          <button
            type="button"
            onClick={snapToMinimum}
            className="shrink-0 rounded-full border border-white/10 px-3 py-1.5 font-mono text-[9px] uppercase tracking-[0.16em] text-slate-300 transition-colors hover:border-sky-300/40 hover:text-white"
          >
            Minimum
          </button>
          <button
            type="button"
            onClick={reset}
            className="shrink-0 rounded-full border border-white/10 px-3 py-1.5 font-mono text-[9px] uppercase tracking-[0.16em] text-slate-400 transition-colors hover:border-white/20 hover:text-slate-200"
          >
            Reset
          </button>
        </div>
      </div>
    </div>
  );
}
Run it locally
npm install
npm run dev     # http://localhost:3000
npm run build   # static production build

Requires Node.js 18.18 or newer. No environment variables, database or API keys are needed — the build is fully static.