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.
// Timeline đáy Studio: thước giờ, đầu phát kéo được, 5 track (Video dải ảnh khung · Phụ đề · Zoom · Đồ hoạ · Nhạc sóng thật).
// Khối phụ đề/zoom/đồ hoạ: kéo thân để dời, kéo mép để đổi giờ, không đè nhau, hít vào mép khối bên cạnh + đầu phát.
// Mượt: khi kéo chỉ đổi transform/width của đúng 1 khối (rAF), thả tay mới ghi vào store (1 bước Undo) và vẽ lại track.
// Dải ảnh + sóng nhạc vẽ trên canvas "dính" (sticky) đúng bề rộng khung nhìn, vẽ lại khi cuộn/phóng.
import { el, tx, icon, iconBtn, fmtT, fmtDb, plain, clamp, t, tokens, store as ls } from './util.js';
const PAD = 14;
const ROWS = ['video', 'cap', 'zoom', 'gfx', 'music'];
const ICON = { video: 'film', cap: 'cap', zoom: 'zoom', gfx: 'gfx', music: 'music' };
const LABEL = { video: 'st.trVideo', cap: 'st.trCap', zoom: 'st.trZoom', gfx: 'st.trGfx', music: 'st.trMusic' };
const LIMIT = { cap: [0.15, 30], zoom: [0.2, 8], gfx: [1.5, 14] };
const SNAP_PX = 8;
const PPS_MIN = 12; const PPS_MAX = 400;
export class Timeline {
constructor(ctx) {
this.ctx = ctx; // {store, player, select(sel), getSel(), seek(t), flagged(u), musicLabel(), onZoomAdd()}
this.pps = 60; this.t = 0; this.focus = 'cap';
this.root = el('section', 'st-tl');
this.root.setAttribute('aria-label', t('st.timeline')); this.root.dataset.i18nAria = 'st.timeline';
// ---- thanh công cụ ----
const bar = el('div', 'tl-bar');
this.bSplit = iconBtn('cut', 'st.splitS', 'mini');
this.bMerge = iconBtn('merge', 'st.mergeNext', 'mini');
this.bDel = iconBtn('trash', 'st.delSel', 'mini');
this.bAddZ = iconBtn('plus', 'st.addZoom', 'mini');
const sep = el('span', 'sep');
const zm = el('div', 'tl-zoomer');
this.bOutZ = iconBtn('minus', 'st.zoomOut', 'mini');
this.range = el('input', null, null, { type: 'range', min: '0', max: '1000', step: '1', 'aria-label': t('st.tlZoom') });
this.range.dataset.i18nAria = 'st.tlZoom';
this.bInZ = iconBtn('plus', 'st.zoomIn', 'mini');
this.bFit = iconBtn('fit', 'st.fitAll', 'mini');
zm.append(icon('mag'), this.bOutZ, this.range, this.bInZ, this.bFit);
this.hint = el('span', 'tl-hint');
bar.append(this.bSplit, this.bMerge, this.bDel, sep, this.bAddZ, this.hint, zm);
// ---- nhãn track + vùng cuộn ----
const main = el('div', 'tl-main');
this.labs = el('div', 'tl-labs');
this.labs.append(el('div', 'lab ruler'));
this.labEls = {};
for (const k of ROWS) {
const b = el('button', 'lab', null, { type: 'button', 'data-k': k });
b.append(icon(ICON[k]), tx('span', null, LABEL[k]));
b.addEventListener('click', () => this.ctx.focusKind?.(k));
this.labEls[k] = b; this.labs.append(b);
}
this.sc = el('div', 'tl-sc');
this.inner = el('div', 'tl-in');
this.ruler = el('div', 'tl-ruler');
this.rows = {};
for (const k of ROWS) { const r = el('div', `tl-row r-${k}`, null, { 'data-k': k }); this.rows[k] = r; }
this.vCanvas = el('canvas', 'tl-cv'); this.vLayer = el('div', 'tl-vl'); this.rows.video.append(this.vCanvas, this.vLayer);
this.mCanvas = el('canvas', 'tl-cv'); this.mLabel = el('span', 'tl-mlab');
this.mBlock = el('div', 'blk mu', null, { 'data-u': 'music' }); this.mBlock.append(this.mLabel);
this.rows.music.append(this.mCanvas, this.mBlock);
this.head = el('div', 'tl-head'); this.head.append(el('i', 'knob'));
this.guide = el('div', 'tl-guide'); this.guide.hidden = true;
this.tip = el('div', 'tl-tip'); this.tip.hidden = true;
this.inner.append(this.ruler, ...ROWS.map((k) => this.rows[k]), this.head, this.guide, this.tip);
this.sc.append(this.inner);
main.append(this.labs, this.sc);
this.root.append(bar, main);
this.els = { cap: new Map(), zoom: new Map(), gfx: new Map() };
this.strip = null; this.wave = null; this.drawQ = 0;
this.bind();
this.setPps(60, true);
}
get dur() { return this.ctx.store.view?.duration || 0; }
x(tt) { return PAD + tt * this.pps; }
tAt(clientX) { const r = this.inner.getBoundingClientRect(); return (clientX - r.left - PAD) / this.pps; }
// ---- phóng to/thu nhỏ ngang ----
ppsToRange(p) { return Math.round((Math.log(p / PPS_MIN) / Math.log(PPS_MAX / PPS_MIN)) * 1000); }
rangeToPps(v) { return PPS_MIN * (PPS_MAX / PPS_MIN) ** (v / 1000); }
setPps(p, quiet, anchorX) {
const old = this.pps;
this.pps = clamp(p, PPS_MIN, PPS_MAX);
this.range.value = String(this.ppsToRange(this.pps));
const ax = anchorX ?? this.sc.clientWidth / 2;
const tAnchor = (this.sc.scrollLeft + ax - PAD) / old;
this.layout();
if (!quiet) this.sc.scrollLeft = Math.max(0, PAD + tAnchor * this.pps - ax);
this.draw();
}
/** Vừa khung: thấy toàn bộ video. */
fitAll() { const w = this.sc.clientWidth || 900; if (this.dur > 0) { this.setPps((w - PAD * 2 - 20) / this.dur, true); this.sc.scrollLeft = 0; } }
/**
* Mức phóng khi mở: mức đã dùng lần trước trên máy này (localStorage), không có thì mức để khối phụ đề trung vị hiện
* đủ 2 chữ đầu (~6,4 px/ký tự cỡ 11 px + lề 16 px). Video dài thì cuộn ngang.
*/
openDefault() {
const saved = Number(ls.get('lumreels.studio.pps'));
let p = Number.isFinite(saved) && saved >= PPS_MIN && saved <= PPS_MAX ? saved : null;
if (p == null) {
const need = (this.ctx.store.doc?.lines || []).filter((l) => l.end - l.start > 0.05).map((l) => {
const ws = tokens(l.text).slice(0, 2).map((w) => w.w).join(' ');
return ([...ws].length * 6.4 + 18) / (l.end - l.start);
}).sort((a, b) => a - b);
p = need.length ? need[Math.floor(need.length / 2)] : 60;
p = clamp(p, 40, PPS_MAX);
}
this.setPps(p, true); this.sc.scrollLeft = 0;
}
remember() { ls.set('lumreels.studio.pps', Math.round(this.pps * 10) / 10); }
// ---- vẽ toàn bộ (nạp / đổi doc / phóng) ----
layout() {
const W = Math.ceil(this.x(this.dur) + PAD + 40);
this.inner.style.width = W + 'px';
this.paintRuler();
this.renderBlocks();
this.setTime(this.t);
}
paintRuler() {
const steps = [0.5, 1, 2, 5, 10, 15, 30, 60];
const step = steps.find((s) => s * this.pps >= 64) || 60;
const minor = step >= 5 ? step / 5 : step / 2;
const kids = [];
for (let s = 0; s <= this.dur + 1e-6; s += minor) {
const major = Math.abs(s / step - Math.round(s / step)) < 1e-6;
const i = el('i', major ? 'mj' : null); i.style.transform = `translateX(${this.x(s).toFixed(1)}px)`; kids.push(i);
if (major) { const sp = el('span', 'mono', step < 1 ? fmtT(s) : `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`); sp.style.transform = `translateX(${(this.x(s) + 4).toFixed(1)}px)`; kids.push(sp); }
}
this.ruler.replaceChildren(...kids);
}
items(kind) {
const d = this.ctx.store.doc; if (!d) return [];
if (kind === 'cap') return d.lines.map((l) => ({ u: l.u, a: l.start, b: l.end, label: plain(l.text), ref: l }));
if (kind === 'zoom') return d.zooms.map((z) => ({ u: z.u, a: z.at, b: z.at + z.dur, label: `${t(z.kind === 'punch' ? 'st.punchS' : 'st.pushS')} ${z.scale.toFixed(2)}×`, ref: z }));
return d.gfx.map((g) => ({ u: g.u, a: g.at, b: g.until, label: `${t('gfx.' + g.type)}${g.data?.title || g.data?.text || g.data?.label ? ' · ' + (g.data.title || g.data.text || g.data.label) : ''}`, ref: g }));
}
renderBlocks() {
const sel = this.ctx.getSel?.();
const ro = !!this.ctx.store.view?.readOnly;
const errs = this.ctx.store.doc ? this.ctx.store.lineErrors() : new Map();
for (const kind of ['cap', 'zoom', 'gfx']) {
const map = this.els[kind]; const seen = new Set();
for (const it of this.items(kind)) {
seen.add(it.u);
let b = map.get(it.u);
if (!b) {
b = el('div', 'blk', null, { 'data-u': it.u, 'data-k': kind });
b.append(el('span', 't'));
map.set(it.u, b); this.rows[kind].append(b);
}
this.place(b, it.a, it.b);
const lab = b.firstChild; if (lab.textContent !== it.label) lab.textContent = it.label;
b.title = `${it.label} · ${fmtT(it.a)}–${fmtT(it.b)}`;
b.className = `blk ${kind}` + (sel?.kind === kind && sel.u === it.u ? ' on' : '') + (kind === 'cap' && this.ctx.flagged?.(it.u) ? ' w' : '')
+ (kind === 'cap' && errs.has(it.u) ? ' bad' : '') + (ro ? ' ro' : '');
}
for (const [u, b] of map) if (!seen.has(u)) { b.remove(); map.delete(u); }
}
this.paintVideoMarks();
// nhạc: 1 khối suốt video
const m = this.ctx.store.doc?.music;
const on = m && m.source !== 'none';
this.mBlock.hidden = !on;
if (on) {
this.place(this.mBlock, 0, this.dur);
this.mLabel.textContent = `${this.ctx.musicLabel?.() || ''} · ${fmtDb(m.gainDb)}`;
this.mBlock.classList.toggle('on', this.ctx.getSel?.()?.kind === 'music');
}
this.rows.music.classList.toggle('empty', !on);
this.rows.music.dataset.empty = on ? '' : t('st.noMusic');
this.draw();
}
place(b, a, z) {
const x = this.x(a); const w = Math.max(3, (z - a) * this.pps - 2);
b.style.transform = `translateX(${x.toFixed(1)}px)`; b.style.width = `${w.toFixed(1)}px`;
b.classList.toggle('narrow', w < 34);
}
setTime(tt) {
this.t = tt;
const x = this.x(tt);
this.head.style.transform = `translateX(${(x - 1).toFixed(1)}px)`;
// đang phát: giữ đầu phát trong khung nhìn
if (this.follow) {
const v0 = this.sc.scrollLeft; const w = this.sc.clientWidth;
if (x > v0 + w - 60 || x < v0) this.sc.scrollLeft = Math.max(0, x - 80);
}
}
setFocus(kind) {
this.focus = kind; this.root.dataset.focus = kind;
for (const k of ROWS) this.labEls[k].classList.toggle('on', k === kind);
}
setStrip(meta) {
this.strip = null;
if (!meta?.url) { this.draw(); return; }
const img = new Image(); img.decoding = 'async';
img.onload = () => { this.strip = { img, ...meta }; this.draw(); };
img.src = meta.url;
}
setWave(w) { this.wave = w || null; this.draw(); }
// ---- canvas: chỉ vẽ phần đang nhìn ----
draw() { cancelAnimationFrame(this.drawQ); this.drawQ = requestAnimationFrame(() => { this.drawVideo(); this.drawMusic(); }); }
sizeCanvas(c, h) {
const w = this.sc.clientWidth; const dpr = Math.min(2, window.devicePixelRatio || 1);
if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) { c.width = Math.round(w * dpr); c.height = Math.round(h * dpr); c.style.width = w + 'px'; c.style.height = h + 'px'; }
const g = c.getContext('2d'); g.setTransform(dpr, 0, 0, dpr, 0, 0); g.clearRect(0, 0, w, h);
return { g, w };
}
drawVideo() {
const c = this.vCanvas; const h = this.rows.video.clientHeight - 8; if (h <= 0) return;
const { g, w } = this.sizeCanvas(c, h);
const sl = this.sc.scrollLeft;
const x0 = this.x(0) - sl; const x1 = this.x(this.dur) - sl;
if (x1 < 0 || x0 > w) return;
g.save();
g.beginPath(); g.roundRect(x0, 0, x1 - x0, h, 7); g.clip();
g.fillStyle = '#26241f'; g.fillRect(x0, 0, x1 - x0, h);
const s = this.strip;
if (s) {
const tw = (h * s.tileW) / s.tileH;
const from = Math.max(x0, Math.floor((0 - x0) / tw) * tw + x0);
for (let x = from; x < Math.min(w, x1); x += tw) {
const tt = (x + tw / 2 - x0) / this.pps;
const i = clamp(Math.floor(tt / s.every), 0, s.n - 1);
g.drawImage(s.img, i * s.tileW, 0, s.tileW, s.tileH, x, 0, tw + 0.5, h);
}
}
// vết cắt
g.fillStyle = '#131210';
for (const ct of this.ctx.store.view?.cuts || []) { const x = this.x(ct) - sl; if (x > -2 && x < w + 2) g.fillRect(x - 1, 0, 2, h); }
g.restore();
g.strokeStyle = 'rgba(255,255,255,.16)'; g.lineWidth = 1.5; g.beginPath(); g.roundRect(x0 + 0.75, 0.75, x1 - x0 - 1.5, h - 1.5, 7); g.stroke();
}
drawMusic() {
const c = this.mCanvas; const h = this.rows.music.clientHeight - 8; if (h <= 0) return;
const { g, w } = this.sizeCanvas(c, h);
const m = this.ctx.store.doc?.music; const wv = this.wave;
if (!m || m.source === 'none' || !wv?.peaks?.length) return;
const sl = this.sc.scrollLeft;
const amp = clamp(10 ** ((m.gainDb + 18) / 20) * 0.85, 0.06, 1);
const mid = h / 2 + 5; const half = (h - 18) / 2;
g.fillStyle = 'rgba(93,211,158,.85)';
const x0 = Math.max(0, this.x(0) - sl); const x1 = Math.min(w, this.x(this.dur) - sl);
for (let x = Math.floor(x0); x < x1; x += 2) {
const tt = (x + sl - PAD) / this.pps;
const mt = (m.start + tt) % (wv.seconds || 1);
const p = wv.peaks[Math.min(wv.peaks.length - 1, Math.floor(mt * wv.rate))] || 0;
let k = 1; if (m.fadeOut > 0 && tt > this.dur - m.fadeOut) k = Math.max(0, (this.dur - tt) / m.fadeOut);
const y = Math.max(0.5, p * half * amp * k);
g.fillRect(x, mid - y, 1.3, y * 2);
}
}
// ---- thao tác ----
bind() {
this.sc.addEventListener('scroll', () => this.draw(), { passive: true });
new ResizeObserver(() => this.draw()).observe(this.sc);
this.range.addEventListener('input', () => { this.setPps(this.rangeToPps(Number(this.range.value))); this.remember(); });
this.bInZ.addEventListener('click', () => { this.setPps(this.pps * 1.4); this.remember(); });
this.bFit.addEventListener('click', () => this.fitAll());
this.bOutZ.addEventListener('click', () => { this.setPps(this.pps / 1.4); this.remember(); });
this.sc.addEventListener('wheel', (e) => {
if (e.ctrlKey || e.metaKey) {
e.preventDefault();
const r = this.sc.getBoundingClientRect();
this.setPps(this.pps * Math.exp(-e.deltaY * 0.0022), false, e.clientX - r.left); this.remember();
} else if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) { e.preventDefault(); this.sc.scrollLeft += e.deltaY; }
}, { passive: false });
this.bSplit.addEventListener('click', () => this.ctx.splitAtHead?.());
this.bMerge.addEventListener('click', () => this.ctx.mergeSel?.());
this.bDel.addEventListener('click', () => this.ctx.deleteSel?.());
this.bAddZ.addEventListener('click', () => this.ctx.onZoomAdd?.());
// thước + đầu phát: bấm để tua, kéo để rê
const scrub = (e) => {
e.preventDefault();
const target = e.currentTarget; target.setPointerCapture(e.pointerId);
this.ctx.player.pause();
const go = (ev) => this.ctx.seek(clamp(this.tAt(ev.clientX), 0, this.dur));
go(e);
const mv = (ev) => go(ev);
const up = () => { target.removeEventListener('pointermove', mv); target.removeEventListener('pointerup', up); target.removeEventListener('pointercancel', up); this.head.classList.remove('drag'); };
this.head.classList.add('drag');
target.addEventListener('pointermove', mv); target.addEventListener('pointerup', up); target.addEventListener('pointercancel', up);
};
this.ruler.addEventListener('pointerdown', scrub);
this.head.addEventListener('pointerdown', scrub);
this.inner.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return;
const b = e.target.closest('.blk');
if (b && b.dataset.k) return this.down(e, b);
const vc = e.target.closest('.vcut');
if (vc) { this.ctx.select({ kind: 'cut', i: Number(vc.dataset.i) }); return; }
if (e.target.closest('.r-video')) return this.videoDown(e);
if (b === this.mBlock) { this.ctx.select({ kind: 'music', u: 'music' }); return; }
const row = e.target.closest('.tl-row');
if (row) { this.ctx.player.pause(); this.ctx.seek(clamp(this.tAt(e.clientX), 0, this.dur)); this.ctx.select(null); this.ctx.focusKind?.(row.dataset.k, true); }
});
this.inner.addEventListener('dblclick', (e) => {
const b = e.target.closest('.blk.cap'); if (b) this.inlineEdit(b.dataset.u);
});
// phím trên khối đang focus: Enter sửa chữ (thay bấm đúp)
}
/** Bắt đầu kéo 1 khối: mode l (mép trái) / r (mép phải) / move (thân). */
/**
* Bắt đầu kéo 1 khối: mode l (mép trái) / r (mép phải) / move (thân).
* Cảm ứng: chạm nhanh = chọn; khối CHƯA chọn mà vuốt = cuộn timeline; khối đã chọn hoặc bấm giữ 350 ms = kéo
* (mép rộng 16 px cho ngón tay).
*/
down(e, b) {
const kind = b.dataset.k; const u = b.dataset.u;
const it = this.items(kind).find((x) => x.u === u); if (!it) return;
const ro = !!this.ctx.store.view?.readOnly;
const touch = e.pointerType === 'touch';
const r = b.getBoundingClientRect(); const off = e.clientX - r.left;
const edge = Math.min(touch ? 16 : 8, r.width / 3);
const mode = off <= edge ? 'l' : off >= r.width - edge ? 'r' : 'move';
const sorted = this.items(kind).filter((x) => x.u !== u).sort((p, q) => p.a - q.a);
const prev = sorted.filter((x) => x.b <= it.a + 1e-3).pop(); const next = sorted.find((x) => x.a >= it.b - 1e-3);
const lo = prev ? prev.b : 0; const hi = next ? next.a : this.dur;
const [minL, maxL] = LIMIT[kind];
const snaps = [this.t, ...sorted.flatMap((x) => [x.a, x.b])];
const sel = this.ctx.getSel?.();
const st = { kind, u, mode, x0: e.clientX, a0: it.a, b0: it.b, moved: false, lo, hi, minL, maxL, snaps, b, ref: it.ref,
armed: !touch || (sel?.kind === kind && sel.u === u), pan: false, sl0: this.sc.scrollLeft };
b.setPointerCapture(e.pointerId);
let raf = 0; let last = null;
const hold = touch && !st.armed ? setTimeout(() => { if (!st.moved && !st.pan) { st.armed = true; b.classList.add('armed'); this.ctx.select({ kind, u }, { quiet: true }); navigator.vibrate?.(12); } }, 350) : 0;
const mv = (ev) => {
const dx = ev.clientX - st.x0;
if (st.pan) { this.sc.scrollLeft = st.sl0 - dx; return; }
if (!st.moved) {
if (Math.abs(dx) < (touch ? 6 : 3)) return;
clearTimeout(hold);
if (!st.armed) { st.pan = true; this.sc.scrollLeft = st.sl0 - dx; return; } // vuốt khối chưa chọn: cuộn
if (ro) return;
st.moved = true; this.ctx.store.begin(); b.classList.add('drag'); this.ctx.select({ kind, u }, { quiet: true });
}
last = dx;
if (!raf) raf = requestAnimationFrame(() => { raf = 0; this.dragTo(st, last); });
};
const up = () => {
clearTimeout(hold);
b.removeEventListener('pointermove', mv); b.removeEventListener('pointerup', up); b.removeEventListener('pointercancel', up);
cancelAnimationFrame(raf); b.classList.remove('armed');
if (st.moved) { if (last != null) this.dragTo(st, last); b.classList.remove('drag'); this.guide.hidden = true; this.tip.hidden = true; this.ctx.store.end(); }
else if (!st.pan) this.ctx.select({ kind, u });
};
b.addEventListener('pointermove', mv); b.addEventListener('pointerup', up); b.addEventListener('pointercancel', up);
}
// ---- track video: tách clip (S), chọn vùng (kéo), xoá = cắt bỏ đoạn; chỗ đã cắt hiện gạch chéo, bấm để chọn (Xoá = trả lại) ----
/** Mốc chia clip: đầu/cuối, điểm tách, mép chỗ cắt. */
clipBounds() {
const d = this.ctx.store.doc;
return [...new Set([0, this.dur, ...(d?.vsplits || []), ...(d?.cuts || []).flat()].map((x) => Math.round(x * 1000) / 1000))].sort((a, b) => a - b);
}
/** Clip (giữa 2 mốc, không nằm trong chỗ cắt) chứa tt. */
clipAt(tt) {
const bs = this.clipBounds();
for (let k = 0; k + 1 < bs.length; k++) if (tt >= bs[k] && tt < bs[k + 1] && !this.ctx.store.cutAt((bs[k] + bs[k + 1]) / 2)) return [bs[k], bs[k + 1]];
return null;
}
paintVideoMarks() {
const d = this.ctx.store.doc; const sel = this.ctx.getSel?.();
const kids = [];
(d?.cuts || []).forEach(([a, b], i) => {
const c = el('div', 'vcut' + (sel?.kind === 'cut' && sel.i === i ? ' on' : ''), null, { 'data-i': String(i), title: `${fmtT(a)}–${fmtT(b)}` });
c.style.transform = `translateX(${this.x(a).toFixed(1)}px)`; c.style.width = `${Math.max(2, (b - a) * this.pps).toFixed(1)}px`;
kids.push(c);
});
for (const s of d?.vsplits || []) { const i = el('i', 'vsplit'); i.style.transform = `translateX(${(this.x(s) - 1).toFixed(1)}px)`; kids.push(i); }
if (sel?.kind === 'clip') {
const v = el('div', 'vsel'); v.style.transform = `translateX(${this.x(sel.a).toFixed(1)}px)`; v.style.width = `${Math.max(2, (sel.b - sel.a) * this.pps).toFixed(1)}px`;
kids.push(v);
}
this.vLayer.replaceChildren(...kids);
}
/** Bấm track video: tua + chọn clip chứa chỗ bấm; kéo: chọn vùng [a, b]. */
videoDown(e) {
this.ctx.player.pause();
const t0 = clamp(this.tAt(e.clientX), 0, this.dur);
const row = this.rows.video; row.setPointerCapture(e.pointerId);
let moved = false; let t1 = t0;
const mv = (ev) => {
t1 = clamp(this.tAt(ev.clientX), 0, this.dur);
if (!moved && Math.abs(ev.clientX - e.clientX) < 4) return;
moved = true;
this.ctx.select({ kind: 'clip', a: Math.min(t0, t1), b: Math.max(t0, t1) }, { quiet: true });
this.paintVideoMarks();
};
const up = () => {
row.removeEventListener('pointermove', mv); row.removeEventListener('pointerup', up); row.removeEventListener('pointercancel', up);
this.ctx.focusKind?.('video', true);
if (moved) { const a = Math.min(t0, t1); const b = Math.max(t0, t1); this.ctx.select(b - a >= 1 / 30 ? { kind: 'clip', a, b } : null); return; }
this.ctx.seek(t0);
const c = this.clipAt(t0);
this.ctx.select(c ? { kind: 'clip', a: c[0], b: c[1] } : null);
};
row.addEventListener('pointermove', mv); row.addEventListener('pointerup', up); row.addEventListener('pointercancel', up);
}
/** 1 khung kéo: tính giờ mới (kẹp + hít), ghi tạm vào doc, chỉ đổi transform/width của khối đó. */
dragTo(st, dx) {
const dt = dx / this.pps; const thr = SNAP_PX / this.pps;
let a = st.a0; let z = st.b0; let snapAt = null;
const snap = (v) => { let best = null; for (const s of st.snaps) if (Math.abs(s - v) <= thr && (best == null || Math.abs(s - v) < Math.abs(best - v))) best = s; return best; };
if (st.mode === 'move') {
const len = st.b0 - st.a0;
a = st.a0 + dt;
const sa = snap(a); const sb = snap(a + len);
if (sa != null && (sb == null || Math.abs(sa - a) <= Math.abs(sb - a - len))) { a = sa; snapAt = sa; } else if (sb != null) { a = sb - len; snapAt = sb; }
a = clamp(a, st.lo, Math.max(st.lo, st.hi - len)); z = a + len;
} else if (st.mode === 'l') {
a = st.a0 + dt; const s = snap(a); if (s != null) { a = s; snapAt = s; }
a = clamp(a, Math.max(st.lo, st.b0 - st.maxL), st.b0 - st.minL);
} else {
z = st.b0 + dt; const s = snap(z); if (s != null) { z = s; snapAt = s; }
z = clamp(z, st.a0 + st.minL, Math.min(st.hi, st.a0 + st.maxL));
}
a = Math.round(a * 100) / 100; z = Math.round(z * 100) / 100;
// ghi tạm vào doc (store.begin đã chụp bản trước)
const r = st.ref;
if (st.kind === 'cap') { r.start = a; r.end = z; } else if (st.kind === 'zoom') { r.at = a; r.dur = Math.round((z - a) * 100) / 100; } else { r.at = a; r.until = z; }
this.place(st.b, a, z);
this.guide.hidden = snapAt == null || (Math.abs(snapAt - a) > 1e-3 && Math.abs(snapAt - z) > 1e-3);
if (!this.guide.hidden) this.guide.style.transform = `translateX(${this.x(snapAt).toFixed(1)}px)`;
this.tip.hidden = false;
this.tip.textContent = st.mode === 'l' ? fmtT(a) : st.mode === 'r' ? fmtT(z) : `${fmtT(a)} – ${fmtT(z)}`;
this.tip.style.transform = `translate(${this.x(st.mode === 'r' ? z : a).toFixed(1)}px, ${st.b.parentElement.offsetTop + st.b.offsetTop - 24}px)`;
this.ctx.onDrag?.(st.kind, st.u);
}
/** Bấm đúp khối phụ đề: ô sửa chữ ngay trên khối (Enter lưu, Esc huỷ). */
inlineEdit(u) {
if (this.ctx.store.view?.readOnly) return;
const b = this.els.cap.get(u); const l = this.ctx.store.doc.lines.find((x) => x.u === u); if (!b || !l) return;
this.ctx.select({ kind: 'cap', u }, { quiet: true });
const inp = el('input', 'tl-edit', null, { type: 'text', maxlength: '200', spellcheck: 'false', 'aria-label': t('st.lineText') });
inp.value = l.text;
const x = this.x(l.start);
inp.style.transform = `translate(${x.toFixed(1)}px, ${b.offsetTop + this.rows.cap.offsetTop - 2}px)`;
inp.style.width = `${Math.max((l.end - l.start) * this.pps, 200)}px`;
this.inner.append(inp); inp.focus(); inp.select();
let done = false;
const finish = (save) => {
if (done) return; done = true;
const v = inp.value.trim(); inp.remove();
if (save && v && v !== l.text) this.ctx.store.commit((d) => { const x2 = d.lines.find((y) => y.u === u); if (x2) x2.text = v; });
this.ctx.afterInline?.();
};
inp.addEventListener('keydown', (e) => { e.stopPropagation(); if (e.key === 'Enter') finish(true); else if (e.key === 'Escape') finish(false); });
inp.addEventListener('blur', () => finish(true));
}
scrollToTime(tt) {
const x = this.x(tt); const v0 = this.sc.scrollLeft; const w = this.sc.clientWidth;
if (x < v0 + 40 || x > v0 + w - 40) this.sc.scrollLeft = Math.max(0, x - w / 3);
}
}