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.

8.0 KB
Raw Blame
// Bảng "Nhật ký": vì sao 1 job hỏng, không cần mở terminal. Dùng chung cho thẻ job (Dựng từ mẫu), thẻ edit, Studio
// và mục "Nhật ký app" ở chân trang. API chỉ đọc (server/logs.mjs): GET /api/logs/(job|edit)/:id, /api/logs/server,
// thêm ?download=1 để tải .txt. Server đã lọc bí mật; mọi chữ vào DOM bằng textContent.
// Gọi: window.LumLog.open({ kind: 'job' | 'edit' | 'server', id, title? }) · LumLog.button(kind, id, failed) → <button>.
(() => {
  const I = window.I18N;
  const t = (k, v) => I.t(k, v);
  const KINDS = ['job', 'edit', 'server'];
  const ID_RE = /^[\w-]{1,80}$/;
  let dlg = null; let cur = null; let data = null; let busy = false;

  function h(tag, cls, text, attrs = {}) {
    const e = document.createElement(tag);
    if (cls) e.className = cls;
    if (text != null) e.textContent = text;
    for (const [k, v] of Object.entries(attrs)) if (v != null) e.setAttribute(k, String(v));
    return e;
  }
  const url = (c, extra = '') => (c.kind === 'server' ? '/api/logs/server' : `/api/logs/${c.kind}/${encodeURIComponent(c.id)}`) + extra;

  function build() {
    dlg = h('dialog', 'logp', null, { 'aria-labelledby': 'logpTitle' });
    const head = h('div', 'logp-head');
    const ttl = h('div', 'logp-ttl');
    ttl.append(h('strong', null, '', { id: 'logpTitle' }), h('span', 'logp-sub'));
    const x = h('button', 'x', '×', { type: 'button' });
    x.addEventListener('click', () => dlg.close());
    head.append(ttl, x);
    const sum = h('div', 'logp-sum', null, { role: 'status', 'aria-live': 'polite' });
    const act = h('div', 'logp-act');
    const bCopy = h('button', 'mini logp-copy', '', { type: 'button' });
    const aDl = h('a', 'mini logp-dl', '', { download: '' });
    const bRe = h('button', 'mini logp-re', '', { type: 'button' });
    bCopy.addEventListener('click', copy);
    bRe.addEventListener('click', () => load());
    act.append(bCopy, aDl, bRe);
    const rawH = h('div', 'logp-rawh');
    const pre = h('pre', 'logp-raw', null, { tabindex: '0' });
    dlg.append(head, sum, act, rawH, pre);
    dlg.addEventListener('close', () => { cur = null; data = null; });
    document.body.append(dlg);
  }

  function paintStatic() {
    if (!dlg || !cur) return;
    dlg.querySelector('#logpTitle').textContent = t(cur.kind === 'server' ? 'log.titleServer' : 'log.title');
    dlg.querySelector('.logp-sub').textContent = cur.kind === 'server' ? t('log.subServer') : [cur.title || data?.title || '', cur.id].filter(Boolean).join(' · ');
    dlg.querySelector('.x').setAttribute('aria-label', t('log.close'));
    dlg.querySelector('.logp-copy').textContent = t('log.copy');
    const a = dlg.querySelector('.logp-dl'); a.textContent = t('log.download'); a.href = url(cur, '?download=1');
    dlg.querySelector('.logp-re').textContent = t('log.reload');
  }
  const stepName = (v) => {
    if (!v.step) return '';
    if (v.kind === 'job') return ['generating', 'waiting_agent', 'previewing', 'rendering'].includes(v.step) ? t('st.' + v.step) : v.step;
    return I.srv(v.step);
  };
  function paint() {
    paintStatic();
    if (!dlg || !cur) return;
    const sum = dlg.querySelector('.logp-sum'); const pre = dlg.querySelector('.logp-raw'); const rawH = dlg.querySelector('.logp-rawh');
    sum.replaceChildren(); sum.className = 'logp-sum';
    if (busy && !data) { sum.append(h('p', 'logp-muted', t('log.loading'))); pre.textContent = ''; rawH.textContent = ''; return; }
    if (data?.loadError) { sum.classList.add('bad'); sum.append(h('p', null, t('log.loadErr', { e: data.loadError }))); pre.textContent = ''; rawH.textContent = ''; return; }
    const v = data;
    if (!v) return;
    if (v.kind !== 'server') {
      const row = h('div', 'logp-row');
      const stCls = v.failed ? 'error' : v.status === 'done' ? 'done' : 'run';
      const stTxt = v.kind === 'job' ? (['scheduled', 'queued', 'generating', 'waiting_agent', 'previewing', 'rendering', 'done', 'error'].includes(v.status) ? t('st.' + v.status) : v.status)
        : (['queued', 'running', 'done', 'error'].includes(v.status) ? t('ed.st.' + v.status) : v.status);
      row.append(h('span', 'st ' + stCls, stTxt));
      if (v.failed && v.step) row.append(h('span', 'logp-step', t('log.step', { s: stepName(v) })));
      sum.append(row);
      if (v.failed) {
        sum.classList.add('bad');
        if (v.why) {
          sum.append(h('p', 'logp-why', t('log.why.' + v.why)));
          sum.append(h('p', 'logp-fix', t('log.fix.' + v.why)));
        } else sum.append(h('p', 'logp-why', t('log.whyUnknown')));
        if (v.error) {
          const d = h('details', 'logp-errd'); if (!v.why) d.open = true;
          d.append(h('summary', null, t('log.rawError')), h('code', 'logp-err', v.error));
          sum.append(d);
        }
      } else sum.append(h('p', 'logp-muted', t(v.status === 'done' ? 'log.okDone' : 'log.okRunning')));
    } else sum.append(h('p', 'logp-muted', t('log.serverNote', { n: v.lines.length })));
    rawH.textContent = v.lines.length ? t('log.rawHead', { n: v.lines.length, total: v.total }) : t('log.empty');
    const atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 8 || !pre.textContent;
    pre.textContent = v.lines.join('\n');
    if (atEnd) pre.scrollTop = pre.scrollHeight;
  }

  async function load() {
    if (!cur) return;
    const c = cur; busy = true; paint();
    try {
      const r = await fetch(url(c));
      const j = await r.json().catch(() => ({}));
      if (cur !== c) return;
      data = r.ok ? j : { loadError: I.srv(j.error || ('HTTP ' + r.status)) };
    } catch (e) { if (cur === c) data = { loadError: e.message }; }
    busy = false; paint();
  }
  function plainText() {
    const v = data; if (!v || v.loadError) return '';
    const head = [];
    if (v.kind === 'server') head.push(t('log.titleServer'));
    else {
      head.push(`${t('log.title')}: ${[cur?.title || v.title, v.id].filter(Boolean).join(' · ')}`);
      head.push(dlg.querySelector('.logp-row')?.textContent || v.status);
      if (v.failed) head.push(v.why ? `${t('log.why.' + v.why)} ${t('log.fix.' + v.why)}` : t('log.whyUnknown'));
      if (v.error) head.push(v.error);
    }
    return `${head.join('\n')}\n${'-'.repeat(40)}\n${v.lines.join('\n')}\n`;
  }
  async function copy() {
    const b = dlg.querySelector('.logp-copy'); const txt = plainText();
    let ok = false;
    try { await navigator.clipboard.writeText(txt); ok = true; } catch {
      // không có clipboard API (http, quyền): chọn chữ để người dùng Ctrl+C
      const pre = dlg.querySelector('.logp-raw'); const sel = getSelection(); const rg = document.createRange(); rg.selectNodeContents(pre); sel.removeAllRanges(); sel.addRange(rg);
    }
    b.textContent = t(ok ? 'log.copied' : 'log.copyManual');
    setTimeout(() => { if (b.isConnected) b.textContent = t('log.copy'); }, 1800);
  }

  function open(c) {
    if (!c || !KINDS.includes(c.kind) || (c.kind !== 'server' && !ID_RE.test(String(c.id || '')))) return;
    if (!dlg) build();
    cur = { kind: c.kind, id: c.id || null, title: c.title || '' }; data = null;
    paint();
    if (!dlg.open) dlg.showModal();
    load();
  }
  /** Nút "Nhật ký" (failed → nổi màu cảnh báo, chữ "Xem lỗi"). */
  function button(kind, id, failed, extraCls = '') {
    const b = h('button', `log-btn${failed ? ' bad' : ''}${extraCls ? ' ' + extraCls : ''}`, t(failed ? 'log.btnErr' : 'log.btn'), { type: 'button', 'data-log-kind': kind, 'data-log-id': id });
    return b;
  }
  // mọi nút có data-log-kind (vẽ bằng HTML chuỗi ở app.js hoặc bằng button()) → mở bảng
  document.addEventListener('click', (e) => {
    const b = e.target.closest?.('[data-log-kind]');
    if (!b) return;
    e.preventDefault(); e.stopPropagation();
    open({ kind: b.dataset.logKind, id: b.dataset.logId, title: b.dataset.logTitle || '' });
  }, true);
  window.addEventListener('lumreels:lang', () => { if (dlg?.open) paint(); });

  window.LumLog = { open, button };
})();