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.
// Lớp đồ hoạ thông tin (graphics[] trong EDL): counter, bar_chart, compare, spec_table, checklist, price_tag, sticker,
// line_chart, title_card. Ba phần:
// 1. LLM chọn đoạn hay (--target) và lập kế hoạch đồ hoạ THEO CHỈ SỐ CHỮ; code kiểm (số phải có trong lời, đúng loại,
// mốc nằm trong đoạn giữ, đồ hoạ lớn không chồng nhau) — sai thì LLM sửa 1 vòng, vẫn sai thì bỏ mục hỏng.
// 2. Code đổi chỉ số chữ → giây nguồn (start/end + mốc hiện từng dòng), giữ ≥ 1,5 s, thêm zoom nhẹ + sfx khi vào,
// rồi đặt vị trí né mặt (khung mặt bản ra, sau reframe + zoom, do `lumedit faces` đo).
// 3. Vẽ trong cảnh HyperFrames của lớp phụ đề: HTML/SVG, render(t) thuần theo t.
import { extractNumbers, numbersInText, spokenMatch, fmtVi, unitAfter, unitOf, sameUnit, quantityText } from './numbers.mjs';
import { toOutputNearest, inKeep, timelineOf, outputDuration, hookDur, OUT, SAFE } from './edl.mjs';
export const GRAPHIC_TYPES = ['counter', 'bar_chart', 'compare', 'spec_table', 'checklist', 'price_tag', 'sticker', 'line_chart', 'title_card'];
export const BIG = new Set(['bar_chart', 'compare', 'spec_table', 'checklist', 'line_chart', 'title_card']);
export const MIN_GRAPHIC = 1.5; // giây bản ra
export const HOLD = 0.7; // giữ thêm sau chữ cuối của đồ hoạ
export const MAX_GRAPHIC = 14;
export const ENTER = 0.35; export const LEAVE = 0.22; // khớp với vùng kính mờ vẽ trong lumedit.py
const W_BIG = 840; const W_SMALL = 620;
const key = (w) => String(w).toLowerCase().normalize('NFC').replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');
// ---- cỡ chữ vừa ô (ước theo bề rộng ký tự trung bình của Be Vietnam Pro/Manrope đậm) ----------------------------------
const CHAR = 0.6; const CHAR_UP = 0.7;
/** Cỡ chữ lớn nhất ≤ max để text vừa widthPx trên `lines` dòng; null nếu phải nhỏ hơn min. */
export function fitSize(text, widthPx, max, min = 22, { upper = false, lines = 1 } = {}) {
const n = Math.max(1, [...String(text)].length);
const s = Math.floor((widthPx * lines) / (n * (upper ? CHAR_UP : CHAR)));
if (s >= max) return max;
return s >= min ? s : null;
}
// ---- kích thước gốc (chưa thu nhỏ) của từng loại: code dàn trang và HTML dùng chung -----------------------------------
const HDR = 92;
export function baseSize(g) {
const d = g.data; const hdr = d.title || d.unit ? HDR : 0;
switch (g.type) {
case 'counter': return { w: W_SMALL, h: d.label ? 250 : 190 };
case 'price_tag': return { w: W_SMALL, h: 220 + (d.label ? 50 : 0) + (d.old != null ? 56 : 0) };
case 'sticker': return { w: Math.min(W_BIG, 100 + [...d.text].length * 42), h: 130 };
case 'title_card': return { w: W_BIG, h: d.kicker ? 270 : 210 };
case 'bar_chart': return { w: W_BIG, h: hdr + 60 + 380 };
case 'line_chart': return { w: W_BIG, h: hdr + 60 + 340 };
case 'compare': return { w: W_BIG, h: hdr + 112 + d.rows.length * 92 + 60 };
case 'spec_table': return { w: W_BIG, h: hdr + d.rows.length * 84 + 60 };
case 'checklist': return { w: W_BIG, h: hdr + d.items.length * 88 + 60 };
default: return { w: W_BIG, h: 300 };
}
}
// ---- 1a. chọn đoạn hay (--target) -------------------------------------------------------------------------------------
/** Giây bản ra ước cho 1 dải chữ [a..b] khi khoảng lặng bị rút còn ≤ pause. */
export function speechSeconds(words, a, b, pause = 0.3) {
let s = 0;
for (let i = a; i <= b; i++) {
s += Math.max(0.05, words[i].e - words[i].s);
if (i < b) s += Math.min(pause, Math.max(0, words[i + 1].s - words[i].e));
}
return s;
}
function linesWithIndex(words, { exclude = null, showSec = true } = {}) {
const lines = []; let line = []; let skipped = false;
const flush = () => { if (line.length) { lines.push(line.join(' ')); line = []; } };
for (let k = 0; k < words.length; k++) {
const w = words[k];
if (exclude?.has(w.i)) { if (!skipped) { flush(); lines.push('… (đoạn không dùng) …'); skipped = true; } continue; }
skipped = false;
if (!line.length && showSec) line.push(`(${w.s.toFixed(1)}s)`);
line.push(`[${w.i}]${w.w}`);
if (/[.?!]$/.test(w.w) || line.length > 18) flush();
}
flush();
return lines.join('\n');
}
export function buildSelectPrompt({ words, target, style, content, names, duration, errors, previous }) {
return `Mày là biên tập viên short dọc tiếng Việt (TikTok/Reels/Shorts). Video nguồn người dùng tự quay dài ${(duration / 60).toFixed(1)} phút.
Nhiệm vụ: chọn các đoạn HAY NHẤT để ghép thành 1 short khoảng ${target} giây (sau khi rút khoảng lặng), giữ nguyên thứ tự thời gian.
Chỉ trả về MỘT khối JSON.
# Kiểu edit: ${style.name}
${style.guide.split('\n## ')[0]}
# Lời dặn của người dùng
${content?.trim() || '(không có)'}
# Tên riêng đúng
${names?.length ? names.join(', ') : '(không có)'}
# Lời chép ([i] = số thứ tự chữ, đầu dòng là giây nguồn)
${linesWithIndex(words)}
# Định dạng trả về
{
"segments": [{"from": <i>, "to": <i>, "role": "hook|body|end", "why": "<ngắn>"}],
"notes": "<1 câu: short nói về gì>"
}
Luật:
- Đoạn ĐẦU (role "hook") phải giữ người xem trong 2 giây đầu: câu hỏi gây tò mò, con số gây sốc, nhận định mạnh. Không mở bằng câu chào/giới thiệu kênh.
- Đoạn CUỐI (role "end") là câu chốt/kết luận/lời khuyên, nghe trọn ý. Không kết giữa câu.
- Ở giữa (role "body"): các ý chính, ưu tiên chỗ người nói đọc SỐ LIỆU (giá, %, FPS, thông số, so sánh) vì kiểu này có đồ hoạ bảng biểu.
- Mỗi đoạn bắt đầu ở đầu câu và kết ở cuối câu (≥ 4 chữ). Các đoạn theo thứ tự tăng dần, không chồng nhau.
- Tổng thời lượng nói ≈ ${target} giây (code tự tính; được phép ${Math.round(target * 0.8)}–${Math.round(target * 1.3)} giây). Bỏ phần chào, lan man, quảng cáo kênh.
${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;
}
/** Kiểm lựa chọn đoạn. Trả {errors, clean:{segments}, seconds}. */
export function checkSelection(sel, words, target, pause = 0.3) {
const errors = []; const n = words.length; const segs = [];
const raw = Array.isArray(sel?.segments) ? sel.segments : null;
if (!raw?.length) return { errors: ['thiếu "segments"'], clean: { segments: [] }, seconds: 0 };
let last = -1;
for (const s of [...raw].sort((a, b) => a.from - b.from)) {
if (!Number.isInteger(s.from) || !Number.isInteger(s.to) || s.from < 0 || s.to >= n || s.from > s.to) { errors.push(`đoạn ${JSON.stringify(s)}: from/to không hợp lệ (0..${n - 1})`); continue; }
if (s.from <= last) { errors.push(`đoạn ${s.from}–${s.to} chồng đoạn trước`); continue; }
if (s.to - s.from < 3) { errors.push(`đoạn ${s.from}–${s.to} quá ngắn (< 4 chữ)`); continue; }
segs.push({ from: s.from, to: s.to, role: ['hook', 'body', 'end'].includes(s.role) ? s.role : 'body', why: String(s.why || '') });
last = s.to;
}
if (segs.length && segs[0].role !== 'hook') errors.push('đoạn đầu phải là "hook"');
if (segs.length && segs[segs.length - 1].role !== 'end') errors.push('đoạn cuối phải là "end"');
const seconds = segs.reduce((a, s) => a + speechSeconds(words, s.from, s.to, pause), 0);
if (seconds < target * 0.8 || seconds > target * 1.3) errors.push(`tổng ${seconds.toFixed(1)} s, cần ${Math.round(target * 0.8)}–${Math.round(target * 1.3)} s (mục tiêu ${target} s)`);
return { errors, clean: { segments: segs }, seconds };
}
/** Lựa chọn còn hỏng sau 2 vòng: giữ đoạn hợp lệ, quá dài thì bỏ bớt đoạn body từ cuối lên. */
function trimSelection(segs, words, target, pause) {
const out = [...segs];
const total = () => out.reduce((a, s) => a + speechSeconds(words, s.from, s.to, pause), 0);
while (total() > target * 1.3 && out.length > 2) {
const k = out.map((s, i) => [s, i]).filter(([s, i]) => s.role === 'body' && i > 0 && i < out.length - 1).pop();
if (!k) break;
out.splice(k[1], 1);
}
return out;
}
/** --target: LLM chọn đoạn → {exclude:Set(chỉ số chữ không dùng), segments, seconds, warnings}. */
export async function selectSegments({ words, target, style, content, names, duration, callClaude, parse, log = console.log }) {
const pause = Math.min(style.pause ?? 0.3, 0.3);
let text = ''; let prev = null; const warnings = [];
for (let round = 1; round <= 2; round++) {
let checked;
try {
const r = await callClaude(buildSelectPrompt({ words, target, style, content, names, duration, errors: prev?.errors, previous: prev ? text.slice(0, 4000) : '' }), { log });
text = r.text;
checked = checkSelection(parse(text), words, target, pause);
} catch (e) { checked = { errors: [`không đọc được JSON: ${e.message}`], clean: { segments: [] }, seconds: 0 }; }
if (!checked.errors.length) { prev = checked; break; }
log(` chọn đoạn vòng ${round}: ${checked.errors.slice(0, 3).join('; ')}`);
prev = checked;
if (round === 2) warnings.push(...checked.errors.map((e) => 'chọn đoạn: ' + e));
}
let segs = prev.clean.segments;
if (!segs.length) throw new Error('LLM không chọn được đoạn nào cho --target');
segs = trimSelection(segs, words, target, pause);
const keepIdx = new Set();
for (const s of segs) for (let i = s.from; i <= s.to; i++) keepIdx.add(i);
const exclude = new Set(words.filter((w) => !keepIdx.has(w.i)).map((w) => w.i));
const seconds = segs.reduce((a, s) => a + speechSeconds(words, s.from, s.to, pause), 0);
return { exclude, segments: segs, seconds, warnings };
}
// ---- 1b. kế hoạch đồ hoạ --------------------------------------------------------------------------------------------
/** Loại đồ hoạ kiểu này được dùng (style.graphics.types; không ghi thì cả 9 loại). */
export const allowedTypes = (style) => (Array.isArray(style?.graphics?.types) && style.graphics.types.length ? style.graphics.types.filter((t) => GRAPHIC_TYPES.includes(t)) : GRAPHIC_TYPES);
/** Những gì engine tự vẽ thêm theo thẻ kiểu, để LLM không làm trùng. */
function engineNotes(style) {
const n = [];
if (style.graphics?.pinFirst) n.push('- title_card ĐẦU TIÊN được ghim ở mép trên suốt clip (thu nhỏ sau 3 giây): chỉ cần 1 title_card ở chữ đầu tiên được giữ, không thêm đồ hoạ lớn nào khác.');
if (style.graphics?.stepTracker) n.push('- Code vẽ thanh tiến độ bước ở mép trên suốt clip, mỗi title_card có kicker "BƯỚC n" là 1 chấm (tick khi sang bước sau): ghi kicker đúng dạng "BƯỚC 1", "BƯỚC 2"…');
if (style.hook?.text) n.push('- Code tự vẽ chữ móc to 0–2 giây đầu (hookText): KHÔNG dùng title_card làm chữ móc.');
return n.length ? `\n# Engine tự làm\n${n.join('\n')}\n` : '';
}
export function buildGraphicsPrompt({ words, exclude, style, content, names, errors, previous }) {
const g = style.graphics;
const types = allowedTypes(style);
return `Mày là designer đồ hoạ thông tin cho short dọc tiếng Việt.
Đọc lời chép (chỉ phần được giữ) và lập kế hoạch đồ hoạ bảng biểu hiện đúng lúc người nói nói tới.
Chỉ trả về MỘT khối JSON.
# Kiểu edit: ${style.name}
${style.guide}
# Lời dặn của người dùng
${content?.trim() || '(không có)'}
# Tên riêng đúng (dùng đúng chính tả này trong nhãn)
${names?.length ? names.join(', ') : '(không có)'}
# Lời chép ([i] = số thứ tự chữ; đầu dòng là giây nguồn; máy nghe có thể sai chính tả tên riêng)
${linesWithIndex(words, { exclude })}
${engineNotes(style)}
# Các loại đồ hoạ được dùng cho kiểu này (at/until/word là chỉ số chữ [i]; KHÔNG dùng loại khác)
${[
['counter', "counter: số đếm lên khi người nói đọc 1 con số. {\"type\":\"counter\",\"at\":i,\"until\":j,\"value\":<số>,\"prefix\":\"\",\"suffix\":\"triệu đ|%|FPS|GB…\",\"label\":\"<≤ 26 ký tự>\"}"],
['price_tag', "price_tag: tem giá dập xuống. {\"type\":\"price_tag\",\"at\":i,\"until\":j,\"value\":<số>,\"suffix\":\"triệu\",\"label\":\"<tên máy ≤ 24>\",\"old\":<giá cũ, tuỳ chọn>}"],
['sticker', "sticker: tem chữ ngắn dập xuống (nhận định mạnh). {\"type\":\"sticker\",\"at\":i,\"until\":j,\"text\":\"<≤ 16 ký tự>\"}"],
['bar_chart', "bar_chart: 2–5 cột so sánh, cột mọc lên lúc người nói nói tới mục đó. {\"type\":\"bar_chart\",\"at\":i,\"until\":j,\"title\":\"<≤ 30>\",\"unit\":\"triệu\",\"items\":[{\"label\":\"<≤ 12>\",\"value\":<số>,\"word\":i}]}"],
['line_chart', "line_chart: 3–7 điểm giá lên xuống theo thời gian/mốc. {\"type\":\"line_chart\",\"at\":i,\"until\":j,\"title\":\"<≤ 30>\",\"unit\":\"triệu\",\"points\":[{\"label\":\"<≤ 8>\",\"value\":<số>,\"word\":i}]}"],
['compare', "compare: bảng A vs B, dòng hiện dần. {\"type\":\"compare\",\"at\":i,\"until\":j,\"title\":\"<≤ 30, tuỳ chọn>\",\"a\":\"<≤ 12>\",\"b\":\"<≤ 12>\",\"rows\":[{\"label\":\"<≤ 14>\",\"a\":\"<≤ 12>\",\"b\":\"<≤ 12>\",\"word\":i,\"winner\":\"a|b|null\"}]} (1–5 dòng)"],
['spec_table', "spec_table: bảng thông số, dòng nổi lên theo chữ. {\"type\":\"spec_table\",\"at\":i,\"until\":j,\"title\":\"<≤ 30>\",\"unit\":\"<đơn vị chung của các ô số, tuỳ chọn>\",\"rows\":[{\"label\":\"<≤ 14>\",\"value\":\"<≤ 14>\",\"word\":i}]} (1–6 dòng)"],
['checklist', "checklist: các ý tick dần. {\"type\":\"checklist\",\"at\":i,\"until\":j,\"title\":\"<≤ 30, tuỳ chọn>\",\"items\":[{\"text\":\"<≤ 30>\",\"word\":i,\"ok\":true|false}]} (2–5 ý)"],
['title_card', "title_card: thẻ chương khi chuyển ý lớn. {\"type\":\"title_card\",\"at\":i,\"until\":j,\"kicker\":\"<≤ 20, tuỳ chọn>\",\"title\":\"<≤ 28>\"}"],
].filter(([t]) => types.includes(t)).map(([, l]) => '- ' + l).join('\n')}
Mọi loại nhận thêm "estimate": true nếu có số KHÔNG được nói thẳng mà mày suy ra (đồ hoạ sẽ ghi "ước tính"). Hạn chế dùng.
# Định dạng trả về
{ "graphics": [ ... ], "notes": "<1 câu>" }
Luật:
- SỐ: mọi con số trên đồ hoạ (value, số trong nhãn/ô) phải là số người nói THẬT SỰ nói ra trong lời chép. Không bịa, không làm tròn, không tự tính. Người nói "9 rưỡi" (triệu) → value 9.5, suffix "triệu". Khoảng "22-23" → dùng 1 số đã nói hoặc ghi chữ "22–23" trong ô bảng.
- ĐƠN VỊ: mọi con số phải mang đơn vị người nói dùng (triệu, nghìn, %, GB, FPS, W…): trong suffix/unit, hoặc ngay trong ô ("sát 30 triệu"). Người nói bỏ lửng đơn vị mà câu trước/sau đang nói cùng loại số (vd đang đọc giá bằng triệu) thì vẫn ghi đơn vị đó. Không ghi số trơn.
- MỐC: "at" = chữ đầu tiên của ý đó (đồ hoạ hiện lúc này), "until" = chữ cuối của ý; mỗi dòng/cột/điểm có "word" = chữ người nói nói tới mục đó (at ≤ word ≤ until). Counter/price_tag: "at" là chữ của chính con số.
- Đồ hoạ LỚN (bar_chart, line_chart, compare, spec_table, checklist, title_card) KHÔNG được chồng thời gian nhau. Đồ hoạ nhỏ (counter, price_tag, sticker) không chồng nhau, có thể hiện cùng 1 đồ hoạ lớn chỉ khi bổ sung cho nó.
- Mỗi đồ hoạ hiện ít nhất 1,5 giây (code tự giữ thêm ~0,7 s sau "until"). Mật độ ${g.perMinute[0]}–${g.perMinute[1]} đồ hoạ mỗi phút; không phải câu nào cũng cần.
- Chỉ dùng chữ trong phần được giữ. Nhãn ngắn, viết đúng tên riêng (vd "RTX 5070 Ti"), không viết hoa toàn bộ trừ sticker.
${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;
}
/**
* Kiểm kế hoạch đồ hoạ. words: toàn bộ chữ (chỉ số = vị trí). usable(i): chữ i còn được giữ.
* spoken: các giá trị số trong lời (extractNumbers trên mọi chữ + số trong tên riêng người dùng khai).
* Trả {errors, clean:[mục hợp lệ]}.
*/
export function checkGraphics(plan, words, usable, spoken, types = GRAPHIC_TYPES) {
const errors = []; const clean = [];
const list = Array.isArray(plan?.graphics) ? plan.graphics : null;
if (!list) return { errors: ['thiếu mảng "graphics"'], clean };
const n = words.length;
const idx = (i) => Number.isInteger(i) && i >= 0 && i < n;
list.forEach((g, gi) => {
const errs = []; const where = `graphics[${gi}] (${g?.type})`;
const bad = (m) => errs.push(`${where}: ${m}`);
if (!g || !GRAPHIC_TYPES.includes(g.type)) { errors.push(`${where}: loại không hợp lệ (có: ${types.join(', ')})`); return; }
if (!types.includes(g.type)) { errors.push(`${where}: kiểu này không dùng ${g.type} (chỉ: ${types.join(', ')})`); return; }
if (!idx(g.at) || !idx(g.until) || g.at > g.until) { errors.push(`${where}: at/until không hợp lệ (0..${n - 1}, at ≤ until)`); return; }
if (!usable(g.at) || !usable(g.until)) bad(`at ${g.at}/until ${g.until} rơi vào chữ bị bỏ`);
const estimate = g.estimate === true;
const numOk = (v, what) => { if (!estimate && !spokenMatch(v, spoken)) bad(`${what} ${v} không có trong lời người nói (không bịa số; nếu suy ra thì "estimate": true)`); };
const textOk = (s, what, max, { need = true } = {}) => {
const t = typeof s === 'string' || typeof s === 'number' ? String(s).trim() : '';
if (!t) { if (need) bad(`thiếu ${what}`); return ''; }
if ([...t].length > max) bad(`${what} "${t}" dài quá ${max} ký tự`);
for (const v of numbersInText(t)) numOk(v, `số trong ${what} "${t}"`);
return t;
};
const wordOk = (i, what) => {
if (!idx(i)) { bad(`${what}: "word" không hợp lệ`); return false; }
if (i < g.at || i > g.until) bad(`${what}: word ${i} nằm ngoài at..until (${g.at}..${g.until})`);
if (!usable(i)) bad(`${what}: word ${i} rơi vào chữ bị bỏ`);
return true;
};
const num = (v, what) => { const x = Number(v); if (v === null || v === '' || !Number.isFinite(x)) { bad(`${what} phải là số`); return null; } numOk(x, what); return x; };
const out = { type: g.type, at: g.at, until: g.until, estimate, data: {} };
const d = out.data;
switch (g.type) {
case 'counter': case 'price_tag': {
d.value = num(g.value, 'value');
d.prefix = textOk(g.prefix, 'prefix', 6, { need: false });
d.suffix = textOk(g.suffix, 'suffix', 10, { need: false });
d.label = textOk(g.label, 'label', g.type === 'counter' ? 26 : 24, { need: false });
if (g.type === 'price_tag' && g.old != null && g.old !== '') d.old = num(g.old, 'old');
break;
}
case 'sticker': d.text = textOk(g.text, 'text', 16); break;
case 'title_card': d.kicker = textOk(g.kicker, 'kicker', 20, { need: false }); d.title = textOk(g.title, 'title', 28); break;
case 'bar_chart': case 'line_chart': {
const arr = g.type === 'bar_chart' ? g.items : g.points;
const [lo, hi] = g.type === 'bar_chart' ? [2, 5] : [3, 7];
d.title = textOk(g.title, 'title', 30, { need: false }); d.unit = textOk(g.unit, 'unit', 10, { need: false });
if (!Array.isArray(arr) || arr.length < lo || arr.length > hi) { bad(`cần ${lo}–${hi} ${g.type === 'bar_chart' ? 'items' : 'points'}`); break; }
d[g.type === 'bar_chart' ? 'items' : 'points'] = arr.map((it, k) => {
wordOk(it?.word, `mục ${k}`);
return { label: textOk(it?.label, `label mục ${k}`, g.type === 'bar_chart' ? 12 : 8), value: num(it?.value, `value mục ${k}`), word: it?.word, hi: it?.highlight === true };
});
break;
}
case 'compare': {
d.title = textOk(g.title, 'title', 30, { need: false }); d.unit = textOk(g.unit, 'unit', 10, { need: false }); d.a = textOk(g.a, 'a', 12); d.b = textOk(g.b, 'b', 12);
if (!Array.isArray(g.rows) || g.rows.length < 1 || g.rows.length > 5) { bad('cần 1–5 rows'); break; }
d.rows = g.rows.map((r, k) => { wordOk(r?.word, `dòng ${k}`); return { label: textOk(r?.label, `label dòng ${k}`, 14), a: textOk(r?.a, `a dòng ${k}`, 12), b: textOk(r?.b, `b dòng ${k}`, 12), word: r?.word, winner: ['a', 'b'].includes(r?.winner) ? r.winner : null }; });
break;
}
case 'spec_table': {
d.title = textOk(g.title, 'title', 30, { need: false }); d.unit = textOk(g.unit, 'unit', 10, { need: false });
if (!Array.isArray(g.rows) || g.rows.length < 1 || g.rows.length > 6) { bad('cần 1–6 rows'); break; }
d.rows = g.rows.map((r, k) => { wordOk(r?.word, `dòng ${k}`); return { label: textOk(r?.label, `label dòng ${k}`, 14), value: textOk(r?.value, `value dòng ${k}`, 14), word: r?.word }; });
break;
}
case 'checklist': {
d.title = textOk(g.title, 'title', 30, { need: false });
if (!Array.isArray(g.items) || g.items.length < 2 || g.items.length > 5) { bad('cần 2–5 items'); break; }
d.items = g.items.map((r, k) => { wordOk(r?.word, `ý ${k}`); return { text: textOk(r?.text, `text ý ${k}`, 30), word: r?.word, ok: r?.ok !== false }; });
break;
}
default: break;
}
if (errs.length) { errors.push(...errs); return; }
clean.push(out);
});
// chồng thời gian (theo giây nguồn của chữ; code còn giữ thêm HOLD và kiểm lại theo giây bản ra)
const span = (g) => [words[g.at].s, words[g.until].e];
const keepClean = [];
for (const g of clean.sort((a, b) => a.at - b.at)) {
const [s] = span(g);
const clash = keepClean.find((o) => (BIG.has(o.type) === BIG.has(g.type)) && span(o)[1] > s - 0.05);
if (clash) { errors.push(`${g.type} ở chữ ${g.at} chồng thời gian với ${clash.type} (${clash.at}..${clash.until}); đồ hoạ ${BIG.has(g.type) ? 'lớn' : 'nhỏ'} không được hiện cùng lúc`); continue; }
keepClean.push(g);
}
return { errors, clean: keepClean };
}
/** Giá trị số người nói ra (mọi chữ, kể cả đoạn không dùng) + số trong tên riêng người dùng khai. */
export function spokenNumbers(words, names = []) {
const vals = extractNumbers(words.map((w) => w.w)).map((x) => x.value);
for (const nm of names) vals.push(...numbersInText(nm));
return vals;
}
// ---- 1c. đơn vị và độ tin của số trên đồ hoạ ---------------------------------------------------------------------------
const UNIT_BACK = 45; const UNIT_FWD = 12; // giây nguồn: tìm đơn vị người nói dùng cho cùng loại số quanh đó
/** Chữ (chỉ số đầu..cuối) mang giá trị v gần chữ ref nhất, trong [lo, hi]; null nếu không có. */
export function numberWordNear(words, v, ref, lo, hi) {
lo = Math.max(0, lo); hi = Math.min(words.length - 1, hi);
if (hi < lo) return null;
const slice = words.slice(lo, hi + 1);
let best = null;
for (const x of extractNumbers(slice.map((w) => w.w))) {
if (!spokenMatch(v, [x.value])) continue;
const from = lo + x.from; const to = lo + x.to;
const d = ref < from ? from - ref : ref > to ? ref - to : 0;
if (!best || d < best.d || (d === best.d && to - from < best.to - best.from)) best = { from, to, d };
}
return best && { from: best.from, to: best.to };
}
/** Đơn vị người nói dùng cho số ở chữ [from..to]: ngay sau số, hoặc từ số cùng cỡ gần đó (≤ 45 s trước, ≤ 12 s sau). */
export function spokenUnit(words, from, to, v) {
const toks = words.map((w) => w.w);
const own = unitAfter(toks, to) || (from !== to ? unitAfter(toks, from) : null);
if (own) return { unit: own.unit, inferred: false, from, to: own.at };
const t0 = words[from].s; let best = null;
let lo = from; while (lo > 0 && words[lo - 1].s >= t0 - UNIT_BACK) lo--;
let hi = to; while (hi + 1 < words.length && words[hi + 1].s <= words[to].e + UNIT_FWD) hi++;
for (let k = lo; k <= hi; k++) {
if (k >= from && k <= to) continue;
const dg = /\d/.test(words[k].w) ? numbersInText(words[k].w.replace(/^[-–]/, ''))[0] : null;
if (dg == null || !(dg > 0)) continue;
const ratio = dg / Math.abs(v || 1);
if (ratio < 0.2 || ratio > 5) continue; // khác cỡ: không cùng loại số
const u = unitAfter(toks, k);
if (!u) continue;
const dist = k < from ? t0 - words[k].s : 2 * (words[k].s - words[to].e);
if (!best || dist < best.dist) best = { unit: u.unit, inferred: true, from: k, to: u.at, dist };
}
return best;
}
const spanText = (words, a, b) => words.slice(a, b + 1).map((w) => w.w).join(' ');
const sep = (u) => (/^[%°]/.test(u) ? '' : ' ');
/**
* Điền đơn vị còn thiếu cho số trên đồ hoạ (kế hoạch theo chỉ số chữ, đã qua checkGraphics): counter/price_tag thiếu
* suffix, biểu đồ thiếu unit, ô bảng là lượng mà chưa có đơn vị. Đơn vị lấy từ lời: ngay sau số, hoặc câu xung quanh
* đang nói cùng cỡ số. Sửa tại chỗ. Trả [{type, text, unit, from: "lời có đơn vị", at}] để ghi log/notes.
*/
export function fillUnits(plan, words) {
const notes = [];
const near = (g, v, ref) => numberWordNear(words, v, ref ?? g.at, Math.min(ref ?? g.at, g.at) - 4, Math.max(ref ?? g.at, g.until) + 8);
const note = (g, text, u) => notes.push({ type: g.type, text, unit: u.unit, from: spanText(words, Math.max(0, u.from - (u.inferred ? 1 : 0)), u.to), at: +words[u.from].s.toFixed(2), inferred: u.inferred });
for (const g of plan || []) {
const d = g.data;
if ((g.type === 'counter' || g.type === 'price_tag') && !d.suffix && Number.isFinite(d.value)) {
const n = near(g, d.value);
const u = n && spokenUnit(words, n.from, n.to, d.value);
if (u) { d.suffix = u.unit; note(g, fmtVi(d.value), u); }
}
if ((g.type === 'bar_chart' || g.type === 'line_chart') && !d.unit) {
const arr = d.items || d.points || [];
for (const it of arr) {
const n = near(g, it.value, it.word);
const u = n && spokenUnit(words, n.from, n.to, it.value);
if (u) { d.unit = u.unit; note(g, fmtVi(it.value), u); break; }
}
}
if (g.type === 'spec_table' || g.type === 'compare') {
const cells = [];
for (const r of d.rows || []) for (const f of g.type === 'spec_table' ? ['value'] : ['a', 'b']) {
const q = quantityText(r[f]);
if (q.quantity) cells.push({ r, f, q });
}
const need = cells.filter((c) => !c.q.unit);
if (!need.length || d.unit) continue;
const found = need.map((c) => {
const v = numbersInText(c.r[c.f])[0];
const n = v != null ? near(g, v, c.r.word) : null;
return { c, u: n ? spokenUnit(words, n.from, n.to, v) : null };
});
const units = [...new Set(found.filter((x) => x.u).map((x) => x.u.unit))];
const explicit = [...new Set(cells.filter((c) => c.q.unit).map((c) => c.q.unit))];
if (units.length === 1 && found.every((x) => x.u) && explicit.every((x) => sameUnit(x, units[0]))) {
if (!explicit.length) d.unit = units[0];
else for (const x of found) x.c.r[x.c.f] = `${x.c.r[x.c.f]}${sep(units[0])}${units[0]}`;
note(g, found.map((x) => x.c.r[x.c.f]).join(' / '), found[0].u);
} else {
for (const x of found) if (x.u) { x.c.r[x.c.f] = `${x.c.r[x.c.f]}${sep(x.u.unit)}${x.u.unit}`; note(g, x.c.r[x.c.f], x.u); }
}
}
}
return notes;
}
export const LOW_PROB = 0.6; // xác suất whisper dưới mức này: số máy nghe không chắc
const HEAR_BEFORE = 1.6; const HEAR_AFTER = 0.9;
/** Các giá trị số trong 1 ô chữ, mỗi giá trị 1 lần, không ghép 2 số liền nhau ("35, 37" không thành 3537). */
function cellNumbers(text) {
const toks = String(text).split(/\s+/).filter(Boolean);
const seen = new Set(); const out = [];
for (const x of extractNumbers(toks)) {
if (x.to === x.from + 1 && /^\d+[,.]?$/.test(toks[x.from]) && /^\d+[,.]?$/.test(toks[x.to]) && !/rưỡi|rưởi/.test(toks[x.to])) continue;
if (!seen.has(x.value)) { seen.add(x.value); out.push(x.value); }
}
return out;
}
/**
* Mọi số in trên đồ hoạ (giá trị, cột/điểm, ô bảng, ý checklist): {gi, where, value, unit (đơn vị đồ hoạ ghi), from, to
* (chữ người nói), span: [a, b] giây nguồn để nghe lại riêng}. Số không tìm thấy gần mốc: from = null.
*/
export function figureList(plan, words) {
const out = [];
const add = (gi, g, where, value, unit, ref) => {
if (!Number.isFinite(value)) return;
const n = numberWordNear(words, value, ref, Math.min(ref, g.at) - 6, Math.max(ref, g.until) + 8);
const f = { gi, type: g.type, where, value, unit: unit || '', from: n?.from ?? null, to: n?.to ?? null, estimate: !!g.estimate };
if (n) f.span = [+Math.max(0, words[n.from].s - HEAR_BEFORE).toFixed(2), +(words[n.to].e + HEAR_AFTER).toFixed(2)];
out.push(f);
};
(plan || []).forEach((g, gi) => {
const d = g.data;
if (g.type === 'counter' || g.type === 'price_tag') { add(gi, g, 'value', d.value, d.suffix, g.at); if (d.old != null) add(gi, g, 'old', d.old, d.suffix, g.at); }
for (const [arr, name] of [[d.items, 'mục'], [d.points, 'điểm']]) {
if (!Array.isArray(arr) || g.type === 'checklist') continue;
arr.forEach((it, k) => add(gi, g, `${name} ${k}`, it.value, d.unit, it.word));
}
if (g.type === 'spec_table' || g.type === 'compare') {
(d.rows || []).forEach((r, k) => {
for (const f of g.type === 'spec_table' ? ['value'] : ['a', 'b']) {
const q = quantityText(r[f]);
if (!q.quantity) continue;
for (const v of cellNumbers(r[f])) add(gi, g, `dòng ${k}${g.type === 'compare' ? ' ' + f : ''}`, v, q.unit || d.unit, r.word);
}
});
}
if (g.type === 'checklist') (d.items || []).forEach((it, k) => { for (const v of cellNumbers(it.text)) add(gi, g, `ý ${k}`, v, quantityText(it.text).unit, it.word); });
});
return out;
}
/**
* Độ tin của từng số (figureList). heard: {"a-b": [{text, words:[{w,s,e,p}]}]} = các khoảng nghe lại riêng (lumedit hear),
* có thể rỗng. Số "không chắc" khi: chỉ thấy ở lần nghe lại / xác suất whisper < 0,6; nghe lại riêng không ra số đó;
* nghe lại ra đơn vị khác ("80%" mà đồ hoạ ghi "80 GPU"); hoặc đơn vị trên đồ hoạ khác đơn vị người nói đặt sau số.
* Trả [{...figure, said, heard, why}] các số không chắc.
*/
export function checkFigures(figs, words, heard = {}) {
const low = [];
const toks = words.map((w) => w.w);
for (const f of figs) {
const why = [];
let said = ''; let heardText = '';
if (f.from == null) { if (!f.estimate) why.push('không thấy số này ở chỗ đồ hoạ hiện'); } // số ước tính (đã ghi "ước tính") vốn không được nói thẳng
else {
said = spanText(words, Math.max(0, f.from - 2), Math.min(words.length - 1, f.to + 2));
const ws = words.slice(f.from, f.to + 1);
if (ws.some((w) => w.unsure)) why.push('chỉ nghe được ở lần nghe lại, máy không chắc');
const p = Math.min(...ws.map((w) => (w.p == null ? 1 : w.p)));
if (p < LOW_PROB) why.push(`máy nghe không chắc (xác suất ${p.toFixed(2)})`);
const spoken = unitAfter(toks, f.to)?.unit || null;
if (f.unit && spoken && !sameUnit(f.unit, spoken) && unitOf(f.unit)) why.push(`đồ hoạ ghi "${f.unit}" nhưng người nói nói "${spoken}"`);
const segs = f.span ? heard[`${f.span[0].toFixed(2)}-${f.span[1].toFixed(2)}`] : null;
const hw0 = segs ? segs.flatMap((s) => s.words || []) : [];
if (hw0.length) { // nghe lại không ra chữ nào (đoạn quá ngắn/nhạc): không kết luận gì
const hw = hw0;
heardText = segs.map((s) => s.text).join(' ').trim();
const nums = extractNumbers(hw.map((w) => w.w));
const hit = nums.filter((x) => spokenMatch(f.value, [x.value]));
if (!hit.length) why.push(`nghe lại riêng không ra số ${fmtVi(f.value)} (nghe: "${heardText}")`);
else {
const hu = hit.map((x) => unitAfter(hw.map((w) => w.w), x.to)?.unit).find(Boolean) || null;
const shown = f.unit || spoken;
if (hu && shown && !sameUnit(hu, shown)) why.push(`nghe lại là "${fmtVi(f.value)}${sep(hu)}${hu}", đồ hoạ ghi "${fmtVi(f.value)}${sep(shown)}${shown}"`);
else if (hu && !shown) why.push(`nghe lại có đơn vị "${hu}" mà lần đầu không nghe ra`);
}
}
}
if (why.length) low.push({ ...f, said, heard: heardText, why: why.join('; ') });
}
return low;
}
/**
* Bỏ số không chắc khỏi đồ hoạ (không in số đáng ngờ lên đồ hoạ): counter/price_tag bỏ cả đồ hoạ; biểu đồ bỏ cột/điểm
* (còn dưới 2 cột / 3 điểm thì bỏ cả); bảng bỏ dòng (hết dòng thì bỏ); checklist bỏ ý (còn dưới 2 thì bỏ).
* Trả {plan: kế hoạch mới, dropped: ["…"]}.
*/
export function dropLowFigures(plan, low) {
const dropped = [];
const byG = new Map();
for (const f of low) { if (!byG.has(f.gi)) byG.set(f.gi, []); byG.get(f.gi).push(f); }
const out = [];
(plan || []).forEach((g, gi) => {
const fl = byG.get(gi);
if (!fl) { out.push(g); return; }
const d = g.data;
const idxOf = (where) => Number((/(\d+)/.exec(where) || [])[1]);
const drop = (why) => dropped.push(`${g.type} ở chữ ${g.at}: ${why}`);
if (g.type === 'counter' || g.type === 'price_tag') {
if (fl.some((f) => f.where === 'value')) { drop('bỏ cả đồ hoạ'); return; }
delete d.old; out.push(g); drop('bỏ giá cũ'); return;
}
const rm = new Set(fl.map((f) => idxOf(f.where)));
const key = g.type === 'bar_chart' || g.type === 'checklist' ? 'items' : g.type === 'line_chart' ? 'points' : 'rows';
const min = { bar_chart: 2, line_chart: 3, checklist: 2 }[g.type] ?? 1;
const left = (d[key] || []).filter((_, k) => !rm.has(k));
if (left.length < min) { drop('bỏ cả đồ hoạ'); return; }
d[key] = left; drop(`bỏ ${rm.size} ${key === 'rows' ? 'dòng' : 'mục'}`);
out.push(g);
});
return { plan: out, dropped };
}
/** LLM lập kế hoạch đồ hoạ; sai → sửa 1 vòng; vẫn sai → bỏ mục hỏng. */
export async function planGraphics({ words, dropped, style, content, names, callClaude, parse, log = console.log }) {
const usable = (i) => !dropped.has(i);
const spoken = spokenNumbers(words, names);
let text = ''; let prev = null; const warnings = [];
for (let round = 1; round <= 2; round++) {
let checked;
try {
const r = await callClaude(buildGraphicsPrompt({ words, exclude: dropped, style, content, names, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '' }), { log });
text = r.text;
checked = checkGraphics(parse(text), words, usable, spoken, allowedTypes(style));
} catch (e) { checked = { errors: [`không đọc được JSON: ${e.message}`], clean: prev?.clean || [] }; }
if (!checked.errors.length) return { graphics: checked.clean, rounds: round, warnings, raw: text };
log(` đồ hoạ vòng ${round}: ${checked.errors.length} lỗi: ${checked.errors.slice(0, 3).join('; ')}`);
prev = checked;
}
warnings.push(...prev.errors.map((e) => 'đồ hoạ bỏ mục hỏng: ' + e));
return { graphics: prev.clean, rounds: 2, warnings, raw: text };
}
// ---- 2. kế hoạch (chỉ số chữ) → graphics[] của EDL (giây nguồn) ---------------------------------------------------------
/**
* plan: các mục đã kiểm (state.graphics). keep: đoạn giữ của EDL. Mục nào rơi vào đoạn bỏ (sửa bằng lời cắt mất)
* thì bỏ. Kéo dài tới ≥ MIN_GRAPHIC giây bản ra nếu còn chỗ trước đồ hoạ cùng hạng sau; hết chỗ thì bỏ (cảnh báo).
* Trả {graphics, zooms, sfx, warnings}.
*/
/**
* Lúc chữ bắt đầu, kẹp vào đoạn giữ chứa giữa chữ: mép đoạn giữ đặt theo khoảng lặng thật nên có khi muộn hơn
* mốc whisper của chữ đầu đoạn vài chục ms; mốc đồ hoạ/zoom/sfx rơi ra ngoài keep thì bị lọc hoặc làm EDL hỏng.
*/
export function wordStart(keep, w) {
const mid = (w.s + w.e) / 2;
const k = keep.find((x) => mid >= x.start - 1e-6 && mid <= x.end + 1e-6);
return k ? Math.min(Math.max(w.s, k.start), k.end) : w.s;
}
export function compileGraphics({ plan, words, keep, style }) {
const warnings = []; const gs = [];
const byI = new Map(words.map((w) => [w.i, w]));
const outEnd = outputDuration(keep);
const items = [...(plan || [])].sort((a, b) => a.at - b.at);
items.forEach((p, n) => {
const wa = byI.get(p.at); const wu = byI.get(p.until);
if (!wa || !wu || !inKeep(keep, (wa.s + wa.e) / 2)) { warnings.push(`đồ hoạ ${p.type} ở chữ ${p.at}: chữ đã bị bỏ, không hiện`); return; }
const t = (i) => { const w = byI.get(i); return +wordStart(keep, w || wa).toFixed(3); };
const data = JSON.parse(JSON.stringify(p.data));
for (const arr of [data.items, data.points, data.rows]) if (Array.isArray(arr)) for (const it of arr) { it.at = t(it.word); delete it.word; }
const a0 = wordStart(keep, wa);
data.at = +a0.toFixed(3);
gs.push({ id: `g${n + 1}`, type: p.type, start: +Math.max(0, a0 - 0.05).toFixed(3), end: +(wu.e + HOLD).toFixed(3), estimate: !!p.estimate, data, box: null, face: null, squeeze: null });
});
// ghim tiêu đề (pinFirst): title_card đầu tiên hiện suốt clip ở mép trên → bỏ trần 14 s; đồ hoạ lớn khác sẽ chồng nó nên bỏ
const pinIdx = style.graphics?.pinFirst ? gs.findIndex((g) => g.type === 'title_card') : -1;
if (pinIdx >= 0) {
for (let k = gs.length - 1; k >= 0; k--) {
if (k !== pinIdx && BIG.has(gs[k].type)) { warnings.push(`đồ hoạ ${gs[k].type} ở ${gs[k].start.toFixed(2)} s: thẻ tiêu đề đang ghim suốt clip, bỏ`); gs.splice(k, 1); }
}
}
// giây bản ra: ≥ 1,5 s; không vượt đồ hoạ cùng hạng tiếp theo; ≤ 14 s
const out = [];
for (let k = 0; k < gs.length; k++) {
const g = gs[k];
const o0 = toOutputNearest(keep, g.start);
if (pinIdx >= 0 && g.type === 'title_card') {
g.end = +outputToSource(keep, outEnd).toFixed(3); g.data.pin = true;
g.outStart = +o0.toFixed(3); g.outEnd = +outEnd.toFixed(3);
out.push(g); continue;
}
const next = gs.slice(k + 1).find((x) => BIG.has(x.type) === BIG.has(g.type));
const limit = Math.min(outEnd, next ? toOutputNearest(keep, next.start) - 0.05 : outEnd);
let o1 = Math.min(toOutputNearest(keep, g.end), limit, o0 + MAX_GRAPHIC);
if (o1 - o0 < MIN_GRAPHIC) o1 = Math.min(limit, o0 + MIN_GRAPHIC);
if (o1 - o0 < MIN_GRAPHIC - 1e-6) { warnings.push(`đồ hoạ ${g.type} ở ${g.start.toFixed(2)} s: không đủ ${MIN_GRAPHIC} s trước đồ hoạ sau, bỏ`); continue; }
g.end = +outputToSource(keep, o1).toFixed(3);
g.outStart = +o0.toFixed(3); g.outEnd = +o1.toFixed(3);
out.push(g);
}
// zoom nhẹ khi vào đồ hoạ lớn, tiếng động khi vào
const gz = style.graphics;
const zooms = out.filter((g) => BIG.has(g.type) && gz.zoom).map((g) => ({ at: g.data.at, dur: +Math.min(8, Math.max(0.6, Math.min(2.4, g.outEnd - g.outStart))).toFixed(3), scale: gz.zoom, kind: 'push' }));
const sfx = [];
for (const g of out) {
const name = BIG.has(g.type) ? gz.sfxBig : ['price_tag', 'sticker'].includes(g.type) ? gz.sfxStamp : gz.sfxSmall;
if (name) sfx.push({ at: g.data.at, name, gainDb: gz.sfxGainDb });
if (g.type === 'checklist' && gz.sfxTick) for (const it of g.data.items) if (it.at > g.data.at + 0.2) sfx.push({ at: it.at, name: gz.sfxTick, gainDb: gz.sfxGainDb - 4 });
}
for (const g of out) { delete g.outStart; delete g.outEnd; }
return { graphics: out, zooms, sfx, warnings };
}
/** Giây bản ra → giây nguồn (trong keep). */
export function outputToSource(keep, o) {
let acc = hookDur(keep);
if (o < acc) return keep.hook.start + Math.max(0, o);
for (const k of keep) { const d = k.end - k.start; if (o <= acc + d + 1e-9) return k.start + Math.max(0, o - acc); acc += d; }
return keep[keep.length - 1].end;
}
// ---- 2b. dàn trang né mặt -------------------------------------------------------------------------------------------------
const PAD = 20;
const rectHit = (a, b) => a.x < b[2] && a.x + a.w > b[0] && a.y < b[3] && a.y + a.h > b[1];
const boxHit = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
export const GOOD_SCALE = 0.8; // dưới mức này chữ trên đồ hoạ khó đọc trên điện thoại → thu hình
export const MIN_SCALE = 0.5;
export const MIN_SQUEEZE = 0.62; // thu hình nhỏ nhất (tỉ lệ)
const WIDE_SQUEEZE = 0.62; // khung ngang: cột cạnh mặt chỉ cho đồ hoạ < mức này → thử thu hình
/** Khung mặt sau khi thu hình k quanh điểm (540, ay). */
export const squeezeBox = (b, q) => (b && q ? [Math.round(OUT.width / 2 + (b[0] - OUT.width / 2) * q.scale), Math.round(q.anchorY + (b[1] - q.anchorY) * q.scale),
Math.round(OUT.width / 2 + (b[2] - OUT.width / 2) * q.scale), Math.round(q.anchorY + (b[3] - q.anchorY) * q.scale)] : b);
/**
* Đặt vị trí từng đồ hoạ: lấy hợp khung mặt (bản ra) trong suốt thời gian hiện, chọn dải trống lớn nhất phía trên
* hoặc dưới mặt (trong vùng an toàn, trên phụ đề), thu nhỏ cho vừa.
* Cận mặt (dải trống quá hẹp, đồ hoạ phải thu < 0,8×): THU HÌNH `squeeze` {scale, anchorY} trong lúc đồ hoạ hiện —
* lumedit thu cả khung hình quanh điểm (giữa, cằm) nên cằm đứng yên, đỉnh đầu hạ xuống, phần trống lấp bằng chính hình
* đó làm mờ tối — để đồ hoạ có chỗ ở cỡ đọc được mà mặt không xuống dưới phụ đề.
* Đồ hoạ nhỏ hiện cùng lúc dùng chung khung mặt đã thu của đồ hoạ đang hiện.
* faces: {step, boxes:[[t,[x0,y0,x1,y1]|null]]}. captionTop: px mép trên phụ đề. Ghi g.box, g.face, g.squeeze. Trả warnings.
*/
export const STEP_BAR = { get y() { return Math.round(SAFE.y0 * OUT.height) + 4; }, h: 44 }; // thanh tiến độ bước (stepTracker): dải chấm ở mép trên vùng an toàn (9:16: y 196)
export function layoutGraphics(graphics, keep, faces, captionTop, { stepTracker = false } = {}) {
const warnings = [];
const Y0 = stepTracker ? STEP_BAR.y + STEP_BAR.h + 16 : Math.round(SAFE.y0 * OUT.height) + 8;
const Y1 = Math.min(captionTop - 24, Math.round(SAFE.y1 * OUT.height));
const X0 = Math.round(SAFE.x0 * OUT.width); const X1 = Math.round(SAFE.x1 * OUT.width);
const wide = OUT.width > OUT.height; // 16:9, 4:3: đặt được cột cạnh mặt
const placed = [];
const out = [];
for (const g of graphics) {
const o0 = toOutputNearest(keep, g.start); const o1 = toOutputNearest(keep, g.end);
if (g.data?.pin) {
// thẻ ghim: cố định sát mép trên vùng an toàn suốt clip (không né mặt theo từng lúc; podcast mặt thường ở giữa khung)
const { w, h } = baseSize(g); const s = +Math.min(1, (X1 - X0) / w).toFixed(3);
const box = { x: Math.round(OUT.width / 2 - (w * s) / 2), y: Math.round(SAFE.y0 * OUT.height), w: Math.round(w * s), h: Math.round(h * s), scale: s };
g.box = box; g.face = null; g.squeeze = null;
placed.push({ o0, o1, box, squeeze: null });
out.push(g); continue;
}
let fb = null;
for (const [t, b] of faces?.boxes || []) {
if (!b || t < o0 - 0.15 || t > o1 + 0.15) continue;
fb = fb ? [Math.min(fb[0], b[0]), Math.min(fb[1], b[1]), Math.max(fb[2], b[2]), Math.max(fb[3], b[3])] : [...b];
}
const face0 = fb ? [Math.max(0, fb[0] - PAD), Math.max(0, fb[1] - PAD), Math.min(OUT.width, fb[2] + PAD), Math.min(OUT.height, fb[3] + PAD)] : null;
const over = placed.filter((p) => p.o0 < o1 - 1e-3 && p.o1 > o0 + 1e-3);
const inherited = over.find((p) => p.squeeze)?.squeeze || null; // đang có đồ hoạ thu hình: mặt đã ở chỗ mới
const { w, h } = baseSize(g);
const fit = (face) => {
let bands = [[Y0, Y1]];
const blockers = [];
if (face && face[2] > X0 && face[0] < X1) blockers.push([face[1], face[3]]);
for (const p of over) blockers.push([p.box.y - 16, p.box.y + p.box.h + 16]);
for (const [b0, b1] of blockers) bands = bands.flatMap(([a, b]) => (b1 <= a || b0 >= b ? [[a, b]] : [[a, Math.min(b, b0)], [Math.max(a, b1), b]].filter(([x, y]) => y - x > 40)));
let best = null;
for (const [a, b] of bands) {
const s = Math.min(1, (b - a) / h, (X1 - X0) / w);
if (!best || s > best.s + 1e-6) best = { a, b, s };
}
if (wide) {
// khung ngang: thêm cột trái/phải của mặt (cả chiều cao vùng an toàn) — mặt thường ở giữa, trên/dưới mặt không đủ cao
let cols = [[X0, X1]];
const bx = [];
if (face && face[3] > Y0 && face[1] < Y1) bx.push([face[0], face[2]]);
for (const p of over) bx.push([p.box.x - 16, p.box.x + p.box.w + 16]);
for (const [b0, b1] of bx) cols = cols.flatMap(([a, b]) => (b1 <= a || b0 >= b ? [[a, b]] : [[a, Math.min(b, b0)], [Math.max(a, b1), b]].filter(([x, y]) => y - x > 60)));
for (const [a, b] of cols) {
const s = Math.min(1, (b - a) / w, (Y1 - Y0) / h);
if (!best || s > best.s + 0.02) best = { col: true, a, b, s };
}
}
return best;
};
let squeeze = null; let face = squeezeBox(face0, inherited);
let best = fit(face);
// khung ngang: cột cạnh mặt trước; cột hẹp quá (4:3, mặt to) mới thu hình lấy chỗ phía trên đầu
if (face0 && (!wide || !best || best.s < WIDE_SQUEEZE) && !inherited && !over.length && (!best || best.s < GOOD_SCALE)) {
// thu hình quanh (giữa, cằm): đỉnh đầu hạ xuống ay − (ay − top)·k; cần đỉnh đầu ≥ Y0 + cỡ đồ hoạ
const ay = Math.min(face0[3], Y1);
for (const s of wide ? [1, 0.92, 0.85, GOOD_SCALE, 0.72, 0.64] : [1, 0.92, 0.85, GOOD_SCALE]) { // khung ngang thấp 1080: cho thu đồ hoạ thêm
const k = (ay - Y0 - s * h - 12) / Math.max(1, ay - face0[1]);
if (k >= MIN_SQUEEZE && k < 1 && s * w <= X1 - X0) { squeeze = { scale: +Math.min(0.97, k).toFixed(3), anchorY: ay }; break; }
}
if (squeeze) { face = squeezeBox(face0, squeeze); best = fit(face); }
}
if (!best || best.s < MIN_SCALE) { warnings.push(`đồ hoạ ${g.type} ở ${o0.toFixed(1)} s: không đủ chỗ né mặt (${best ? 'chỉ thu được ' + best.s.toFixed(2) : 'không còn dải trống'}), bỏ`); continue; }
const s = +best.s.toFixed(3);
const bw = Math.round(w * s); const bh = Math.round(h * s);
// dải phía trên mặt: dính sát dưới (gần mặt); dải dưới mặt: dính sát trên; không có mặt: giữa dải
let y; let x = Math.round(OUT.width / 2 - bw / 2);
if (best.col) {
// cột cạnh mặt: dính sát phía mặt (cột trái → mép phải cột, cột phải → mép trái), giữa theo chiều dọc vùng an toàn
x = face && best.b <= face[0] + 1 ? Math.round(best.b - bw) : face && best.a >= face[2] - 1 ? Math.round(best.a) : Math.round((best.a + best.b - bw) / 2);
y = Math.round(Math.max(Y0, Math.min(Y1 - bh, (Y0 + Y1 - bh) / 2)));
} else if (face && best.b <= face[1] + 1) y = Math.round(best.b - bh);
else if (face && best.a >= face[3] - 1) y = Math.round(best.a);
else y = Math.round((best.a + best.b - bh) / 2);
const box = { x, y, w: bw, h: bh, scale: s };
g.box = box; g.face = face; g.squeeze = squeeze;
placed.push({ o0, o1, box, squeeze: squeeze || inherited });
out.push(g);
}
graphics.length = 0; graphics.push(...out);
return warnings;
}
/** Kiểm lớp đồ hoạ của EDL (gọi từ validateEdl). */
export function graphicsErrors(edl) {
const errs = []; const add = (p, m) => errs.push({ code: 'graphic', path: p, msg: m });
const keep = timelineOf(edl); const gs = edl.graphics || [];
const X0 = SAFE.x0 * OUT.width - 1; const X1 = SAFE.x1 * OUT.width + 1; const Y0 = SAFE.y0 * OUT.height - 1; const Y1 = SAFE.y1 * OUT.height + 1;
const T = gs.map((g) => [toOutputNearest(keep, g.start), toOutputNearest(keep, g.end)]);
gs.forEach((g, i) => {
const p = `graphics.${i}`;
if (!inKeep(keep, g.data.at ?? g.start)) add(p, `đồ hoạ ${g.type} ở ${g.start} s rơi vào đoạn bị bỏ`);
if (T[i][1] - T[i][0] < MIN_GRAPHIC - 1e-3) add(p, `đồ hoạ ${g.type} chỉ hiện ${(T[i][1] - T[i][0]).toFixed(2)} s (< ${MIN_GRAPHIC} s)`);
if (!g.box) { add(p, `đồ hoạ ${g.type} chưa có vị trí`); return; }
const b = g.box;
if (b.x < X0 || b.x + b.w > X1 || b.y < Y0 || b.y + b.h > Y1) add(p, `đồ hoạ ${g.type} tràn vùng an toàn (${b.x},${b.y} ${b.w}×${b.h})`);
if (g.face && rectHit(b, g.face)) add(p, `đồ hoạ ${g.type} đè mặt`);
for (let k = 0; k < i; k++) {
const o = gs[k];
if (!(T[k][0] < T[i][1] - 1e-3 && T[k][1] > T[i][0] + 1e-3)) continue;
if (BIG.has(o.type) && BIG.has(g.type)) add(p, `2 đồ hoạ lớn cùng lúc (${o.type} và ${g.type})`);
if (o.squeeze && g.squeeze) add(p, `2 đồ hoạ cùng thu hình (${o.type} và ${g.type})`);
if (o.box && boxHit(o.box, b)) add(p, `đồ hoạ ${g.type} đè ${o.type}`);
}
});
return errs;
}
// ---- 3. vẽ (HyperFrames, render(t) thuần) -------------------------------------------------------------------------------
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const decimalsOf = (v) => (Number.isInteger(v) ? 0 : Math.min(2, (String(v).split('.')[1] || '').length));
/** HTML tĩnh của 1 đồ hoạ (cỡ gốc). Phần chuyển động do GFX_RUNTIME đặt theo t. */
function graphicHtml(g, k) {
const d = g.data; const { w, h } = baseSize(g);
const est = g.estimate ? '<div class="est">ước tính</div>' : '';
const htxt = (d.title || '') + (d.unit ? ` · ${d.unit}` : '');
const head = d.title || d.unit ? `<div class="hdr" style="font-size:${fitSize(htxt, w - 220, 40, 24) || 24}px">${esc(d.title || '')}${d.unit ? `<span class="u">${d.title ? ' · ' : ''}${esc(d.unit)}</span>` : ''}</div>` : '';
const inner = w - 64;
let body = '';
switch (g.type) {
case 'counter': {
const big = fitSize(`${d.prefix}${fmtVi(d.value)}${d.suffix ? ' ' + d.suffix : ''}`, inner, 112, 48);
body = `${d.label ? `<div class="lbl">${esc(d.label)}</div>` : ''}<div class="num big" style="font-size:${big || 48}px"><span>${esc(d.prefix)}</span><span class="v" data-v="${d.value}" data-dec="${decimalsOf(d.value)}">${fmtVi(d.value)}</span>${d.suffix ? `<span class="suf">${/^[%°]/.test(d.suffix) ? "" : " "}${esc(d.suffix)}</span>` : ''}</div>`;
break;
}
case 'price_tag': {
const big = fitSize(`${d.prefix}${fmtVi(d.value)} ${d.suffix}`, inner - 40, 104, 44);
body = `<div class="tag">${d.label ? `<div class="lbl dark">${esc(d.label)}</div>` : ''}${d.old != null ? `<div class="old num">${fmtVi(d.old)} ${esc(d.suffix)}</div>` : ''}<div class="num big dark" style="font-size:${big || 44}px">${esc(d.prefix)}${fmtVi(d.value)}<span class="suf">${/^[%°]/.test(d.suffix) ? "" : " "}${esc(d.suffix)}</span></div><div class="hole"></div></div>`;
break;
}
case 'sticker': body = `<div class="stk" style="font-size:${fitSize(d.text.toUpperCase(), w - 70, 62, 36, { upper: true }) || 36}px">${esc(d.text.toUpperCase())}</div>`; break;
case 'title_card': body = `<div class="bar"></div>${d.kicker ? `<div class="kick">${esc(d.kicker)}</div>` : ''}<div class="ttl" style="font-size:${fitSize(d.title, inner - 30, 70, 40, { lines: 1 }) || 40}px">${esc(d.title)}</div>`; break;
case 'bar_chart': {
const n = d.items.length; const gap = 28; const cw = Math.floor((inner - gap * (n - 1)) / n);
const maxV = Math.max(...d.items.map((x) => Math.abs(x.value))) || 1;
const hiIdx = d.items.some((x) => x.hi) ? null : d.items.findIndex((x) => x.value === Math.max(...d.items.map((y) => y.value)));
body = `${head}<div class="bars">${d.items.map((it, j) => {
const vs = `${fmtVi(it.value)}`;
return `<div class="col" style="width:${cw}px"><div class="bv num" style="font-size:${fitSize(vs + (d.unit ? ' ' : ''), cw, 40, 22) || 22}px"><span class="v" data-v="${it.value}" data-dec="${decimalsOf(it.value)}">${vs}</span></div>`
+ `<div class="bt"><div class="bf${it.hi || j === hiIdx ? ' acc' : ''}" data-h="${Math.round(256 * Math.abs(it.value) / maxV)}"></div></div>`
+ `<div class="bl" style="font-size:${fitSize(it.label, cw, 28, 18, { lines: 2 }) || 18}px">${esc(it.label)}</div></div>`;
}).join('')}</div>`;
break;
}
case 'line_chart': {
const P = d.points; const cw = inner; const ch = 270; const vals = P.map((p) => p.value);
const lo = Math.min(...vals); const hi = Math.max(...vals); const pad = (hi - lo) * 0.18 || Math.abs(hi) * 0.1 || 1;
const y = (v) => Math.round(30 + (ch - 50) * (1 - (v - (lo - pad)) / ((hi + pad) - (lo - pad))));
const x = (j) => Math.round(72 + (cw - 144) * (P.length === 1 ? 0.5 : j / (P.length - 1)));
g._pts = P.map((p, j) => [x(j), y(p.value)]);
body = `${head}<svg class="lc" width="${cw}" height="${ch + 70}" viewBox="0 0 ${cw} ${ch + 70}">
${[0, 1, 2, 3].map((q) => `<line x1="0" x2="${cw}" y1="${30 + q * (ch - 50) / 3}" y2="${30 + q * (ch - 50) / 3}" class="grid"/>`).join('')}
<path class="area" d=""/><path class="line" d=""/>
${P.map((p, j) => `<g class="pt" data-j="${j}"><circle cx="${x(j)}" cy="${y(p.value)}" r="11"/><text class="pv num" x="${x(j)}" y="${y(p.value) - 24}" text-anchor="middle">${fmtVi(p.value)}</text><text class="px" x="${x(j)}" y="${ch + 52}" text-anchor="middle">${esc(p.label)}</text></g>`).join('')}
</svg>`;
break;
}
case 'compare': body = `${head}<div class="cmp-h"><div class="cn" style="font-size:${fitSize(d.a, 290, 38, 22) || 22}px">${esc(d.a)}</div><div class="vs">VS</div><div class="cn" style="font-size:${fitSize(d.b, 290, 38, 22) || 22}px">${esc(d.b)}</div></div>`
+ d.rows.map((r) => `<div class="row cmp"><div class="ca num${r.winner === 'a' ? ' win' : ''}" style="font-size:${fitSize(r.a, 280, 36, 20) || 20}px">${esc(r.a)}</div><div class="cl" style="font-size:${fitSize(r.label, 200, 25, 16) || 16}px">${esc(r.label)}</div><div class="cb num${r.winner === 'b' ? ' win' : ''}" style="font-size:${fitSize(r.b, 280, 36, 20) || 20}px">${esc(r.b)}</div></div>`).join('');
break;
case 'spec_table': body = head + d.rows.map((r) => `<div class="row spec"><div class="sl" style="font-size:${fitSize(r.label, 360, 30, 18) || 18}px">${esc(r.label)}</div><div class="sv num" style="font-size:${fitSize(r.value, 380, 38, 20) || 20}px">${esc(r.value)}</div></div>`).join(''); break;
case 'checklist': body = head + d.items.map((r) => `<div class="row chk"><svg class="cb" width="52" height="52" viewBox="0 0 52 52"><rect x="3" y="3" width="46" height="46" rx="12"/><path class="${r.ok ? 'tick' : 'cross'}" d="${r.ok ? 'M14 27 L23 36 L39 17' : 'M16 16 L36 36 M36 16 L16 36'}"/></svg><div class="ct" style="font-size:${fitSize(r.text, inner - 90, 32, 20) || 20}px">${esc(r.text)}</div></div>`).join(''); break;
default: break;
}
const b = g.box;
const solid = ['price_tag', 'sticker'].includes(g.type);
return `<div class="gw" id="g${k}" style="left:${b.x}px;top:${b.y}px;width:${b.w}px;height:${b.h}px${d.pin ? ';transform-origin:50% 0' : ''}"><div class="g ${g.type}${solid ? ' solid' : ''}" style="width:${w}px;height:${h}px;transform:scale(${b.scale})">${est}${body}</div></div>`;
}
/** Phần chèn vào cảnh phụ đề: {css, html, data, runtime}. look.accent = màu nhấn duy nhất. */
/** Thẻ title_card có kicker "BƯỚC n" (kiểu hướng dẫn) → mốc bản ra của từng bước, theo thứ tự. */
export function stepTimes(edl) {
const keep = timelineOf(edl);
return (edl.graphics || []).filter((g) => g.type === 'title_card' && /^(bước|buoc)\s*\d+/u.test(String(g.data?.kicker || '').normalize('NFC').toLowerCase().trim()))
.map((g) => +toOutputNearest(keep, g.start).toFixed(3)).sort((a, b) => a - b);
}
export const DEFAULT_ACCENT = '#FCE802';
/** V7: accent đi thẳng vào CSS → chỉ nhận đúng dạng #RRGGBB, sai thì dùng màu mặc định. */
export function safeAccent(v) {
return typeof v === 'string' && /^#[0-9A-Fa-f]{6}$/.test(v) ? v : DEFAULT_ACCENT;
}
export function graphicsScene(edl, { accent: accentIn = DEFAULT_ACCENT, stepTracker = false, dur = null } = {}) {
const accent = safeAccent(accentIn);
const gs = edl.graphics || [];
const keep = timelineOf(edl);
const st = stepTracker ? stepTimes(edl) : [];
const steps = st.length >= 2 ? { t: st, end: +(dur ?? outputDuration(keep)).toFixed(3) } : null;
const stepHtml = steps ? `<div id="stepbar" style="top:${STEP_BAR.y}px;height:${STEP_BAR.h}px">${st.map((_, k) => `${k ? '<i class="sl"></i>' : ''}<div class="sd" id="sd${k}"><span>${k + 1}</span><svg viewBox="0 0 40 40"><path d="M11 21 l6 6 l12 -13"/></svg></div>`).join('')}</div>` : '';
const html = gs.map((g, k) => graphicHtml(g, k)).join('\n ') + stepHtml;
const data = gs.map((g) => {
const tt = (s) => +toOutputNearest(keep, s).toFixed(3);
const d = g.data;
const items = (d.items || d.points || d.rows || []).map((it) => tt(it.at));
const pts = g._pts || null; delete g._pts;
return { type: g.type, t0: tt(g.start), t1: tt(g.end), at: tt(d.at ?? g.start), items, pts, pin: !!d.pin };
});
const css = `
.gw { position:absolute; visibility:hidden; opacity:0; transform-origin:50% 50%; }
.g { position:absolute; left:0; top:0; transform-origin:0 0; box-sizing:border-box; padding:30px 32px; border-radius:38px; color:#fff;
font-family:'Be Vietnam Pro', sans-serif; font-weight:700; overflow:hidden;
background:linear-gradient(160deg, rgba(34,38,48,.80), rgba(10,12,17,.74)); border:2px solid rgba(255,255,255,.14);
box-shadow:0 22px 60px rgba(0,0,0,.38), inset 0 1px 0 rgba(255,255,255,.16); }
.g.solid { background:none; border:none; box-shadow:none; padding:0; overflow:visible; }
.num { font-family:'Manrope', sans-serif; font-weight:800; font-variant-numeric:tabular-nums; letter-spacing:-0.01em; }
.est { position:absolute; right:26px; top:22px; font-size:22px; font-weight:600; padding:4px 14px; border-radius:99px; border:1.5px solid ${accent}; color:${accent}; }
.hdr { font-weight:800; line-height:1.15; height:${HDR - 30}px; white-space:nowrap; padding-right:150px; }
.lbl { font-size:32px; font-weight:600; opacity:.78; white-space:nowrap; margin-bottom:6px; }
.lbl.dark, .num.dark { color:#111; opacity:1; }
.big { line-height:1.08; white-space:nowrap; color:#fff; }
.big .suf, .suf { color:${accent}; font-size:.52em; font-weight:800; }
.counter .big .v { color:${accent}; }
.hdr .u { color:${accent}; font-weight:700; font-size:.8em; }
.bars { display:flex; gap:28px; align-items:flex-end; height:380px; }
.col { display:flex; flex-direction:column; align-items:center; height:380px; justify-content:flex-end; }
.bv { height:52px; line-height:52px; white-space:nowrap; }
.bt { width:100%; display:flex; align-items:flex-end; }
.bf { width:100%; height:0; border-radius:16px 16px 6px 6px; background:rgba(255,255,255,.34); }
.bf.acc { background:${accent}; box-shadow:0 0 30px ${accent}55; }
.bl { height:70px; box-sizing:border-box; padding-top:10px; text-align:center; line-height:1.15; font-weight:600; opacity:.9; }
.lc .grid { stroke:rgba(255,255,255,.10); stroke-width:2; }
.lc .line { fill:none; stroke:${accent}; stroke-width:7; stroke-linecap:round; stroke-linejoin:round; }
.lc .area { fill:${accent}; opacity:.14; stroke:none; }
.lc circle { fill:#11141b; stroke:${accent}; stroke-width:6; }
.lc .pv { fill:#fff; font-size:30px; } .lc .px { fill:rgba(255,255,255,.72); font-size:24px; font-family:'Be Vietnam Pro'; font-weight:600; }
.row { display:flex; align-items:center; box-sizing:border-box; }
.cmp-h { display:flex; align-items:center; height:96px; margin-bottom:14px; border-bottom:2px solid rgba(255,255,255,.12); }
.cmp-h .cn { width:300px; text-align:center; font-weight:800; white-space:nowrap; }
.cmp-h .vs { width:176px; text-align:center; font-weight:800; font-size:30px; color:#111; }
.cmp-h .vs { background:${accent}; border-radius:99px; height:54px; line-height:54px; width:96px; margin:0 40px; }
.row.cmp { height:92px; }
.cmp .ca, .cmp .cb { width:300px; text-align:center; white-space:nowrap; }
.cmp .cl { width:176px; text-align:center; opacity:.68; font-weight:600; line-height:1.15; }
.cmp .win { color:${accent}; }
.row.spec { height:84px; justify-content:space-between; border-bottom:2px solid rgba(255,255,255,.09); padding-left:20px; position:relative; }
.row.spec::before { content:''; position:absolute; left:0; top:24px; bottom:24px; width:6px; border-radius:4px; background:${accent}; }
.spec .sl { opacity:.72; font-weight:600; white-space:nowrap; } .spec .sv { white-space:nowrap; }
.row.chk { height:88px; gap:24px; }
.chk .cb rect { fill:rgba(255,255,255,.08); stroke:rgba(255,255,255,.35); stroke-width:3; }
.chk .cb path { fill:none; stroke-width:7; stroke-linecap:round; stroke-linejoin:round; }
.chk .cb .tick { stroke:${accent}; } .chk .cb .cross { stroke:rgba(255,255,255,.55); }
.chk .ct { font-weight:600; white-space:nowrap; }
.g.title_card { display:flex; flex-direction:column; justify-content:center; }
.title_card .bar { position:absolute; left:0; top:0; bottom:0; width:14px; background:${accent}; }
.title_card .kick { color:${accent}; font-size:30px; font-weight:800; letter-spacing:.06em; text-transform:uppercase; margin:0 0 10px 16px; }
.title_card .ttl { font-weight:800; line-height:1.12; margin-left:16px; white-space:nowrap; }
.tag { position:relative; background:${accent}; border-radius:30px 30px 30px 30px; padding:26px 36px 26px 76px; box-shadow:0 18px 44px rgba(0,0,0,.40); }
.tag .hole { position:absolute; left:26px; top:50%; width:26px; height:26px; margin-top:-13px; border-radius:50%; background:rgba(0,0,0,.55); }
.tag .old { color:#111; opacity:.6; font-size:36px; text-decoration:line-through; text-decoration-thickness:4px; }
.tag .suf { color:#111; }
.stk { display:inline-block; background:${accent}; color:#111; font-weight:800; padding:22px 36px; border-radius:22px; white-space:nowrap; line-height:1.1; box-shadow:0 16px 40px rgba(0,0,0,.42); border:5px solid #111; }`;
const stepCss = steps ? `
#stepbar { position:absolute; left:0; width:${OUT.width}px; display:flex; align-items:center; justify-content:center; gap:0; opacity:0; }
#stepbar .sd { position:relative; width:${STEP_BAR.h}px; height:${STEP_BAR.h}px; border-radius:50%; box-sizing:border-box; border:3px solid rgba(255,255,255,.55);
background:rgba(10,12,17,.55); color:#fff; font:800 22px/38px 'Be Vietnam Pro', sans-serif; text-align:center; }
#stepbar .sd.on { background:${accent}; border-color:${accent}; color:#111; box-shadow:0 0 18px ${accent}88; }
#stepbar .sd svg { position:absolute; left:0; top:0; width:100%; height:100%; opacity:0; }
#stepbar .sd path { fill:none; stroke:#111; stroke-width:5; stroke-linecap:round; stroke-linejoin:round; stroke-dasharray:30; stroke-dashoffset:30; }
#stepbar .sl { display:block; width:34px; height:4px; border-radius:2px; background:rgba(255,255,255,.35); }
#stepbar .sl.on { background:${accent}; }` : '';
return { css: css + stepCss, html, data, steps };
}
/** Hàm vẽ chạy trong trang: G = graphicsScene().data. Thuần theo t. */
export const GFX_RUNTIME = String.raw`
function gfxRender(t, G) {
var clamp = function (x) { return x < 0 ? 0 : x > 1 ? 1 : x; };
var prog = function (t, a, d) { return clamp((t - a) / d); };
var outCubic = function (x) { return 1 - Math.pow(1 - x, 3); };
var outBack = function (x) { var c = 1.9, c3 = c + 1; return 1 + c3 * Math.pow(x - 1, 3) + c * Math.pow(x - 1, 2); };
var fmt = function (v, dec) { var s = Math.abs(v).toFixed(dec).split('.'); return (v < 0 ? '\u2212' : '') + s[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.') + (s[1] ? ',' + s[1] : ''); };
for (var k = 0; k < G.length; k++) {
var g = G[k], el = document.getElementById('g' + k);
if (!(t >= g.t0 && t < g.t1)) { el.style.visibility = 'hidden'; el.style.opacity = 0; continue; }
el.style.visibility = 'visible';
var u = t - g.t0, stamp = g.type === 'price_tag' || g.type === 'sticker';
var a = Math.min(prog(t, g.t0, 0.15), clamp((g.t1 - t) / ${LEAVE}));
var s, rot = 0;
if (stamp) { var q = prog(t, g.t0, 0.26); s = q < 1 ? 1.65 - 0.65 * outCubic(q) - Math.sin(q * Math.PI) * 0.04 : 1; rot = g.type === 'sticker' ? -5 : -3; }
else s = 0.86 + 0.14 * outBack(prog(t, g.t0, ${ENTER}));
s *= 1 - 0.04 * (1 - clamp((g.t1 - t) / ${LEAVE}));
if (g.pin) s *= 1 - 0.2 * outCubic(prog(t, g.t0 + 3, 0.4)); // thẻ ghim: 3 s đầu cỡ thật, rồi thu về 0,8
el.style.opacity = a;
el.style.transform = 'scale(' + s.toFixed(4) + ') rotate(' + rot + 'deg)';
var vs = el.querySelectorAll('.v');
if (g.type === 'counter') {
var v = vs[0], k1 = outCubic(prog(t, g.at, 0.9));
v.textContent = fmt(Number(v.dataset.v) * k1, Number(v.dataset.dec));
}
if (g.type === 'bar_chart') {
var bf = el.querySelectorAll('.bf'), bl = el.querySelectorAll('.bl'), bv = el.querySelectorAll('.bv');
for (var j = 0; j < bf.length; j++) {
var kb = prog(t, g.items[j], 0.55), e = kb > 0 ? outBack(kb) : 0;
bf[j].style.height = Math.max(0, Number(bf[j].dataset.h) * e).toFixed(1) + 'px';
bv[j].style.opacity = prog(t, g.items[j] + 0.1, 0.2); bl[j].style.opacity = 0.35 + 0.65 * prog(t, g.items[j], 0.2);
vs[j].textContent = fmt(Number(vs[j].dataset.v) * outCubic(kb), Number(vs[j].dataset.dec));
}
}
if (g.type === 'compare' || g.type === 'spec_table' || g.type === 'checklist') {
var rows = el.querySelectorAll('.row');
for (var r = 0; r < rows.length; r++) {
var kr = outCubic(prog(t, g.items[r], 0.32));
rows[r].style.opacity = kr; rows[r].style.transform = 'translateY(' + ((1 - kr) * 26).toFixed(1) + 'px)';
if (g.type === 'checklist') {
var p = rows[r].querySelector('path'), kt = prog(t, g.items[r] + 0.12, 0.28);
p.style.strokeDasharray = 80; p.style.strokeDashoffset = (80 * (1 - outCubic(kt))).toFixed(1);
}
if (g.type === 'compare') { var w = rows[r].querySelectorAll('.win'); for (var x = 0; x < w.length; x++) w[x].style.transform = 'scale(' + (1 + 0.12 * Math.sin(Math.PI * prog(t, g.items[r] + 0.3, 0.3))).toFixed(3) + ')'; }
}
}
if (g.type === 'line_chart') {
var P = g.pts, d = '', ar = '', last = null, base = 270 - 20;
for (var i = 0; i < P.length; i++) {
var kp = prog(t, g.items[i], 0.45);
var pt = el.querySelector('.pt[data-j="' + i + '"]');
if (kp <= 0) { pt.style.opacity = 0; continue; }
var px = P[i][0], py = P[i][1];
if (last) { var e2 = outCubic(kp); px = last[0] + (P[i][0] - last[0]) * e2; py = last[1] + (P[i][1] - last[1]) * e2; }
d += (d ? ' L' : 'M') + px.toFixed(1) + ' ' + py.toFixed(1);
ar += (ar ? ' L' : 'M') + px.toFixed(1) + ' ' + (ar ? py.toFixed(1) : base + ' L' + px.toFixed(1) + ' ' + py.toFixed(1));
last = [px, py];
pt.style.opacity = prog(t, g.items[i] + 0.3, 0.15);
if (kp < 1) break;
}
el.querySelector('.line').setAttribute('d', d);
el.querySelector('.area').setAttribute('d', last ? ar + ' L' + last[0].toFixed(1) + ' ' + base + ' Z' : '');
}
if (g.type === 'title_card') {
var kc = outCubic(prog(t, g.t0, 0.45));
el.querySelector('.bar').style.transform = 'scaleY(' + kc.toFixed(3) + ')';
el.querySelector('.ttl').style.transform = 'translateX(' + (-(1 - kc) * 40).toFixed(1) + 'px)';
}
}
}
function stepsRender(t, S) {
if (!S) return;
var clamp = function (x) { return x < 0 ? 0 : x > 1 ? 1 : x; };
var bar = document.getElementById('stepbar');
bar.style.opacity = clamp(t / 0.3) * clamp((S.end - t) / 0.25);
var n = S.t.length, links = bar.querySelectorAll('.sl');
for (var k = 0; k < n; k++) {
var el = document.getElementById('sd' + k);
var on = t >= S.t[k], doneAt = k + 1 < n ? S.t[k + 1] : S.end - 0.6, done = t >= doneAt;
el.className = 'sd' + (on ? ' on' : '');
var u = clamp((t - S.t[k]) / 0.25), pop = on ? 1 + 0.25 * Math.sin(Math.PI * u) : 1;
el.style.transform = 'scale(' + pop.toFixed(3) + ')';
var svg = el.querySelector('svg'), num = el.querySelector('span'), kt = clamp((t - doneAt) / 0.25);
svg.style.opacity = done ? 1 : 0; num.style.opacity = done ? 0 : 1;
el.querySelector('path').style.strokeDashoffset = (30 * (1 - kt)).toFixed(1);
if (k) links[k - 1].className = 'sl' + (on ? ' on' : '');
}
}`;
/** Chữ nhấn số cho phụ đề: chữ có chữ số, và đơn vị/hệ số đứng ngay sau chữ số. */
const UNIT_AFTER = new Set(['nghìn', 'ngàn', 'triệu', 'tỷ', 'tỉ', 'k', 'đ', 'đồng', '%', 'phần', 'trăm', 'rưỡi', 'fps', 'gb', 'w', 'mhz', 'ghz']);
export function numberHighlights(capWords) {
const out = [];
capWords.forEach((w, k) => {
if (/\d/.test(w.w)) out.push(w.i);
else if (k && /\d/.test(capWords[k - 1].w) && UNIT_AFTER.has(key(w.w))) out.push(w.i);
});
return out;
}