import './style.css'; import { BODY, COVER, FACE_MARKUP, HEART, LEFT_HAND, LEFT_HAND_MARKUP, LIT, RIGHT_HAND, RIGHT_HAND_MARKUP } from './huggy'; import { N, SoftBody, smoothClosedPath } from './body'; import { LogoSampler, loadLogo, overlayGeometry, placementTransform, type LogoAsset, type Placement } from './logo'; import { SpringPose, poseTransform, solveLeftHand, solveRightHand, type GripChoice, type Pose } from './hands'; import { DEFAULT_WARP, LogoWarp, squishLevel, type EdgeShape, type Offsets, type WarpParams } from './warp'; import { createTuner, type ParamSpec, type SweetSpot } from './tuner'; import './ui'; import { FieldWarp } from './warpField'; import { CURRENT_VERSION, VERSIONS, type Version } from './versions'; const SVG_NS = 'http://www.w3.org/2000/svg'; const SAMPLES = ['pydantic', 'openrouter', 'fal', 'pytorch', 'meta']; /** How each sample's name is written. */ const SAMPLE_NAMES: Record = { pydantic: 'Pydantic', openrouter: 'OpenRouter', fal: 'Fal', pytorch: 'PyTorch', meta: 'Meta' }; const SHOW_CONTACT_SHADOW = false; // backlogged, see BACKLOG.md const ENABLE_LOGO_SQUISH = true; const VIEWBOX = { x: -40, y: -60, w: 1480, h: 820 }; // --------------------------------------------------------------------------------------------- // Scene const stage = document.getElementById('stage')!; stage.insertAdjacentHTML( 'beforeend', ` ${FACE_MARKUP} ${RIGHT_HAND_MARKUP} ${LEFT_HAND_MARKUP} ${HEART.markup} `, ); const scene = document.getElementById('scene') as unknown as SVGSVGElement; const $ = (id: string) => document.getElementById(id) as unknown as T; const el = { drop: $('drop'), bodyFill: $('bodyFill'), bodyStroke: $('bodyStroke'), bodyClipPath: $('bodyClipPath'), bodyShadow: $('bodyShadow'), cover: $('cover'), logoLayer: $('logoLayer'), logoContent: $('logoContent'), contactShadow: $('contactShadow'), huggySquishShadow: $('huggySquishShadow'), logoSquishShadow: $('logoSquishShadow'), pressShadow: $('pressShadow'), contactShadowGroup: $('contactShadowGroup'), rightHand: $('rightHand'), leftHand: $('leftHand'), heart: $('heart'), debug: $('debugLayer'), status: document.getElementById('status')!, }; // --------------------------------------------------------------------------------------------- // State const body = new SoftBody(); // Probe body used to evaluate the squish at the freeze depth (never drawn). const probe = new SoftBody(body.params); const rightHand = new SpringPose(150, 18); const leftHand = new SpringPose(110, 15); // Hands can be dragged and pinned; a pinned hand stays put until its magnet button snaps it // back to its automatic (adaptive) position. type HandSide = 'left' | 'right'; const handPinned: Record = { left: null, right: null }; let logo: LogoAsset | null = null; let placement: Placement = { cx: 860, cy: 330, scale: 1, rot: 0 }; let sampler: LogoSampler | null = null; let engaged = false; let hug = 0; // 0..1, eased let hugVel = 0; let cover = 0; let coverVel = 0; let heartScale = 0; let heartVel = 0; let grip: GripChoice | null = null; let warp: LogoWarp | FieldWarp | null = null; // Selected squish version (Version dropdown); remembered across reloads. const VERSION_KEY = 'hugging-partnership.version'; // A saved choice of a reverted version falls back to the current one. // Developer tools (version picker, sweet-spot recording) only in the dev server; the public // Space (a production build) is for users: always the current version, no recording. const DEV_TOOLS = import.meta.env.DEV; const savedVersion = DEV_TOOLS ? VERSIONS.find((v) => v.id === localStorage.getItem(VERSION_KEY)) : undefined; let version: Version = savedVersion && !savedVersion.label.includes('(reverted)') ? savedVersion : CURRENT_VERSION; let squish = 0; // global squish level 0..1 (how deep the logo is in Huggy) // How close (px) the logo must get to the right cheek before the mouth cover starts to grow. const DEFAULT_COVER_REACH = 74; // designer sweet spots: 77 (Pydantic), 70 (Fal) let coverReach = DEFAULT_COVER_REACH; // Logo-squish settings shared by every logo's warp (the tuning panel edits these). const warpParams: WarpParams = { ...DEFAULT_WARP }; // The current logo's source, so a sweet spot can be reloaded exactly. let logoSource: { name: string; sample: boolean; svg: string } | null = null; let debug = false; const CHEEK_EASE = 0.7; // < 1: the cheek squish grows faster in the early part (1 = linear with the squish level) let firstFit = true; // the first logo snaps the camera into place; later ones glide function setStatus(msg: string) { el.status.textContent = msg; } function logoSize(): number { return logo ? Math.max(logo.vbW, logo.vbH) * placement.scale : 0; } function updateSampler() { sampler = logo ? new LogoSampler(logo, placement) : null; if (logo) el.logoContent.setAttribute('transform', placementTransform(logo, placement)); renderDebugOverlay(); updateResetState(); } /** Reset (next to the Size / Rotate sliders) puts only those back: the default size and no * rotation; the logo stays where it is. It's dimmed (and inactive) when both already are. */ const defaultLogoSize = () => Number(($('size')).defaultValue) || 600; function updateResetState() { const btn = document.getElementById('reset') as HTMLButtonElement | null; if (!btn) return; btn.disabled = !logo || (Math.abs(logoSize() - defaultLogoSize()) < 1 && Math.abs(placement.rot) < 1e-3); } function defaultPlacement(asset: LogoAsset, size: number): Placement { const scale = size / Math.max(asset.vbW, asset.vbH); const w = asset.vbW * scale; // Overlap the body edge so the hug starts right away, a little below Huggy's middle. return { cx: BODY.cx + BODY.r + w * 0.5 - Math.min(w * 0.3, 180), cy: BODY.cy + 45, scale, rot: 0 }; } /** A new logo's start: a little below Huggy's middle, slid in until it reaches the same depth * into Huggy whatever its shape (round logos reach in further than angular ones at the same * offset, so a fixed offset made some barely touch and others over-pressed). */ const START_DEPTH = 0.45; // × Huggy's outer radius function startPlacement(asset: LogoAsset, size: number): Placement { const base = defaultPlacement(asset, size); const w = asset.vbW * base.scale; const Rout = BODY.r + BODY.strokeWidth / 2; const depthAt = (cx: number) => { probe.scan(new LogoSampler(asset, { ...base, cx })); return probe.logoDepth; }; let near = BODY.cx + BODY.r - w * 0.3; // deep in let far = BODY.cx + BODY.r + w * 0.5 + 40; // not touching if (depthAt(near) < START_DEPTH * Rout) return { ...base, cx: near }; for (let it = 0; it < 14; it++) { const mid = (near + far) / 2; if (depthAt(mid) > START_DEPTH * Rout) near = mid; else far = mid; } return { ...base, cx: (near + far) / 2 }; } async function useLogo(text: string, name: string, sample = false) { try { const asset = await loadLogo(text, name); if (!sample) stage.classList.remove('welcome'); // their own logo: straight to the hug logo = asset; logoSource = { name, sample, svg: text }; handPinned.left = null; // a new logo starts with both hands on automatic handPinned.right = null; grip = null; const size = Number(($('size')).value); placement = startPlacement(asset, size); ($('rotation')).value = '0'; mountLogo(); fitCamera(!firstFit); firstFit = false; setStatus(''); } catch (err) { setStatus(err instanceof Error ? err.message : String(err)); } } /** (Re)insert the logo's original markup and build the squish engine of the selected version. */ function mountLogo() { if (!logo) return; el.logoContent.innerHTML = logo.markup; updateSampler(); const root = el.logoContent.querySelector('svg'); const maxDim = Math.max(logo.vbW, logo.vbH); if (!ENABLE_LOGO_SQUISH || !root) warp = null; else if (version.engine === 'field') { const fw = new FieldWarp(root, logo.vbX, logo.vbY, maxDim); fw.params = warpParams; warp = fw; } else { // v8 uses finer path pieces so bend ends land close to where the wall meets Huggy. const lw = new LogoWarp(root, logo.vbX, logo.vbY, maxDim, version.mode?.smoothHandles ? 0.01 : 0.02); lw.params = warpParams; lw.mode = { ...(version.mode ?? lw.mode) }; warp = lw; } frozenShape = null; // a new logo / engine never inherits a previous frozen squish frozenEdge = null; } async function loadSample(name: string) { markSample(name); const res = await fetch(`./samples/${name}.svg`); await useLogo(await res.text(), name, true); } // --------------------------------------------------------------------------------------------- // Frame update function springScalar(x: number, v: number, target: number, k: number, d: number, dt: number): [number, number] { const a = k * (target - x) - d * v; v += a * dt; return [x + v * dt, v]; } /** * Contact shadow on the logo, only where a logo edge borders a visible bulge (so the body * never shows "through" the logo): * - stroke far edge: the body squeezes out from under a stroke → band just inside that edge; * - far wall: a bulge presses against the next stroke → band just inside that wall. * Bands taper at their ends and are clipped to the logo by the logo mask. */ function contactShadowPath(): string { const W = 13; const R = BODY.r; let d = ''; const s = sampler; if (!s) return ''; // Snap a point onto the real logo edge (the ray march is only 3px accurate) and return it // with the edge's outward normal. Offsetting along that normal, not along the ray, keeps // the band hugging the edge even where a ray grazes it at a shallow angle. const snap = (x: number, y: number) => { let n = s.normal(x, y); for (let it = 0; it < 3; it++) { const dist = s.sdf(x, y); x -= n.x * dist; y -= n.y * dist; n = s.normal(x, y); } return { x, y, n }; }; const band = (run: number[], edgeOf: (i: number) => number) => { if (run.length < 2) return; const pts = run.map((i) => { const r = edgeOf(i); return snap(BODY.cx + body.cos[i] * r, BODY.cy + body.sin[i] * r); }); // Split where the snapped edge jumps (the run crossed onto a different edge). let start = 0; for (let j = 1; j <= pts.length; j++) { const jump = j < pts.length && Math.hypot(pts[j].x - pts[j - 1].x, pts[j].y - pts[j - 1].y) > 22; if (j === pts.length || jump) { const seg = pts.slice(start, j); if (seg.length >= 2) { const outer: string[] = []; const inner: string[] = []; seg.forEach((p, k) => { const t = (k + 0.5) / seg.length; const taper = Math.pow(Math.sin(Math.PI * t), 0.6); const f = (x: number, y: number) => `${x.toFixed(1)} ${y.toFixed(1)}`; outer.push(f(p.x + p.n.x * 2, p.y + p.n.y * 2)); // a hair outside; the mask trims it inner.push(f(p.x - p.n.x * W * taper, p.y - p.n.y * W * taper)); }); d += `M${outer.join('L')}L${inner.reverse().join('L')}Z`; } start = j; } } }; const collect = (test: (i: number) => boolean, edgeOf: (i: number) => number) => { let origin = -1; for (let i = 0; i < N; i++) if (!test(i)) { origin = i; break; } if (origin < 0) origin = 0; let run: number[] = []; for (let n = 0; n <= N; n++) { const i = (origin + n) % N; if (n < N && test(i)) run.push(i); else { band(run, edgeOf); run = []; } } }; // Stroke far edge, where the body squeezes out from under a stroke. collect( (i) => body.rays[i].eligible && body.rays[i].base > R + 1 && body.r[i] > body.rays[i].base + 4, (i) => body.rays[i].base, ); // Far wall touched by the bulge. collect( (i) => body.rays[i].eligible && body.r[i] >= body.rays[i].wall - 3, (i) => body.rays[i].wall, ); return d; } /** Huggy's outline radius at an angle, from a radius-per-ray array. */ function radiusAt(rays: Float32Array, a: number) { const f = ((a / (Math.PI * 2)) * N + N) % N; const i = Math.floor(f); const t = f - i; return rays[i] * (1 - t) + rays[(i + 1) % N] * t; } /** * Logo squish with a freeze depth: up to `freezeDepth` the logo squishes normally. When it * first gets deeper, the squish shape at exactly the freeze depth is captured once (computed * with the logo backed out along the hug direction) and reused while it stays deeper, so the * shape stops changing and just moves with the drag. Coming back out, it blends from the * frozen shape to the live squish over a short depth band, so there's no jump. Changing a * squish setting retakes the snapshot. */ let frozenShape: Offsets | null = null; let frozenEdge: EdgeShape | null = null; // v8: frozen edge bow only let frozenKey = ''; function applyLogoSquish(hugAmount: number) { if (!warp) return; // Earlier versions: logo squish didn't follow the squish level, and nothing froze. const logoSquish = version.depthDriven ? squish : 1; if (!version.freeze || !(warp instanceof LogoWarp)) { frozenShape = null; warp.apply(sampler, hugAmount, body.touching, (a) => radiusAt(body.r, a), logoSquish); return; } const Rout = BODY.r + BODY.strokeWidth / 2; const freeze = warpParams.freezeDepth * Rout; const band = 0.04 * Rout; const key = version.id + JSON.stringify(warpParams) + JSON.stringify(body.params) + hugAmount.toFixed(2); const depth = body.logoDepth; if (!sampler || !logo || hugAmount < 0.98 || depth < freeze - band) { // Live squish (also while a hug fades in/out). frozenShape = null; frozenEdge = null; warp.apply(sampler, hugAmount, body.touching, (a) => radiusAt(body.r, a), squish); return; } if (version.freezeEdgeOnly) { // v8: only the edge bow freezes; pocket bends keep following Huggy's swell at any depth. frozenShape = null; if (!frozenEdge || frozenKey !== key) { warp.frozenEdge = null; captureAtFreezeDepth(depth, freeze, hugAmount); frozenEdge = warp.snapshotEdge(); frozenKey = key; } warp.frozenEdge = frozenEdge ? { shape: frozenEdge, amount: (depth - (freeze - band)) / band } : null; warp.apply(sampler, hugAmount, body.touching, (a) => radiusAt(body.r, a), squish); warp.frozenEdge = null; return; } if (!frozenShape || frozenKey !== key) { captureAtFreezeDepth(depth, freeze, hugAmount); frozenShape = warp.snapshot(); frozenKey = key; } if (!frozenShape) return; if (depth >= freeze) { warp.showFrozen(frozenShape); } else { // Just above the freeze depth: blend the live squish into the frozen shape. warp.apply(sampler, hugAmount, body.touching, (a) => radiusAt(body.r, a), squish); warp.showFrozen(frozenShape, (depth - (freeze - band)) / band); } } /** Apply the squish as it is with the logo backed out along the hug direction to exactly the * freeze depth (for capturing the frozen shape). */ function captureAtFreezeDepth(depth: number, freeze: number, hugAmount: number) { if (!(warp instanceof LogoWarp) || !sampler || !logo) return; { // Capture the shape at exactly the freeze depth: back the logo out along the hug direction. let dx = placement.cx - BODY.cx; let dy = placement.cy - BODY.cy; const len = Math.hypot(dx, dy) || 1; dx /= len; dy /= len; let back = depth - freeze; let virt = sampler; for (let it = 0; it < 5; it++) { virt = new LogoSampler(logo, { ...placement, cx: placement.cx + dx * back, cy: placement.cy + dy * back }); probe.scan(virt); const err = probe.logoDepth - freeze; if (Math.abs(err) < 0.5) break; back += err; } const frozenSquish = squishLevel(freeze, warpParams); probe.solveTargets(hugAmount, frozenSquish); warp.apply(virt, hugAmount, probe.touching, (a) => radiusAt(probe.target, a), frozenSquish); } } function frame(dt: number) { body.scan(sampler); // Engage / release with hysteresis. const wasEngaged = engaged; if (!engaged && sampler && (body.overlapArea > 150 || body.minGap < 10)) engaged = true; if (engaged && (!sampler || (body.overlapArea === 0 && body.minGap > 70))) engaged = false; if (engaged && !wasEngaged) { body.poke(160); heartVel = 9; } [hug, hugVel] = springScalar(hug, hugVel, engaged ? 1 : 0, 90, 16, dt); const hugClamped = Math.max(0, Math.min(1.15, hug)); // Global squish level: how deep the logo is in Huggy drives every squish effect. squish = squishLevel(body.logoDepth, warpParams); body.solveTargets(Math.min(1, hugClamped), squish); body.step(dt); // Hands. if (engaged && sampler) { rightHand.target = solveRightHand(sampler); grip = solveLeftHand(sampler, grip, body.touching); leftHand.target = grip ? grip.pose : { x: 0, y: 0, rot: 0 }; } else { rightHand.target = { x: 0, y: 0, rot: 0 }; leftHand.target = { x: 0, y: 0, rot: 0 }; grip = null; } if (handPinned.right) rightHand.target = handPinned.right; if (handPinned.left) leftHand.target = handPinned.left; rightHand.step(dt); applyLogoSquish(Math.min(1, hugClamped)); renderSquishShadows(); leftHand.step(dt); // Mouth cover: cheek squish when the logo is close to the right cheek. let coverTarget = 0; if (sampler && engaged) { const dist = sampler.distToLogo(COVER.cheek.x, COVER.cheek.y); // 0 until the logo is really pressing near the cheek; full once it reaches the cheek point. const near = coverReach > 0 ? Math.max(0, Math.min(1, (coverReach - dist) / coverReach)) : 0; // v8: the cheek squishes in step with the logo (same squish level), not before it. // (Eased out: it starts with the logo squish but builds a bit faster early on.) coverTarget = version.cheekFollowsSquish ? near * Math.pow(squish, CHEEK_EASE) : near; } [cover, coverVel] = springScalar(cover, coverVel, coverTarget, 120, 16, dt); [heartScale, heartVel] = springScalar(heartScale, heartVel, engaged ? 1 : 0, 160, 12, dt); render(); } /** v8: thin moon shadows along every pocket bow, on the logo and on Huggy (overlays). */ function renderSquishShadows() { const shadows = warp instanceof LogoWarp && warp.mode.shadows ? warp.shadows : []; el.logoSquishShadow.setAttribute('d', shadows.map((s) => s.logo).join('')); el.huggySquishShadow.setAttribute('d', shadows.map((s) => s.huggy).join('')); el.pressShadow.setAttribute('d', warp instanceof LogoWarp && warp.mode.shadows && warp.mode.pressArc ? warp.pressShadow : ''); } function render() { const pts = body.points(); const d = smoothClosedPath(pts); el.bodyFill.setAttribute('d', d); el.bodyStroke.setAttribute('d', d); el.bodyClipPath.setAttribute('d', d); const lit = smoothClosedPath(body.points(LIT.s, LIT.dx, LIT.dy)); const e = BODY.r * 2.2; // generous box around the body; the body clip trims it el.bodyShadow.setAttribute( 'd', `M${BODY.cx - e} ${BODY.cy - e}H${BODY.cx + e}V${BODY.cy + e}H${BODY.cx - e}Z${lit}`, ); const c = Math.max(0, Math.min(1.1, cover)); const lerp = (a: number, b: number) => a + (b - a) * c; const { rest, squished } = COVER; const cx = lerp(rest.cx, squished.cx); const cy = lerp(rest.cy, squished.cy); el.cover.setAttribute('cx', cx.toFixed(2)); el.cover.setAttribute('cy', cy.toFixed(2)); el.cover.setAttribute('rx', lerp(rest.rx, squished.rx).toFixed(2)); el.cover.setAttribute('ry', lerp(rest.ry, squished.ry).toFixed(2)); el.cover.setAttribute('transform', `rotate(${COVER.rotate} ${cx.toFixed(2)} ${cy.toFixed(2)})`); el.cover.style.display = c < 0.01 ? 'none' : ''; // Contact shadow painting is on the backlog (see BACKLOG.md); keep it off for now. if (SHOW_CONTACT_SHADOW) { el.contactShadow.setAttribute('d', logo ? contactShadowPath() : ''); el.contactShadowGroup.setAttribute('opacity', (0.24 * Math.max(0, Math.min(1, hug))).toFixed(3)); } else { el.contactShadow.setAttribute('d', ''); } el.rightHand.setAttribute('transform', poseTransform(rightHand.pose, RIGHT_HAND.tip)); el.leftHand.setAttribute('transform', poseTransform(leftHand.pose, LEFT_HAND.grip)); // Hand shadows on the logo follow the hands, nudged down-left. const shift = `translate(${HAND_SHADOW.dx} ${HAND_SHADOW.dy}) `; handShadowEls.right.setAttribute('transform', shift + (el.rightHand.getAttribute('transform') ?? '')); handShadowEls.left.setAttribute('transform', shift + (el.leftHand.getAttribute('transform') ?? '')); placeMagnets(); // Heart: visible while hugging (it is part of the default art too). const hs = Math.max(0, heartScale); el.heart.setAttribute( 'transform', `translate(${HEART.cx} ${HEART.cy}) scale(${hs.toFixed(3)}) translate(${-HEART.cx} ${-HEART.cy})`, ); el.heart.style.display = hs < 0.02 ? 'none' : ''; if (debug) renderDebugMarks(); } function renderDebugOverlay() { el.debug.innerHTML = ''; if (!debug || !logo) return; const g = overlayGeometry(logo); el.debug.insertAdjacentHTML( 'beforeend', ``, ); } function renderDebugMarks() { const marks = document.getElementById('debugMarks'); if (!marks) return; let html = ``; for (let i = 0; i < N; i += 2) { const ray = body.rays[i]; if (!ray.eligible) continue; const x = BODY.cx + body.cos[i] * ray.wall; const y = BODY.cy + body.sin[i] * ray.wall; html += ``; } if (grip) html += ``; html += ``; marks.innerHTML = html; } let last = performance.now(); function loop(now: number) { const dt = Math.min(1 / 30, (now - last) / 1000); last = now; frame(dt); requestAnimationFrame(loop); } // --------------------------------------------------------------------------------------------- // Interaction function toScene(evt: { clientX: number; clientY: number }) { const pt = scene.createSVGPoint(); pt.x = evt.clientX; pt.y = evt.clientY; return pt.matrixTransform(scene.getScreenCTM()!.inverse()); } /** * Make sure a drag always ends when the pointer is released, even if the release never reaches * the dragged element (released outside the window, a context menu or app switch in between, * or pointer capture lost): otherwise the dragged thing keeps following the cursor, which stays * over it, with no button pressed. */ function guardDrag(target: Element, endDrag: (pointerId: number | null) => void) { target.addEventListener('lostpointercapture', (e) => endDrag((e as PointerEvent).pointerId)); window.addEventListener('pointerup', (e) => endDrag(e.pointerId)); window.addEventListener('pointercancel', (e) => endDrag(e.pointerId)); window.addEventListener('blur', () => endDrag(null)); } /** A mouse move with no button pressed means the release was missed. */ const releasedWithoutUp = (e: PointerEvent) => e.pointerType === 'mouse' && e.buttons === 0; let drag: { dx: number; dy: number; id: number } | null = null; el.logoLayer.addEventListener('pointerdown', (e) => { if (!logo) return; const p = toScene(e); drag = { dx: placement.cx - p.x, dy: placement.cy - p.y, id: e.pointerId }; try { el.logoLayer.setPointerCapture(e.pointerId); } catch { /* some synthetic / pen pointers can't be captured; the guards below still end the drag */ } el.logoLayer.classList.add('dragging'); }); el.logoLayer.addEventListener('pointermove', (e) => { if (!drag || e.pointerId !== drag.id || pinch) return; if (releasedWithoutUp(e)) { endLogoDrag(e.pointerId); return; } const p = toScene(e); placement = { ...placement, cx: p.x + drag.dx, cy: p.y + drag.dy }; updateSampler(); }); function endLogoDrag(pointerId: number | null) { if (!drag || (pointerId !== null && pointerId !== drag.id)) return; drag = null; el.logoLayer.classList.remove('dragging'); } el.logoLayer.addEventListener('pointerup', (e) => endLogoDrag(e.pointerId)); el.logoLayer.addEventListener('pointercancel', (e) => endLogoDrag(e.pointerId)); guardDrag(el.logoLayer, endLogoDrag); // ----- Hands: drag to pin, magnet to snap back ----- // Magnet icon: IonIcons "magnet-sharp" by Ben Sperry (MIT, https://github.com/ionic-team/ionicons). const MAGNET_ICON = ``; // Hover / drag outline: a copy of the hand's own shapes drawn behind it, every shape stroked // HALO px wider all round (round joins), so the outline is exactly the same width everywhere // (a filter-based outline grows a square kernel and looks uneven). Solid, 0 blur. Hidden via // opacity="0" so exports never show it; CSS raises it on hover / drag. const HALO = 6; function addHalo(g: SVGGElement) { const halo = document.createElementNS(SVG_NS, 'g'); halo.setAttribute('class', 'hand-halo'); halo.setAttribute('opacity', '0'); halo.setAttribute('pointer-events', 'none'); for (const child of Array.from(g.children)) halo.appendChild(child.cloneNode(true)); halo.querySelectorAll('path').forEach((p) => { const sw = p.getAttribute('stroke') && p.getAttribute('stroke') !== 'none' ? parseFloat(p.getAttribute('stroke-width') ?? '0') || 0 : 0; const filled = (p.getAttribute('fill') ?? '#000') !== 'none'; p.removeAttribute('id'); p.setAttribute('stroke', '#12141F'); p.setAttribute('stroke-width', String(sw + 2 * HALO)); p.setAttribute('stroke-linejoin', 'round'); p.setAttribute('stroke-linecap', 'round'); p.setAttribute('fill', filled ? '#12141F' : 'none'); }); g.insertBefore(halo, g.firstChild); return halo; } /** * Sample points of a hand's visible outline (path points + how far the visible edge, incl. the * outline, extends beyond them), for placing its magnet next to the actual shape. */ function handOutline(g: SVGGElement) { const pts: { path: SVGPathElement; x: number; y: number; ext: number }[] = []; g.querySelectorAll('.hand-halo path').forEach((p) => { const ext = (parseFloat(p.getAttribute('stroke-width') ?? '0') || 0) / 2; const L = p.getTotalLength(); const n = Math.max(12, Math.ceil(L / 8)); for (let i = 0; i < n; i++) { const q = p.getPointAtLength((i / n) * L); pts.push({ path: p, x: q.x, y: q.y, ext }); } }); return pts; } const handEls: Record = { left: el.leftHand, right: el.rightHand }; const handSprings: Record = { left: leftHand, right: rightHand }; const magnets = {} as Record; // Invisible "safe zone" per hand: the area wrapping the hand's top-right edge and its magnet // button, so moving the cursor from the hand to the button never drops the hover. const safeLayer = document.createElementNS(SVG_NS, 'svg'); safeLayer.classList.add('magnet-safe'); stage.appendChild(safeLayer); const safeZones = {} as Record; // A pinned hand's magnet shows while the hand (or the button) is hovered or dragged, and hides // 150 ms after the pointer leaves, so moving from the hand to the button doesn't lose it. // (Touch has no hover: after a tap the buttons stay up a few seconds so they can be tapped.) const MAGNET_HIDE_DELAY = window.matchMedia('(hover: none)').matches ? 3000 : 150; const magnetHover: Record = { left: false, right: false }; // Hidden hands: invisible (and left out of exports); a 30% ghost while the pointer is close // to or over it, so it can be found and shown again. const handHidden: Record = { left: false, right: false }; const handNear: Record = { left: false, right: false }; const hideBtns = {} as Record; const HAND_NEAR = 56; // px around a hidden hand's box that counts as "close" const EYE_OFF = ``; const EYE = ``; function applyHandVisibility(side: HandSide) { const g = handEls[side]; const ghost = magnetHover[side] || handNear[side] || g.classList.contains('dragging'); g.style.opacity = handHidden[side] ? (ghost ? '0.3' : '0') : ''; handShadowEls[side].style.display = handHidden[side] ? 'none' : ''; const b = hideBtns[side]; if (b) { b.innerHTML = handHidden[side] ? EYE : EYE_OFF; b.title = handHidden[side] ? 'Show this hand' : 'Hide this hand'; b.setAttribute('aria-label', `${handHidden[side] ? 'Show' : 'Hide'} the ${side} hand`); } } window.addEventListener('pointermove', (e) => { for (const side of ['left', 'right'] as const) { if (!handHidden[side]) continue; const r = handEls[side].getBoundingClientRect(); const dx = Math.max(r.left - e.clientX, 0, e.clientX - r.right); const dy = Math.max(r.top - e.clientY, 0, e.clientY - r.bottom); const near = Math.hypot(dx, dy) < HAND_NEAR; if (near !== handNear[side]) { handNear[side] = near; applyHandVisibility(side); placeMagnets(); } } }); const magnetTimer: Record = { left: 0, right: 0 }; function setMagnetHover(side: HandSide, on: boolean) { window.clearTimeout(magnetTimer[side]); if (on) magnetHover[side] = true; else magnetTimer[side] = window.setTimeout(() => { magnetHover[side] = false; placeMagnets(); applyHandVisibility(side); }, MAGNET_HIDE_DELAY); placeMagnets(); applyHandVisibility(side); } // Hand shadows on the logo (as in the Figma hugs): each hand's silhouette, outline included, // shifted a little down-left, as a 20% black overlay masked to the logo, under the hands. const HAND_SHADOW = { dx: -2, dy: 6 }; const HAND_ROT_STEP = 3; // degrees per scroll event, at most const handWheel = {} as Record void>; const handShadowEls = { left: document.getElementById('leftHandShadow') as unknown as SVGGElement, right: document.getElementById('rightHandShadow') as unknown as SVGGElement, }; for (const side of ['left', 'right'] as const) { const target = handShadowEls[side]; for (const child of Array.from(handEls[side].children)) target.appendChild(child.cloneNode(true)); target.querySelectorAll('*').forEach((n) => n.removeAttribute('id')); target.querySelectorAll('path, ellipse, circle, rect, polygon').forEach((p) => { const sw = p.getAttribute('stroke') && p.getAttribute('stroke') !== 'none' ? parseFloat(p.getAttribute('stroke-width') ?? '0') || 0 : 0; p.setAttribute('fill', '#000'); p.setAttribute('stroke', sw > 0 ? '#000' : 'none'); if (sw > 0) p.setAttribute('stroke-linejoin', 'round'); }); } for (const side of ['left', 'right'] as const) { const g = handEls[side]; const spring = handSprings[side]; let drag: { id: number; start: { x: number; y: number }; pose0: Pose } | null = null; g.addEventListener('pointerdown', (e) => { e.stopPropagation(); drag = { id: e.pointerId, start: toScene(e), pose0: { ...spring.pose } }; try { g.setPointerCapture(e.pointerId); } catch { /* some synthetic / pen pointers can't be captured; dragging still works */ } g.classList.add('dragging'); }); g.addEventListener('pointermove', (e) => { if (!drag || e.pointerId !== drag.id) return; if (releasedWithoutUp(e)) { end(e.pointerId); return; } const p = toScene(e); const pose = { x: drag.pose0.x + p.x - drag.start.x, y: drag.pose0.y + p.y - drag.start.y, rot: drag.pose0.rot }; handPinned[side] = pose; // Follow the pointer directly while dragging (no spring lag). spring.pose = { ...pose }; spring.vel = { x: 0, y: 0, rot: 0 }; }); function end(pointerId: number | null) { if (!drag || (pointerId !== null && pointerId !== drag.id)) return; drag = null; g.classList.remove('dragging'); } g.addEventListener('pointerup', (e) => end(e.pointerId)); g.addEventListener('pointercancel', (e) => end(e.pointerId)); guardDrag(g, end); // Scroll over a hand to rotate it (pins it, like dragging). It turns around its own centre, // so it spins in place; the step follows the scroll amount (a wheel notch ≈ 3°, trackpads // turn it smoothly). const anchor = side === 'left' ? LEFT_HAND.grip : RIGHT_HAND.tip; const box = g.getBBox(); const centre = { x: box.x + box.width / 2, y: box.y + box.height / 2 }; // hand-local handWheel[side] = (e: WheelEvent) => { { const delta = e.deltaY || e.deltaX; if (!delta) return; const stepDeg = Math.max(-HAND_ROT_STEP, Math.min(HAND_ROT_STEP, delta * 0.05)); const base = handPinned[side] ?? spring.pose; const rot = base.rot + (stepDeg * Math.PI) / 180; // Keep the hand's centre where it is: anchor + p + R(rot)(centre − anchor) stays fixed. const at = (pose: Pose) => { const c = Math.cos(pose.rot); const s = Math.sin(pose.rot); const vx = centre.x - anchor.x; const vy = centre.y - anchor.y; return { x: anchor.x + pose.x + c * vx - s * vy, y: anchor.y + pose.y + s * vx + c * vy }; }; const fixed = at(base); const c = Math.cos(rot); const s = Math.sin(rot); const vx = centre.x - anchor.x; const vy = centre.y - anchor.y; const pose = { x: fixed.x - anchor.x - (c * vx - s * vy), y: fixed.y - anchor.y - (s * vx + c * vy), rot }; handPinned[side] = pose; spring.pose = { ...pose }; spring.vel = { x: 0, y: 0, rot: 0 }; setMagnetHover(side, true); } }; addHalo(g); const btn = document.createElement('button'); btn.className = 'magnet'; btn.type = 'button'; btn.hidden = true; btn.title = 'Snap back to the automatic position'; btn.setAttribute('aria-label', `Snap the ${side} hand back to its automatic position`); btn.innerHTML = MAGNET_ICON; btn.addEventListener('click', () => { handPinned[side] = null; // the spring eases it back to the adaptive pose btn.hidden = true; }); stage.appendChild(btn); magnets[side] = btn; const hide = document.createElement('button'); hide.className = 'magnet hand-hide'; hide.type = 'button'; hide.hidden = true; hide.addEventListener('click', () => { handHidden[side] = !handHidden[side]; applyHandVisibility(side); placeMagnets(); }); stage.appendChild(hide); hideBtns[side] = hide; applyHandVisibility(side); const zone = document.createElementNS(SVG_NS, 'polygon'); zone.style.display = 'none'; safeLayer.appendChild(zone); safeZones[side] = zone; for (const target of [g, btn, hide, zone] as Element[]) { target.addEventListener('pointerenter', () => setMagnetHover(side, true)); target.addEventListener('pointerleave', () => setMagnetHover(side, false)); } // The zone overlaps the hand's edge: it only catches the pointer once it has left the hand, // and steps aside as soon as the pointer is over the hand again, so the hand stays grabbable. g.addEventListener('pointerenter', () => zone.classList.remove('armed')); g.addEventListener('pointerleave', () => zone.classList.add('armed')); zone.addEventListener('pointermove', (e) => { if (document.elementsFromPoint(e.clientX, e.clientY).some((el) => g.contains(el))) zone.classList.remove('armed'); }); } const outlines = {} as Record>; const noHover = window.matchMedia('(hover: none)'); const MAGNET_GAP = 12; // px of breathing room between the hand's outline and the button const SAFE_REACH = 110; // safe zone covers the hand's outline within this distance of the button const SAFE_MARGIN = 8; // and this much room around the button /** Convex hull (monotone chain), counter-clockwise. */ function convexHull(points: { x: number; y: number }[]) { const p = points.slice().sort((a, b) => a.x - b.x || a.y - b.y); if (p.length < 3) return p; const cross = (o: { x: number; y: number }, a: { x: number; y: number }, b: { x: number; y: number }) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); const lower: typeof p = []; for (const q of p) { while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], q) <= 0) lower.pop(); lower.push(q); } const upper: typeof p = []; for (let i = p.length - 1; i >= 0; i--) { const q = p[i]; while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], q) <= 0) upper.pop(); upper.push(q); } return lower.slice(0, -1).concat(upper.slice(0, -1)); } /** * Keep each pinned hand's magnet just outside the hand's actual top-right-most point (same * rule for both hands, whatever their shape or rotation), clear of its hover outline. */ function placeMagnets() { if (!magnets.left) return; const st = stage.getBoundingClientRect(); const D = Math.SQRT1_2; for (const side of ['left', 'right'] as const) { const btn = magnets[side]; const hide = hideBtns[side]; const zone = safeZones[side]; const hovered = magnetHover[side] || handEls[side].classList.contains('dragging') || (handHidden[side] && handNear[side]); // Magnet: a pinned, visible hand (always shown on touch, which has no hover). const showMagnet = !!handPinned[side] && !handHidden[side] && (hovered || noHover.matches); // Hide / show: on hover (or close to a hidden hand). const showHide = hovered; if (!showMagnet && !showHide) { btn.hidden = true; hide.hidden = true; zone.style.display = 'none'; continue; } if (!outlines[side]) outlines[side] = handOutline(handEls[side]); let best = -Infinity; let bx = 0; let by = 0; const edge: { x: number; y: number }[] = []; // the hand's visible outline, screen px for (const p of outlines[side]) { const m = p.path.getScreenCTM(); if (!m) continue; const x = m.a * p.x + m.c * p.y + m.e; const y = m.b * p.x + m.d * p.y + m.f; const ext = p.ext * Math.hypot(m.a, m.b); // visible edge beyond the path, in screen px edge.push({ x, y }); const reach = (x - y) * D + ext; if (reach > best) { best = reach; bx = x + ext * D; by = y - ext * D; } } const r = 14; // button radius (28 px buttons) const cx = bx + (r + MAGNET_GAP) * D; const cy = by - (r + MAGNET_GAP) * D; // Buttons in a row from the hand's top-right point: [magnet] [hide]. Each has a fixed slot // (the hide button only takes the first slot when the hand isn't pinned), so hiding the // hand — which also hides its magnet — never moves the hide button: it can be toggled // back and forth in place. const spots: { x: number; y: number }[] = []; const put = (b: HTMLButtonElement, show: boolean, slot: number) => { b.hidden = !show; if (!show) return; const x = cx + slot * (2 * r + 6); spots.push({ x, y: cy }); b.style.left = `${x - st.left}px`; b.style.top = `${cy - st.top}px`; }; put(btn, showMagnet, 0); put(hide, showHide, handPinned[side] ? 1 : 0); // Safe zone: convex hull of the buttons (plus a margin) and the hand's outline near them, // so any straight path from that part of the hand to a button stays inside. const pts = edge.filter((q) => Math.hypot(q.x - cx, q.y - cy) < SAFE_REACH); const rr = r + SAFE_MARGIN; for (const sp of spots) { for (let k = 0; k < 16; k++) { const a = (k / 16) * Math.PI * 2; pts.push({ x: sp.x + Math.cos(a) * rr, y: sp.y + Math.sin(a) * rr }); } } zone.setAttribute('points', convexHull(pts).map((q) => `${(q.x - st.left).toFixed(1)},${(q.y - st.top).toFixed(1)}`).join(' ')); zone.style.display = ''; } } const sizeInput = $('size'); const rotInput = $('rotation'); function setSize(px: number) { if (!logo) return; px = Math.max(140, Math.min(1000, px)); placement = { ...placement, scale: px / Math.max(logo.vbW, logo.vbH) }; sizeInput.value = String(Math.round(px)); updateSampler(); } function setRotation(deg: number, wrap = true) { // Scroll / pinch turn freely (wrap past ±180°); the slider just stops at its ends, so its // handle never jumps to the other end (+180° and −180° are the same angle). deg = wrap ? ((deg + 540) % 360) - 180 : Math.max(-180, Math.min(180, deg)); placement = { ...placement, rot: (deg * Math.PI) / 180 }; rotInput.value = String(Math.round(deg)); updateSampler(); } sizeInput.addEventListener('input', () => setSize(Number(sizeInput.value))); rotInput.addEventListener('input', () => setRotation(Number(rotInput.value), false)); function logoWheel(e: WheelEvent) { if (!logo) return; if (e.shiftKey) setRotation((placement.rot * 180) / Math.PI + Math.sign(e.deltaY || e.deltaX) * 3); // A trackpad pinch arrives as ctrl + wheel with small deltas: scale faster for it. else setSize(logoSize() * Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015))); } // ----- Transform gestures keep their target ----- // A scroll / trackpad pinch that starts on the logo (or a hand) keeps going to it until the // gesture pauses, even when the cursor drifts off it as it shrinks or turns. Without this the // transform would stop mid-gesture (and a pinch would zoom the page instead). // While a modifier key that the gesture started with (Shift to rotate, or Ctrl / Cmd) is // still held down, the lock never expires, however long the pause; letting go releases it. const WHEEL_LOCK_MS = 260; type Mod = 'Shift' | 'Control' | 'Meta'; const keysDown = new Set(); let wheelOwner: { kind: 'logo' | HandSide; t: number; mods: Mod[] } | null = null; window.addEventListener('keydown', (e) => keysDown.add(e.key)); window.addEventListener('keyup', (e) => { keysDown.delete(e.key); if (wheelOwner && wheelOwner.mods.includes(e.key as Mod)) wheelOwner.mods = wheelOwner.mods.filter((m) => keysDown.has(m)); }); window.addEventListener('blur', () => { keysDown.clear(); if (wheelOwner) wheelOwner.mods = []; }); const heldMods = (e: WheelEvent): Mod[] => (['Shift', 'Control', 'Meta'] as const).filter( (m) => keysDown.has(m) && (m === 'Shift' ? e.shiftKey : m === 'Control' ? e.ctrlKey : e.metaKey), ); stage.addEventListener( 'wheel', (e) => { const locked = wheelOwner && (wheelOwner.mods.some((m) => keysDown.has(m)) || e.timeStamp - wheelOwner.t < WHEEL_LOCK_MS); let kind = locked ? wheelOwner!.kind : null; if (!kind) { const t = e.target as Element; if (t.closest('#rightHand')) kind = 'right'; else if (t.closest('#leftHand')) kind = 'left'; else if (logo && t.closest('#logoLayer')) kind = 'logo'; } if (!kind) { wheelOwner = null; if (e.ctrlKey && (e.target as Element).closest('#scene')) e.preventDefault(); // no page zoom on the canvas return; } e.preventDefault(); e.stopPropagation(); // Keep the modifiers the gesture started with (and any still held from before). const mods = locked ? [...new Set([...wheelOwner!.mods.filter((m) => keysDown.has(m)), ...heldMods(e)])] : heldMods(e); wheelOwner = { kind, t: e.timeStamp, mods }; if (safariGesture) return; // Safari's own pinch / twist events are handling it if (kind === 'logo') logoWheel(e); else handWheel[kind](e); }, { passive: false, capture: true }, ); // Safari: trackpad pinch and two-finger twist come as gesture events (scale + rotation). // A gesture that starts on the logo resizes and turns it, wherever the cursor goes after. let safariGesture: { size0: number; rot0: number } | null = null; type SafariGestureEvent = Event & { scale: number; rotation: number }; stage.addEventListener('gesturestart', (e) => { if (!logo || !(e.target as Element).closest?.('#logoLayer')) return; e.preventDefault(); safariGesture = { size0: logoSize(), rot0: (placement.rot * 180) / Math.PI }; }); stage.addEventListener('gesturechange', (e) => { if (!safariGesture) return; e.preventDefault(); const g = e as SafariGestureEvent; setSize(safariGesture.size0 * g.scale); setRotation(safariGesture.rot0 + g.rotation); }); stage.addEventListener('gestureend', (e) => { if (!safariGesture) return; e.preventDefault(); safariGesture = null; }); $('reset').addEventListener('click', () => { if (!logo) return; // Only size and rotation; the logo keeps its position. setSize(defaultLogoSize()); setRotation(0, false); fitCamera(); }); // ----- Camera: fit Huggy + the logo into the free part of the stage ----- // The scene's viewBox is fitted to the content (Huggy, the heart above it, the logo) inside // the stage area that isn't covered by the toolbar (or the Advanced sheet on wide screens), so // a phone shows the hug large instead of a small strip in a wide frame. It re-fits on resize, // new logo, reset and when the sheet opens / closes (smoothly), never while dragging. let cam = { ...VIEWBOX }; const CAMERA_FOCUS = 0.84; let camTween = 0; const narrow = window.matchMedia('(max-width: 760px)'); function contentBox() { let x0 = BODY.cx - BODY.r - 24; let x1 = BODY.cx + BODY.r + 24; let y0 = BODY.cy - BODY.r - 100; // heart let y1 = BODY.cy + BODY.r + 24; if (logo) { const w = logo.vbW * placement.scale; const h = logo.vbH * placement.scale; const c = Math.abs(Math.cos(placement.rot)); const s = Math.abs(Math.sin(placement.rot)); const bw = (w * c + h * s) / 2; const bh = (w * s + h * c) / 2; x0 = Math.min(x0, placement.cx - bw); x1 = Math.max(x1, placement.cx + bw); y0 = Math.min(y0, placement.cy - bh); y1 = Math.max(y1, placement.cy + bh); } return { x0, y0, x1, y1 }; } function setCam(c: typeof cam) { cam = c; scene.setAttribute('viewBox', `${c.x.toFixed(2)} ${c.y.toFixed(2)} ${c.w.toFixed(2)} ${c.h.toFixed(2)}`); } function fitCamera(animate = true) { const r = stage.getBoundingClientRect(); if (!r.width || !r.height) return; const b = contentBox(); const dock = document.querySelector('.dock'); const top = 8; const bottom = (dock?.offsetHeight ?? 0) + (narrow.matches ? 20 : 32); const right = document.body.classList.contains('sheet-open') && !narrow.matches ? 364 : 0; const side = narrow.matches ? 8 : 24; const aw = Math.max(80, r.width - 2 * side - right); const ah = Math.max(80, r.height - top - bottom); // Comfortable focus size, not edge to edge: the hug takes up to FOCUS of the free area, and // never more than a little past the original fixed framing (so big screens look as before). const fit = Math.min(aw / (b.x1 - b.x0), ah / (b.y1 - b.y0)); const original = Math.min(r.width / VIEWBOX.w, r.height / VIEWBOX.h); // (The cap is for larger screens; on phones the original framing was tiny.) const s = narrow.matches ? fit * CAMERA_FOCUS : Math.min(fit * CAMERA_FOCUS, original * 1.1); const target = { x: (b.x0 + b.x1) / 2 - (side + aw / 2) / s, y: (b.y0 + b.y1) / 2 - (top + ah / 2) / s, w: r.width / s, h: r.height / s, }; cancelAnimationFrame(camTween); if (!animate) return setCam(target); const from = { ...cam }; const t0 = performance.now(); const ease = (t: number) => 1 - Math.pow(1 - t, 3); const stepCam = (now: number) => { const t = Math.min(1, (now - t0) / 420); const k = ease(t); setCam({ x: from.x + (target.x - from.x) * k, y: from.y + (target.y - from.y) * k, w: from.w + (target.w - from.w) * k, h: from.h + (target.h - from.h) * k, }); if (t < 1) camTween = requestAnimationFrame(stepCam); }; camTween = requestAnimationFrame(stepCam); } let resizeRaf = 0; window.addEventListener('resize', () => { cancelAnimationFrame(resizeRaf); resizeRaf = requestAnimationFrame(() => fitCamera(false)); }); window.addEventListener('layoutchange', () => fitCamera()); // ----- Pinch: two fingers on the logo resize and rotate it (touch has no scroll wheel) ----- const touches = new Map(); let pinch: { a: number; b: number; d0: number; ang0: number; mid0: { x: number; y: number }; size0: number; rot0: number; cx0: number; cy0: number } | null = null; const midScene = (p: { x: number; y: number }, q: { x: number; y: number }) => toScene({ clientX: (p.x + q.x) / 2, clientY: (p.y + q.y) / 2 }); stage.addEventListener( 'pointerdown', (e) => { if (e.pointerType !== 'touch') return; touches.set(e.pointerId, { x: e.clientX, y: e.clientY }); // A second finger while the logo is held starts a pinch (it may land anywhere on stage). if (drag && logo && !pinch && touches.size === 2 && touches.has(drag.id)) { const other = [...touches.keys()].find((id) => id !== drag!.id)!; const p = touches.get(drag.id)!; const q = touches.get(other)!; pinch = { a: drag.id, b: other, d0: Math.max(10, Math.hypot(q.x - p.x, q.y - p.y)), ang0: Math.atan2(q.y - p.y, q.x - p.x), mid0: midScene(p, q), size0: logoSize(), rot0: (placement.rot * 180) / Math.PI, cx0: placement.cx, cy0: placement.cy, }; try { stage.setPointerCapture(e.pointerId); } catch { /* synthetic pointers */ } } }, true, ); window.addEventListener('pointermove', (e) => { if (!touches.has(e.pointerId)) return; touches.set(e.pointerId, { x: e.clientX, y: e.clientY }); if (!pinch || !logo) return; const p = touches.get(pinch.a); const q = touches.get(pinch.b); if (!p || !q) return; const d = Math.hypot(q.x - p.x, q.y - p.y); const ang = Math.atan2(q.y - p.y, q.x - p.x); const mid = midScene(p, q); setSize(pinch.size0 * (d / pinch.d0)); setRotation(pinch.rot0 + ((ang - pinch.ang0) * 180) / Math.PI); placement = { ...placement, cx: pinch.cx0 + mid.x - pinch.mid0.x, cy: pinch.cy0 + mid.y - pinch.mid0.y }; updateSampler(); }); const liftTouch = (e: PointerEvent) => { if (!touches.delete(e.pointerId) || !pinch) return; pinch = null; // The finger still down keeps dragging from where it is (no jump). const rest = drag && touches.get(drag.id); if (drag && rest) { const p = toScene({ clientX: rest.x, clientY: rest.y }); drag.dx = placement.cx - p.x; drag.dy = placement.cy - p.y; } }; window.addEventListener('pointerup', liftTouch); window.addEventListener('pointercancel', liftTouch); $('debug').addEventListener('change', (e) => { debug = (e.target as HTMLInputElement).checked; stage.classList.toggle('show-debug', debug); // also shows the hands' safe hover zones renderDebugOverlay(); }); $('file').addEventListener('change', async (e) => { const file = (e.target as HTMLInputElement).files?.[0]; if (file) { markSample(null); await useLogo(await file.text(), file.name.replace(/\.svg$/i, '')); } (e.target as HTMLInputElement).value = ''; }); // Welcome overlay: on landing the stage sits behind the upload / drop prompt. It goes away // once a logo is loaded (upload, drop, the agent API) or the visitor goes for the examples. const demoVideo = $('dropVideo'); const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)'); demoVideo.src = './demo.mp4'; // (set here: a file from public/, served as is) // Plays (muted, looping) only while the landing overlay is up; with reduced motion it stays // on its poster frame. const syncDemoVideo = () => { if (stage.classList.contains('welcome') && !reducedMotion.matches) void demoVideo.play().catch(() => {}); else demoVideo.pause(); }; new MutationObserver(syncDemoVideo).observe(stage, { attributes: true, attributeFilter: ['class'] }); syncDemoVideo(); const dismissWelcome = () => stage.classList.remove('welcome'); $('dropUpload').addEventListener('click', () => $('file').click()); $('dropExample').addEventListener('click', (e) => { dismissWelcome(); // ...and open the Examples menu, so the other logos are one click away. e.stopPropagation(); // (the menu closes on outside clicks; this click is the one opening it) const menu = document.querySelector('.tgroup[data-group="examples"]'); if (menu && !menu.classList.contains('open')) menu.querySelector('.tg-btn')?.click(); }); el.drop.addEventListener('click', (e) => { // A click beside the prompt shows the stage (not one on the buttons or the demo video). if (!(e.target as Element).closest('button, .drop-video')) dismissWelcome(); }); window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && stage.classList.contains('welcome')) dismissWelcome(); }); stage.addEventListener('dragover', (e) => { e.preventDefault(); stage.classList.add('dragover'); }); stage.addEventListener('dragleave', (e) => { // Only when the file really leaves the stage (not when it crosses onto the prompt). if (!(e.relatedTarget instanceof Node) || !stage.contains(e.relatedTarget)) stage.classList.remove('dragover'); }); stage.addEventListener('drop', async (e) => { e.preventDefault(); stage.classList.remove('dragover'); const file = e.dataTransfer?.files?.[0]; if (!file) return; if (!/svg/i.test(file.type) && !/\.svg$/i.test(file.name)) { setStatus('Please drop an SVG file.'); return; } markSample(null); await useLogo(await file.text(), file.name.replace(/\.svg$/i, '')); }); const samplesEl = document.getElementById('samples')!; for (const name of SAMPLES) { const b = document.createElement('button'); b.className = 'chip'; b.textContent = SAMPLE_NAMES[name] ?? name; b.dataset.sample = name; b.setAttribute('aria-pressed', 'false'); b.addEventListener('click', () => loadSample(name)); samplesEl.appendChild(b); } /** Highlight the sample on stage (none for an uploaded logo). */ function markSample(name: string | null) { samplesEl.querySelectorAll('.chip').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.sample === name))); } // --------------------------------------------------------------------------------------------- // Squish tuning panel (live sliders + sweet-spot recording) const tuneSpecs: ParamSpec[] = [ { key: 'huggy.areaGain', group: 'Huggy swell', label: 'Swell amount (area)', min: 0, max: 1.2, step: 0.01, hint: 'Versions 1–3: how much of the area the logo overlaps comes back out as swell in the pockets.', get: () => body.params.areaGain ?? 0.3, set: (v) => (body.params.areaGain = v), }, { key: 'huggy.swellAmount', group: 'Huggy swell', label: 'Swell amount', min: 0, max: 1.5, step: 0.01, hint: 'How much of the min→max swell range Huggy reaches as the logo goes deeper (1 = reaches max swell at full squish depth).', get: () => body.params.swellAmount, set: (v) => (body.params.swellAmount = v), }, { key: 'huggy.minBulge', group: 'Huggy swell', label: 'Min swell (px)', min: 0, max: 60, step: 1, hint: 'Swell height as soon as a hug starts, even with a light touch.', get: () => body.params.minBulge, set: (v) => (body.params.minBulge = v), }, { key: 'huggy.maxBulge', group: 'Huggy swell', label: 'Max swell (px)', min: 10, max: 120, step: 1, hint: 'Swell height cap once the logo is fully in (the cap grows from min swell with depth).', get: () => body.params.maxBulge, set: (v) => (body.params.maxBulge = v), }, { key: 'face.coverReach', group: 'Huggy swell', label: 'Cheek squish reach (px)', min: 0, max: 200, step: 1, hint: 'How close the logo must get to the right cheek before the mouth cover starts to grow (0 = off).', get: () => coverReach, set: (v) => (coverReach = v), }, { key: 'logo.strength', group: 'Logo squish', label: 'Edge bow depth (px)', min: 0, max: 90, step: 1, hint: 'Max depth of the inward bow on the logo edge facing Huggy (reached at full squish depth).', get: () => warpParams.strength, set: (v) => (warpParams.strength = v), }, { key: 'logo.pocketStrength', group: 'Logo squish', label: 'Inner edge bow depth (px)', min: 0, max: 70, step: 1, hint: 'Max depth of the bow on inner edges (edges facing an empty space inside the logo, sealed hole or not) that Huggy swells against, reached at full squish depth.', get: () => warpParams.pocketStrength, set: (v) => (warpParams.pocketStrength = v), }, { key: 'logo.startDepth', group: 'Logo squish', label: 'Bend starts inside rim (×R)', min: 0, max: 0.4, step: 0.01, hint: 'How far inside Huggy’s rim the edge bend begins (Figma: ~0.15).', get: () => warpParams.startDepth, set: (v) => (warpParams.startDepth = v), }, { key: 'logo.zeroDeg', group: 'Logo squish', label: 'Bend spread (°)', min: 20, max: 120, step: 1, hint: 'How far around Huggy (from the hug direction) the edge bend reaches before fading out.', get: () => warpParams.zeroDeg, set: (v) => (warpParams.zeroDeg = v), }, { key: 'logo.depthPerLength', group: 'Logo squish', label: 'Short-edge limit', min: 0.05, max: 0.5, step: 0.01, hint: 'Short bent sections bow less: depth ≤ this × section length.', get: () => warpParams.depthPerLength, set: (v) => (warpParams.depthPerLength = v), }, { key: 'logo.fullDepth', group: 'Logo squish', label: 'Full squish at depth (×R)', min: 0.1, max: 1, step: 0.01, hint: 'Global rule: all squish (edge bow, inner edge bow, Huggy swell cap) grows as the logo goes deeper, reaching its max this far past the bend start.', get: () => warpParams.fullDepth, set: (v) => (warpParams.fullDepth = v), }, { key: 'logo.freezeDepth', group: 'Logo squish', label: 'Freeze squish at depth (×R)', min: 0.2, max: 1, step: 0.01, hint: 'Past this depth inside Huggy the logo keeps its squish shape and just moves with the drag, so it can’t distort further.', get: () => warpParams.freezeDepth, set: (v) => (warpParams.freezeDepth = v), }, { key: 'logo.minThickness', group: 'Logo squish', label: 'Min stroke width (×)', min: 0.1, max: 0.95, step: 0.01, hint: 'A squeezed stroke always keeps at least this fraction of its original width.', get: () => warpParams.minThickness, set: (v) => (warpParams.minThickness = v), }, { key: 'logo.twoSided', group: 'Logo squish', label: 'Two-sided squeeze limit (×)', min: 0, max: 0.9, step: 0.01, hint: 'When two bows squeeze one stroke from opposite sides, the stronger wins and both together take at most this fraction of the stroke width (keeps curves from distorting).', get: () => warpParams.twoSided, set: (v) => (warpParams.twoSided = v), }, ]; // Tuning defaults follow the selected version (the object is updated in place on switch). const tuneDefaults: Record = { ...version.defaults }; /** Switch the squish version: its engine, its default settings and its relevant sliders. */ function setVersion(v: Version) { version = v; localStorage.setItem(VERSION_KEY, v.id); body.params.swellMode = v.swellMode; body.params.swellShape = v.swellShape ?? 'dome'; body.params.swellSmooth = !!v.swellSmooth; for (const k of Object.keys(tuneDefaults)) delete tuneDefaults[k]; Object.assign(tuneDefaults, v.defaults); versionSelect.value = v.id; versionDesc.textContent = v.desc; if (tuner) { tuner.applyValues(v.defaults); tuner.setVisible(v.uses); } mountLogo(); } const versionSelect = document.getElementById('version') as HTMLSelectElement; const versionDesc = document.getElementById('versionDesc')!; for (const v of VERSIONS) { const o = document.createElement('option'); o.value = v.id; o.textContent = v.label; versionSelect.appendChild(o); } versionSelect.addEventListener('change', () => { const v = VERSIONS.find((x) => x.id === versionSelect.value); if (v) setVersion(v); }); body.params.swellMode = version.swellMode; body.params.swellShape = version.swellShape ?? 'dome'; body.params.swellSmooth = !!version.swellSmooth; // Start from the selected version's defaults (the panel then restores your own tweaks). for (const p of tuneSpecs) if (typeof version.defaults[p.key] === 'number') p.set(version.defaults[p.key]); versionSelect.value = version.id; versionDesc.textContent = version.desc; if (!DEV_TOOLS) versionSelect.closest('.section')?.setAttribute('hidden', ''); const tuner = createTuner(document.getElementById('tuner')!, { spots: DEV_TOOLS, specs: tuneSpecs, defaults: tuneDefaults, context: () => logo && logoSource ? { ...logoSource, version: version.id, hands: { left: handPinned.left, right: handPinned.right }, placement: { cx: placement.cx, cy: placement.cy, size: logoSize(), rotDeg: (placement.rot * 180) / Math.PI }, } : null, restore: async (spot: SweetSpot) => { const v = VERSIONS.find((x) => x.id === spot.version); if (v && v.id !== version.id) setVersion(v); if (spot.logo.sample) await loadSample(spot.logo.name); else if (spot.logo.svg) await useLogo(spot.logo.svg, spot.logo.name); if (!logo) return; const { cx, cy, size, rotDeg } = spot.placement; placement = { cx, cy, scale: size / Math.max(logo.vbW, logo.vbH), rot: (rotDeg * Math.PI) / 180 }; sizeInput.value = String(Math.round(size)); rotInput.value = String(Math.round(rotDeg)); updateSampler(); for (const side of ['left', 'right'] as const) { const pose = spot.hands?.[side] ?? null; handPinned[side] = pose ? { ...pose } : null; if (pose) { handSprings[side].pose = { ...pose }; handSprings[side].vel = { x: 0, y: 0, rot: 0 }; } } }, }); tuner.setVisible(version.uses); // --------------------------------------------------------------------------------------------- // Export /** Union of the visible layers' bounds in scene coordinates. */ function contentBounds() { const inv = scene.getScreenCTM()!.inverse(); const parts: SVGGraphicsElement[] = [el.bodyFill, el.logoContent, el.rightHand, el.leftHand]; if (el.heart.style.display !== 'none') parts.push(el.heart); let x0 = Infinity; let y0 = Infinity; let x1 = -Infinity; let y1 = -Infinity; for (const part of parts) { if (part === el.logoContent && !logo) continue; const bb = part.getBBox(); const m = inv.multiply(part.getScreenCTM()!); for (const [px, py] of [ [bb.x, bb.y], [bb.x + bb.width, bb.y], [bb.x, bb.y + bb.height], [bb.x + bb.width, bb.y + bb.height], ]) { const p = new DOMPoint(px, py).matrixTransform(m); x0 = Math.min(x0, p.x); y0 = Math.min(y0, p.y); x1 = Math.max(x1, p.x); y1 = Math.max(y1, p.y); } } return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }; } function exportSvgText(): { text: string; width: number; height: number } { const bb = contentBounds(); const pad = 24; const x = bb.x - pad; const y = bb.y - pad; const w = bb.width + pad * 2; const h = bb.height + pad * 2; const clone = scene.cloneNode(true) as SVGSVGElement; clone.querySelector('#debugLayer')?.remove(); clone.querySelectorAll('.dragging').forEach((n) => n.classList.remove('dragging')); // no hover/drag outline in exports // Hidden hands (and their shadows on the logo) are left out; visible ones export solid. for (const side of ['left', 'right'] as const) { const hand = clone.querySelector(`#${side}Hand`); if (handHidden[side]) { hand?.remove(); clone.querySelector(`#${side}HandShadow`)?.remove(); } else hand?.style.removeProperty('opacity'); } clone.removeAttribute('id'); clone.setAttribute('viewBox', `${x.toFixed(1)} ${y.toFixed(1)} ${w.toFixed(1)} ${h.toFixed(1)}`); clone.setAttribute('width', w.toFixed(0)); clone.setAttribute('height', h.toFixed(0)); clone.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); const heart = clone.querySelector('#heart') as SVGGElement | null; if (heart && heart.style.display === 'none') heart.remove(); return { text: new XMLSerializer().serializeToString(clone), width: w, height: h }; } function download(blob: Blob, filename: string) { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = filename; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 2000); } function baseName() { return `huggy-x-${(logo?.name ?? 'partner').replace(/[^\w-]+/g, '-').toLowerCase()}`; } $('exportSvg').addEventListener('click', () => { const { text } = exportSvgText(); download(new Blob([text], { type: 'image/svg+xml' }), `${baseName()}.svg`); }); /** Render the current scene to a transparent PNG at `scale` × its size. */ function exportPngBlob(scale = 2): Promise { const { text, width, height } = exportSvgText(); return new Promise((resolve, reject) => { const img = new Image(); const url = URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' })); img.onload = () => { const canvas = document.createElement('canvas'); canvas.width = Math.round(width * scale); canvas.height = Math.round(height * scale); canvas.getContext('2d')!.drawImage(img, 0, 0, canvas.width, canvas.height); URL.revokeObjectURL(url); canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('PNG export failed'))), 'image/png'); }; img.onerror = () => reject(new Error('PNG export failed')); img.src = url; }); } $('exportPng').addEventListener('click', async () => { download(await exportPngBlob(2), `${baseName()}.png`); }); // --------------------------------------------------------------------------------------------- // Agent API: load an SVG logo, let the hug settle, return the default export. Used by the // agent Space (headless browser) so tools / agents get the same result as the Export buttons. (window as unknown as { hugApi: unknown }).hugApi = { /** * @param svg the partner logo (SVG source) * @param size logo size (longest side, 140–1000; default 600) * @param rotation logo rotation in degrees (−180–180; default 0) * @param format 'png' (default) or 'svg' * @param scale PNG scale (default 2) */ async hug(opts: { svg: string; name?: string; size?: number; rotation?: number; format?: 'png' | 'svg'; scale?: number }) { if (typeof opts?.svg !== 'string' || !/]/i.test(opts.svg)) throw new Error('Expected SVG source (an element).'); markSample(null); await useLogo(opts.svg, opts.name || 'partner'); if (!logo) throw new Error(el.status.textContent || 'Could not read that SVG.'); if (typeof opts.size === 'number') setSize(opts.size); if (typeof opts.rotation === 'number') setRotation(opts.rotation, false); for (let i = 0; i < 240; i++) frame(1 / 60); // settle: hug, swell, squish, hands const { text, width, height } = exportSvgText(); if (opts.format === 'svg') return { format: 'svg', svg: text, width, height }; const blob = await exportPngBlob(opts.scale ?? 2); const png = await new Promise((resolve) => { const r = new FileReader(); r.onload = () => resolve(String(r.result)); r.readAsDataURL(blob); }); return { format: 'png', png, width: Math.round(width * (opts.scale ?? 2)), height: Math.round(height * (opts.scale ?? 2)) }; }, }; // --------------------------------------------------------------------------------------------- // Debug/test hook (used for tuning against the Figma references). (window as unknown as { __hug: unknown }).__hug = { body, get placement() { return placement; }, get grip() { return grip; }, get logo() { return logo; }, get sampler() { return sampler; }, get warp() { return warp; }, setPlacement(p: Partial) { placement = { ...placement, ...p }; updateSampler(); }, loadSample, /** Load a sample at a given placement (scene px, logo size = longest side) and settle it. */ async setup(name: string, cx: number, cy: number, size: number, rotDeg = 0) { await loadSample(name); if (!logo) return null; placement = { cx, cy, scale: size / Math.max(logo.vbW, logo.vbH), rot: (rotDeg * Math.PI) / 180 }; updateSampler(); for (let i = 0; i < 200; i++) frame(1 / 60); return { overlap: Math.round(body.overlapArea), bulge: +body.bulge.toFixed(1), grip: grip?.point ?? null }; }, exportSvgText, /** Hide (or show) both hands, e.g. to review the logo's edges. */ hideHands(hidden = true) { for (const side of ['left', 'right'] as const) { handHidden[side] = hidden; applyHandVisibility(side); } }, /** Step the simulation manually (rAF pauses in hidden tabs). */ tick(frames = 120) { for (let i = 0; i < frames; i++) frame(1 / 60); }, }; loadSample('pydantic'); requestAnimationFrame(loop);