Skip to content

12 个视觉参考图库与浏览器无限画布 AI 创作台(5,700+ 素材、中英提示词、多图对比、ComfyUI & MCP)· Visual reference library & infinite-canvas AI studio in the browser

42.6 KB
Raw Blame
'use strict';
(() => {
  // Infinite Spatial Canvas Studio (#wbStage -> window.PoseWearCanvas).
  // Turns the center reference board into a pannable, zoomable spatial desk with
  // draggable/resizable reference cards, live-prompt art-direction sticky notes,
  // semantic Bezier flow wires, spatial output hub, pinned generation results, and Zen Focus mode.
  const C = window.PoseWearCatalog;
  if (!C) return;
  const { $, $$, esc, readLS: LS, writeLS: SV } = C;

  const STORAGE_KEY = 'wbCanvas';
  const MIN_SCALE = 0.35;
  const MAX_SCALE = 2.4;
  const MIN_CARD_W = 132;
  const MAX_CARD_W = 340;
  const DEFAULT_CARD_W = 166;
  const HUB_W = 216;
  const NOTE_W = 168;

  let api = null; // Wired from studio.js via init(studioApi)
  let refsList = []; // [{ id, slot, slotIdx, type, material, ref, item, label, src, angle, roleLabel }]
  let resultsList = []; // [{ index, url, prov, model, label, hasBefore }]
  let isSample = true;
  let compactMode = false;
  let zTop = 10;
  let wireRaf = 0;
  let suppressClickUntil = 0;
  let spaceHeld = false;
  let zenMode = false;
  let lastRefSig = '';
  let userCamera = false;
  const outPos = new Map();
  const activePointers = new Map();
  let pinchState = null;

  const saved = LS(STORAGE_KEY) || {};
  const state = {
    tx: Number.isFinite(saved.tx) ? saved.tx : 0,
    ty: Number.isFinite(saved.ty) ? saved.ty : 0,
    scale: Number.isFinite(saved.scale) ? clamp(saved.scale, MIN_SCALE, MAX_SCALE) : 1,
    showWires: saved.showWires !== false,
    nodes: saved.nodes && typeof saved.nodes === 'object' ? { ...saved.nodes } : {},
    hub: saved.hub && Number.isFinite(saved.hub.x) && Number.isFinite(saved.hub.y) ? { ...saved.hub } : null,
    notes: Array.isArray(saved.notes)
      ? saved.notes
          .filter(n => n && typeof n.id === 'string')
          .slice(0, 16)
          .map(n => ({
            id: n.id,
            text: typeof n.text === 'string' ? n.text : '',
            x: Number.isFinite(n.x) ? n.x : 168,
            y: Number.isFinite(n.y) ? n.y : 196,
            linked: n.linked !== false,
          }))
      : [],
  };

  function clamp(v, lo, hi) {
    return Math.min(hi, Math.max(lo, v));
  }

  function snap(v) {
    return Math.round(v / 8) * 8;
  }

  let saveTimer = null;
  function persist() {
    clearTimeout(saveTimer);
    saveTimer = setTimeout(() => {
      SV(STORAGE_KEY, {
        tx: Math.round(state.tx),
        ty: Math.round(state.ty),
        scale: Math.round(state.scale * 1000) / 1000,
        showWires: state.showWires,
        nodes: state.nodes,
        hub: state.hub,
        notes: state.notes,
      });
    }, 180);
  }

  function vpMetrics() {
    const vp = $('#wbCanvasVp');
    if (!vp) return { w: 720, h: 640 };
    const r = vp.getBoundingClientRect();
    return { w: r.width || 720, h: r.height || 640 };
  }

  function isCompactViewport() {
    const { w } = vpMetrics();
    return window.innerWidth <= 560 || (w > 0 && w < 460);
  }

  function applyCamera() {
    const world = $('#wbCanvasWorld');
    const stage = $('#wbStage');
    const pct = $('#wbZoomPct');
    if (pct) pct.textContent = Math.round(state.scale * 100) + '%';
    if (!world || !stage) return;

    if (compactMode) {
      world.style.transform = '';
      stage.style.removeProperty('--cv-x');
      stage.style.removeProperty('--cv-y');
      stage.style.removeProperty('--cv-step');
      return;
    }

    const { w, h } = vpMetrics();
    const ox = w / 2 + state.tx;
    const oy = h / 2 + state.ty;
    world.style.transform = `translate3d(${ox}px, ${oy}px, 0) scale(${state.scale})`;

    const step = Math.max(10, Math.min(44, 18 * state.scale));
    stage.style.setProperty('--cv-x', `${ox % step}px`);
    stage.style.setProperty('--cv-y', `${oy % step}px`);
    stage.style.setProperty('--cv-step', `${step}px`);
  }

  function defaultRefPos(idx, total, sample) {
    if (sample) {
      const spread = total <= 1 ? 0 : 210;
      const start = -((total - 1) * spread) / 2;
      return { x: start + idx * spread, y: -26, w: 186 };
    }
    if (total === 1) return { x: -164, y: -8, w: 182 };
    if (total === 2) return { x: -244 + idx * 176, y: idx === 0 ? -18 : 18, w: 162 };
    if (total === 3) {
      const slots = [
        { x: -254, y: -124, w: 156 },
        { x: -78, y: -124, w: 156 },
        { x: -254, y: 128, w: 156 },
      ];
      return slots[idx];
    }
    const cols = total >= 7 ? 3 : 2;
    const col = idx % cols;
    const row = Math.floor(idx / cols);
    const rows = Math.ceil(total / cols);
    const colStep = 176;
    const rowStep = 256;
    const yStart = -((rows - 1) * rowStep) / 2;
    return { x: -94 - (cols - 1 - col) * colStep, y: yStart + row * rowStep, w: 152 };
  }

  function defaultHubPos(total) {
    if (total <= 1) return { x: 162, y: -6 };
    if (total <= 3) return { x: 176, y: -4 };
    return { x: 188, y: -6 };
  }

  function defaultNotePos(idx) {
    const hub = state.hub || defaultHubPos(refsList.length);
    if (idx === 0 && refsList.length === 3) return { x: -78, y: 128 };
    if (idx === 0 && refsList.length === 1) return { x: -164, y: 184 };
    return {
      x: hub.x + (idx % 2) * 224,
      y: hub.y + 258 + Math.floor(idx / 2) * 144,
    };
  }

  function collides(ax, ay, aw, bx, by, bw) {
    const ah = Math.round(aw * 1.48);
    const bh = Math.round(bw * 1.48);
    return Math.abs(ax - bx) < (aw + bw) / 2 + 14 && Math.abs(ay - by) < (ah + bh) / 2 + 14;
  }

  function placeWithoutOverlap(x, y, w, placed) {
    let cx = x;
    let cy = y;
    for (let tries = 0; tries < 24; tries++) {
      if (!placed.some(p => collides(cx, cy, w, p.x, p.y, p.w))) return { x: cx, y: cy };
      cy += 256;
      if (tries % 4 === 3) {
        cy = y;
        cx -= 176;
      }
    }
    return { x: cx, y: cy };
  }

  function ensurePositions(forceReset = false) {
    const refSig = isSample ? 'sample:' + refsList.length : refsList.map(r => r.id).join('|');
    const listChanged = forceReset || refSig !== lastRefSig;
    lastRefSig = refSig;

    if (forceReset) {
      state.nodes = {};
      state.hub = null;
    }
    const activeIds = new Set(refsList.map(r => r.id));
    for (const id of Object.keys(state.nodes)) {
      if (!activeIds.has(id) && !isSample) delete state.nodes[id];
    }

    if (!isSample) {
      const placed = [];
      refsList.forEach(entry => {
        const cur = state.nodes[entry.id];
        if (cur && cur.pinned) placed.push({ x: cur.x, y: cur.y, w: cur.w || DEFAULT_CARD_W });
      });
      refsList.forEach((entry, idx) => {
        const cur = state.nodes[entry.id];
        if (!cur || (!cur.pinned && listChanged)) {
          const def = defaultRefPos(idx, refsList.length, false);
          const pos = placeWithoutOverlap(def.x, def.y, def.w, placed);
          state.nodes[entry.id] = {
            x: pos.x,
            y: pos.y,
            w: def.w,
            flip: cur ? !!cur.flip : false,
            pinned: false,
            z: cur?.z || ++zTop,
          };
          placed.push({ x: pos.x, y: pos.y, w: def.w });
        } else if (!cur.pinned) {
          placed.push({ x: cur.x, y: cur.y, w: cur.w || DEFAULT_CARD_W });
        }
      });
    }

    if (!state.hub || (!state.hub.pinned && listChanged)) {
      const defHub = defaultHubPos(refsList.length);
      state.hub = { x: defHub.x, y: defHub.y, pinned: false };
    }
    if (forceReset) {
      state.notes.forEach((n, i) => {
        const p = defaultNotePos(i);
        n.x = p.x;
        n.y = p.y;
      });
    }
    return listChanged;
  }

  function ratioDims(ar) {
    const map = {
      auto: [3, 4],
      '2:3': [2, 3],
      '3:4': [3, 4],
      '9:16': [9, 16],
      '1:1': [1, 1],
      '4:3': [4, 3],
      '16:9': [16, 9],
    };
    const [rw, rh] = map[ar] || [3, 4];
    const maxW = HUB_W - 24;
    const maxH = 196;
    const scale = Math.min(maxW / rw, maxH / rh);
    return { w: Math.round(rw * scale), h: Math.round(rh * scale) };
  }

  function cardNodeEl(id) {
    return $(`#wbBoardCards .board-card[data-nid="${CSS.escape(id)}"]`);
  }

  function scheduleWires() {
    if (wireRaf) return;
    wireRaf = requestAnimationFrame(() => {
      wireRaf = 0;
      drawWires();
    });
  }

  function drawWires() {
    const svg = $('#wbCanvasWires');
    if (!svg) return;
    if (compactMode || !state.showWires || (isSample && !state.notes.length)) {
      svg.innerHTML = '';
      return;
    }
    const hubEl = $('#wbCanvasOutputs .cv-hub');
    if (!hubEl) {
      svg.innerHTML = '';
      return;
    }

    const hubPos = state.hub || defaultHubPos(refsList.length);
    const hubW = hubEl.offsetWidth || HUB_W;
    const hubH = hubEl.offsetHeight || 280;
    const hubLeft = hubPos.x - hubW / 2;
    const hubRight = hubPos.x + hubW / 2;
    const targetY = hubPos.y;
    const paths = [];
    const busy = !!(api && api.isBusy());
    let usedLeftPort = false;
    let usedRightPort = false;

    const makeHorizCurve = (sx, sy, tx, ty, cls, dir) => {
      const dx = Math.max(54, Math.abs(tx - sx) * 0.48) * dir;
      const d = `M ${sx} ${sy} C ${sx + dx} ${sy}, ${tx - dx} ${ty}, ${tx} ${ty}`;
      return `<path class="cv-wire ${cls}${busy ? ' pulse' : ''}" d="${d}"/><circle class="cv-port ${cls}" cx="${sx}" cy="${sy}" r="3.5"/>`;
    };

    refsList.forEach(entry => {
      const node = state.nodes[entry.id];
      const el = cardNodeEl(entry.id);
      if (!node || !el) return;
      const w = el.offsetWidth || node.w || DEFAULT_CARD_W;
      if (node.x > hubPos.x + hubW * 0.25) {
        usedRightPort = true;
        paths.push(makeHorizCurve(node.x - w / 2, node.y, hubRight, targetY, 'ref-wire', -1));
      } else {
        usedLeftPort = true;
        paths.push(makeHorizCurve(node.x + w / 2, node.y, hubLeft, targetY, 'ref-wire', 1));
      }
    });

    state.notes.forEach(note => {
      if (!note.linked || !note.text.trim()) return;
      const el = $(`#wbCanvasNotes .cv-note[data-note-id="${CSS.escape(note.id)}"]`);
      const w = el ? el.offsetWidth : NOTE_W;
      const h = el ? el.offsetHeight : 120;
      if (note.x + w / 2 < hubLeft + 16) {
        usedLeftPort = true;
        paths.push(makeHorizCurve(note.x + w / 2, note.y, hubLeft, targetY, 'note-wire', 1));
      } else if (note.x - w / 2 > hubRight - 16) {
        usedRightPort = true;
        paths.push(makeHorizCurve(note.x - w / 2, note.y, hubRight, targetY, 'note-wire', -1));
      } else {
        // Above or below hub: route vertically into nearest vertical edge of hub
        const below = note.y >= hubPos.y;
        const sx = note.x;
        const sy = below ? note.y - h / 2 : note.y + h / 2;
        const tx = hubPos.x;
        const ty = below ? hubPos.y + hubH / 2 : hubPos.y - hubH / 2;
        const dy = Math.max(36, Math.abs(sy - ty) * 0.5) * (below ? -1 : 1);
        const d = `M ${sx} ${sy} C ${sx} ${sy + dy}, ${tx} ${ty - dy}, ${tx} ${ty}`;
        paths.push(`<path class="cv-wire note-wire${busy ? ' pulse' : ''}" d="${d}"/><circle class="cv-port note-wire" cx="${sx}" cy="${sy}" r="3.5"/>`);
      }
    });

    // Connect pinned historical result iterations to the hub
    resultsList.slice(1, 5).forEach(res => {
      const outEl = $(`#wbCanvasOutputs .cv-out-node[data-out-i="${res.index}"]`);
      if (!outEl) return;
      const ox = Number(outEl.dataset.wx || 0);
      const oy = Number(outEl.dataset.wy || 0);
      const ow = outEl.offsetWidth || 176;
      const rightSide = ox >= hubPos.x;
      const sx = rightSide ? hubRight : hubLeft;
      const tx = rightSide ? ox - ow / 2 : ox + ow / 2;
      const dir = rightSide ? 1 : -1;
      const dx = Math.max(40, Math.abs(tx - sx) * 0.45) * dir;
      paths.push(`<path class="cv-wire out-wire" d="M ${sx} ${targetY} C ${sx + dx} ${targetY}, ${tx - dx} ${oy}, ${tx} ${oy}"/>`);
    });

    if (usedLeftPort) {
      paths.push(`<circle class="cv-port hub-port${busy ? ' pulse' : ''}" cx="${hubLeft}" cy="${targetY}" r="4.5"/>`);
    }
    if (usedRightPort) {
      paths.push(`<circle class="cv-port hub-port${busy ? ' pulse' : ''}" cx="${hubRight}" cy="${targetY}" r="4.5"/>`);
    }
    svg.innerHTML = paths.join('');
  }

  function renderCards() {
    const cards = $('#wbBoardCards');
    if (!cards) return;
    cards.classList.toggle('sample', isSample);
    cards.classList.toggle('many', refsList.length > 3);

    cards.innerHTML = refsList
      .map((entry, idx) => {
        const pos = isSample ? defaultRefPos(idx, refsList.length, true) : state.nodes[entry.id] || defaultRefPos(idx, refsList.length, false);
        const idxBadge = isSample ? '' : `<i class="board-idx" aria-hidden="true">${idx + 1}</i>`;
        const angBadge = entry.angle ? `<em class="board-ang">${esc(entry.angle)}</em>` : '';
        const flipped = !isSample && !!pos.flip;
        const canAngle = !isSample && entry.item?.angles && entry.item.angles.length > 1;
        const cardActions = isSample
          ? ''
          : `<div class="cv-card-bar">` +
            (canAngle ? `<button type="button" data-cv-card="ang" title="切换视角" aria-label="切换视角">↻</button>` : '') +
            `<button type="button" data-cv-card="flip" class="${flipped ? 'on' : ''}" title="画布镜像预览" aria-label="镜像">⇄</button>` +
            `<button type="button" data-cv-card="pick" title="替换素材" aria-label="替换">换</button>` +
            `<button type="button" data-cv-card="rm" title="移除" aria-label="移除">×</button>` +
            `</div><i class="cv-rsz" data-cv-rsz title="拖拽调整卡片大小" aria-hidden="true"></i>`;

        const styleAttr = compactMode
          ? ''
          : ` style="left:${pos.x}px;top:${pos.y}px;width:${pos.w || DEFAULT_CARD_W}px;z-index:${pos.z || idx + 1}"`;

        return (
          `<div class="board-card${flipped ? ' cv-flip' : ''}" role="button" tabindex="0"` +
          ` data-nid="${esc(entry.id)}" data-pick="${esc(entry.material)}" data-type="${esc(entry.material)}"` +
          ` data-slot="${esc(entry.slot || '')}" data-si="${entry.slotIdx ?? 0}"` +
          `${entry.item ? ` data-pk-key="${esc(entry.item.k)}"` : ''}` +
          ` title="${esc(entry.label)}"${styleAttr}>` +
          `${idxBadge}${cardActions}` +
          `<div class="cv-card-media"><img src="${esc(entry.src)}" alt="${esc(entry.label)}"${entry.item?.ref ? ` referrerpolicy="${esc(entry.item.ref)}"` : ''} draggable="false">${angBadge}</div>` +
          `<span>${esc(entry.roleLabel)}</span>` +
          `</div>`
        );
      })
      .join('');
  }

  function renderNotes() {
    const box = $('#wbCanvasNotes');
    if (!box) return;
    if (!state.notes.length) {
      box.innerHTML = '';
      return;
    }
    box.innerHTML = state.notes
      .map(note => {
        const styleAttr = compactMode ? '' : ` style="left:${note.x}px;top:${note.y}px;width:${NOTE_W}px"`;
        return (
          `<article class="cv-note${note.linked ? ' linked' : ''}" data-note-id="${esc(note.id)}"${styleAttr}>` +
          `<header class="cv-note-head" data-note-drag>` +
          `<i class="cv-pin" aria-hidden="true"></i>` +
          `<button type="button" class="cv-note-link${note.linked ? ' on' : ''}" data-note-act="link" aria-pressed="${note.linked}" title="将便签内容自动注入生图提示词">${note.linked ? '↳ 提示词' : '仅备注'}</button>` +
          `<button type="button" class="cv-note-rm" data-note-act="rm" aria-label="删除便签" title="删除便签">×</button>` +
          `</header>` +
          `<textarea rows="3" placeholder="写下光影、构图或情绪备注…" aria-label="画布便签">${esc(note.text)}</textarea>` +
          `</article>`
        );
      })
      .join('');
  }

  function outputNodePos(res, idx, hubPos) {
    const savedPos = outPos.get(res.index);
    if (savedPos) return savedPos;
    return {
      x: hubPos.x + HUB_W + 38 + Math.floor(idx / 2) * 200,
      y: hubPos.y + (idx % 2 === 0 ? -144 : 144),
    };
  }

  function renderOutputs() {
    const box = $('#wbCanvasOutputs');
    if (!box) return;
    if (isSample && !state.notes.length && !resultsList.length) {
      box.innerHTML = '';
      return;
    }
    const meta = api ? api.getMeta() : { ar: 'auto', styleLabel: '', shotLabel: '', jobs: 1, canGo: false, busy: false };
    const hubPos = state.hub || defaultHubPos(refsList.length);
    const dims = ratioDims(meta.ar);
    const latest = resultsList[0] || null;
    const styleAttr = compactMode ? '' : ` style="left:${hubPos.x}px;top:${hubPos.y}px;width:${HUB_W}px"`;

    const tags = [meta.styleLabel, meta.shotLabel, meta.ar !== 'auto' ? meta.ar : ''].filter(Boolean);
    const previewInner = latest
      ? `<img src="${esc(latest.url)}" alt="最新生成结果" data-out-act="view" data-out-i="${latest.index}" draggable="false">`
      : `<div class="cv-hub-wire" style="width:${dims.w}px;height:${dims.h}px"><span>${meta.ar === 'auto' ? '3:4' : esc(meta.ar)}</span><small>${refsList.length} 项输入 · ${meta.jobs} 张</small></div>`;

    const hubActions = latest
      ? `<div class="cv-hub-acts">` +
        `<button type="button" class="sm ghost" data-out-act="view" data-out-i="${latest.index}">对比</button>` +
        `<button type="button" class="sm ghost" data-out-act="use" data-out-i="${latest.index}">当原图</button>` +
        `<button type="button" class="sm ghost cv-hub-dl" data-out-act="dl" data-out-i="${latest.index}" title="下载成品" aria-label="下载成品">↓</button>` +
        `<button type="button" class="sm pri" data-hub-go${meta.canGo && !meta.busy ? '' : ' disabled'}>${meta.busy ? '生成中…' : '再生成'}</button>` +
        `</div>`
      : `<div class="cv-hub-acts">` +
        `<button type="button" class="sm pri cv-hub-go" data-hub-go${meta.canGo && !meta.busy ? '' : ' disabled'}>${meta.busy ? '生成中…' : '从画布生成'}</button>` +
        `</div>`;

    const hubHtml =
      `<section class="cv-hub${latest ? ' has-img' : ''}" data-hub-drag aria-label="生成输出节点"${styleAttr}>` +
      `<header class="cv-hub-head">` +
      `<i class="cv-hub-dot${meta.busy ? ' busy' : ''}" aria-hidden="true"></i>` +
      `<b>${latest ? '最新成品' : '输出预览'}</b>` +
      `<span class="cv-hub-n">${esc(meta.ar === 'auto' ? '自动' : meta.ar)}</span>` +
      `</header>` +
      `<div class="cv-hub-body">${previewInner}</div>` +
      (tags.length ? `<div class="cv-hub-tags">${tags.map(t => `<span>${esc(t)}</span>`).join('')}</div>` : '') +
      `${hubActions}</section>`;

    // Pin previous iterations neatly to the right of the hub on desktop infinite canvas
    const extraOutputs = resultsList
      .slice(1, 5)
      .map((res, idx) => {
        const p = outputNodePos(res, idx, hubPos);
        const posStyle = compactMode ? '' : ` style="left:${p.x}px;top:${p.y}px;width:176px"`;
        return (
          `<article class="cv-out-node" data-out-pos="${idx + 1}" data-out-i="${res.index}" data-wx="${p.x}" data-wy="${p.y}"${posStyle}>` +
          `<img src="${esc(res.url)}" alt="生成结果 ${res.index + 1}" data-out-act="view" data-out-i="${res.index}" draggable="false">` +
          `<div class="cv-out-bar">` +
          `<small>#${res.index + 1}</small>` +
          `<button type="button" class="sm ghost" data-out-act="view" data-out-i="${res.index}">对比</button>` +
          `<button type="button" class="sm ghost" data-out-act="use" data-out-i="${res.index}">当原图</button>` +
          `</div></article>`
        );
      })
      .join('');

    box.innerHTML = hubHtml + extraOutputs;
    syncMeta();
  }

  function syncMeta() {
    if (!api) return;
    const meta = api.getMeta();
    const latest = resultsList[0] || null;
    const hubGo = $('#wbCanvasOutputs [data-hub-go]');
    if (hubGo) {
      hubGo.disabled = !meta.canGo || meta.busy;
      hubGo.textContent = meta.busy ? '生成中…' : latest ? '再生成' : '从画布生成';
    }
    const dot = $('#wbCanvasOutputs .cv-hub-dot');
    if (dot) dot.classList.toggle('busy', !!meta.busy);
    const zenInfo = $('#wbZenInfo');
    if (zenInfo) zenInfo.textContent = `${refsList.length} 项参考 · ${meta.styleLabel || '默认'}${meta.ar !== 'auto' ? ' · ' + meta.ar : ''}`;
    const zenGo = $('#wbZenGo');
    if (zenGo) {
      zenGo.disabled = !meta.canGo || meta.busy;
      zenGo.textContent = meta.busy ? '生成中…' : '生成';
    }
    if ($('#wbCanvasWires')?.childElementCount) scheduleWires();
  }

  function updateHud() {
    const ph0 = $('#wbPh0');
    if (ph0) ph0.dataset.layout = compactMode ? 'compact' : 'spatial';
    const tools = $('#wbCanvasTools');
    const zoomBar = $('#wbCanvasZoom');
    const hideTools = compactMode && isSample && !state.notes.length;
    if (tools) {
      tools.hidden = hideTools;
      const spatialOnly = compactMode || (isSample && !state.notes.length);
      tools.querySelectorAll('[data-cv-act="tidy"], [data-cv-act="fit"], [data-cv-act="wires"]').forEach(b => {
        b.hidden = spatialOnly;
      });
    }
    if (zoomBar) zoomBar.hidden = compactMode;
    const wireBtn = $('#wbCanvasTools [data-cv-act="wires"]');
    if (wireBtn) {
      wireBtn.classList.toggle('on', state.showWires);
      wireBtn.setAttribute('aria-pressed', String(state.showWires));
    }
    const zenBtn = $('#wbCanvasZoom [data-cv-act="zen"]');
    if (zenBtn) {
      zenBtn.classList.toggle('on', zenMode);
      zenBtn.setAttribute('aria-pressed', String(zenMode));
    }
    const zenBar = $('#wbZenBar');
    if (zenBar) zenBar.hidden = !zenMode || compactMode;
  }

  function fitToView(animate = true) {
    if (compactMode) return;
    const boxes = [];
    refsList.forEach((entry, idx) => {
      const pos = isSample ? defaultRefPos(idx, refsList.length, true) : state.nodes[entry.id];
      if (!pos) return;
      const w = pos.w || DEFAULT_CARD_W;
      const h = Math.round(w * 1.48);
      boxes.push([pos.x - w / 2, pos.y - h / 2, pos.x + w / 2, pos.y + h / 2]);
    });
    if (!isSample && state.hub) {
      boxes.push([state.hub.x - HUB_W / 2, state.hub.y - 160, state.hub.x + HUB_W / 2, state.hub.y + 160]);
      resultsList.slice(1, 5).forEach((res, idx) => {
        const p = outputNodePos(res, idx, state.hub);
        boxes.push([p.x - 92, p.y - 135, p.x + 92, p.y + 135]);
      });
    }
    state.notes.forEach(n => {
      boxes.push([n.x - NOTE_W / 2, n.y - 68, n.x + NOTE_W / 2, n.y + 68]);
    });
    if (!boxes.length) {
      state.tx = 0;
      state.ty = 0;
      state.scale = 1;
    } else {
      const minX = Math.min(...boxes.map(b => b[0]));
      const minY = Math.min(...boxes.map(b => b[1]));
      const maxX = Math.max(...boxes.map(b => b[2]));
      const maxY = Math.max(...boxes.map(b => b[3]));
      const bw = Math.max(180, maxX - minX);
      const bh = Math.max(180, maxY - minY);
      const { w, h } = vpMetrics();
      const padX = 76;
      const padY = 96;
      const nextScale = clamp(Math.min((w - padX) / bw, (h - padY) / bh, 1.05), MIN_SCALE, 1.25);
      const cx = (minX + maxX) / 2;
      const cy = (minY + maxY) / 2;
      state.scale = Math.round(nextScale * 100) / 100;
      state.tx = Math.round(-cx * state.scale);
      state.ty = Math.round(-cy * state.scale);
    }
    const world = $('#wbCanvasWorld');
    if (animate && world && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
      world.classList.add('anim');
      setTimeout(() => world.classList.remove('anim'), 260);
    }
    applyCamera();
    persist();
  }

  function zoomBy(factor, anchorX, anchorY) {
    if (compactMode) return;
    const { w, h } = vpMetrics();
    const prev = state.scale;
    const next = clamp(Math.round(prev * factor * 100) / 100, MIN_SCALE, MAX_SCALE);
    if (next === prev) return;
    const ax = anchorX ?? w / 2;
    const ay = anchorY ?? h / 2;
    const wx = (ax - w / 2 - state.tx) / prev;
    const wy = (ay - h / 2 - state.ty) / prev;
    state.scale = next;
    state.tx = ax - w / 2 - wx * next;
    state.ty = ay - h / 2 - wy * next;
    userCamera = true;
    applyCamera();
    persist();
  }

  function addNote(worldX, worldY) {
    const idx = state.notes.length;
    const def = defaultNotePos(idx);
    const note = {
      id: 'n_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 5),
      text: '',
      x: Number.isFinite(worldX) ? snap(worldX) : snap(def.x),
      y: Number.isFinite(worldY) ? snap(worldY) : snap(def.y),
      linked: true,
    };
    state.notes.push(note);
    if (state.notes.length > 16) state.notes.shift();
    renderNotes();
    renderOutputs();
    updateHud();
    scheduleWires();
    persist();
    const ta = $(`#wbCanvasNotes .cv-note[data-note-id="${CSS.escape(note.id)}"] textarea`);
    ta?.focus({ preventScroll: true });
    return note;
  }

  function setZen(on) {
    zenMode = !compactMode && !!on;
    $('#studio')?.classList.toggle('zen', zenMode);
    updateHud();
    requestAnimationFrame(() => {
      applyCamera();
      fitToView(true);
    });
  }

  function sync(payload) {
    refsList = payload.refs || [];
    resultsList = payload.results || [];
    isSample = !!payload.sample;
    compactMode = isCompactViewport();
    if (compactMode && zenMode) setZen(false);
    const listChanged = ensurePositions(false);
    renderCards();
    renderNotes();
    renderOutputs();
    updateHud();
    if (listChanged && !compactMode && !userCamera && !isSample && refsList.length > 0) {
      const { w, h } = vpMetrics();
      const needsFit = refsList.some(entry => {
        const p = state.nodes[entry.id];
        if (!p) return false;
        const hw = (p.w || DEFAULT_CARD_W) / 2;
        const hh = Math.round(hw * 1.48);
        const sx1 = w / 2 + state.tx + (p.x - hw) * state.scale;
        const sx2 = w / 2 + state.tx + (p.x + hw) * state.scale;
        const sy1 = h / 2 + state.ty + (p.y - hh) * state.scale;
        const sy2 = h / 2 + state.ty + (p.y + hh) * state.scale;
        return sx1 < 16 || sx2 > w - 16 || sy1 < 44 || sy2 > h - 44;
      });
      if (needsFit) fitToView(false);
      else applyCamera();
    } else {
      applyCamera();
    }
    scheduleWires();
  }

  function linkedNotesText() {
    return state.notes
      .filter(n => n.linked && n.text.trim())
      .map(n => n.text.trim())
      .join('\n');
  }

  function tidy() {
    userCamera = false;
    outPos.clear();
    ensurePositions(true);
    renderCards();
    renderNotes();
    renderOutputs();
    scheduleWires();
    fitToView(true);
    persist();
  }

  function clearLayout() {
    state.nodes = {};
    state.hub = null;
    state.tx = 0;
    state.ty = 0;
    state.scale = 1;
    lastRefSig = '';
    userCamera = false;
    outPos.clear();
    persist();
  }

  // ---------- Pointer Interactions (Pan / Drag Node / Resize / Drag Hub / Drag Note / Drag Output / Pinch) ----------
  function bindEvents() {
    const vp = $('#wbCanvasVp');
    const ph0 = $('#wbPh0');
    if (!vp || !ph0) return;

    let drag = null;

    vp.addEventListener('pointerdown', e => {
      if (compactMode || e.button === 2) return;
      if (e.pointerType === 'touch') {
        activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
        if (activePointers.size === 2) {
          drag = null;
          const pts = [...activePointers.values()];
          const dist = Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y) || 1;
          const r = vp.getBoundingClientRect();
          pinchState = {
            dist,
            scale: state.scale,
            tx: state.tx,
            ty: state.ty,
            mx: (pts[0].x + pts[1].x) / 2 - r.left,
            my: (pts[0].y + pts[1].y) / 2 - r.top,
          };
          return;
        }
      }
      if (e.target.closest('button, textarea, input, select, a')) return;

      // Resize card handle
      const rsz = e.target.closest('[data-cv-rsz]');
      if (rsz) {
        const card = rsz.closest('.board-card');
        const id = card?.dataset.nid;
        const node = id && state.nodes[id];
        if (!node) return;
        e.preventDefault();
        e.stopPropagation();
        node.z = ++zTop;
        card.style.zIndex = String(node.z);
        drag = { kind: 'resize', pointerId: e.pointerId, id, card, sx: e.clientX, startW: node.w || DEFAULT_CARD_W, moved: false };
        return;
      }

      // Drag Sticky Note by header
      const noteHead = e.target.closest('[data-note-drag]');
      if (noteHead) {
        const noteEl = noteHead.closest('.cv-note');
        const note = state.notes.find(n => n.id === noteEl?.dataset.noteId);
        if (!note) return;
        e.preventDefault();
        drag = { kind: 'note', pointerId: e.pointerId, note, el: noteEl, sx: e.clientX, sy: e.clientY, ox: note.x, oy: note.y, moved: false };
        return;
      }

      // Drag Output Hub
      const hubHead = e.target.closest('.cv-hub-head');
      if (hubHead && state.hub) {
        const hubEl = hubHead.closest('.cv-hub');
        e.preventDefault();
        drag = { kind: 'hub', pointerId: e.pointerId, el: hubEl, sx: e.clientX, sy: e.clientY, ox: state.hub.x, oy: state.hub.y, moved: false };
        return;
      }

      // Drag pinned generated output iteration
      const outNode = !spaceHeld ? e.target.closest('.cv-out-node') : null;
      if (outNode) {
        const outIdx = Number(outNode.dataset.outI || 0);
        const ox = Number(outNode.dataset.wx || 0);
        const oy = Number(outNode.dataset.wy || 0);
        drag = { kind: 'out', pointerId: e.pointerId, outIdx, el: outNode, sx: e.clientX, sy: e.clientY, ox, oy, moved: false };
        return;
      }

      // Drag Spatial Reference Card (unless Space held -> pan canvas)
      const card = !spaceHeld && !isSample ? e.target.closest('.board-card') : null;
      if (card) {
        const id = card.dataset.nid;
        const node = id && state.nodes[id];
        if (!node) return;
        node.z = ++zTop;
        card.style.zIndex = String(node.z);
        drag = { kind: 'card', pointerId: e.pointerId, id, card, sx: e.clientX, sy: e.clientY, ox: node.x, oy: node.y, moved: false };
        return;
      }

      // Pan empty canvas
      if (e.button === 0 || e.button === 1) {
        drag = { kind: 'pan', pointerId: e.pointerId, sx: e.clientX, sy: e.clientY, ox: state.tx, oy: state.ty, moved: false };
      }
    });

    const onPointerMove = e => {
      if (e.pointerType === 'touch' && activePointers.has(e.pointerId)) {
        activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
        if (pinchState && activePointers.size === 2) {
          const pts = [...activePointers.values()];
          const dist = Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y) || 1;
          const r = vp.getBoundingClientRect();
          const mx = (pts[0].x + pts[1].x) / 2 - r.left;
          const my = (pts[0].y + pts[1].y) / 2 - r.top;
          const { w, h } = vpMetrics();
          const next = clamp(Math.round(pinchState.scale * (dist / pinchState.dist) * 100) / 100, MIN_SCALE, MAX_SCALE);
          const wx = (pinchState.mx - w / 2 - pinchState.tx) / pinchState.scale;
          const wy = (pinchState.my - h / 2 - pinchState.ty) / pinchState.scale;
          state.scale = next;
          state.tx = mx - w / 2 - wx * next;
          state.ty = my - h / 2 - wy * next;
          userCamera = true;
          applyCamera();
          return;
        }
      }
      if (!drag) return;
      const dx = e.clientX - drag.sx;
      const dy = e.clientY - drag.sy;
      if (!drag.moved) {
        if (Math.hypot(dx, dy) < 5) return;
        drag.moved = true;
        if (drag.kind === 'pan') vp.classList.add('panning');
        try { vp.setPointerCapture(drag.pointerId); } catch {}
      }

      if (drag.kind === 'pan') {
        state.tx = drag.ox + dx;
        state.ty = drag.oy + dy;
        userCamera = true;
        applyCamera();
      } else if (drag.kind === 'card') {
        const node = state.nodes[drag.id];
        if (!node) return;
        drag.card.classList.add('dragging');
        node.x = snap(drag.ox + dx / state.scale);
        node.y = snap(drag.oy + dy / state.scale);
        node.pinned = true;
        drag.card.style.left = node.x + 'px';
        drag.card.style.top = node.y + 'px';
        scheduleWires();
      } else if (drag.kind === 'resize') {
        const node = state.nodes[drag.id];
        if (!node) return;
        node.w = clamp(snap(drag.startW + dx / state.scale), MIN_CARD_W, MAX_CARD_W);
        node.pinned = true;
        drag.card.style.width = node.w + 'px';
        scheduleWires();
      } else if (drag.kind === 'note') {
        drag.el.classList.add('dragging');
        drag.note.x = snap(drag.ox + dx / state.scale);
        drag.note.y = snap(drag.oy + dy / state.scale);
        drag.el.style.left = drag.note.x + 'px';
        drag.el.style.top = drag.note.y + 'px';
        scheduleWires();
      } else if (drag.kind === 'hub' && state.hub) {
        drag.el.classList.add('dragging');
        state.hub.x = snap(drag.ox + dx / state.scale);
        state.hub.y = snap(drag.oy + dy / state.scale);
        state.hub.pinned = true;
        drag.el.style.left = state.hub.x + 'px';
        drag.el.style.top = state.hub.y + 'px';
        scheduleWires();
      } else if (drag.kind === 'out') {
        drag.el.classList.add('dragging');
        const nx = snap(drag.ox + dx / state.scale);
        const ny = snap(drag.oy + dy / state.scale);
        outPos.set(drag.outIdx, { x: nx, y: ny });
        drag.el.dataset.wx = String(nx);
        drag.el.dataset.wy = String(ny);
        drag.el.style.left = nx + 'px';
        drag.el.style.top = ny + 'px';
        scheduleWires();
      }
    };

    const endDrag = e => {
      if (e.pointerType === 'touch') {
        activePointers.delete(e.pointerId);
        if (pinchState && activePointers.size < 2) {
          pinchState = null;
          persist();
        }
      }
      if (!drag) return;
      if (drag.moved) {
        suppressClickUntil = performance.now() + 180;
        persist();
        try { vp.releasePointerCapture(drag.pointerId); } catch {}
      }
      drag.card?.classList.remove('dragging');
      drag.el?.classList.remove('dragging');
      vp.classList.remove('panning');
      drag = null;
    };
    window.addEventListener('pointermove', onPointerMove);
    window.addEventListener('pointerup', endDrag);
    window.addEventListener('pointercancel', endDrag);

    // Keyboard activation for role="button" spatial reference cards
    vp.addEventListener('keydown', e => {
      if ((e.key === 'Enter' || e.key === ' ') && e.target.classList?.contains('board-card')) {
        e.preventDefault();
        e.target.click();
      }
    });

    // Prevent click from triggering picker or lightbox right after dragging a card/output
    vp.addEventListener('click', e => {
      if (performance.now() < suppressClickUntil && e.target.closest('.board-card, .cv-out-node')) {
        e.preventDefault();
        e.stopPropagation();
      }
    }, true);

    // Double-click empty canvas to drop an Art-Direction Sticky Note right there
    vp.addEventListener('dblclick', e => {
      if (compactMode || e.target.closest('.board-card, .cv-note, .cv-hub, .cv-out-node, button, textarea')) return;
      const r = vp.getBoundingClientRect();
      const wx = (e.clientX - r.left - r.width / 2 - state.tx) / state.scale;
      const wy = (e.clientY - r.top - r.height / 2 - state.ty) / state.scale;
      addNote(wx, wy);
    });

    // Figma-grade cursor-centered continuous wheel/pinch zoom + trackpad horizontal/diagonal pan
    vp.addEventListener('wheel', e => {
      if (compactMode) return;
      if (e.target.closest('textarea')) return;
      e.preventDefault();
      const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 240 : 1;
      const dx = e.deltaX * unit;
      const dy = e.deltaY * unit;
      if (!e.ctrlKey && !e.metaKey && Math.abs(dx) > 0) {
        state.tx -= dx;
        state.ty -= dy;
        userCamera = true;
        applyCamera();
        persist();
        return;
      }
      const r = vp.getBoundingClientRect();
      const pinch = e.ctrlKey || e.metaKey;
      const sensitivity = pinch ? 0.0085 : 0.0014;
      const factor = Math.exp(-clamp(dy, -140, 140) * sensitivity);
      zoomBy(factor, e.clientX - r.left, e.clientY - r.top);
    }, { passive: false });

    // Delegate actions inside #wbPh0
    ph0.addEventListener('click', e => {
      const hudAct = e.target.closest('[data-cv-act]')?.dataset.cvAct;
      if (hudAct) {
        if (hudAct === 'note') addNote();
        else if (hudAct === 'tidy') tidy();
        else if (hudAct === 'fit') {
          userCamera = false;
          fitToView(true);
        }
        else if (hudAct === 'zin') zoomBy(1.18);
        else if (hudAct === 'zout') zoomBy(1 / 1.18);
        else if (hudAct === 'zreset') {
          userCamera = false;
          state.scale = 1;
          state.tx = 0;
          state.ty = 0;
          applyCamera();
          persist();
        } else if (hudAct === 'wires') {
          state.showWires = !state.showWires;
          updateHud();
          drawWires();
          persist();
        } else if (hudAct === 'zen') {
          setZen(!zenMode);
        }
        return;
      }

      const cardActBtn = e.target.closest('[data-cv-card]');
      if (cardActBtn) {
        e.preventDefault();
        e.stopPropagation();
        const card = cardActBtn.closest('.board-card');
        const id = card?.dataset.nid;
        const act = cardActBtn.dataset.cvCard;
        const slot = card?.dataset.slot;
        const si = Number(card?.dataset.si || 0);
        if (act === 'flip' && id && state.nodes[id]) {
          state.nodes[id].flip = !state.nodes[id].flip;
          card.classList.toggle('cv-flip', state.nodes[id].flip);
          cardActBtn.classList.toggle('on', state.nodes[id].flip);
          persist();
        } else if (act === 'pick') {
          api?.openPicker(card.dataset.pick, card);
        } else if (act === 'ang') {
          api?.cycleAngle(slot, si);
        } else if (act === 'rm') {
          api?.removeRef(slot, si);
        }
        return;
      }

      const noteActBtn = e.target.closest('[data-note-act]');
      if (noteActBtn) {
        const noteEl = noteActBtn.closest('.cv-note');
        const idx = state.notes.findIndex(n => n.id === noteEl?.dataset.noteId);
        if (idx < 0) return;
        const act = noteActBtn.dataset.noteAct;
        if (act === 'rm') {
          state.notes.splice(idx, 1);
          renderNotes();
          renderOutputs();
          updateHud();
          scheduleWires();
          persist();
          api?.onNotesChange();
        } else if (act === 'link') {
          state.notes[idx].linked = !state.notes[idx].linked;
          renderNotes();
          scheduleWires();
          persist();
          api?.onNotesChange();
        }
        return;
      }

      if (e.target.closest('[data-hub-go]') || e.target.id === 'wbZenGo') {
        api?.generate();
        return;
      }

      const outActBtn = e.target.closest('[data-out-act]');
      if (outActBtn) {
        const act = outActBtn.dataset.outAct;
        const i = Number(outActBtn.dataset.outI || 0);
        if (act === 'view') api?.viewResult(i);
        else if (act === 'use') api?.useResultAsPerson(i);
        else if (act === 'dl') api?.downloadResult?.(i);
      }
    });

    // Live sticky-note editing -> instant prompt injection
    ph0.addEventListener('input', e => {
      const ta = e.target.closest('.cv-note textarea');
      if (!ta) return;
      const noteEl = ta.closest('.cv-note');
      const note = state.notes.find(n => n.id === noteEl?.dataset.noteId);
      if (!note) return;
      note.text = ta.value;
      scheduleWires();
      persist();
      if (note.linked) api?.onNotesChange();
    });

    // Keyboard shortcuts when Studio is active and not typing
    addEventListener('keydown', e => {
      if (!document.body.classList.contains('studio')) return;
      const ae = document.activeElement;
      const typing = ae && /^(INPUT|TEXTAREA|SELECT)$/.test(ae.tagName);
      if (e.key === 'Escape' && zenMode && $('#pk')?.hidden && $('#cfg')?.hidden && $('#recipeBox')?.hidden) {
        e.preventDefault();
        setZen(false);
        return;
      }
      if (typing || e.ctrlKey || e.metaKey || e.altKey) return;
      if (e.code === 'Space') {
        if (!ae || !/^(BUTTON|A|SUMMARY)$/.test(ae.tagName) && ae.getAttribute?.('role') !== 'button') {
          e.preventDefault();
        }
        spaceHeld = true;
        vp.classList.add('space');
      } else if (e.key === '0') {
        userCamera = false;
        fitToView(true);
      }
    });
    const clearSpace = () => {
      if (!spaceHeld) return;
      spaceHeld = false;
      vp.classList.remove('space');
    };
    addEventListener('keyup', e => {
      if (e.code === 'Space') clearSpace();
    });
    addEventListener('blur', clearSpace);

    // Re-sync compact mode, camera & wires on viewport resize or hidden-to-visible tab switch
    let resizeRaf = 0;
    let lastVpW = 0;
    const handleResize = () => {
      if (resizeRaf || !document.body.classList.contains('studio')) return;
      resizeRaf = requestAnimationFrame(() => {
        resizeRaf = 0;
        const rect = vp.getBoundingClientRect();
        if (!rect.width && !rect.height) {
          lastVpW = 0;
          return;
        }
        const revealed = lastVpW === 0 && rect.width > 0;
        lastVpW = rect.width;
        const nextCompact = isCompactViewport();
        if (nextCompact !== compactMode) {
          compactMode = nextCompact;
          if (compactMode && zenMode) setZen(false);
          renderCards();
          renderNotes();
          renderOutputs();
          updateHud();
        }
        if (revealed && !compactMode && !userCamera && !isSample && refsList.length > 0) {
          const { w, h } = vpMetrics();
          const needsFit = refsList.some(entry => {
            const p = state.nodes[entry.id];
            if (!p) return false;
            const hw = (p.w || DEFAULT_CARD_W) / 2;
            const hh = Math.round(hw * 1.48);
            const sx1 = w / 2 + state.tx + (p.x - hw) * state.scale;
            const sx2 = w / 2 + state.tx + (p.x + hw) * state.scale;
            const sy1 = h / 2 + state.ty + (p.y - hh) * state.scale;
            const sy2 = h / 2 + state.ty + (p.y + hh) * state.scale;
            return sx1 < 16 || sx2 > w - 16 || sy1 < 44 || sy2 > h - 44;
          });
          if (needsFit) fitToView(false);
          else applyCamera();
        } else {
          applyCamera();
        }
        scheduleWires();
      });
    };
    addEventListener('resize', handleResize);
    if (typeof ResizeObserver !== 'undefined') {
      new ResizeObserver(handleResize).observe(vp);
    }
  }

  function init(studioApi) {
    api = studioApi;
    bindEvents();
    compactMode = isCompactViewport();
    updateHud();
    applyCamera();
  }

  window.PoseWearCanvas = {
    init,
    sync,
    syncMeta,
    tidy,
    fitToView,
    addNote,
    setZen,
    isZen: () => zenMode,
    linkedNotesText,
    clearLayout,
    getState: () => ({
      tx: state.tx,
      ty: state.ty,
      scale: state.scale,
      showWires: state.showWires,
      notes: state.notes.map(n => ({ ...n })),
      nodes: { ...state.nodes },
      zen: zenMode,
      compact: compactMode,
    }),
  };
})();