diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 2a2c9474..e7012b86 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -6,16 +6,16 @@ This file was checked on 2026-11-04 against the repo files, `node_modules/ = { chrome: 0, liquid: 1, jelly: 2 }; -vec4 blobSmooth(vec4 a, vec4 b, float k) { - float h = k > 0.0 ? max(k - abs(a.x - b.x), 0.0) / k : 0.0; - float weight = b.x < a.x ? 1.0 - 0.5 * h * h : 0.5 * h * h; - return vec4(min(a.x, b.x) - h * h * h * k / 6.0, mix(a.yzw, b.yzw, weight)); +const VERT = `#version 300 es +in vec2 a_pos; +void main() { gl_Position = vec4(a_pos, 0.0, 1.0); } +`; + +const FRAG = `#version 300 es +precision highp float; +out vec4 outColor; + +uniform vec2 u_res; // canvas size in device pixels +uniform float u_radius; // orb radius in device pixels +uniform float u_time; +uniform float u_body; // body radius in orb radii (breath and spring) +uniform float u_bend; // edge bend amount +uniform float u_flow; // how fast the bend travels +uniform vec3 u_drops[${DROPS}]; // x, y, radius (radius 0 = unused), in orb radii +uniform vec3 u_stops[4]; +uniform vec4 u_at; // stop positions +uniform int u_material; +uniform float u_eyes; // 0 none, 1 drawn +uniform float u_open; // lid openness +uniform float u_gaze; // -1..1 + +float smin(float a, float b, float k) { + float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); + return mix(b, a, h) - k * h * (1.0 - h); } -vec4 blobShape(vec2 p, float z) { - vec4 body = blobPart(p, 0, z); - for (int i = 1; i < BLOB_MAX; i++) { - if (i >= blobCount) break; - body = blobSmooth(body, blobPart(p, i, z), blobInfo[i].z); +float shape(vec2 p) { + float a = atan(p.y, p.x); + float t = u_time * u_flow; + float wave = 0.55 * sin(2.0 * a + t * 1.9 + 0.4) + + 0.30 * sin(3.0 * a - t * 2.4 + 1.7) + + 0.15 * sin(5.0 * a + t * 3.1 + 2.9); + float d = length(p) - u_body * (1.0 + 0.11 * u_bend * wave); + for (int i = 0; i < ${DROPS}; i++) { + vec3 dr = u_drops[i]; + if (dr.z > 0.0) d = smin(d, length(p - dr.xy) - dr.z, 0.32); } - return body; + return d; } -// Same radial gradient as the CSS orb: centred at 35% / 30% of the orb box, -// reaching its farthest corner (1.91 radii away). -vec3 blobTint() { - float t = clamp(length(vBlobSpot - blobCenter - vec2(-0.3, 0.4) * blobRef) / (1.91 * blobRef), 0.0, 1.0); - vec3 c = mix(tint0, tint1, smoothstep(0.0, tintStops.x, t)); - c = mix(c, tint2, smoothstep(tintStops.x, tintStops.y, t)); - return mix(c, tint3, smoothstep(tintStops.y, 1.0, t)); +vec3 ramp(float x) { + vec3 c = u_stops[0]; + c = mix(c, u_stops[1], smoothstep(u_at.x, u_at.y, x)); + c = mix(c, u_stops[2], smoothstep(u_at.y, u_at.z, x)); + c = mix(c, u_stops[3], smoothstep(u_at.z, u_at.w, x)); + return c; } -// Two plain ovals that sit on the dome: they follow the blob's centre as it -// wobbles, narrow as the gaze turns towards the edge, and flatten to a line -// when the lids close. A small highlight sits top-left in each. -void blobEyes(vec2 p) { - if (eyeOn < 0.5) return; - for (int s = 0; s < 2; s++) { - float side = s == 0 ? -1.0 : 1.0; - vec2 base = vec2(0.3 * side, 0.1) + eyeLook; - float fore = sqrt(max(0.25, 1.0 - dot(base, base))); - vec2 c = eyeCenter + base * blobRef; - vec2 rad = vec2(0.105 * fore, 0.15 * max(eyeOpen, 0.05)) * blobRef; - float d = (length((p - c) / rad) - 1.0) * min(rad.x, rad.y); - float m = clamp(0.5 - d / max(fwidth(d), 0.0001), 0.0, 1.0); - eyeMask = max(eyeMask, m); - float cd = length(p - c - vec2(-0.035, 0.05) * blobRef) - 0.032 * blobRef * clamp(eyeOpen * 1.6 - 0.4, 0.0, 1.0); - eyeCatch = max(eyeCatch, clamp(0.5 - cd / max(fwidth(cd), 0.0001), 0.0, 1.0) * m); - } +// A soft studio: a bright sky fading to the agent's deeper colours below, with +// no hard horizon (a dark line across the face could read as a mouth). +vec3 studio(vec3 r) { + float y = r.y + 0.45; + vec3 sky = mix(u_stops[1], u_stops[0], smoothstep(0.15, 1.0, y)); + vec3 floorTone = mix(u_stops[2], u_stops[3], smoothstep(0.1, -0.5, y)); + vec3 c = mix(floorTone, sky, smoothstep(-0.2, 0.35, y)); + // A soft window light from the upper left, and a faint bounce light low on the right. + c += vec3(1.0) * 0.55 * smoothstep(0.86, 0.97, dot(r, normalize(vec3(-0.55, 0.62, 0.56)))); + c += u_stops[1] * 0.25 * smoothstep(0.7, 0.95, dot(r, normalize(vec3(0.6, -0.55, 0.58)))); + return c; } -`; -const SURFACE = ` - vec4 blobBase = blobShape(vBlobSpot, 0.0); - float blobAlpha = clamp(0.5 - blobBase.x / max(fwidth(blobBase.x), 0.0001), 0.0, 1.0); - if (blobAlpha <= 0.0) discard; - blobEyes(vBlobSpot); - float blobLow = 0.0; - float blobHigh = blobTop; - float blobZ = min(sqrt(max(-blobBase.x, 0.0) * max(2.0 * blobRef + blobBase.x, 0.0)), blobTop); - for (int k = 0; k < 8; k++) { - vec4 blobTry = blobShape(vBlobSpot, blobZ); - if (blobTry.x > 0.0) blobHigh = blobZ; - else blobLow = blobZ; - float blobNext = blobZ - blobTry.x / max(blobTry.w, 0.0001); - blobZ = blobNext > blobLow && blobNext < blobHigh ? blobNext : 0.5 * (blobLow + blobHigh); +float oval(vec2 p, vec2 c, vec2 r) { + vec2 q = (p - c) / r; + return (length(q) - 1.0) * min(r.x, r.y); +} + +void main() { + vec2 p = (gl_FragCoord.xy - 0.5 * u_res) / u_radius; + float d = shape(p); + float px = 1.5 / u_radius; + float cover = 1.0 - smoothstep(-px, px, d); + if (cover <= 0.0) { outColor = vec4(0.0); return; } + + // Normal of a dome over the shape. + vec2 e = vec2(0.004, 0.0); + vec2 g = vec2(shape(p + e.xy) - shape(p - e.xy), shape(p + e.yx) - shape(p - e.yx)); + vec2 out2 = length(g) > 0.0 ? normalize(g) : vec2(0.0); + float depth = clamp(-d / max(u_body, 0.2), 0.0, 1.0); + float rho = 1.0 - depth; + vec3 n = normalize(vec3(out2 * rho, sqrt(max(0.0, 1.0 - rho * rho)) + 0.02)); + + vec3 view = vec3(0.0, 0.0, 1.0); + vec3 r = reflect(-view, n); + float fres = pow(1.0 - max(n.z, 0.0), 3.0); + vec2 hl = vec2(-0.3, 0.4) * u_body; + vec3 tint = ramp(clamp(length(p - hl) / (1.35 * u_body), 0.0, 1.0)); + vec3 light = normalize(vec3(-0.5, 0.6, 0.65)); + float spec = pow(max(dot(r, light), 0.0), 48.0); + + vec3 col; + float alpha = 1.0; + if (u_material == 0) { + col = mix(studio(r), tint, 0.32); + col = mix(col, u_stops[3] * 0.8, fres * 0.35); + col += spec * 0.6; + } else if (u_material == 1) { + col = mix(tint, studio(r), 0.38); + col += spec * 0.45; + col = mix(col, u_stops[3], fres * 0.25); + } else { + col = tint * (0.82 + 0.25 * depth); + col = mix(col, u_stops[0], fres * 0.5); + col += spec * 0.5; + alpha = mix(0.72, 0.94, depth); + } + + if (u_eyes > 0.5) { + float s = u_body; + vec2 shift = vec2(u_gaze * 0.06, 0.0) * s; + vec2 rad = vec2(0.10, 0.15 * max(u_open, 0.06)) * s; + for (int i = 0; i < 2; i++) { + float side = i == 0 ? -1.0 : 1.0; + vec2 c = vec2(side * 0.30, 0.10) * s + shift; + float ed = oval(p, c, rad); + float ink = 1.0 - smoothstep(-px, px, ed); + vec2 shine = c + vec2(-0.32 * rad.x, 0.42 * rad.y); + float glint = (1.0 - smoothstep(-px, px, length(p - shine) - 0.3 * rad.x)) * step(0.35, u_open); + col = mix(col, vec3(0.090, 0.078, 0.169), ink); + col = mix(col, vec3(1.0), glint * ink); + } } - vec4 blobAt = blobShape(vBlobSpot, blobZ); - vec3 blobNormal = normalize(vec3(blobAt.yz, blobAt.w / blobLift)); - gl_FragDepth = blobDepth.x - blobDepth.y * blobZ * blobLift; -`; -const SURFACE_NORMAL = ` - float faceDirection = 1.0; - vec3 normal = normalize((viewMatrix * vec4(blobNormal, 0.0)).xyz); - vec3 nonPerturbedNormal = normal; + float a = cover * alpha; + outColor = vec4(clamp(col, 0.0, 1.0) * a, a); +} `; -const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v)); -const mix = (a: number, b: number, t: number) => a + (b - a) * t; -const between = ([a, b]: [number, number]) => mix(a, b, Math.random()); - -function finish(m: THREE.MeshPhysicalMaterial, kind: BlobMaterial) { - m.color.set("#ffffff"); - m.iridescence = 0; - if (kind === "chrome") { - m.metalness = 1; - m.roughness = 0.08; - m.clearcoat = 0; - m.envMapIntensity = 1.25; - } else if (kind === "jelly") { - m.metalness = 0; - m.roughness = 0.25; - m.clearcoat = 1; - m.clearcoatRoughness = 0.04; - m.envMapIntensity = 0.7; - } else { - m.metalness = 0.4; - m.roughness = 0.18; - m.clearcoat = 1; - m.clearcoatRoughness = 0.05; - m.envMapIntensity = 0.85; +const hex = (h: string): [number, number, number] => { + const v = parseInt(h.replace("#", ""), 16); + return [((v >> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255]; +}; + +type Drop = { angle: number; born: number; life: number; reach: number; radius: number; kind: "splash" | "bud" }; + +function compile(gl: WebGL2RenderingContext, type: number, src: string) { + const sh = gl.createShader(type); + if (!sh) return null; + gl.shaderSource(sh, src); + gl.compileShader(sh); + if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) { + console.warn("Liquid Aeon shader:", gl.getShaderInfoLog(sh)); + gl.deleteShader(sh); + return null; } - m.needsUpdate = true; + return sh; } +/** The still orb shown until the first frame is drawn (the shader can take a moment to compile). */ +const stillOrb = (agent: Agent) => + `radial-gradient(circle at 35% 30%, ${AGENT_STOPS[agent].map(([c, at]) => `${c} ${Math.round(at * 100)}%`).join(", ")})`; + export default function BlobCanvas({ agent, state, popId, material, eyes, size, onSettled }: BlobCanvasProps) { - const rootRef = useRef(null); - const live = useRef({ agent, state, popId, material, eyes, size, onSettled }); - // Layout effect runs before the effects below, so they always see fresh props. - useLayoutEffect(() => { - live.current = { agent, state, popId, material, eyes, size, onSettled }; + const canvas = useRef(null); + const [drawn, setDrawn] = useState(false); + const firstFrame = useRef(setDrawn); + // Everything the frame loop reads lives in one ref, so props never restart WebGL. + const live = useRef({ agent, state, material, eyes, size, onSettled, popId, popAt: -1, kick: false, paused: true, ready: false }); + useEffect(() => { + const l = live.current; + l.agent = agent; + l.state = state; + l.material = material; + l.eyes = eyes; + l.size = size; + l.onSettled = onSettled; }); - const poke = useRef<{ restyle: () => void; splash: () => void } | null>(null); - useEffect(() => { - const root = rootRef.current; - if (!root) return; - - let renderer: THREE.WebGLRenderer; - try { - renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true, premultipliedAlpha: true, powerPreference: "low-power" }); - } catch { - return; + const l = live.current; + if (state === "pop" && (l.popAt < 0 || popId !== l.popId)) { + l.popId = popId; + l.kick = true; + // Set up but not drawing (off screen, hidden tab, no WebGL): there is no splash to wait for. + if (l.ready && l.paused) { + l.kick = false; + l.onSettled(popId); + } } - renderer.setClearColor(0x000000, 0); - renderer.outputColorSpace = THREE.SRGBColorSpace; - renderer.toneMapping = THREE.NeutralToneMapping; - const canvas = renderer.domElement; - canvas.style.cssText = "display:block;width:100%;height:100%"; - canvas.setAttribute("aria-hidden", "true"); - root.appendChild(canvas); - - const scene = new THREE.Scene(); - const pmrem = new THREE.PMREMGenerator(renderer); - const environment = pmrem.fromScene(new RoomEnvironment(), 0.03); - pmrem.dispose(); - scene.environment = environment.texture; - scene.environmentRotation.set(-0.9, 0.35, 0); - - const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 1, 6000); - camera.position.set(0, 0, 2000); - - const field = { - blobSeg: { value: new Float32Array(MAX_PARTS * 4) }, - blobInfo: { value: new Float32Array(MAX_PARTS * 4) }, - blobCount: { value: 0 }, - blobLift: { value: 1 }, - blobTop: { value: 1 }, - blobRef: { value: 1 }, - blobDepth: { - value: new THREE.Vector2((camera.position.z - camera.near) / (camera.far - camera.near), 1 / (camera.far - camera.near)), - }, - blobCenter: { value: new THREE.Vector2() }, - tint0: { value: new THREE.Color() }, - tint1: { value: new THREE.Color() }, - tint2: { value: new THREE.Color() }, - tint3: { value: new THREE.Color() }, - tintStops: { value: new THREE.Vector2(0.3, 0.65) }, - eyeOn: { value: 0 }, - eyeCenter: { value: new THREE.Vector2() }, - eyeLook: { value: new THREE.Vector2() }, - eyeOpen: { value: 1 }, - eyeInk: { value: new THREE.Color(EYE_INK) }, - }; + // A late pop id with no splash showing (shouldn't happen) just settles. + if (state !== "pop") l.popId = popId; + }, [popId, state]); - const skin = new THREE.MeshPhysicalMaterial({ transparent: true }); - skin.onBeforeCompile = (shader) => { - Object.assign(shader.uniforms, field); - shader.vertexShader = shader.vertexShader - .replace("void main() {", "varying vec2 vBlobSpot;\nvoid main() {") - .replace("#include ", "#include \n\tvBlobSpot = (modelMatrix * vec4(transformed, 1.0)).xy;"); - shader.fragmentShader = shader.fragmentShader - .replace("void main() {", `${FIELD}\nvoid main() {\n${SURFACE}`) - .replace( - "vec4 diffuseColor = vec4( diffuse, opacity );", - "vec4 diffuseColor = vec4( mix( diffuse * blobTint(), eyeInk, eyeMask ), opacity * blobAlpha );" - ) - .replace("#include ", SURFACE_NORMAL) - // Eyes are glossy but not metal, so they stay dark instead of mirroring the room. - .replace("#include ", "#include \n\tmetalnessFactor = mix( metalnessFactor, 0.0, eyeMask );") - .replace("#include ", "#include \n\troughnessFactor = mix( roughnessFactor, 0.3, eyeMask );") - .replace("#include ", "#include \n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, vec3( 1.4 ), eyeCatch );"); - }; - const blob = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), skin); - blob.frustumCulled = false; - scene.add(blob); - - const view = { width: 1, height: 1 }; - const core: Ball[] = Array.from({ length: CORE }, (_, i) => ({ - x: 0, y: 0, vx: 0, vy: 0, spread: i / (CORE - 1), angle: (i / CORE) * Math.PI * 2, shape: 0, tx: 0, ty: 0, grow: 1, - })); - const drops: Drop[] = []; - const swell = { value: 0, velocity: 0 }; - const seeds = Array.from({ length: 4 }, () => Math.random() * Math.PI * 2); - let clock = Math.random() * 60; - let breath = 0; - let nextSplit = 0.6; - let settleTimer = 0; - let popStart = -Infinity; - const eye = { open: 1, lookX: 0, lookY: 0, toX: 0, toY: 0, nextGlance: 2, blinkAt: 2, doubleAt: -1 }; - let raf = 0; - let last = 0; - let onScreen = true; - let alive = true; - - const restyle = () => { - const stops = AGENT_STOPS[live.current.agent]; - field.tint0.value.set(stops[0][0]); - field.tint1.value.set(stops[1][0]); - field.tint2.value.set(stops[2][0]); - field.tint3.value.set(stops[3][0]); - field.tintStops.value.set(stops[1][1], stops[2][1]); - finish(skin, live.current.material); - }; - - const radius = () => live.current.size / 2; - - const spawn = (count: number, speed: [number, number], rSize: [number, number], hold: [number, number]) => { - const R = radius(); - const offset = Math.random() * Math.PI * 2; - for (let i = 0; i < count; i++) { - if (drops.length >= MAX_DROPS) drops.shift(); - const angle = offset + (i / count) * Math.PI * 2 + (Math.random() - 0.5) * (Math.PI / count); - const pace = R * between(speed); - drops.push({ - x: Math.cos(angle) * R * 0.3, - y: Math.sin(angle) * R * 0.3, - vx: Math.cos(angle) * pace, - vy: Math.sin(angle) * pace, - r: R * between(rSize), - age: 0, - hold: between(hold), - sink: -1, - }); + useEffect(() => { + const el = canvas.current; + if (!el) return; + const mine = live.current; + const settleNow = () => { + const l = mine; + l.paused = true; + l.ready = true; + if (l.kick || l.popAt >= 0) { + l.kick = false; + l.popAt = -1; + l.onSettled(l.popId); } }; - - // Splash: the blob swells from nothing past full size, throws droplets - // that drift out, then pulls them back in and settles. - const splash = () => { - const R = radius(); - swell.value = 0.05; - swell.velocity = 0; - popStart = performance.now(); - // A timer, not the frame loop: blobs scrolled out of view stop drawing - // but must still settle. - window.clearTimeout(settleTimer); - const id = live.current.popId; - settleTimer = window.setTimeout(() => live.current.onSettled(id), POP_MS); - for (const ball of core) { - const a = Math.random() * Math.PI * 2; - const push = R * mix(3, 6, Math.random()); - ball.vx += Math.cos(a) * push; - ball.vy += Math.sin(a) * push; - } - spawn(6, [3.2, 4.6], [0.1, 0.2], [0.22, 0.34]); + const gl = el.getContext("webgl2", { alpha: true, premultipliedAlpha: true, antialias: false }); + if (!gl || gl.isContextLost()) return settleNow(); + + const vs = compile(gl, gl.VERTEX_SHADER, VERT); + const fs = compile(gl, gl.FRAGMENT_SHADER, FRAG); + const prog = gl.createProgram(); + if (!vs || !fs || !prog) return settleNow(); + gl.attachShader(prog, vs); + gl.attachShader(prog, fs); + gl.linkProgram(prog); + if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return settleNow(); + gl.useProgram(prog); + + const buf = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, buf); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW); + const loc = gl.getAttribLocation(prog, "a_pos"); + gl.enableVertexAttribArray(loc); + gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0); + gl.enable(gl.BLEND); + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + + const u = (name: string) => gl.getUniformLocation(prog, name); + const U = { + res: u("u_res"), + radius: u("u_radius"), + time: u("u_time"), + body: u("u_body"), + bend: u("u_bend"), + flow: u("u_flow"), + drops: u("u_drops"), + stops: u("u_stops"), + at: u("u_at"), + material: u("u_material"), + eyes: u("u_eyes"), + open: u("u_open"), + gaze: u("u_gaze"), }; - const calmDown = () => { - drops.length = 0; - swell.value = Math.max(swell.value, 1); - swell.velocity = 0; - for (const ball of core) { - ball.x = ball.tx; - ball.y = ball.ty; - ball.vx = 0; - ball.vy = 0; - } + // Physics state. + let scale = 1; + let speed = 0; + let bend = PARAMS.rest.morph; + let flow = PARAMS.rest.morphSpeed; + let wobble = PARAMS.rest.wobble; + let gaze = 0; + let drops: Drop[] = []; + let nextBud = 1.2; + let blinkAt = nextBlinkIn("rest"); + let blinkStart = -10; + let secondBlink = -1; + let flowTime = 0; + let last = performance.now(); + const t0 = last; + let frame = 0; + let running = false; + let onScreen = true; + const dropData = new Float32Array(DROPS * 3); + + const startSplash = (now: number) => { + const s = (now - t0) / 1000; + scale = 0.18; + speed = 0; + const count = 5; + const turn = Math.random() * Math.PI * 2; + drops = Array.from({ length: count }, (_, i) => ({ + angle: turn + (i / count) * Math.PI * 2 + (Math.random() - 0.5) * 0.6, + born: s, + life: (POP_MS / 1000) * (0.62 + Math.random() * 0.18), + reach: 1.15 + Math.random() * 0.35, + radius: 0.13 + Math.random() * 0.09, + kind: "splash" as const, + })); + live.current.popAt = now; }; const resize = () => { - view.width = Math.max(1, root.clientWidth); - view.height = Math.max(1, root.clientHeight); - renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); - renderer.setSize(view.width, view.height, false); - camera.left = -view.width / 2; - camera.right = view.width / 2; - camera.top = view.height / 2; - camera.bottom = -view.height / 2; - camera.updateProjectionMatrix(); - start(); + const ratio = Math.min(window.devicePixelRatio || 1, 2); + const css = live.current.size * CANVAS_SCALE; + const px = Math.round(css * ratio); + if (el.width !== px || el.height !== px) { + el.width = px; + el.height = px; + } + return { px, radius: (live.current.size / 2) * ratio }; }; - const integrate = (b: { x: number; y: number; vx: number; vy: number }, tx: number, ty: number, k: number, damp: number, h: number) => { - b.vx += ((tx - b.x) * k - b.vx * damp) * h; - b.vy += ((ty - b.y) * k - b.vy * damp) * h; - b.x += b.vx * h; - b.y += b.vy * h; - }; + const step = (now: number) => { + frame = requestAnimationFrame(step); + const l = live.current; + const dt = Math.min(0.05, (now - last) / 1000); + last = now; + const s = (now - t0) / 1000; - const step = (dt: number) => { - const { state } = live.current; - const p = PARAMS[state]; - const R = radius(); - const steps = Math.max(1, Math.ceil(dt / (1 / 240))); - const h = dt / steps; - const bounce = mix(0.95, 0.4, p.wobble); - - breath += dt; - clock += dt * 4 * Math.pow(p.morphSpeed, 1.5); - const bend = p.morph * (0.6 + 0.4 * Math.sin(clock * 0.71 + seeds[0])); - const bendAngle = clock * 0.23 + seeds[1]; - const fold = p.morph * 0.8 * (0.5 + 0.5 * Math.sin(clock * 0.53 + seeds[2])); - const foldAngle = seeds[3] - clock * 0.17; - let strain = 0; - for (const ball of core) { - ball.shape = bend * Math.cos(2 * (ball.angle - bendAngle)) + fold * Math.cos(3 * (ball.angle - foldAngle)); - strain += (ball.shape * ball.shape) / CORE; + if (l.kick) { + l.kick = false; + startSplash(now); } - const hold = 1 / (1 + 0.3 * strain); - for (const ball of core) { - const out = R * clamp(0.14 + 0.75 * ball.shape, 0, 0.8) * hold; - ball.tx = Math.cos(ball.angle) * out; - ball.ty = Math.sin(ball.angle) * out; - ball.grow = (1 + 0.35 * ball.shape) * hold; + const popping = l.state === "pop" && l.popAt >= 0; + const popProgress = popping ? Math.min(1, (now - l.popAt) / POP_MS) : 1; + if (popping && now - l.popAt >= POP_MS) { + l.popAt = -1; + l.onSettled(l.popId); } - if (p.splitEvery) { - nextSplit -= dt; - if (nextSplit <= 0) { - spawn(Math.random() < 0.5 ? 1 : 2, [1.1, 1.7], [0.12, 0.2], [0.18, 0.3]); - nextSplit = between(p.splitEvery); + // Ease the shape targets toward the current state. + const target = PARAMS[l.state]; + const ease = 1 - Math.exp(-dt * 4); + bend += (target.morph - bend) * ease; + flow += (target.morphSpeed - flow) * ease; + wobble += (target.wobble - wobble) * ease; + flowTime += dt; + + // Body spring toward 1: less damping means more jiggle. + const stiff = 150; + const damp = 2 * Math.sqrt(stiff) * (1 - 0.82 * wobble); + speed += (stiff * (1 - scale) - damp * speed) * dt; + scale += speed * dt; + + // While working, now and then a droplet buds off and rejoins. + if (l.state === "work" && target.splitEvery) { + nextBud -= dt; + if (nextBud <= 0) { + const [lo, hi] = target.splitEvery; + nextBud = lo + Math.random() * (hi - lo); + if (drops.length < DROPS) { + drops.push({ angle: Math.random() * Math.PI * 2, born: s, life: 0.95 + Math.random() * 0.5, reach: 1.05 + Math.random() * 0.25, radius: 0.15 + Math.random() * 0.07, kind: "bud" }); + speed -= 0.5; // the body gives a little as it lets go + } } } - - const swellTarget = breathe(breath); - const coreK = 520; - for (let i = 0; i < steps; i++) { - for (const ball of core) { - const k = coreK * mix(1.3, 0.7, ball.spread); - integrate(ball, ball.tx, ball.ty, k, 2 * Math.sqrt(k) * bounce, h); + drops = drops.filter((d) => s - d.born < d.life); + + const body = scale * breathe(s); + dropData.fill(0); + drops.forEach((d, i) => { + const k = (s - d.born) / d.life; + // Out fast, back slower: sin of a bent clock. + const out = d.kind === "splash" ? Math.sin(Math.PI * Math.pow(k, 0.7)) : Math.sin(Math.PI * k); + const dist = body * (0.35 + (d.reach - 0.35) * out); + const r = d.radius * (d.kind === "splash" ? 1 - 0.35 * k : 0.7 + 0.3 * out); + dropData[i * 3] = Math.cos(d.angle) * dist; + dropData[i * 3 + 1] = Math.sin(d.angle) * dist; + dropData[i * 3 + 2] = r; + }); + + // Eyes: blinks (sometimes double at rest), squint through a splash, reading gaze while working. + let open = 1; + if (l.eyes) { + if (s >= blinkAt) { + blinkStart = s; + secondBlink = l.state === "rest" && Math.random() < DOUBLE_BLINK_CHANCE ? s + DOUBLE_BLINK_GAP_S : -1; + blinkAt = s + nextBlinkIn(l.state); } - for (const d of drops) { - d.age += h; - if (d.sink >= 0) { - d.sink = Math.min(1, d.sink + h / 0.16); - d.x *= 1 - 12 * h; - d.y *= 1 - 12 * h; - } else if (d.age < d.hold) { - const ease = Math.exp(-4 * h); - d.vx *= ease; - d.vy *= ease; - d.x += d.vx * h; - d.y += d.vy * h; - } else { - integrate(d, 0, 0, 90, 2 * Math.sqrt(90) * 0.55, h); - } + if (secondBlink > 0 && s >= secondBlink) { + blinkStart = s; + secondBlink = -1; } - const swellK = 300; - swell.velocity += ((swellTarget - swell.value) * swellK - swell.velocity * 2 * Math.sqrt(swellK) * mix(0.8, 0.3, p.wobble)) * h; - swell.value += swell.velocity * h; + open = blinkOpenness(s - blinkStart); + if (popping) open = Math.min(open, popOpenness(popProgress)); + const gazeTarget = l.state === "work" ? readingGaze(s) : 0; + gaze += (gazeTarget - gaze) * (1 - Math.exp(-dt * 14)); } - for (let i = drops.length - 1; i >= 0; i--) { - const d = drops[i]; - if (d.sink < 0 && d.age > d.hold && Math.hypot(d.x, d.y) < R * 0.5) d.sink = 0; - if (d.sink >= 1 || d.age > 4) drops.splice(i, 1); - } - - }; - - // Lids and gaze. Resting: blinks every 3-6s (sometimes twice) and small - // glances. Splash: squint, then wide open. Working: reads left to right. - const look = (dt: number, now: number) => { - const { state } = live.current; - const t = now / 1000; - let base = 1; - if (state === "pop") { - base = popOpenness((now - popStart) / POP_MS); - eye.toX = 0; - eye.toY = 0; - eye.blinkAt = t + nextBlinkIn("rest"); - } else if (state === "work") { - eye.toX = readingGaze(t) * 0.07; - eye.toY = -0.035; - } else if (t >= eye.nextGlance) { - eye.toX = (Math.random() - 0.5) * 0.1; - eye.toY = (Math.random() - 0.5) * 0.06; - eye.nextGlance = t + mix(2, 4, Math.random()); - } - if (state !== "pop" && t >= eye.blinkAt + 0.2) { - eye.blinkAt = t + nextBlinkIn(state); - if (state === "rest" && Math.random() < DOUBLE_BLINK_CHANCE) eye.doubleAt = eye.blinkAt + DOUBLE_BLINK_GAP_S; - } - if (eye.doubleAt > 0 && t >= eye.doubleAt + 0.2) eye.doubleAt = -1; - const lid = Math.min(blinkOpenness(t - eye.blinkAt), eye.doubleAt > 0 ? blinkOpenness(t - eye.doubleAt) : 1); - // Fast follow for gaze (a jump back to the line start must look quick). - const k = 1 - Math.exp(-dt * (state === "work" ? 30 : 12)); - eye.lookX += (eye.toX - eye.lookX) * k; - eye.lookY += (eye.toY - eye.lookY) * k; - eye.open = state === "pop" ? base : eye.open + (base - eye.open) * (1 - Math.exp(-dt * 10)); - field.eyeOn.value = live.current.eyes ? 1 : 0; - field.eyeLook.value.set(eye.lookX, eye.lookY); - field.eyeOpen.value = eye.open * lid; + const { px, radius } = resize(); + gl.viewport(0, 0, px, px); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + const stops = AGENT_STOPS[l.agent]; + gl.uniform2f(U.res, px, px); + gl.uniform1f(U.radius, radius); + gl.uniform1f(U.time, flowTime); + gl.uniform1f(U.body, body); + gl.uniform1f(U.bend, bend); + gl.uniform1f(U.flow, flow * 2.2); + gl.uniform3fv(U.drops, dropData); + gl.uniform3fv(U.stops, stops.flatMap(([c]) => hex(c))); + gl.uniform4f(U.at, stops[0][1], stops[1][1], stops[2][1], stops[3][1]); + gl.uniform1i(U.material, MATERIAL_ID[l.material]); + gl.uniform1f(U.eyes, l.eyes ? 1 : 0); + gl.uniform1f(U.open, open); + gl.uniform1f(U.gaze, gaze); + gl.drawArrays(gl.TRIANGLES, 0, 3); + firstFrame.current(true); }; - const build = () => { - const R = radius(); - const out = drops.filter((d) => d.sink < 0).reduce((sum, d) => sum + Math.pow(d.r / R, 3), 0); - const r = R * Math.max(swell.value, 0) * Math.cbrt(Math.max(0.55, 1 - out * 1.6)); - const seg = field.blobSeg.value; - const info = field.blobInfo.value; - let n = 0; - let reach = 0; - let top = 1; - const put = (x: number, y: number, pr: number, k: number) => { - seg.set([x, -y, x, -y], n * 4); - info.set([pr, pr, k, 0], n * 4); - reach = Math.max(reach, Math.hypot(x, y) + pr + k); - top = Math.max(top, pr + k); - n++; - }; - for (const ball of core) put(ball.x * swell.value, ball.y * swell.value, r * HEAD_RADIUS * ball.grow, r * HEAD_BLEND); - for (const d of drops) { - const dr = d.r * Math.min(1, d.age / 0.05) * (d.sink < 0 ? 1 : Math.cbrt(1 - d.sink)); - if (dr > 0.5) put(d.x, d.y, dr, Math.min(R * 0.55, dr * 1.8)); + const play = () => { + const want = onScreen && document.visibilityState === "visible"; + if (want && !running) { + running = true; + live.current.paused = false; + last = performance.now(); + frame = requestAnimationFrame(step); + } else if (!want) { + running = false; + cancelAnimationFrame(frame); + // A splash nobody can see still has to finish, or the blob would stay "popping". + settleNow(); } - field.blobCount.value = n; - field.blobTop.value = top; - field.blobRef.value = Math.max(r, 1); - field.blobLift.value = 1; - field.blobCenter.value.set(0, 0); - // Eyes ride the middle of the wobbling core, not the fixed box centre. - let cx = 0; - let cy = 0; - for (const ball of core) { - cx += ball.x / CORE; - cy += ball.y / CORE; - } - field.eyeCenter.value.set(cx * swell.value, -cy * swell.value); - const box = Math.min(reach + 4, Math.max(view.width, view.height)); - blob.scale.set(box * 2, box * 2, 1); - blob.visible = r >= 0.5; }; - const tick = (now: number) => { - raf = 0; - if (!alive || !onScreen) return; - const dt = Math.min(1 / 30, Math.max(1 / 240, (now - last) / 1000)); - last = now; - step(dt); - look(dt, now); - build(); - renderer.render(scene, camera); - raf = requestAnimationFrame(tick); - }; - - function start() { - if (raf || !alive || !onScreen) return; - last = performance.now(); - raf = requestAnimationFrame(tick); - } - - const resizeObserver = new ResizeObserver(resize); - resizeObserver.observe(root); - // Stop drawing while the blob is scrolled out of view. - const io = new IntersectionObserver(([entry]) => { - onScreen = entry.isIntersecting; - // A splash that finished while out of view should not replay late. - if (onScreen && performance.now() - popStart > POP_MS) calmDown(); - if (onScreen) start(); + const seen = new IntersectionObserver((entries) => { + onScreen = entries.some((e) => e.isIntersecting); + play(); }); - io.observe(root); - - poke.current = { restyle, splash }; - restyle(); - resize(); - if (live.current.state === "pop") splash(); - else swell.value = 1; + seen.observe(el); + document.addEventListener("visibilitychange", play); + const lost = (e: Event) => { + e.preventDefault(); + running = false; + cancelAnimationFrame(frame); + settleNow(); + }; + el.addEventListener("webglcontextlost", lost); + play(); + live.current.ready = true; return () => { - alive = false; - cancelAnimationFrame(raf); - window.clearTimeout(settleTimer); - poke.current = null; - resizeObserver.disconnect(); - io.disconnect(); - blob.geometry.dispose(); - skin.dispose(); - environment.dispose(); - renderer.dispose(); - canvas.remove(); + running = false; + mine.paused = true; + mine.ready = false; + cancelAnimationFrame(frame); + seen.disconnect(); + document.removeEventListener("visibilitychange", play); + el.removeEventListener("webglcontextlost", lost); + gl.deleteBuffer(buf); + gl.deleteProgram(prog); + gl.deleteShader(vs); + gl.deleteShader(fs); + // Hand the context back once the canvas has really gone (browsers cap how + // many can be open). Not at once: a quick remount reuses this canvas. + window.setTimeout(() => { + if (!el.isConnected) gl.getExtension("WEBGL_lose_context")?.loseContext(); + }, 0); }; }, []); - useEffect(() => { - poke.current?.restyle(); - }, [agent, material]); - - const firstPop = useRef(popId); - useEffect(() => { - if (popId !== firstPop.current) poke.current?.splash(); - }, [popId]); - - const box = size * CANVAS_SCALE; + const css = size * CANVAS_SCALE; + const inset = (css - size) / 2; return ( -
+ <> + {!drawn && } + + ); } diff --git a/components/referrals/evidence-box.tsx b/components/referrals/evidence-box.tsx index 8c756dcc..3844bf4b 100644 --- a/components/referrals/evidence-box.tsx +++ b/components/referrals/evidence-box.tsx @@ -198,7 +198,7 @@ export function EvidenceBox({ )}

