Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

29.2 KB
Raw Blame
// Bảng phải của Studio: đổi theo icon cột trái (Phụ đề · Nhạc · Zoom · Đồ hoạ · Sửa bằng lời) và theo khối đang chọn.
// Chữ từ server (dòng phụ đề, tên nhạc, ô đồ hoạ, lời sửa) chỉ vào DOM qua textContent / value / new Option.
import { el, tx, icon, iconBtn, fmtT, fmtDb, paintWords, plain, clamp, r2, t, I } from './util.js';

const GFX_KEYS = ['kicker', 'title', 'unit', 'label', 'prefix', 'value', 'suffix', 'old', 'text', 'a', 'b'];
const ROW_KEYS = { items: ['text', 'label', 'value', 'ok'], rows: ['label', 'value', 'a', 'b'], points: ['label', 'value'] };

export class Inspector {
  constructor(ctx) {
    this.ctx = ctx; // {store, player, seek, select, getSel, review, mode(), setMode, uploadMusic(file), revise(text), musicName(src)}
    this.root = el('aside', 'st-insp');
    this.head = el('h3', 'st-ih');
    this.body = el('div', 'st-ib');
    this.grab = el('button', 'st-grab', null, { type: 'button', 'aria-label': t('st.closeSheet') }); this.grab.dataset.i18nAria = 'st.closeSheet';
    this.grab.addEventListener('click', () => this.ctx.closeSheet?.());
    this.root.append(this.grab, this.head, this.body);
    this.capTab = 'lines';
    this.nowU = null;
  }
  setHead(iconName, key, extra) {
    const h = [icon(iconName), tx('span', null, key)];
    if (extra) h.push(extra);
    this.head.replaceChildren(...h);
  }
  /** Vẽ lại bảng theo chế độ. light=true: chỉ cập nhật chữ, không dựng lại ô đang gõ. */
  render() {
    const mode = this.ctx.mode();
    const a = document.activeElement;
    if (this.root.contains(a) && a.matches('input[type=text],input[type=number],input[type=range],textarea') && this.lastMode === mode && this.lastSel === JSON.stringify(this.ctx.getSel())) { this.lightUpdate(); return; }
    this.lastMode = mode; this.lastSel = JSON.stringify(this.ctx.getSel());
    const ro = !!this.ctx.store.view?.readOnly;
    this.root.classList.toggle('ro', ro);
    if (mode === 'cap') this.renderCap();
    else if (mode === 'music') this.renderMusic();
    else if (mode === 'zoom') this.renderZoom();
    else if (mode === 'gfx') this.renderGfx();
    else if (mode === 'ai') this.renderAi();
    else if (mode === 'review') this.renderReview();
    else if (mode === 'video') this.renderVideo();
    if (ro && mode !== 'ai') this.body.prepend(tx('p', 'st-note', 'st.readOnly'));
  }
  lightUpdate() {
    // dòng đang gõ: cập nhật chữ ở danh sách (nếu có) — giữ nguyên ô nhập
    for (const li of this.body.querySelectorAll('.st-ln[data-u]')) {
      const l = this.ctx.store.doc.lines.find((x) => x.u === li.dataset.u); if (!l) continue;
      const tm = li.querySelector('.tm'); if (tm) tm.textContent = fmtT(l.start);
      const s = li.querySelector('.tx'); if (s) paintWords(s, l.text);
    }
  }
  commit(fn, key) { return key ? this.ctx.store.commitTyping(key, fn) : this.ctx.store.commit(fn); }

