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.
// UI 1 trang: lưới mẫu, ô nội dung, danh sách job. Không framework. Chữ giao diện lấy từ i18n.js (window.I18N).
(() => {
const $ = (s, el = document) => el.querySelector(s);
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const I = window.I18N;
const t = (k, v) => I.t(k, v);
const status = (s) => (['scheduled', 'queued', 'generating', 'waiting_agent', 'previewing', 'rendering', 'done', 'error'].includes(s) ? t('st.' + s) : s);
const RUNNING = ['queued', 'generating', 'previewing', 'rendering'];
const CATS = ['faceless', 'ads', 'multi-style', 'viet-nam'];
const catName = (c) => (CATS.includes(c) ? t('cat.' + c) : c);
// Nhãn nguồn của mẫu (L13): gốc / của tôi (tự tạo) / cộng đồng (gói nhập). Chữ của gói chỉ vào textContent (L9).
const SOURCES = ['builtin', 'local', 'pack'];
const srcOf = (x) => (SOURCES.includes(x?.source) ? x.source : 'builtin');
const srcLabel = (x) => t('src.' + srcOf(x));
/** Tạo phần tử: props {class, text, attrs:{}, data:{}}; con là phần tử hoặc chuỗi (thành nút chữ). */
function h(tag, props = {}, ...kids) {
const el = document.createElement(tag);
if (props.class) el.className = props.class;
if (props.text != null) el.textContent = props.text;
for (const [k, v] of Object.entries(props.attrs || {})) if (v != null && v !== false) el.setAttribute(k, v === true ? '' : String(v));
for (const [k, v] of Object.entries(props.data || {})) el.dataset[k] = String(v);
for (const c of kids.flat()) if (c != null && c !== false) el.append(c instanceof Node ? c : document.createTextNode(String(c)));
return el;
}
const srcBadge = (x) => h('span', { class: 'src src-' + srcOf(x), text: srcLabel(x) });
const modeLabel = (m) => ({ auto: t('modeLabel.auto'), api: 'Claude API', claude: 'Claude Code', manual: t('modeLabel.manual') }[m]);
const fmtTime = (iso) => new Date(iso).toLocaleString(I.locale, { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit', year: 'numeric' });
// datetime-local trả giờ máy không múi giờ → đổi sang ISO có múi giờ để server hiểu đúng.
const runAtValue = () => { const v = $('#runAt').value; return v ? new Date(v).toISOString() : undefined; };
// Thời lượng: số giây (90, 90s) hoặc phút:giây (1:30). Cùng luật với generator/jobs.mjs parseDuration.
const DUR_MIN = 3, DUR_MAX = 600;
function parseDur(v) {
const s0 = String(v ?? '').trim().toLowerCase().replace(/\s+/g, '');
if (!s0) return { error: t('dur.errEmpty') };
let m, s;
if ((m = /^(\d{1,4})(?:s|giây|giay)?$/.exec(s0))) s = Number(m[1]);
else if ((m = /^(\d{1,2}):([0-5]\d)$/.exec(s0))) s = Number(m[1]) * 60 + Number(m[2]);
else if ((m = /^(\d{1,2})(?:m|p|phút|phut)$/.exec(s0))) s = Number(m[1]) * 60;
else return { error: t('dur.errFmt') };
if (s < DUR_MIN) return { error: t('dur.errMin') };
if (s > DUR_MAX) return { error: t('dur.errMax') };
return { s };
}
const fmtDur = (s) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);
// Khoảng thời gian ước tính: "40–120 giây", "4–11 phút", "2–5 giờ"… (đơn vị theo đầu trên)
const dec = (x) => x.toFixed(1).replace('.', t('num.dec'));
const fmtRange = (a, b) => (b < 120 ? `${Math.round(a)}–${Math.round(b)} ${t('unit.sec')}`
: b < 7200 ? `${Math.max(1, Math.round(a / 60))}–${Math.round(b / 60)} ${t('unit.min')}` : `${dec(a / 3600)}–${dec(b / 3600)} ${t('unit.hour')}`);
const durS = () => parseDur($('#duration').value).s;
// Tỉ lệ khung: 9:16 (mặc định) · 16:9 · 4:3 · 3:4 — cùng bảng với engine/ratio.mjs
const RATIO_DIMS = { '9:16': [1080, 1920], '16:9': [1920, 1080], '4:3': [1440, 1080], '3:4': [1080, 1440] };
let ratio = '9:16';
try { const r = localStorage.getItem('lumreels.ratio'); if (RATIO_DIMS[r]) ratio = r; } catch { /* bỏ qua */ }
function setRatio(r, focus) {
if (!RATIO_DIMS[r]) return;
ratio = r;
try { localStorage.setItem('lumreels.ratio', r); } catch { /* bỏ qua */ }
document.querySelectorAll('.ratio[data-ratio]').forEach((b) => { const on = b.dataset.ratio === r; b.classList.toggle('on', on); b.setAttribute('aria-checked', String(on)); b.tabIndex = on ? 0 : -1; if (on && focus) b.focus(); });
paintRatio();
}
function paintRatio() {
const [w, h] = RATIO_DIMS[ratio];
$('#ratioSize').textContent = `${w}×${h}`;
$('#ratioHint').textContent = t('ratio.hint.' + ratio.replace(':', 'x'));
}
document.querySelectorAll('.ratio[data-ratio]').forEach((b) => b.addEventListener('click', () => setRatio(b.dataset.ratio)));
document.querySelector('.ratios').addEventListener('keydown', (e) => {
const keys = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };
if (!(e.key in keys)) return;
e.preventDefault();
const ids = Object.keys(RATIO_DIMS); const i = ids.indexOf(ratio);
setRatio(ids[(i + keys[e.key] + ids.length) % ids.length], true);
});
let templates = [];
let templatesState = 'loading'; // loading | ok | error
// Mẫu đang chọn (theo thứ tự bấm). Chế độ thường: tối đa 1. "Chọn nhiều mẫu": tối đa MAX_PICK, mỗi mẫu 1 job.
const MAX_PICK = 12;
let picks = [];
let multi = false;
const one = () => (picks.length === 1 ? picks[0] : null);
const pickIndex = (id) => picks.findIndex((x) => x.id === id);
let cat = '';
let srcFilter = ''; // '' | 'local' | 'pack' (chip "Của tôi" / "Cộng đồng")
let pollTimer = null;
const JOB_PAGE = 6;
let showAll = false;
let allJobsCount = 0;
// ---------- bản mới ----------
let update = null;
function renderUpdate() {
const box = $('#update-banner');
const u = update;
if (!box || !u) return;
const tx = box.querySelector('.ub-text');
tx.textContent = '';
// u.changes[0] là tiêu đề commit (dữ liệu git), giữ nguyên
tx.append(t('update.text', { n: u.behind, first: u.changes && u.changes[0] ? u.changes[0] : '' }));
const c = document.createElement('code'); c.textContent = 'npm start';
tx.append(c, t('update.after'));
}
async function checkVersion(retry = 3) {
let d;
try { d = await (await fetch('/api/version')).json(); } catch { return; }
const u = d && d.update;
if (!u) { if (retry > 0) setTimeout(() => checkVersion(retry - 1), 8000); return; }
const box = $('#update-banner');
if (!box || !u.ok || !u.behind) return;
const key = 'lumreels-hide-update-' + (u.upstream || '') + '-' + u.behind;
try { if (localStorage.getItem(key)) return; } catch { /* bỏ qua */ }
update = u;
renderUpdate();
box.hidden = false;
box.querySelector('.ub-close').onclick = () => { box.hidden = true; try { localStorage.setItem(key, '1'); } catch { /* bỏ qua */ } };
}
setTimeout(checkVersion, 1500);
// ---------- mẫu ----------
async function loadTemplates() {
templatesState = 'loading'; renderGrid();
try {
templates = await (await fetch('/api/templates')).json();
templatesState = 'ok';
} catch {
templatesState = 'error';
}
renderGrid();
}
// Mã hiện trên thẻ: mẫu gốc "045"; mẫu gói chỉ hiện slug (mã đầy đủ nằm trong aria-label / title).
const shortId = (x) => (srcOf(x) === 'builtin' ? x.id : String(x.id).split('/').pop());
const PLAY_SVG = 'M8 5v14l11-7z';
function playIcon() {
const ns = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(ns, 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');
const path = document.createElementNS(ns, 'path'); path.setAttribute('d', PLAY_SVG); svg.append(path);
return svg;
}
function tplCard(x) {
const k = pickIndex(x.id);
const card = h('div', {
class: `tpl${x.hasGuidance ? '' : ' off'}${k >= 0 ? ' sel' : ''}`, data: { id: x.id },
attrs: { role: 'button', tabindex: 0, 'aria-disabled': String(!x.hasGuidance), 'aria-pressed': String(k >= 0),
'aria-label': t('tpl.aria', { id: x.id, name: x.name, ready: x.hasGuidance, order: multi && k >= 0 ? k + 1 : 0 }) + ' · ' + srcLabel(x) },
});
if (multi && k >= 0) card.append(h('span', { class: 'order', text: k + 1, attrs: { 'aria-hidden': 'true' } }));
// x.thumb do server ghép từ id/slug đã kiểm (/thumbs/045.webp, /pack-thumbs/<gói>/template-<slug>.webp, /poster/…)
card.append(x.thumb ? h('img', { class: 'thumb', attrs: { src: x.thumb, alt: '', loading: 'lazy', decoding: 'async', width: 540, height: 960 } })
: h('div', { class: 'thumb ph', text: t('tpl.noThumb') }));
card.append(h('span', { class: 'badge' + (x.hasGuidance ? ' ready' : ''), text: t(x.hasGuidance ? 'tpl.ready' : 'tpl.noGuide') }));
if (x.video) {
const b = h('button', { class: 'play', data: { play: x.id }, attrs: { type: 'button', 'aria-label': t(x.videoKind === 'demo' ? 'tpl.playDemo' : 'tpl.playRef', { id: x.id }) } });
b.append(playIcon());
card.append(b);
}
card.append(h('div', { class: 'meta' },
h('div', { class: 'id' }, srcBadge(x), h('span', { text: `${shortId(x)} · ${catName(x.category)}` })),
h('div', { class: 't', text: x.name })));
if (srcOf(x) !== 'builtin') card.title = x.id;
return card;
}
function renderGrid() {
const grid = $('#grid');
if (templatesState !== 'ok') {
grid.replaceChildren(h('div', { class: 'empty-grid', text: t(templatesState === 'error' ? 'grid.loadErr' : 'grid.loading') }));
return;
}
const q = $('#q').value.trim().toLowerCase();
const readyOnly = $('#readyOnly').checked;
const list = templates.filter((x) => (!cat || x.category === cat) && (!srcFilter || srcOf(x) === srcFilter) && (!readyOnly || x.hasGuidance) &&
(!q || `${x.name} ${x.genre} ${x.blurb}`.toLowerCase().includes(q) || String(x.id).includes(q)));
const ready = templates.filter((x) => x.hasGuidance).length;
$('#tplCount').textContent = t('pick.count', { ready, total: templates.length });
if (!list.length) {
const empty = h('div', { class: 'empty-grid', text: t(srcFilter && !q ? 'grid.emptySrc.' + srcFilter : 'grid.empty') });
if (srcFilter && !q) empty.append(' ', h('button', { class: 'linkish', text: t('pack.importBtn'), data: { packImport: 1 }, attrs: { type: 'button' } }));
grid.replaceChildren(empty);
return;
}
const focusId = document.activeElement?.closest?.('#grid .tpl')?.dataset.id;
grid.classList.toggle('multi', multi);
grid.replaceChildren(...list.map(tplCard));
if (focusId) [...grid.querySelectorAll('.tpl')].find((el) => el.dataset.id === focusId)?.focus({ preventScroll: true });
}
// Báo nhẹ (tự ẩn), vd chọn quá 12 mẫu.
let noteTimer = null;
function note(msg) {
const el = $('#pickNote');
el.textContent = msg;
clearTimeout(noteTimer);
if (msg) noteTimer = setTimeout(() => { el.textContent = ''; }, 4000);
}
function pick(id) {
const x = templates.find((y) => y.id === id);
if (!x || !x.hasGuidance) return;
if (!multi) picks = [x];
else {
const k = pickIndex(id);
if (k >= 0) picks.splice(k, 1);
else if (picks.length >= MAX_PICK) { note(t('pick.max', { max: MAX_PICK })); return; }
else picks.push(x);
}
note('');
picksChanged();
}
function unpick(id) { const k = pickIndex(id); if (k >= 0) { picks.splice(k, 1); picksChanged(); } }
function setMulti(on) {
multi = on;
$('#multiPick').checked = on;
if (!on) picks = picks.slice(0, 1); // tắt: quay về chọn 1, giữ mẫu đầu tiên
note('');
picksChanged();
}
function picksChanged() {
renderGrid();
renderPicked();
window.dispatchEvent(new Event('lumreels:picked'));
updateWhen();
updateGo();
}
function renderPicked() {
const box = $('#picked');
if (!picks.length) {
box.className = 'picked empty';
box.textContent = multi ? t('picked.noneMulti', { max: MAX_PICK }) : t('picked.none');
return;
}
if (!multi) {
const x = picks[0];
box.className = 'picked';
const info = h('div', {}, h('div', { class: 't' }, srcBadge(x), ` ${shortId(x)} · ${x.name}`), h('div', { class: 'd', text: x.blurb || x.genre || '' }));
if (srcOf(x) !== 'builtin') info.append(h('div', { class: 'd lock', text: t('pack.lockedNote') }));
box.replaceChildren(...(x.thumb ? [h('img', { attrs: { src: x.thumb, alt: '' } })] : []), info);
return;
}
box.className = 'picked multi';
const strip = h('ul', { class: 'strip', attrs: { 'aria-label': t('picked.strip') } }, picks.map((x, i) => h('li', { class: 'pk', attrs: { title: `${x.id} · ${x.name}` } },
x.thumb ? h('img', { attrs: { src: x.thumb, alt: '' } }) : h('span', { class: 'ph' }),
h('span', { class: 'n', text: i + 1, attrs: { 'aria-hidden': 'true' } }),
h('button', { class: 'rm', text: '×', data: { unpick: x.id }, attrs: { type: 'button', 'aria-label': t('picked.remove', { id: x.id, name: x.name }) } }))));
box.replaceChildren(
h('div', { class: 'pm-head' }, h('span', { class: 't', text: t('picked.count', { n: picks.length }) }),
h('button', { class: 'mini', text: t('picked.clear'), data: { clear: 1 }, attrs: { type: 'button' } })),
strip);
}
let viewing = null;
function viewerDesc(x) {
return (x.videoKind === 'demo' ? t('viewer.demo') : x.videoKind === 'ref' ? t('viewer.ref') : '') + (x.blurb || '');
}
function openViewer(id) {
const x = templates.find((y) => y.id === id);
if (!x) return;
viewing = x;
$('#vTitle').textContent = `${x.id} · ${x.name}`;
$('#vDesc').textContent = viewerDesc(x);
const v = $('#vVideo');
v.hidden = !x.video;
if (x.video) { v.src = x.video; v.play().catch(() => {}); }
$('#viewer').showModal();
}
function closeViewer() { const v = $('#vVideo'); v.pause(); v.removeAttribute('src'); v.load(); $('#viewer').close(); viewing = null; }
// ---------- form ----------
function updateGo() {
const n = $('#content').value.length;
$('#chars').textContent = n;
const enough = $('#content').value.trim().length >= 10;
const dur = !!durS();
const ok = picks.length > 0 && enough && dur;
$('#go').disabled = !ok;
$('#go').title = !picks.length ? t('go.needTpl') : !enough ? t('go.needText') : !dur ? t('go.badDur') : '';
const rw = $('#rewrite');
const many = picks.length > 1;
rw.disabled = !ok || many || rwBusy;
rw.title = rwBusy ? t('rw.busy') : !picks.length ? t('rw.needOne') : many ? t('rw.onlyOne') : !enough ? t('rw.needText') : !dur ? t('go.badDur') : '';
rw.querySelector('span').textContent = t(rwBusy ? 'rw.btnBusy' : 'rw.btn');
const hint = $('#rwHint');
hint.classList.toggle('bad', many);
hint.textContent = many ? t('rw.hintMany', { n: picks.length }) : t('rw.hint');
}
// ---------- thời lượng ----------
function updateDur() {
const r = parseDur($('#duration').value);
$('#duration').setAttribute('aria-invalid', r.error ? 'true' : 'false');
document.querySelectorAll('.pre').forEach((b) => b.classList.toggle('on', Number(b.dataset.dur) === r.s));
const hint = $('#durHint');
hint.classList.toggle('bad', !!r.error);
hint.textContent = r.error ? r.error + '.' : r.s >= 60 ? t('dur.eqLong', { s: r.s, f: fmtDur(r.s) }) : t('dur.eq', { s: r.s });
const warn = $('#durWarn');
if (r.s > 60) {
warn.hidden = false;
warn.textContent = t('dur.warn', { f: fmtDur(r.s), range: fmtRange(r.s / 8 * 20, r.s / 8 * 60), scenes: Math.round(r.s / 8) });
} else warn.hidden = true;
updateGo();
}
// ---------- viết lại kịch bản ----------
let rwBusy = false;
let rwResult = null; // bản AI vừa viết, chưa dùng
let rwUndo = null; // nội dung trước khi bấm "Dùng bản này"
let rwView = null; // hàm vẽ lại ô kết quả (đổi ngôn ngữ thì gọi lại)
function rwShow(cls, html) { const b = $('#rwBox'); b.className = 'rw ' + cls; b.innerHTML = html; b.hidden = !html; }
function rwSet(fn) { rwView = fn; if (fn) fn(); else rwShow('', ''); }
async function rewrite() {
const selected = one();
if (rwBusy || !selected) return;
const dur = durS();
rwBusy = true; rwResult = null;
const btn = $('#rewrite');
btn.classList.add('busy');
updateGo();
rwSet(() => rwShow('load', esc(t('rw.loading', { id: selected.id, d: fmtDur(dur) }))));
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), 100_000);
try {
const r = await fetch('/api/rewrite', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: ctl.signal,
body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: dur }),
});
const j = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(j.error || t('err.status', { s: r.status }));
rwResult = j;
const eng = j.engine === 'api' ? 'Claude API' : 'Claude Code';
const cost = j.usage?.costUSD != null ? ` · ≈ $${Number(j.usage.costUSD).toFixed(3)}` : '';
rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.title', { id: j.templateId, d: fmtDur(j.durationS) }))}</span><span class="eng">${eng}${cost}</span></div>
<pre id="rwScript">${esc(j.script)}</pre>
${j.notes ? `<div class="rw-n">${esc(j.notes)}</div>` : ''}
${j.fallbackFrom ? `<div class="rw-n">${esc(t('rw.fallback', { why: j.fallbackFrom }))}</div>` : ''}
<div class="rw-a"><button type="button" class="use" data-rw="use">${esc(t('rw.use'))}</button><button type="button" data-rw="drop">${esc(t('rw.drop'))}</button></div>`));
} catch (e) {
const msg = e.name === 'AbortError' ? null : e.message;
rwSet(() => rwShow('err-box', esc(msg ?? t('rw.timeout'))));
} finally {
clearTimeout(timer);
rwBusy = false;
btn.classList.remove('busy');
updateGo();
}
}
$('#rwBox').addEventListener('click', (e) => {
const a = e.target.closest('[data-rw]')?.dataset.rw;
if (!a) return;
if (a === 'use' && rwResult) {
rwUndo = $('#content').value;
$('#content').value = rwResult.script.slice(0, 4000);
rwResult = null;
rwSet(() => rwShow('', `<div class="rw-h"><span>${esc(t('rw.replaced'))}</span></div><div class="rw-a"><button type="button" data-rw="undo">${esc(t('rw.undo'))}</button><button type="button" data-rw="close">${esc(t('rw.close'))}</button></div>`));
} else if (a === 'undo' && rwUndo !== null) {
$('#content').value = rwUndo; rwUndo = null;
rwSet(null);
} else { rwResult = null; rwSet(null); }
updateGo();
});
async function submit() {
$('#formErr').textContent = '';
const btn = $('#go');
if (!picks.length) return;
btn.disabled = true; btn.classList.add('busy'); btn.querySelector('span').textContent = t('go.sending');
const batch = picks.length > 1;
const common = { content: $('#content').value, durationS: durS(), aspect: ratio, mode: $('#mode').value, model: $('#model').value, runAt: runAtValue(), audio: window.LumAudio?.value() };
try {
const r = await fetch(batch ? '/api/jobs/batch' : '/api/jobs', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch ? { templateIds: picks.map((x) => x.id), ...common } : { templateId: picks[0].id, ...common }),
});
const j = await r.json();
if (!r.ok) throw new Error(j.error || t('form.jobErr'));
const created = batch ? j.jobs : [j];
if (created.length > JOB_PAGE) showAll = true; // cả lô đều hiện trong danh sách
await loadJobs();
document.getElementById('job-' + created[0].id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
} catch (e) {
$('#formErr').textContent = e.message + t('form.retry');
} finally {
btn.classList.remove('busy'); updateWhen(); updateGo();
}
}
// ---------- jobs ----------
async function loadJobs() {
let jobs = [];
try { jobs = await (await fetch('/api/jobs')).json(); } catch { return; }
// log chi tiết cho job đang chạy
allJobsCount = jobs.length;
const detailed = await Promise.all(jobs.slice(0, showAll ? 60 : JOB_PAGE).map(async (j) =>
(RUNNING.includes(j.status) || j.status === 'error' || j.status === 'waiting_agent')
? (await fetch('/api/jobs/' + j.id)).json().catch(() => j) : j));
renderJobs(detailed);
clearTimeout(pollTimer);
if (jobs.some((j) => RUNNING.includes(j.status))) pollTimer = setTimeout(loadJobs, 2000);
else if (jobs.some((j) => j.status === 'scheduled')) pollTimer = setTimeout(loadJobs, 10000);
}
function renderJobs(jobs) {
const box = $('#jobs');
if (!jobs.length) {
box.innerHTML = `<div class="no-jobs">${t('jobs.empty')}</div>`;
return;
}
// giữ video đang phát, không vẽ lại job không đổi (chữ ký có ngôn ngữ: đổi VI/EN thì vẽ lại chữ)
const prev = new Map([...box.querySelectorAll('.job')].map((el) => [el.id, el.dataset.sig]));
const rows = jobs.map((j) => {
const sig = `${j.status}|${j.updatedAt}|${I.lang}`;
if (prev.get('job-' + j.id) === sig && j.status === 'done') return null;
return { id: j.id, sig, html: jobHtml(j) };
});
const frag = [];
jobs.forEach((j, i) => {
const h = rows[i];
if (!h) frag.push(document.getElementById('job-' + j.id));
else {
const d = document.createElement('div'); d.innerHTML = h.html.trim(); const el = d.firstChild; el.dataset.sig = h.sig;
// tên mẫu có thể là chữ của gói (L9): chỉ textContent
const tt = el.querySelector('.tt'); if (tt) tt.textContent = t('job.tpl', { id: j.templateId, name: j.templateTitle || '' }) + (j.templateSource && j.templateSource !== 'builtin' ? ' · ' + t('src.' + (j.templateSource === 'local' ? 'local' : 'pack')) : '');
frag.push(el);
}
});
if (allJobsCount > frag.length) {
const more = document.createElement('button');
more.className = 'more'; more.type = 'button'; more.dataset.sig = 'more';
more.textContent = showAll ? t('jobs.less') : t('jobs.more', { n: allJobsCount - frag.length });
more.addEventListener('click', () => { showAll = !showAll; loadJobs(); });
frag.push(more);
} else if (showAll && allJobsCount > JOB_PAGE) {
const less = document.createElement('button'); less.className = 'more'; less.type = 'button'; less.textContent = t('jobs.less');
less.addEventListener('click', () => { showAll = false; loadJobs(); }); frag.push(less);
}
box.replaceChildren(...frag);
}
function jobHtml(j) {
const running = RUNNING.includes(j.status);
const media = j.links?.mp4
? `<video src="${j.links.mp4}" controls playsinline preload="metadata"></video>`
: j.links?.preview ? `<img src="${j.links.preview}?v=${encodeURIComponent(j.updatedAt)}" alt="${esc(t('job.previewAlt'))}">`
: `<span>${esc(t(running ? 'job.building' : j.status === 'waiting_agent' ? 'job.waitScene' : 'job.noImage'))}</span>`;
const last = (j.log || []).slice(-1)[0] || '';
const out = j.output ? `${j.output.width}×${j.output.height} · ${j.output.fps} · ${Number(j.output.duration).toFixed(1)}s` : '';
const ar = RATIO_DIMS[j.aspect] ? j.aspect : '9:16';
return `<article class="job${ar !== '9:16' ? ' wide-' + ar.replace(':', 'x') : ''}" id="job-${j.id}">
<div class="media" style="aspect-ratio:${ar.replace(':', ' / ')}">${media}</div>
<div>
<div class="head"><span class="st ${j.status} ${running ? 'run' : ''}">${esc(status(j.status))}</span>
<span class="tt"></span></div>
<div class="jid">${j.id} · ${fmtDur(j.durationS)} · ${ar} · ${esc(modeLabel(j.engine || j.mode) || j.mode)}${j.model && j.model.alias && (j.engine || j.mode) !== 'manual' ? ' · ' + esc(j.model.alias) : ''} ${out ? '· ' + out : ''}</div>
${j.status === 'scheduled' ? `<div class="cost">${esc(t('job.at', { t: fmtTime(j.runAt) }))}</div>` : ''}
${j.usage ? `<div class="cost">${esc(t('job.api', { i: (j.usage.inputTokens / 1000).toFixed(1), o: (j.usage.outputTokens / 1000).toFixed(1), c: j.usage.costUSD.toFixed(3) }))}</div>` : ''}
${j.output?.exported ? `<div class="cost">${esc(t('job.exported', { p: j.output.exported }))}</div>` : ''}
<div class="content">${esc(j.content)}</div>
${running && last ? `<div class="jid">${esc(last)}</div>` : ''}
${j.status === 'error' ? `<div class="errmsg">${esc(j.error || t('job.errUnknown'))}${esc(t('job.errTail'))}</div>` : ''}
${j.status === 'waiting_agent' ? `<div class="cmd">${esc(t('job.agent', { prompt: j.paths?.prompt, scene: j.paths?.scene, id: j.id }))}</div>` : ''}
<div class="links">
${j.links?.mp4 ? `<a href="${j.links.mp4}" download>${esc(t('job.mp4'))}</a>` : ''}
${j.links?.preview ? `<a href="${j.links.preview}" target="_blank" rel="noopener">${esc(t('job.preview'))}</a>` : ''}
<a href="${j.links?.prompt}" target="_blank" rel="noopener">Prompt</a>
${j.links?.brief ? `<a href="${j.links.brief}" target="_blank" rel="noopener">Brief</a>` : ''}
${j.status === 'done' && j.links?.mp4 ? `<button type="button" class="to-studio" data-studio="${j.id}">${esc(t('job.studio'))}</button>` : ''}
${['waiting_agent', 'error', 'done'].includes(j.status) ? `<button data-render="${j.id}">${esc(t(j.status === 'done' ? 'job.rerender' : 'job.render'))}</button>` : ''}
<button type="button" class="log-btn${j.status === 'error' ? ' bad' : ''}" data-log-kind="job" data-log-id="${j.id}">${esc(t(j.status === 'error' ? 'log.btnErr' : 'log.btn'))}</button>
</div>
${running && j.log?.length ? `<details class="log"><summary>${esc(t('job.log', { n: j.log.length }))}</summary><pre>${esc(j.log.join('\n'))}</pre></details>` : ''}
</div>
</article>`;
}
async function rerender(id) {
await fetch(`/api/jobs/${id}/render`, { method: 'POST' });
loadJobs();
}
// ---------- sự kiện ----------
$('#grid').addEventListener('click', (e) => {
const play = e.target.closest('[data-play]');
if (play) { e.stopPropagation(); openViewer(play.dataset.play); return; }
const card = e.target.closest('.tpl');
if (card) pick(card.dataset.id);
});
$('#grid').addEventListener('keydown', (e) => {
if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('tpl')) { e.preventDefault(); pick(e.target.dataset.id); }
});
$('#multiPick').addEventListener('change', (e) => setMulti(e.target.checked));
$('#picked').addEventListener('click', (e) => {
const rm = e.target.closest('[data-unpick]');
if (rm) { unpick(rm.dataset.unpick); ($('#picked [data-unpick]') || $('#multiPick')).focus(); return; }
if (e.target.closest('[data-clear]')) { picks = []; picksChanged(); $('#multiPick').focus(); }
});
$('#q').addEventListener('input', renderGrid);
$('#readyOnly').addEventListener('change', renderGrid);
function setChip(c) {
cat = c.dataset.cat || '';
srcFilter = c.dataset.src || '';
document.querySelectorAll('.filters .chip').forEach((x) => { x.classList.toggle('on', x === c); x.setAttribute('aria-checked', x === c); });
renderGrid();
}
document.querySelectorAll('.filters .chip').forEach((c) => c.addEventListener('click', () => setChip(c)));
// packs-panel.js: cài/gỡ gói xong → tải lại lưới; "Xem trong lưới" → bật chip nguồn
window.addEventListener('lumreels:packs', (e) => {
const show = e.detail?.show;
if (show) { const c = document.querySelector(`.filters .chip[data-src="${show === 'local' ? 'local' : 'pack'}"]`); if (c) setChip(c); }
const removed = e.detail?.removed;
if (removed) { picks = picks.filter((x) => !String(x.id).startsWith(removed + '/')); picksChanged(); }
loadTemplates();
});
$('#content').addEventListener('input', updateGo);
$('#rewrite').addEventListener('click', rewrite);
$('#duration').addEventListener('input', updateDur);
document.querySelectorAll('.pre').forEach((b) => b.addEventListener('click', () => { $('#duration').value = b.dataset.dur; updateDur(); }));
$('#go').addEventListener('click', submit);
$('#vClose').addEventListener('click', closeViewer);
$('#viewer').addEventListener('cancel', (e) => { e.preventDefault(); closeViewer(); });
$('#jobs').addEventListener('click', (e) => { const b = e.target.closest('[data-render]'); if (b) { b.disabled = true; rerender(b.dataset.render); } });
function updateWhen() {
const v = $('#runAt').value;
const btn = $('#go').querySelector('span');
if (!btn.closest('.busy')) btn.textContent = t(v ? 'go.schedule' : 'go.build', { n: picks.length });
$('#clearAt').hidden = !v;
}
$('#runAt').addEventListener('input', updateWhen);
$('#clearAt').addEventListener('click', () => { $('#runAt').value = ''; updateWhen(); });
updateWhen();
let cfg = {};
const modeHint = () => {
const m = $('#mode').value;
$('#modeHint').textContent = {
auto: t('mode.hintAuto', { m: modeLabel(cfg.autoResolves) || '…' }),
api: t('mode.hintApi'),
claude: t('mode.hintClaude'),
manual: t('mode.hintManual'),
}[m] + (cfg.outputDir ? t('mode.hintExport') : '');
};
$('#mode').addEventListener('change', modeHint);
// Model: tự chọn = Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D (rẻ hơn, đủ tốt cho DOM/SVG/Canvas)
const MODEL_NAME = { opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku' };
const heavy = (x) => (x?.technique || []).some((y) => /three|webgl|shader/i.test(y));
function modelHint() {
if (picks.length > 1) return modelHintMany();
const selected = one();
const m = $('#model').value;
const rec = selected ? (heavy(selected) ? 'opus' : 'sonnet') : null;
const recTxt = rec ? t('model.rec', { heavy: heavy(selected), m: MODEL_NAME[rec] }) : t('model.pickFirst');
const opt = $('#model').querySelector('[value=auto]');
opt.textContent = rec ? t('model.autoRec', { m: MODEL_NAME[rec] }) : t('model.auto');
const warn = m === 'haiku' && rec === 'opus' ? t('model.haikuWarn') : m !== 'auto' && rec && m !== rec ? t('model.override', { m: MODEL_NAME[m] }) : '';
$('#modelHint').textContent = recTxt + warn + t('model.agentNote');
}
// Nhiều mẫu: "3 mẫu 2D → Sonnet, 1 mẫu 3D/shader → Opus" (mỗi job tự chọn theo mẫu của nó).
function modelHintMany() {
const m = $('#model').value;
const nHeavy = picks.filter(heavy).length, nLight = picks.length - nHeavy;
$('#model').querySelector('[value=auto]').textContent = t('model.autoMany');
const parts = [];
if (nLight) parts.push(t('model.manyLight', { n: nLight, m: MODEL_NAME.sonnet }));
if (nHeavy) parts.push(t('model.manyHeavy', { n: nHeavy, m: MODEL_NAME.opus }));
const txt = m === 'auto' ? t('model.manyAuto', { parts: parts.join(', ') })
: t('model.manyFixed', { n: picks.length, m: MODEL_NAME[m], parts: parts.join(', ') }) + (m === 'haiku' && nHeavy ? t('model.haikuWarnMany') : '');
$('#modelHint').textContent = txt + t('model.agentNote');
}
$('#model').addEventListener('change', modelHint);
window.addEventListener('lumreels:picked', modelHint);
modelHint();
function loadConfig(first) {
return fetch('/api/config').then((r) => r.json()).then((c) => {
cfg = c;
if (first) $('#mode').value = c.defaultMode;
$('#mode').querySelector('[value=claude]').disabled = !c.claudeAvailable;
$('#mode').querySelector('[value=api]').disabled = !c.apiAvailable;
if ($('#mode').selectedOptions[0]?.disabled) $('#mode').value = 'auto';
modeHint();
}).catch(() => {});
}
loadConfig(true);
// doctor-panel.js: khoá vừa lưu/xoá → bật/tắt lại ô "Claude API"; vừa tạo job "Video đầu tiên" → nạp lại danh sách
window.addEventListener('lumreels:config', () => loadConfig(false));
window.addEventListener('lumreels:jobs-reload', () => loadJobs());
// "Sửa nội dung trước" của thẻ Video đầu tiên: điền sẵn form (mẫu, nội dung, thời lượng, khung)
window.addEventListener('lumreels:prefill', (e) => {
const d = e.detail || {};
if (multi) setMulti(false);
if (d.templateId && !picks.some((x) => x.id === d.templateId)) pick(d.templateId);
if (typeof d.content === 'string') { $('#content').value = d.content; $('#content').dispatchEvent(new Event('input', { bubbles: true })); }
if (d.durationS) { $('#duration').value = String(d.durationS); $('#duration').dispatchEvent(new Event('input', { bubbles: true })); }
if (d.ratio) setRatio(d.ratio);
$('#content').focus();
$('#content').scrollIntoView({ behavior: 'smooth', block: 'center' });
});
// Đổi VI/EN: vẽ lại mọi chữ do JS sinh (chữ tĩnh trong HTML đã được i18n.js đổi).
window.addEventListener('lumreels:lang', () => {
renderGrid();
renderPicked();
updateDur(); // gọi luôn updateGo
updateWhen();
modeHint();
modelHint();
renderUpdate();
paintRatio();
if (rwView) rwView();
if (viewing) $('#vDesc').textContent = viewerDesc(viewing);
note(''); // báo nhẹ tự ẩn: bỏ luôn cho khỏi lẫn ngôn ngữ
loadJobs();
});
// learn-panel.js vừa lưu 1 mẫu "Của tôi" → nạp lại danh sách, lọc Của tôi, chọn luôn mẫu đó
window.addEventListener('lumreels:templates', async (e) => {
await loadTemplates();
const ref = e.detail?.pick;
if (!ref) return;
const chip = document.querySelector('.chip[data-cat="mine"]');
if (chip) chip.click();
if (multi) setMulti(false);
pick(ref);
document.querySelector(`#grid .tpl[data-id="${CSS.escape(ref)}"]`)?.scrollIntoView({ block: 'nearest' });
});
updateDur();
setRatio(ratio);
loadTemplates();
loadJobs();
})();