Skip to content

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

9.8 KB
Raw Blame
'use strict';
(() => {
  // Side-by-side Reference Compare Studio (#cmpModal).
  // Compares 2-4 references simultaneously with synced mirror, composition grids,
  // grayscale / 3-tone Notan value blocks, silhouette check, and pose/depth flip.
  const C = window.PoseWearCatalog;
  if (!C) return;
  const { $, esc, TL } = C;

  const state = {
    open: false,
    entries: [], // { originKey, item, ai }
    flip: false,
    grid: 0,
    gray: 0, // 0=off, 1=grayscale, 2=notan-3
    sil: false,
    pair: false,
    prevFocus: null,
  };

  let app = null;

  function activeItem(entry) {
    const base = app.ITEMS[entry.originKey] || entry.item;
    if (!base) return null;
    if (state.pair) {
      const mate = app.poseCounterpart(base, entry.ai);
      if (mate) return { item: mate.item, ai: mate.angle };
    }
    return { item: base, ai: entry.ai };
  }

  function hasPairable() {
    return state.entries.some(entry => {
      const base = app.ITEMS[entry.originKey];
      return base && app.poseCounterpart(base, entry.ai);
    });
  }

  function renderTools() {
    const modal = $('#cmpModal');
    if (!modal) return;
    const setBtn = (key, on) => {
      const btn = modal.querySelector(`[data-ct="${key}"]`);
      if (!btn) return;
      btn.classList.toggle('on', !!on);
      btn.setAttribute('aria-pressed', String(!!on));
    };
    setBtn('flip', state.flip);
    setBtn('grid', state.grid > 0);
    setBtn('gray', state.gray > 0);
    setBtn('sil', state.sil);
    setBtn('pair', state.pair);

    const grayLabel = modal.querySelector('[data-ct="gray"] span');
    if (grayLabel) grayLabel.textContent = state.gray === 2 ? '明度块面' : '灰度';

    const pairBtn = modal.querySelector('[data-ct="pair"]');
    if (pairBtn) pairBtn.hidden = !hasPairable();

    const gridMode = ['', 'thirds', 'cross'][state.grid] || '';
    for (const stage of modal.querySelectorAll('.cmp-stage')) {
      stage.classList.toggle('flipped', state.flip);
      stage.classList.toggle('gray', state.gray > 0);
      stage.classList.toggle('notan', state.gray === 2);
      stage.classList.toggle('sil', state.sil);
      const gridEl = stage.querySelector('.lb-grid');
      if (gridEl) gridEl.dataset.mode = gridMode;
    }
  }

  function renderCards() {
    const grid = $('#cmpGrid');
    const count = $('#cmpCount');
    if (!grid) return;
    grid.dataset.n = String(state.entries.length);
    if (count) count.textContent = `${state.entries.length} / 4`;

    grid.innerHTML = state.entries
      .map((entry, idx) => {
        const resolved = activeItem(entry);
        if (!resolved) return '';
        const { item, ai } = resolved;
        const view = item.angles?.[ai];
        const src = view ? (view.i || view.t) : (item.m || item.i || item.t);
        const label = app.title(item);
        const isFav = app.st.fav.has(item.k);
        const isSel = app.st.sel.includes(item.k);
        const angles = item.angles
          ? `<div class="cmp-angs" role="group" aria-label="拍摄角度">${item.angles
              .map(
                (a, i) =>
                  `<button type="button" class="${i === ai ? 'on' : ''}" data-cai="${i}" aria-pressed="${i === ai}">${esc(a.zh)}</button>`
              )
              .join('')}</div>`
          : '';
        const meta = view
          ? `<span>${esc(TL(item))}</span> · <span>${esc(view.zh)}</span>`
          : `<span>${esc(TL(item))}</span>${item.cat ? ` · <span>${esc(item.cat)}</span>` : ''}`;

        return (
          `<article class="cmp-card" data-ci="${idx}" data-type="${item.type}">` +
          `<div class="cmp-ph" data-img-type="${item.type}">` +
          `<div class="cmp-stage"><img src="${esc(src)}" alt="${esc(label)}"${item.ref ? ` referrerpolicy="${esc(item.ref)}"` : ''} draggable="false"><div class="lb-grid" aria-hidden="true"></div></div>` +
          `<span class="cmp-idx">${idx + 1}</span>` +
          `<button type="button" class="cmp-rm" data-ca="rm" title="移出对比" aria-label="移出对比">×</button>` +
          `${angles}` +
          `</div>` +
          `<div class="cmp-info">` +
          `<h4 title="${esc(label)}">${esc(label)}</h4>` +
          `<small>${meta}</small>` +
          `<div class="cmp-act">` +
          `<button type="button" class="sm ${isFav ? 'on' : ''}" data-ca="fav" aria-pressed="${isFav}" title="${isFav ? '取消收藏' : '收藏'}">${isFav ? '♥' : '♡'}</button>` +
          `<button type="button" class="sm ${isSel ? 'on' : ''}" data-ca="sel" aria-pressed="${isSel}" title="${isSel ? '移出组合' : '加入组合'}">${isSel ? '✓' : '+'}</button>` +
          `<button type="button" class="sm ghost" data-ca="copy">复制</button>` +
          `<button type="button" class="sm ghost" data-ca="open">大图</button>` +
          `</div></div></article>`
        );
      })
      .join('');

    renderTools();
  }

  function preloadCounterparts() {
    const missing = new Set();
    for (const entry of state.entries) {
      const base = app.ITEMS[entry.originKey];
      const pairType = base && app.counterpartType(base);
      if (pairType && !app.DATA[pairType]) missing.add(pairType);
    }
    if (missing.size) {
      Promise.all([...missing].map(t => app.load(t)))
        .then(() => {
          if (state.open) renderTools();
        })
        .catch(() => {});
    }
  }

  function open(input) {
    if (!app) return;
    const rawItems = (Array.isArray(input) ? input : [])
      .map(x => (typeof x === 'string' ? app.ITEMS[x] : x))
      .filter(it => app.ok(it));
    const unique = [];
    const seen = new Set();
    for (const it of rawItems) {
      if (seen.has(it.k)) continue;
      seen.add(it.k);
      unique.push(it);
    }
    if (unique.length < 2) {
      app.toast('请至少选择 2 项素材进行对比');
      return;
    }
    const capped = unique.slice(0, 4);
    if (unique.length > 4) app.toast('同屏对比最多支持 4 项,已展示前 4 项');

    if (window.PoseWearCommandPalette?.isOpen()) window.PoseWearCommandPalette.close();
    if (window.PoseWearSketch?.isOpen()) window.PoseWearSketch.close();

    state.prevFocus = document.activeElement;
    state.entries = capped.map(it => ({ originKey: it.k, item: it, ai: it.ai ?? 0 }));
    state.flip = false;
    state.grid = 0;
    state.gray = 0;
    state.sil = false;
    state.pair = false;
    state.open = true;

    const modal = $('#cmpModal');
    modal.hidden = false;
    document.body.style.overflow = 'hidden';
    renderCards();
    preloadCounterparts();
    $('#cmpClose')?.focus({ preventScroll: true });
  }

  function close() {
    if (!state.open) return;
    state.open = false;
    const modal = $('#cmpModal');
    if (modal) modal.hidden = true;
    $('#cmpGrid')?.replaceChildren();
    document.body.style.overflow = '';
    if (state.prevFocus?.isConnected) state.prevFocus.focus({ preventScroll: true });
    state.prevFocus = null;
  }

  function toggleTool(action) {
    if (!state.open) return;
    if (action === 'flip') {
      state.flip = !state.flip;
    } else if (action === 'grid') {
      state.grid = (state.grid + 1) % 3;
    } else if (action === 'gray') {
      state.sil = false;
      state.gray = (state.gray + 1) % 3;
    } else if (action === 'sil') {
      state.sil = !state.sil;
      if (state.sil) state.gray = 0;
    } else if (action === 'pair') {
      if (!hasPairable()) return;
      state.pair = !state.pair;
      renderCards();
      return;
    }
    renderTools();
  }

  function handleKey(e) {
    if (!state.open) return false;
    const k = (e.key || '').toLowerCase();
    if (e.key === 'Escape') { e.preventDefault(); close(); }
    else if (k === 'h') toggleTool('flip');
    else if (k === 'g') toggleTool('grid');
    else if (k === 'b') toggleTool('gray');
    else if (k === 'u') toggleTool('sil');
    else if (k === 'v') toggleTool('pair');
    else if (e.key === 'Tab') app.trapTab(e, $('#cmpModal'));
    return true;
  }

  function init(appApi) {
    app = appApi;
    const modal = $('#cmpModal');
    if (!modal) return;
    $('#cmpClose')?.addEventListener('click', close);
    modal.addEventListener('click', e => {
      if (e.target === modal) return close();
      const toolBtn = e.target.closest('[data-ct]');
      if (toolBtn) return toggleTool(toolBtn.dataset.ct);

      const card = e.target.closest('.cmp-card');
      if (!card) return;
      const idx = Number(card.dataset.ci);
      const entry = state.entries[idx];
      if (!entry) return;
      const resolved = activeItem(entry);
      if (!resolved) return;

      const angBtn = e.target.closest('[data-cai]');
      if (angBtn) {
        const nextAi = Number(angBtn.dataset.cai);
        if (state.pair) {
          const base = app.ITEMS[entry.originKey];
          const chosenZh = resolved.item.angles?.[nextAi]?.zh;
          const baseIdx = base?.angles?.findIndex(a => a.zh === chosenZh);
          if (baseIdx >= 0) entry.ai = baseIdx;
        } else {
          entry.ai = nextAi;
        }
        renderCards();
        return;
      }

      const act = e.target.closest('[data-ca]')?.dataset.ca;
      if (!act) return;
      if (act === 'rm') {
        state.entries.splice(idx, 1);
        if (state.entries.length < 2) close();
        else renderCards();
      } else if (act === 'fav') {
        app.toggleFav(resolved.item.k);
        renderCards();
      } else if (act === 'sel') {
        app.toggleSel(resolved.item.k);
        renderCards();
      } else if (act === 'copy') {
        const copyItem = { ...resolved.item, ai: resolved.ai };
        app.copyBrief(app.prompt(copyItem, app.st.lang), [copyItem], app.st.lang, '提示词');
      } else if (act === 'open') {
        const target = resolved.item;
        close();
        app.openItem(target.type, target.id);
      }
    });
  }

  window.PoseWearCompare = {
    init,
    open,
    close,
    isOpen: () => state.open,
    handleKey,
  };
  if (window.APP) init(window.APP);
})();