  // ---- Phụ đề ----
  renderCap() {
    const st = this.ctx.store; const n = this.ctx.review.pending();
    this.setHead('cap', 'st.trCap');
    const seg = el('div', 'st-seg', null, { role: 'tablist' });
    const tabs = [['lines', 'st.capLines'], ['look', 'st.capLook'], ['review', null]];
    for (const [id, key] of tabs) {
      const b = el('button', id === this.capTab ? 'on' : '', key ? t(key) : t('st.capReview', { n }), { type: 'button', role: 'tab', 'aria-selected': String(id === this.capTab) });
      if (key) b.dataset.i18n = key;
      b.addEventListener('click', () => { this.capTab = id; this.render(); });
      seg.append(b);
    }
    const kids = [seg];
    if (this.capTab === 'lines') kids.push(this.linesList());
    else if (this.capTab === 'look') kids.push(this.lookPicker());
    else kids.push(this.reviewBody());
    this.body.replaceChildren(...kids);
    if (this.capTab === 'lines') this.scrollSel();
    if (st.view?.draft) this.body.prepend(tx('p', 'st-note warn', 'man.draftNote'));
  }
  linesList() {
    const st = this.ctx.store; const sel = this.ctx.getSel(); const L = st.doc.lines; const bad = st.lineErrors();
    const ol = el('ol', 'st-lines');
    ol.setAttribute('aria-label', t('st.trCap'));
    if (!L.length) { ol.append(tx('li', 'none', 'man.noLines')); return ol; }
    L.forEach((l, k) => {
      const on = sel?.kind === 'cap' && sel.u === l.u;
      const li = el('li', 'st-ln' + (on ? ' sel' : '') + (l.u === this.nowU ? ' now' : '') + (bad.has(l.u) ? ' bad' : ''), null, { 'data-u': l.u });
      if (!on) {
        const b = el('button', 'row', null, { type: 'button' });
        const s = el('span', 'tx'); paintWords(s, l.text);
        b.append(el('span', 'tm mono', fmtT(l.start)), s);
        if (this.ctx.flagged(l.u)) b.append(el('span', 'flag', null, { 'aria-label': t('st.flagged') }));
        b.addEventListener('click', () => { this.ctx.select({ kind: 'cap', u: l.u }); this.ctx.seek(l.start + 0.01); });
        li.append(b);
      } else li.append(...this.lineEditor(l, k, L.length, bad.get(l.u)));
      ol.append(li);
    });
    return ol;
  }
  lineEditor(l, k, n, bad) {
    const ro = !!this.ctx.store.view?.readOnly || !!this.ctx.store.view?.draft;
    const inp = el('input', 'st-ledit', null, { type: 'text', maxlength: '200', spellcheck: 'false', 'aria-label': t('man.lineText', { n: k + 1 }) });
    inp.value = l.text; inp.disabled = ro;
    inp.addEventListener('input', () => this.commit((d) => { const x = d.lines.find((y) => y.u === l.u); if (x) x.text = inp.value; }, 'text:' + l.u));
    inp.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); inp.blur(); } });
    setTimeout(() => { if (this.wantFocus === l.u) { this.wantFocus = null; inp.focus(); inp.setSelectionRange(inp.value.length, inp.value.length); } }, 0);
    const num = (f, v) => {
      const w = el('label', 'st-tbox');
      w.append(icon('clock'));
      const i = el('input', 'mono', null, { type: 'number', step: '0.05', min: '0', inputmode: 'decimal', 'aria-label': t(f === 'start' ? 'man.lineStart' : 'man.lineEnd', { n: k + 1 }) });
      i.value = r2(v).toFixed(2); i.disabled = ro;
      i.addEventListener('change', () => { const x = Number(i.value); if (Number.isFinite(x)) this.commit((d) => { const y = d.lines.find((z) => z.u === l.u); if (y) y[f] = clamp(r2(x), 0, this.ctx.store.view.duration); }); });
      w.append(i); return w;
    };
    const row = el('div', 'st-row');
    const acts = el('span', 'st-acts');
    const hiB = iconBtn('hi', 'st.markHi', 'mini'); hiB.disabled = ro;
    hiB.addEventListener('mousedown', (e) => e.preventDefault()); // giữ vùng chọn trong ô chữ
    hiB.addEventListener('click', () => this.toggleHi(inp, l.u));
    const sp = iconBtn('split', 'man.split', 'mini'); sp.disabled = ro;
    sp.addEventListener('click', () => this.ctx.splitAtHead(l.u));
    const mg = iconBtn('merge', 'man.merge', 'mini'); mg.disabled = ro || k + 1 >= n;
    mg.addEventListener('click', () => this.ctx.store.mergeLine(k));
    const del = iconBtn('trash', 'st.del', 'mini danger'); del.disabled = ro;
    del.addEventListener('click', () => this.ctx.deleteSel());
    acts.append(hiB, sp, mg, del);
    row.append(num('start', l.start), el('span', 'arrow', '→', { 'aria-hidden': 'true' }), num('end', l.end), acts);
    const out = [inp, row];
    for (const it of this.ctx.review.inLine(l)) {
      const p = el('p', 'st-ainote');
      p.append(icon('warn'), it.kind === 'fix' ? t('st.aiFixed', { heard: it.heard, text: it.text || '∅' }) : t('st.figCheck', { text: it.text, said: it.heard }));
      out.push(p);
    }
    if (bad) out.push(el('p', 'st-err', t('st.lineErr.' + bad)));
    return out;
  }
  /** Bọc / bỏ bọc *…* quanh chữ đang chọn trong ô (chữ nhấn). Không chọn gì: từ ở con trỏ. */
  toggleHi(inp, u) {
    let a = inp.selectionStart ?? 0; let b = inp.selectionEnd ?? 0; const v = inp.value;
    if (a === b) { while (a > 0 && !/\s/.test(v[a - 1])) a--; while (b < v.length && !/\s/.test(v[b])) b++; }
    if (a === b) return;
    let seg = v.slice(a, b);
    const wrapped = /^\*.*\*$/.test(seg.trim());
    seg = wrapped ? seg.replace(/\*/g, '') : `*${seg.replace(/\*/g, '').trim()}*`;
    const nv = (v.slice(0, a) + seg + v.slice(b)).replace(/\s+/g, ' ');
    this.commit((d) => { const x = d.lines.find((y) => y.u === u); if (x) x.text = nv; });
    this.wantFocus = u;
  }
  scrollSel() {
    const ol = this.body.querySelector('.st-lines'); if (!ol) return;
    const li = ol.querySelector('.st-ln.sel') || ol.querySelector('.st-ln.now'); if (!li) return;
    const br = this.body.getBoundingClientRect(); const r = li.getBoundingClientRect();
    const top = r.top - br.top + this.body.scrollTop; const h = this.body.clientHeight;
    const seg = this.body.querySelector('.st-seg')?.offsetHeight || 0;
    if (r.top < br.top + seg + 8 || r.bottom > br.bottom - 8) this.body.scrollTop = Math.max(0, top - Math.max(seg + 12, (h - r.height) / 3));
  }
  /** Dòng đang phát tô sáng (không dựng lại cả danh sách). */
  onTime(tt) {
    const L = this.ctx.store.doc?.lines || [];
    const l = L.find((x) => tt >= x.start && tt < x.end);
    const u = l ? l.u : null;
    if (u === this.nowU) return;
    this.body.querySelector(`.st-ln[data-u="${this.nowU}"]`)?.classList.remove('now');
    this.nowU = u;
    const li = u && this.body.querySelector(`.st-ln[data-u="${u}"]`);
    if (li) { li.classList.add('now'); if (!this.ctx.player.video.paused && !this.root.contains(document.activeElement)) this.scrollSel(); }
  }
  lookPicker() {
    const st = this.ctx.store; const v = st.view; const ro = !!v.readOnly || !!v.draft;
    const wrap = el('div', 'st-looks');
    const sw = el('label', 'st-switch');
    const cb = el('input', null, null, { type: 'checkbox', role: 'switch' }); cb.checked = st.doc.hi; cb.disabled = ro;
    cb.addEventListener('change', () => this.commit((d) => { d.hi = cb.checked; }));
    sw.append(cb, tx('span', null, 'man.hiShort'), tx('small', null, 'man.hiTip'));
    // reel nhập vào: phụ đề tắt sẵn (chữ đã nằm trong cảnh), bật ở đây
    const sh = el('label', 'st-switch');
    const cs = el('input', null, null, { type: 'checkbox', role: 'switch' }); cs.checked = st.doc.show !== false; cs.disabled = ro;
    cs.addEventListener('change', () => this.commit((d) => { d.show = cs.checked; }));
    sh.append(cs, tx('span', null, 'st.showCaps'), tx('small', null, 'st.showCapsTip'));
    wrap.append(sh);
    const grid = el('div', 'st-lookgrid', null, { role: 'radiogroup', 'aria-label': t('man.look') });
    for (const l of v.captions.looks) {
      const on = l.id === st.doc.look;
      const b = el('button', 'st-look' + (on ? ' on' : ''), null, { type: 'button', role: 'radio', 'aria-checked': String(on) });
      b.disabled = ro;
      const smp = el('span', 'smp');
      const c = l.css || {};
      smp.style.fontFamily = `${c.font || "'Be Vietnam Pro'"}, sans-serif`; smp.style.fontWeight = String(c.weight || 800);
      smp.append(el('span', null, c.upper ? 'AB' : 'Ab'));
      const hi = el('span', null, c.upper ? 'C' : 'c'); hi.style.color = c.hi || l.hi; smp.append(hi);
      if (c.box) smp.style.background = c.box.bg;
      b.append(smp, el('span', 'nm', I.lang === 'en' ? l.nameEn : l.name));
      b.addEventListener('click', () => this.commit((d) => { d.look = l.id; }));
      grid.append(b);
    }
    wrap.append(sw, grid);
    return wrap;
  }

  // ---- Track video: tách clip / cắt bỏ đoạn ----
  renderVideo() {
    const st = this.ctx.store; const s = this.ctx.getSel(); const ro = !!st.view.readOnly;
    this.setHead('film', 'st.trVideo');
    const kids = [tx('p', 'st-hint', 'st.videoHint')];
    const card = el('div', 'st-card');
    if (s?.kind === 'clip' || s?.kind === 'cut') {
      const [a, b] = s.kind === 'clip' ? [s.a, s.b] : st.doc.cuts[s.i];
      card.append(el('p', 'st-rwhat mono', `${fmtT(a)} → ${fmtT(b)} · ${(b - a).toFixed(2)} s`));
      const act = el('button', 'btn ' + (s.kind === 'clip' ? 'warn' : 'ghost') + ' sm', null, { type: 'button' });
      act.append(icon(s.kind === 'clip' ? 'cut' : 'rotate'), tx('span', null, s.kind === 'clip' ? 'st.cutThis' : 'st.restoreCut'));
      act.disabled = ro; act.addEventListener('click', () => this.ctx.deleteSel());
      card.append(act);
    } else card.append(tx('p', 'st-hint', 'st.videoPick'));
    const sp = el('button', 'btn ghost sm', null, { type: 'button' }); sp.append(icon('split'), tx('span', null, 'st.splitClip')); sp.disabled = ro;
    sp.addEventListener('click', () => this.ctx.splitClip());
    card.append(sp);
    kids.push(card);
    const cuts = st.doc.cuts || [];
    if (cuts.length) {
      kids.push(el('p', 'st-note warn', t('st.cutsPending', { n: cuts.length, s: cuts.reduce((x, [a, b]) => x + b - a, 0).toFixed(1) })));
      const ul = el('ul', 'st-blist');
      cuts.forEach(([a, b], i) => {
        const btn = el('button', s?.kind === 'cut' && s.i === i ? 'on' : '', null, { type: 'button' });
        btn.append(el('span', 'tm mono', fmtT(a)), el('span', 'lb', t('st.cutItem', { a: fmtT(a), b: fmtT(b) })));
        btn.addEventListener('click', () => { this.ctx.select({ kind: 'cut', i }); this.ctx.seek(Math.max(0, a - 0.5)); });
        const li = el('li'); li.append(btn); ul.append(li);
      });
      kids.push(ul);
    }
    this.body.replaceChildren(...kids);
  }

  // ---- Cần xem lại ----
  renderReview() { this.setHead('warn', 'st.reviewH'); this.body.replaceChildren(this.reviewBody()); }
  reviewBody() {
    const R = this.ctx.review; const items = R.items();
    const wrap = el('div', 'st-review');
    if (!items.length) { wrap.append(tx('p', 'st-empty', 'st.reviewNone')); return wrap; }
    const cur = R.current();
    if (cur) {
      const card = el('div', 'st-rcard');
      const top = el('div', 'st-rtop');
      top.append(el('span', 'st-rpos mono', `${R.index() + 1}/${items.length}`), el('span', 'mono st-rtm', cur.at != null ? fmtT(cur.at) : '–'));
      const nav = el('span', 'st-rnav');
      const pv = iconBtn('left', 'st.prevItem', 'mini'); pv.addEventListener('click', () => R.go(-1));
      const nx = iconBtn('right', 'st.nextItem', 'mini'); nx.addEventListener('click', () => R.go(1));
      nav.append(pv, nx); top.append(nav);
      const what = el('p', 'st-rwhat');
      if (cur.kind === 'fix') { what.append(tx('span', 'k', 'st.rFix'), ' '); what.append(el('s', null, cur.heard), ' → ', el('b', null, cur.text || t('ed.hidden'))); }
      else { what.append(tx('span', 'k', 'st.rFig'), ' '); what.append(el('b', null, cur.text), ' · ', el('s', null, cur.heard)); }
      card.append(top, what);
      if (cur.why) card.append(el('p', 'st-rwhy', cur.why));
      const st0 = R.status(cur);
      if (st0) card.append(el('p', 'st-rdone', t('st.rStatus.' + st0)));
      const acts = el('div', 'st-racts');
      const keep = tx('button', 'btn ghost', 'st.rKeep', { type: 'button' }); keep.addEventListener('click', () => R.resolve(cur, 'keep'));
      const fix = tx('button', 'btn ghost', 'st.rEdit', { type: 'button' }); fix.addEventListener('click', () => R.edit(cur));
      const back = tx('button', 'btn warn', 'st.rRevert', { type: 'button' }); back.addEventListener('click', () => R.revert(cur));
      back.disabled = !R.canRevert(cur) || !!this.ctx.store.view?.readOnly;
      if (back.disabled) back.title = t(cur.kind === 'fig' && !R.figTarget(cur) ? 'st.rNoGfx' : 'st.rNoRevert');
      if (cur.kind === 'fig') {
        const tg = R.figTarget(cur);
        const v = tg && R.figRevertValue(cur, tg);
        card.append(el('p', 'st-rwhy', tg ? t('st.rGfxCell', { g: t('gfx.' + tg.g.type), cell: String(tg.cur), to: v == null ? '–' : String(v) }) : t('st.rNoGfx')));
      }
      fix.disabled = !!this.ctx.store.view?.readOnly;
      acts.append(keep, fix, back);
      card.append(acts);
      wrap.append(card);
    }
    const ul = el('ul', 'st-rlist');
    items.forEach((it, i) => {
      const b = el('button', 'st-ritem' + (i === R.index() ? ' on' : '') + (R.status(it) ? ' done' : ''), null, { type: 'button' });
      const txt = el('span', 'rx');
      if (it.kind === 'fix') txt.append(el('s', null, it.heard), ' → ', el('b', null, it.text || t('ed.hidden')));
      else txt.append(el('b', null, it.text), ' · ', el('s', null, it.heard));
      b.append(el('span', 'tm mono', it.at != null ? fmtT(it.at) : '–'), txt, R.status(it) ? icon('check') : el('span'));
      b.addEventListener('click', () => R.goto(i));
      const li = el('li'); li.append(b); ul.append(li);
    });
    wrap.append(ul);
    return wrap;
  }

  // ---- Nhạc ----
  renderMusic() {
    const st = this.ctx.store; const v = st.view; const m = st.doc.music; const ro = !!v.readOnly;
    this.setHead('music', 'st.trMusic');
    const sel = el('select', 'st-sel', null, { id: 'stMusicSrc' });
    const opts = [];
    if (v.music.on) opts.push(new Option(t('man.musicKeep', { name: this.ctx.musicName('keep') }), 'keep'));
    opts.push(new Option(t('ed.noMusic'), 'none'));
    for (const s of v.music.synth) opts.push(new Option(t('man.synth', { id: s }), `synth:${s}`));
    for (const u of v.music.uploads) opts.push(new Option(t('man.uploaded', { name: u.name }), `upload:${u.file}`));
    sel.replaceChildren(...opts); sel.value = m.source; sel.disabled = ro;
    sel.addEventListener('change', () => this.commit((d) => { d.music.source = sel.value; }));
    const file = el('input', null, null, { type: 'file', accept: 'audio/*,.mp3,.wav,.m4a,.aac,.ogg,.flac,.opus', hidden: true });
    const up = el('button', 'btn ghost sm', null, { type: 'button' }); up.append(icon('upload'), tx('span', null, 'st.uploadMusic')); up.disabled = ro;
    up.addEventListener('click', () => file.click());
    file.addEventListener('change', () => { const f = file.files[0]; file.value = ''; if (f) this.ctx.uploadMusic(f); });
    this.musicMsg = this.musicMsg || el('p', 'st-note', null, { 'aria-live': 'polite' });
    const g1 = this.field('man.music', sel, 'stMusicSrc');
    const upRow = el('div', 'st-row'); upRow.append(up, file);
    const kids = [g1, upRow, this.musicMsg];
    if (m.source !== 'none') {
      kids.push(this.slider('st.gain', -40, 0, 1, m.gainDb, fmtDb, (x) => (d) => { d.music.gainDb = x; }, 'gain', ro));
      kids.push(this.check('man.duckS', m.duck, (c) => (d) => { d.music.duck = c; }, ro));
      kids.push(this.slider('man.fadeS', 0, 10, 0.5, m.fadeOut, (x) => `${x} s`, (x) => (d) => { d.music.fadeOut = x; }, 'fade', ro));
      kids.push(this.slider('man.startS', 0, 120, 0.5, m.start, (x) => `${x} s`, (x) => (d) => { d.music.start = x; }, 'mstart', ro));
    }
    kids.push(el('hr'));
    kids.push(this.slider('man.voiceS', -12, 12, 1, st.doc.voice.gainDb, fmtDb, (x) => (d) => { d.voice.gainDb = x; }, 'voice', ro, 'man.loudHint'));
    const sfx = this.check('man.sfx', st.doc.sfx.on, (c) => (d) => { d.sfx.on = c; }, ro || !v.sfx.count);
    const sl = sfx.querySelector('span'); delete sl.dataset.i18n; sl.textContent = t('man.sfx', { n: v.sfx.count });
    kids.push(sfx);
    this.body.replaceChildren(...kids);
  }
  field(key, input, id) { const w = el('div', 'st-field'); const l = tx('label', null, key, { for: id }); w.append(l, input); return w; }
  slider(key, min, max, step, val, fmt, mk, tkey, ro, hintKey) {
    const id = 'st-' + tkey;
    const w = el('div', 'st-field st-slide');
    const l = tx('label', null, key, { for: id });
    const r = el('input', null, null, { type: 'range', id, min: String(min), max: String(max), step: String(step) }); r.value = String(val); r.disabled = !!ro;
    const o = el('output', 'mono', fmt(val), { for: id });
    r.addEventListener('input', () => { const x = Number(r.value); o.textContent = fmt(x); this.commit(mk(x), tkey); });
    w.append(l, r, o);
    if (hintKey) { w.title = t(hintKey); w.dataset.i18nTitle = hintKey; }
    return w;
  }
  check(key, val, mk, ro) {
    const w = el('label', 'st-switch');
    const c = el('input', null, null, { type: 'checkbox', role: 'switch' }); c.checked = !!val; c.disabled = !!ro;
    c.addEventListener('change', () => this.commit(mk(c.checked)));
    w.append(c, tx('span', null, key));
    return w;
  }

  // ---- Zoom ----
  renderZoom() {
    const st = this.ctx.store; const sel = this.ctx.getSel(); const ro = !!st.view.readOnly;
    const add = el('button', 'btn ghost sm', null, { type: 'button' }); add.append(icon('plus'), tx('span', null, 'st.addZoom')); add.disabled = ro;
    add.addEventListener('click', () => this.ctx.addZoom());
    this.setHead('zoom', 'st.trZoom', add);
    const kids = [];
    const z = sel?.kind === 'zoom' && st.doc.zooms.find((x) => x.u === sel.u);
    if (z) {
      const box = el('div', 'st-card');
      const kinds = el('div', 'st-seg sm', null, { role: 'radiogroup', 'aria-label': t('st.zoomKind') });
      for (const k of ['push', 'punch']) {
        const b = tx('button', z.kind === k ? 'on' : '', k === 'push' ? 'st.push' : 'st.punch', { type: 'button', role: 'radio', 'aria-checked': String(z.kind === k) });
        b.disabled = ro;
        b.addEventListener('click', () => this.commit((d) => { const y = d.zooms.find((q) => q.u === z.u); if (y) y.kind = k; }));
        kinds.append(b);
      }
      box.append(kinds, tx('p', 'st-hint', z.kind === 'push' ? 'st.pushHint' : 'st.punchHint'));
      box.append(this.slider('st.zStrength', 1.02, 1.6, 0.01, z.scale, (x) => `${Number(x).toFixed(2)}×`, (x) => (d) => { const y = d.zooms.find((q) => q.u === z.u); if (y) y.scale = x; }, 'zs-' + z.u, ro));
      const maxDur = this.zoomRoom(z);
      box.append(this.slider('st.zLength', 0.2, Math.max(0.2, Math.min(8, maxDur)), 0.1, Math.min(z.dur, maxDur), (x) => `${Number(x).toFixed(1)} s`, (x) => (d) => { const y = d.zooms.find((q) => q.u === z.u); if (y) y.dur = x; }, 'zd-' + z.u, ro));
      const tr = el('div', 'st-row');
      const go = el('button', 'btn ghost sm', fmtT(z.at), { type: 'button' }); go.prepend(icon('clock'));
      go.addEventListener('click', () => this.ctx.seek(z.at));
      const del = el('button', 'btn ghost sm danger', null, { type: 'button' }); del.append(icon('trash'), tx('span', null, 'st.del')); del.disabled = ro;
      del.addEventListener('click', () => this.ctx.deleteSel());
      tr.append(go, del); box.append(tr);
      kids.push(box);
    } else kids.push(tx('p', 'st-hint', 'st.zoomPick'));
    kids.push(this.blockList(st.doc.zooms.map((x) => ({ u: x.u, at: x.at, label: `${t(x.kind === 'punch' ? 'st.punch' : 'st.push')} · ${x.scale.toFixed(2)}× · ${x.dur.toFixed(1)} s` })), 'zoom', 'man.noZoom'));
    this.body.replaceChildren(...kids);
  }
  zoomRoom(z) {
    const next = this.ctx.store.doc.zooms.filter((x) => x.u !== z.u && x.at >= z.at).sort((a, b) => a.at - b.at)[0];
    return Math.min(next ? next.at - z.at : Infinity, this.ctx.store.view.duration - z.at);
  }
  blockList(list, kind, emptyKey) {
    const sel = this.ctx.getSel();
    const ul = el('ul', 'st-blist');
    if (!list.length) { ul.append(tx('li', 'none', emptyKey)); return ul; }
    for (const it of list.sort((a, b) => a.at - b.at)) {
      const b = el('button', sel?.u === it.u ? 'on' : '', null, { type: 'button' });
      b.append(el('span', 'tm mono', fmtT(it.at)), el('span', 'lb', it.label));
      b.addEventListener('click', () => { this.ctx.select({ kind, u: it.u }); this.ctx.seek(it.at + 0.01); });
      const li = el('li'); li.append(b); ul.append(li);
    }
    return ul;
  }

  // ---- Đồ hoạ ----
  renderGfx() {
    const st = this.ctx.store; const sel = this.ctx.getSel(); const ro = !!st.view.readOnly;
    this.setHead('gfx', 'st.trGfx');
    const kids = [];
    const g = sel?.kind === 'gfx' && st.doc.gfx.find((x) => x.u === sel.u);
    if (g) {
      const box = el('div', 'st-card');
      const top = el('div', 'st-row');
      top.append(el('b', 'st-gtype', t('gfx.' + g.type)));
      if (g.estimate) top.append(tx('span', 'st-pill warn', 'st.estimate'));
      box.append(top);
      const times = el('div', 'st-row');
      const tnum = (f, v) => {
        const w = el('label', 'st-tbox'); w.append(icon('clock'));
        const i = el('input', 'mono', null, { type: 'number', step: '0.05', min: '0', inputmode: 'decimal', 'aria-label': t(f === 'at' ? 'st.gStart' : 'st.gEnd') });
        i.value = r2(v).toFixed(2); i.disabled = ro;
        i.addEventListener('change', () => { const x = Number(i.value); if (!Number.isFinite(x)) return; this.ctx.setGfxTime(g.u, f, x); });
        w.append(i); return w;
      };
      times.append(tnum('at', g.at), el('span', 'arrow', '→', { 'aria-hidden': 'true' }), tnum('until', g.until));
      box.append(times);
      const d = g.data || {};
      for (const k of GFX_KEYS) if (k in d && (typeof d[k] === 'string' || typeof d[k] === 'number')) box.append(this.gfxInput(g, [k], d[k], t('gf.' + k), ro));
      for (const arr of Object.keys(ROW_KEYS)) {
        if (!Array.isArray(d[arr])) continue;
        d[arr].forEach((row, i) => {
          const grp = el('fieldset', 'st-grow');
          grp.append(el('legend', null, t('gf.row', { n: i + 1 })));
          for (const f of ROW_KEYS[arr]) {
            if (!(f in row)) continue;
            if (typeof row[f] === 'boolean') {
              const w = el('label', 'st-switch sm');
              const c = el('input', null, null, { type: 'checkbox' }); c.checked = row[f]; c.disabled = ro;
              c.addEventListener('change', () => this.commit((dd) => { const y = dd.gfx.find((q) => q.u === g.u); if (y) y.data[arr][i][f] = c.checked; }));
              w.append(c, tx('span', null, 'gf.ok')); grp.append(w);
            } else grp.append(this.gfxInput(g, [arr, i, f], row[f], t('gf.' + f), ro));
          }
          box.append(grp);
        });
      }
      const del = el('button', 'btn ghost sm danger', null, { type: 'button' }); del.append(icon('trash'), tx('span', null, 'st.delGfx')); del.disabled = ro;
      del.addEventListener('click', () => this.ctx.deleteSel());
      box.append(del);
      kids.push(box);
    } else kids.push(tx('p', 'st-hint', 'st.gfxPick'));
    kids.push(this.blockList(st.doc.gfx.map((x) => ({ u: x.u, at: x.at, label: `${t('gfx.' + x.type)}${x.data?.title || x.data?.text || x.data?.label ? ' · ' + (x.data.title || x.data.text || x.data.label) : ''}` })), 'gfx', 'man.noGfx'));
    this.body.replaceChildren(...kids);
  }
  gfxInput(g, pathKeys, val, label, ro) {
    const w = el('label', 'st-field');
    w.append(el('span', null, label));
    const isNum = typeof val === 'number';
    const i = el('input', isNum ? 'mono' : null, null, { type: isNum ? 'number' : 'text', step: isNum ? 'any' : null, inputmode: isNum ? 'decimal' : null, maxlength: isNum ? null : '30' });
    i.value = String(val); i.disabled = ro;
    i.addEventListener('input', () => {
      let x = i.value; if (isNum) { x = Number(x); if (!Number.isFinite(x) || i.value === '') return; }
      this.commit((d) => {
        const y = d.gfx.find((q) => q.u === g.u); if (!y) return;
        let o = y.data; for (let k = 0; k < pathKeys.length - 1; k++) o = o[pathKeys[k]];
        o[pathKeys[pathKeys.length - 1]] = x;
      }, 'g:' + g.u + pathKeys.join('.'));
    });
    w.append(i);
    return w;
  }

  // ---- Sửa bằng lời (AI) ----
  renderAi() {
    const st = this.ctx.store; const v = this.ctx.job();
    this.setHead('ai', 'st.aiH');
    const busy = this.ctx.busy();
    const changes = st.changes;
    const form = el('form', 'st-ai');
    const ta = el('textarea', null, null, { rows: '3', maxlength: '1000', id: 'stAiText', placeholder: t('ed.revisePhS') });
    ta.dataset.i18nPlaceholder = 'ed.revisePhS';
    ta.value = this.aiDraft || '';
    ta.addEventListener('input', () => { this.aiDraft = ta.value; });
    const lab = tx('label', 'sr', 'ed.reviseLabel', { for: 'stAiText' });
    const chips = el('div', 'st-chips');
    for (const k of ['ed.p1', 'ed.p2', 'ed.p3']) {
      const c = tx('button', 'chip', k, { type: 'button' });
      c.addEventListener('click', () => { ta.value = t(k); this.aiDraft = ta.value; ta.focus(); });
      chips.append(c);
    }
    const go = el('button', 'btn pri', null, { type: 'submit' }); go.append(icon('ai'), tx('span', null, 'st.aiGo'));
    go.disabled = busy || !!st.view.readOnly || changes > 0 || v?.status !== 'done';
    form.append(lab, ta, chips, go);
    form.addEventListener('submit', (e) => { e.preventDefault(); const s = ta.value.trim(); if (s) { this.ctx.revise(s); this.aiDraft = ''; } });
    const kids = [tx('p', 'st-hint', 'st.aiHint'), form];
    if (changes > 0) kids.push(el('p', 'st-note warn', t('st.aiPending', { n: changes })));
    if (st.view.readOnly) kids.push(tx('p', 'st-note', 'st.readOnly'));
    // các lần sửa
    const revs = v?.revisions || [];
    if (revs.length) {
      kids.push(tx('h4', 'st-h4', 'ed.histH'));
      const ol = el('ol', 'st-hist');
      for (const r of [...revs].reverse()) {
        const li = el('li');
        li.append(el('b', 'mono', `r${r.n}`), ' ');
        if (r.manual) li.append(tx('span', 'st-pill', 'man.tag'), ' ', r.instruction || '');
        else li.append(`“${r.instruction || ''}”`);
        if (r.notes) li.append(el('small', null, r.notes));
        ol.append(li);
      }
      kids.push(ol);
    }
    this.body.replaceChildren(...kids);
  }
}