- Sources: the NPI Registry, the CMS Medicare files, the CMS Provider Data Catalog, the state license list, OpenStreetMap (© OpenStreetMap contributors, ODbL) and their own website. Never Psychology Today or other directories. + Sources: the NPI Registry, the CMS Medicare files, the CMS Provider Data Catalog, the Illinois license list (Illinois Department of Financial and Professional Regulation (IDFPR), via data.illinois.gov, ODbL 1.0), OpenStreetMap (© OpenStreetMap contributors, ODbL) and their own website. Never Psychology Today or other directories.

{ev?.stale && !checking &&

It’s been a while since the last check.

} diff --git a/components/shared/prompt-bar.tsx b/components/shared/prompt-bar.tsx index d5896f79..436b6b0f 100644 --- a/components/shared/prompt-bar.tsx +++ b/components/shared/prompt-bar.tsx @@ -1,50 +1,21 @@ "use client"; -// Prompt Bar (UI-011): the one text box for talking to Aeon: the chat panel, -// the dashboard chat box, typed answers in onboarding, and the website chat. -// "Ask anything", an attach button, the dictation mic (clinician only) and a -// send button that turns into Stop while Aeon is working. Dictated words drop -// into the box for her to read first; nothing is sent on its own. -// Adapted from React Bits Prompt Bar (MIT, reactbits.dev/c/micro/prompt-bar): -// only the pieces the shelf keeps (no commands, sources or sparks), the -// send-to-stop morph, lucide icons, Caseload colours. Where React Bits puts its -// model and effort pickers, `controls` holds ours: Aeon's mode (Manual, Auto, -// Bypass) on the chat home. +// Prompt Bar (UI-011): the one message box for talking to Aeon. +// Original Practice-OS code (written 2026-11-04). +// +// Enter sends, Shift+Enter starts a new line. While Aeon works the send button +// turns into Stop. The mic (clinician only, never the public website chat) +// records with the Voice Pill, turns the audio into text and drops the words +// into the box for her to read first: dictation never sends on its own. +// Pickers such as Aeon's mode picker sit inside the bar, bottom left +// (`controls`). Two shapes: "box" puts the text above the buttons; "pill" is +// one 56px row that grows as she types more. -import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode, type SyntheticEvent } from "react"; -import { animate, useMotionValue, useMotionValueEvent, useReducedMotion } from "motion/react"; -import { Plus } from "lucide-react"; -import { cn } from "@/lib/utils"; +import { ArrowUp, LoaderCircle, Plus, Square } from "lucide-react"; +import { useEffect, useId, useLayoutEffect, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from "react"; import { transcribeWav } from "./dictation-audio"; -import { StatusMark } from "./status-mark"; import { VoicePill } from "./voice-pill"; -const ARROW_UP = [12, 4.5, 18.5, 11, 14.25, 11, 14.25, 19.5, 9.75, 19.5, 9.75, 11, 5.5, 11]; -const SQUARE = [12, 6, 18, 6, 18, 12, 18, 18, 6, 18, 6, 12, 6, 6]; -const mixN = (a: number, b: number, t: number) => a + (b - a) * t; -const shape = (t: number) => { - let d = ""; - for (let i = 0; i < ARROW_UP.length; i += 2) d += `${i ? "L" : "M"}${mixN(ARROW_UP[i], SQUARE[i], t).toFixed(2)} ${mixN(ARROW_UP[i + 1], SQUARE[i + 1], t).toFixed(2)}`; - return `${d}Z`; -}; - -/** The send arrow folds into a stop square while Aeon is working. */ -function SendGlyph({ busy }: { busy: boolean }) { - const reduce = useReducedMotion(); - const pathRef = useRef(null); - const t = useMotionValue(busy ? 1 : 0); - useEffect(() => { - const controls = animate(t, busy ? 1 : 0, reduce ? { duration: 0 } : { duration: 0.32, ease: [0.77, 0, 0.175, 1] }); - return () => controls.stop(); - }, [busy, reduce, t]); - useMotionValueEvent(t, "change", (v) => pathRef.current?.setAttribute("d", shape(v))); - return ( - - - - ); -} - export type PromptBarProps = { /** Sends the message. Return a promise to keep the text until it is accepted. */ onSend: (text: string) => void | Promise; @@ -64,7 +35,7 @@ export type PromptBarProps = { onAttach?: () => void; /** Attachment cards above the text (use AttachmentList). */ attachments?: ReactNode; - /** Pickers in the bar's bottom row, left, where React Bits keeps its model picker (e.g. the mode picker). */ + /** Pickers in the bar's bottom row, left (e.g. the mode picker). */ controls?: ReactNode; disabled?: boolean; /** Most rows before the box scrolls. */ @@ -74,7 +45,10 @@ export type PromptBarProps = { className?: string; }; -type DictationState = { kind: "idle" } | { kind: "working" } | { kind: "error"; message: string }; +type Heard = { at: "idle" } | { at: "transcribing" } | { at: "failed"; message: string }; + +const roundBtn = + "grid size-touch shrink-0 place-items-center rounded-full transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-40"; export function PromptBar({ onSend, @@ -89,191 +63,195 @@ export function PromptBar({ attachments, controls, disabled = false, - maxRows = 6, + maxRows = 8, shape = "box", - className, + className = "", }: PromptBarProps) { - const pill = shape === "pill"; const [text, setText] = useState(defaultValue); - const [dict, setDict] = useState({ kind: "idle" }); - const boxRef = useRef(null); - const composing = useRef(false); - const statusId = useId(); + const [heard, setHeard] = useState({ at: "idle" }); + const [recording, setRecording] = useState(false); + const box = useRef(null); + const alertId = useId(); + + // A new prefill (another "Ask Aeon" button) replaces the text; an unchanged one never does. + const [prefill, setPrefill] = useState(defaultValue); + if (prefill !== defaultValue) { + setPrefill(defaultValue); + if (defaultValue) setText(defaultValue); + } // Grow with the text up to maxRows, then scroll. - useEffect(() => { - const el = boxRef.current; + useLayoutEffect(() => { + const el = box.current; if (!el) return; el.style.height = "auto"; const line = parseFloat(getComputedStyle(el).lineHeight) || 22; - el.style.height = `${Math.min(el.scrollHeight, line * maxRows + 4)}px`; - }, [text, maxRows]); + const pad = parseFloat(getComputedStyle(el).paddingTop) + parseFloat(getComputedStyle(el).paddingBottom); + const most = line * maxRows + pad; + // Empty: one row, so a long placeholder on a phone never makes the bar taller. + const want = text ? el.scrollHeight : line + pad; + el.style.height = `${Math.min(want, most)}px`; + el.style.overflowY = text && el.scrollHeight > most ? "auto" : "hidden"; + }, [text, maxRows, shape]); + + const mounted = useRef(true); + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); - const canSend = text.trim().length > 0 && !disabled && dict.kind !== "working"; + const empty = text.trim().length === 0; + const canSend = !empty && !busy && !disabled; - const submit = async (e?: SyntheticEvent) => { - e?.preventDefault(); - if (busy) { - onStop?.(); - return; - } + const send = () => { if (!canSend) return; const message = text.trim(); - // Clear at once, like any chat box; put the words back if sending fails. setText(""); - try { - await onSend(message); - } catch { - setText((now) => now || message); - } finally { - boxRef.current?.focus(); + setHeard({ at: "idle" }); + const result = onSend(message); + // Not accepted: give her words back, unless she has started typing again. + if (result && typeof result.then === "function") { + result.catch(() => { + if (mounted.current) setText((now) => (now ? now : message)); + }); } }; + const onSubmit = (e: FormEvent) => { + e.preventDefault(); + send(); + }; + const onKeyDown = (e: KeyboardEvent) => { - if (e.key === "Enter" && !e.shiftKey && !composing.current && !e.nativeEvent.isComposing) { + if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); - void submit(); + send(); } }; - const insert = (words: string) => { - const el = boxRef.current; - if (!words) return; - setText((current) => { - const at = el && document.activeElement === el ? el.selectionStart : current.length; - const before = current.slice(0, at); - const after = current.slice(at); - const gapBefore = before && !/\s$/.test(before) ? " " : ""; - const gapAfter = after && !/^\s/.test(after) ? " " : ""; - return `${before}${gapBefore}${words}${gapAfter}${after}`; - }); - requestAnimationFrame(() => { - el?.focus(); - if (el) el.selectionStart = el.selectionEnd = el.value.length; - }); - }; - - const onRecorded = async (wav: Blob) => { - setDict({ kind: "working" }); + const heardWords = async (wav: Blob) => { + setHeard({ at: "transcribing" }); try { - const words = await transcribe(wav); + const words = (await transcribe(wav)).trim(); + if (!mounted.current) return; + setHeard({ at: "idle" }); if (!words) { - setDict({ kind: "error", message: "Didn't catch any words. Try again a little closer to the mic." }); + setHeard({ at: "failed", message: "Didn't catch any words. Try again a little closer to the mic." }); return; } - insert(words); - setDict({ kind: "idle" }); + setText((now) => (now.trim() ? `${now.trimEnd()} ${words}` : words)); + requestAnimationFrame(() => { + const el = box.current; + if (!el) return; + el.focus(); + el.setSelectionRange(el.value.length, el.value.length); + }); } catch (err) { - setDict({ kind: "error", message: err instanceof Error ? err.message : "Couldn't turn that recording into text." }); + if (mounted.current) setHeard({ at: "failed", message: err instanceof Error && err.message ? err.message : "Couldn't turn that recording into text." }); } }; - const field = ( -