Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eeccece373 | ||
|
|
d60b30e7d6 | ||
|
|
6917b6faf3 | ||
|
|
c00db123f7 | ||
|
|
087e74a025 | ||
|
|
59e6af3877 | ||
|
|
adf10afda5 |
No files matched your search
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "aacut",
|
||||
"private": true,
|
||||
"version": "1.0.1",
|
||||
"version": "1.0.6",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "yarn clean && node scripts/patch-sdk-offline.mjs && yarn build:worker && vite build",
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""验证顶栏新增「更多素材」菜单:出现 + 点击新窗口打开目标 URL"""
|
||||
import sys, asyncio
|
||||
|
||||
BASE = "https://127.0.0.1:3005"
|
||||
TARGET = "https://doc.88531.cn/docs/mrfx/mrfx-1g99qum57n5qk"
|
||||
|
||||
async def main():
|
||||
from playwright.async_api import async_playwright
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(args=["--ignore-certificate-errors"])
|
||||
ctx = await browser.new_context(ignore_https_errors=True,
|
||||
viewport={"width": 1600, "height": 900})
|
||||
page = await ctx.new_page()
|
||||
errs = []
|
||||
page.on("pageerror", lambda e: errs.append(str(e)))
|
||||
|
||||
await page.goto(BASE + "/", wait_until="domcontentloaded", timeout=120000)
|
||||
await page.wait_for_timeout(6000)
|
||||
|
||||
link = page.locator("a", has_text="更多素材")
|
||||
n = await link.count()
|
||||
print("菜单项存在:", n, "PASS" if n == 1 else "FAIL")
|
||||
if n:
|
||||
info = await link.first.evaluate("el => ({href: el.href, target: el.target, text: el.innerText.trim()})")
|
||||
print("链接:", info)
|
||||
print("URL正确:", "PASS" if info["href"] == TARGET else "FAIL " + info["href"])
|
||||
print("新窗口:", "PASS" if info["target"] == "_blank" else "FAIL")
|
||||
|
||||
# 点击并捕获新标签页
|
||||
async with ctx.expect_page() as newp:
|
||||
await link.first.click()
|
||||
np = await newp.value
|
||||
await np.wait_for_load_state("domcontentloaded", timeout=60000)
|
||||
print("新标签URL:", np.url, "PASS" if np.url.rstrip("/") == TARGET.rstrip("/") else "FAIL")
|
||||
title = await np.title()
|
||||
print("目标页title:", title)
|
||||
await np.close()
|
||||
|
||||
print("JS errors:", errs[:5])
|
||||
await page.screenshot(path="/vol1/1000/HD1/APP/hermes/awork/unicut_nav_check.png")
|
||||
await browser.close()
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""复现:项目列表卡片改名是否真正落库/刷新后是否保留。
|
||||
用法: python3 scripts/dbg_rename.py
|
||||
"""
|
||||
import sys, asyncio, json
|
||||
|
||||
BASE = "https://127.0.0.1:3005"
|
||||
|
||||
|
||||
async def main():
|
||||
from playwright.async_api import async_playwright
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(args=["--ignore-certificate-errors"])
|
||||
ctx = await browser.new_context(ignore_https_errors=True,
|
||||
viewport={"width": 1600, "height": 900})
|
||||
page = await ctx.new_page()
|
||||
errs = []
|
||||
page.on("pageerror", lambda e: errs.append(str(e)))
|
||||
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded", timeout=120000)
|
||||
await page.wait_for_timeout(5000)
|
||||
|
||||
# 预置本地存储文件夹句柄(与 e2e_quickvideo_cover.py 的 GUARD 一致)
|
||||
GUARD = """async () => {
|
||||
try {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
const db = await new Promise((res, rej) => {
|
||||
const rq = indexedDB.open('H5VideoLocalDB');
|
||||
rq.onupgradeneeded = () => rq.result.createObjectStore('folderHandles');
|
||||
rq.onsuccess = () => res(rq.result);
|
||||
rq.onerror = () => rej(rq.error);
|
||||
});
|
||||
const done = await new Promise((res, rej) => {
|
||||
const tx = db.transaction('folderHandles', 'readwrite');
|
||||
const st = tx.objectStore('folderHandles');
|
||||
const rec = { id: 'root', handle: root };
|
||||
if (st.keyPath) st.put(rec); else st.put(rec, 'root');
|
||||
tx.oncomplete = () => res(true);
|
||||
tx.onerror = () => rej(tx.error);
|
||||
});
|
||||
db.close();
|
||||
return done;
|
||||
} catch (e) { return String(e); }
|
||||
}"""
|
||||
print("GUARD:", await page.evaluate(GUARD))
|
||||
await page.reload(wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(6000)
|
||||
|
||||
print("URL:", page.url)
|
||||
print("TITLE:", await page.title())
|
||||
|
||||
# 若无项目,先创建一个
|
||||
if await page.locator("input[class*='__name__']").count() == 0:
|
||||
btn = page.get_by_text("创建项目", exact=True).first
|
||||
if await btn.count():
|
||||
await btn.click()
|
||||
await page.wait_for_timeout(6000)
|
||||
# 创建后可能跳进编辑器,返回列表
|
||||
if "workspace/draft" not in page.url:
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded", timeout=120000)
|
||||
await page.wait_for_timeout(5000)
|
||||
print("创建后 name input count:", await page.locator("input[class*='__name__']").count())
|
||||
|
||||
# 列表卡片名输入框
|
||||
inputs = page.locator("input[class*='__name__']")
|
||||
n = await inputs.count()
|
||||
print("input.title count:", n)
|
||||
if n == 0:
|
||||
# 打印可见输入框与页面骨架
|
||||
allin = page.locator("input")
|
||||
print("all input count:", await allin.count())
|
||||
for i in range(min(await allin.count(), 8)):
|
||||
el = allin.nth(i)
|
||||
print(" input", i, await el.get_attribute("class"),
|
||||
repr(await el.get_attribute("value")),
|
||||
"visible=", await el.is_visible())
|
||||
print("BODY:", (await page.inner_text("body"))[:600])
|
||||
await browser.close()
|
||||
return 1
|
||||
|
||||
old = await inputs.first.get_attribute("value")
|
||||
print("原名:", repr(old))
|
||||
|
||||
# 聚焦 + 全选 + 输入 + 失焦
|
||||
await inputs.first.click()
|
||||
await page.keyboard.press("Control+a")
|
||||
await page.keyboard.type("RENAME_TEST_001")
|
||||
await page.keyboard.press("Tab")
|
||||
await page.wait_for_timeout(2000)
|
||||
|
||||
val_after = await inputs.first.input_value()
|
||||
print("失焦后输入框:", repr(val_after))
|
||||
|
||||
# 读 IndexedDB projects 表
|
||||
async def read_meta():
|
||||
return await page.evaluate("""async () => {
|
||||
try {
|
||||
const rq = indexedDB.open('H5VideoLocalDB');
|
||||
const db = await new Promise((res, rej) => { rq.onsuccess=()=>res(rq.result); rq.onerror=()=>rej(rq.error); });
|
||||
const tx = db.transaction('projects','readonly');
|
||||
const all = await new Promise((res, rej) => {
|
||||
const r = tx.objectStore('projects').getAll();
|
||||
r.onsuccess=()=>res(r.result); r.onerror=()=>rej(r.error);
|
||||
});
|
||||
return all.map(x => ({id:x.id, name:x.name, updatedAt:x.updatedAt}));
|
||||
} catch(e){ return 'ERR:'+e; }
|
||||
}""")
|
||||
|
||||
meta1 = await read_meta()
|
||||
print("失焦后 IndexedDB:", json.dumps(meta1, ensure_ascii=False))
|
||||
|
||||
# 刷新
|
||||
await page.reload(wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(5000)
|
||||
inputs2 = page.locator("input[class*='__name__']")
|
||||
n2 = await inputs2.count()
|
||||
print("刷新后 input.title count:", n2)
|
||||
if n2:
|
||||
print("刷新后输入框值:", repr(await inputs2.first.input_value()))
|
||||
meta2 = await read_meta()
|
||||
print("刷新后 IndexedDB:", json.dumps(meta2, ensure_ascii=False))
|
||||
|
||||
print("JS errors:", errs[:5])
|
||||
await browser.close()
|
||||
return 0
|
||||
|
||||
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""复现用户路径: ①改名按回车 ②改名后立即点开项目再返回列表 ③改名后失焦点空白处"""
|
||||
import sys, asyncio, json
|
||||
|
||||
BASE = "https://127.0.0.1:3005"
|
||||
|
||||
GUARD = """async () => {
|
||||
try {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
const db = await new Promise((res, rej) => {
|
||||
const rq = indexedDB.open('H5VideoLocalDB');
|
||||
rq.onupgradeneeded = () => rq.result.createObjectStore('folderHandles');
|
||||
rq.onsuccess = () => res(rq.result);
|
||||
rq.onerror = () => rej(rq.error);
|
||||
});
|
||||
await new Promise((res, rej) => {
|
||||
const tx = db.transaction('folderHandles', 'readwrite');
|
||||
const st = tx.objectStore('folderHandles');
|
||||
const rec = { id: 'root', handle: root };
|
||||
if (st.keyPath) st.put(rec); else st.put(rec, 'root');
|
||||
tx.oncomplete = () => res(true);
|
||||
tx.onerror = () => rej(tx.error);
|
||||
});
|
||||
db.close();
|
||||
return 'ok';
|
||||
} catch (e) { return String(e); }
|
||||
}"""
|
||||
|
||||
READ_META = """async () => {
|
||||
try {
|
||||
const rq = indexedDB.open('H5VideoLocalDB');
|
||||
const db = await new Promise((res, rej) => { rq.onsuccess=()=>res(rq.result); rq.onerror=()=>rej(rq.error); });
|
||||
const tx = db.transaction('projects','readonly');
|
||||
const all = await new Promise((res, rej) => {
|
||||
const r = tx.objectStore('projects').getAll();
|
||||
r.onsuccess=()=>res(r.result); r.onerror=()=>rej(r.error);
|
||||
});
|
||||
return all.map(x => ({id:x.id, name:x.name, dtitle:(x.data&&x.data.title)||null}));
|
||||
} catch(e){ return 'ERR:'+e; }
|
||||
}"""
|
||||
|
||||
|
||||
async def main():
|
||||
from playwright.async_api import async_playwright
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(args=["--ignore-certificate-errors"])
|
||||
ctx = await browser.new_context(ignore_https_errors=True,
|
||||
viewport={"width": 1600, "height": 900})
|
||||
page = await ctx.new_page()
|
||||
errs = []
|
||||
page.on("pageerror", lambda e: errs.append(str(e)))
|
||||
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded", timeout=120000)
|
||||
await page.wait_for_timeout(4000)
|
||||
await page.evaluate(GUARD)
|
||||
await page.reload(wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(6000)
|
||||
|
||||
inputs = page.locator("input[class*='__name__']")
|
||||
if await inputs.count() == 0:
|
||||
btn = page.get_by_text("创建项目", exact=True).first
|
||||
await btn.click()
|
||||
await page.wait_for_timeout(6000)
|
||||
if "workspace/draft" not in page.url:
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(5000)
|
||||
inputs = page.locator("input[class*='__name__']")
|
||||
|
||||
print("卡片数:", await inputs.count())
|
||||
print("初始:", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
|
||||
# ① 改名 + 按回车(不点别处)
|
||||
await inputs.first.click()
|
||||
await page.keyboard.press("Control+a")
|
||||
await page.keyboard.type("VIA_ENTER_KEY")
|
||||
await page.keyboard.press("Enter")
|
||||
await page.wait_for_timeout(2500)
|
||||
print("①回车后 input:", repr(await inputs.first.input_value()))
|
||||
print("①回车后 DB:", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
|
||||
# ② 改名后立即点开第一张卡片(打开项目)
|
||||
await inputs.first.click()
|
||||
await page.keyboard.press("Control+a")
|
||||
await page.keyboard.type("VIA_OPEN_PROJECT")
|
||||
await page.keyboard.press("Tab")
|
||||
await page.wait_for_timeout(1500)
|
||||
print("②失焦后 DB:", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
# 点卡片标题区打开项目
|
||||
card_a = page.locator("a[href*='/editor/']").first
|
||||
if await card_a.count():
|
||||
await card_a.click()
|
||||
await page.wait_for_timeout(8000)
|
||||
print("②打开后 URL:", page.url)
|
||||
# 编辑器顶栏标题
|
||||
t = await page.evaluate("""() => {
|
||||
const el = document.querySelector('input[placeholder]');
|
||||
return el ? el.value : null;
|
||||
}""")
|
||||
print("②编辑器标题输入框:", repr(t))
|
||||
print("②DB(编辑器内):", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
# 返回列表
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(6000)
|
||||
inputs = page.locator("input[class*='__name__']")
|
||||
print("②返回列表 input:", repr(await inputs.first.input_value()) if await inputs.count() else "N/A")
|
||||
print("②返回后 DB:", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
|
||||
print("JS errors:", errs[:5])
|
||||
await browser.close()
|
||||
|
||||
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""反向同步验证:列表卡片改名 -> 打开编辑器顶栏显示新名 -> 再改顶栏 -> 回列表"""
|
||||
import sys, asyncio, json
|
||||
|
||||
BASE = "https://127.0.0.1:3005"
|
||||
|
||||
GUARD = """async () => {
|
||||
try {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
const db = await new Promise((res, rej) => {
|
||||
const rq = indexedDB.open('H5VideoLocalDB');
|
||||
rq.onupgradeneeded = () => rq.result.createObjectStore('folderHandles');
|
||||
rq.onsuccess = () => res(rq.result);
|
||||
rq.onerror = () => rej(rq.error);
|
||||
});
|
||||
await new Promise((res, rej) => {
|
||||
const tx = db.transaction('folderHandles', 'readwrite');
|
||||
const st = tx.objectStore('folderHandles');
|
||||
const rec = { id: 'root', handle: root };
|
||||
if (st.keyPath) st.put(rec); else st.put(rec, 'root');
|
||||
tx.oncomplete = () => res(true);
|
||||
tx.onerror = () => rej(tx.error);
|
||||
});
|
||||
db.close();
|
||||
return 'ok';
|
||||
} catch (e) { return String(e); }
|
||||
}"""
|
||||
|
||||
READ_META = """async () => {
|
||||
try {
|
||||
const rq = indexedDB.open('H5VideoLocalDB');
|
||||
const db = await new Promise((res, rej) => { rq.onsuccess=()=>res(rq.result); rq.onerror=()=>rej(rq.error); });
|
||||
const tx = db.transaction('projects','readonly');
|
||||
const all = await new Promise((res, rej) => {
|
||||
const r = tx.objectStore('projects').getAll();
|
||||
r.onsuccess=()=>res(r.result); r.onerror=()=>rej(r.error);
|
||||
});
|
||||
return all.map(x => ({id:x.id, name:x.name, dtitle:(x.data&&x.data.title)||null}));
|
||||
} catch(e){ return 'ERR:'+e; }
|
||||
}"""
|
||||
|
||||
|
||||
async def main():
|
||||
from playwright.async_api import async_playwright
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(args=["--ignore-certificate-errors"])
|
||||
ctx = await browser.new_context(ignore_https_errors=True,
|
||||
viewport={"width": 1600, "height": 900})
|
||||
page = await ctx.new_page()
|
||||
errs = []
|
||||
page.on("pageerror", lambda e: errs.append(str(e)))
|
||||
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded", timeout=120000)
|
||||
await page.wait_for_timeout(4000)
|
||||
await page.evaluate(GUARD)
|
||||
await page.reload(wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(6000)
|
||||
|
||||
inputs = page.locator("input[class*='__name__']")
|
||||
if await inputs.count() == 0:
|
||||
btn = page.get_by_text("创建项目", exact=True).first
|
||||
await btn.click()
|
||||
await page.wait_for_timeout(6000)
|
||||
if "workspace/draft" not in page.url:
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(5000)
|
||||
inputs = page.locator("input[class*='__name__']")
|
||||
|
||||
# ① 列表改名
|
||||
await inputs.first.click()
|
||||
await page.keyboard.press("Control+a")
|
||||
await page.keyboard.type("LIST_RENAME_X")
|
||||
await page.keyboard.press("Tab")
|
||||
await page.wait_for_timeout(2500)
|
||||
print("①列表改名后 DB:", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
|
||||
# ② 打开项目,看顶栏
|
||||
await page.locator("div[class*='__item__'] a").first.click()
|
||||
await page.wait_for_timeout(10000)
|
||||
inp = page.locator("#projectName")
|
||||
top = await inp.input_value() if await inp.count() else "N/A"
|
||||
print("②顶栏显示:", repr(top), "PASS" if top == "LIST_RENAME_X" else "FAIL")
|
||||
|
||||
# ③ 顶栏再改 -> 回列表
|
||||
await inp.click()
|
||||
await page.keyboard.press("Control+a")
|
||||
await page.keyboard.type("TOPBAR_RENAME_Y")
|
||||
await inp.press("Tab") # 触发失焦即时同步
|
||||
await page.wait_for_timeout(2500)
|
||||
print("③顶栏改后 DB:", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(6000)
|
||||
inputs2 = page.locator("input[class*='__name__']")
|
||||
v = await inputs2.first.input_value() if await inputs2.count() else "N/A"
|
||||
print("④回列表卡片名:", repr(v), "PASS" if v == "TOPBAR_RENAME_Y" else "FAIL")
|
||||
print("④DB:", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
print("JS errors:", errs[:5])
|
||||
await browser.close()
|
||||
|
||||
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""复现:编辑器顶栏项目名输入框修改是否有效(即时值/落库/刷新/列表名)"""
|
||||
import sys, asyncio, json
|
||||
|
||||
BASE = "https://127.0.0.1:3005"
|
||||
GUID = None # 用现有第一个项目
|
||||
|
||||
GUARD = """async () => {
|
||||
try {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
const db = await new Promise((res, rej) => {
|
||||
const rq = indexedDB.open('H5VideoLocalDB');
|
||||
rq.onupgradeneeded = () => rq.result.createObjectStore('folderHandles');
|
||||
rq.onsuccess = () => res(rq.result);
|
||||
rq.onerror = () => rej(rq.error);
|
||||
});
|
||||
await new Promise((res, rej) => {
|
||||
const tx = db.transaction('folderHandles', 'readwrite');
|
||||
const st = tx.objectStore('folderHandles');
|
||||
const rec = { id: 'root', handle: root };
|
||||
if (st.keyPath) st.put(rec); else st.put(rec, 'root');
|
||||
tx.oncomplete = () => res(true);
|
||||
tx.onerror = () => rej(tx.error);
|
||||
});
|
||||
db.close();
|
||||
return 'ok';
|
||||
} catch (e) { return String(e); }
|
||||
}"""
|
||||
|
||||
READ_META = """async () => {
|
||||
try {
|
||||
const rq = indexedDB.open('H5VideoLocalDB');
|
||||
const db = await new Promise((res, rej) => { rq.onsuccess=()=>res(rq.result); rq.onerror=()=>rej(rq.error); });
|
||||
const tx = db.transaction('projects','readonly');
|
||||
const all = await new Promise((res, rej) => {
|
||||
const r = tx.objectStore('projects').getAll();
|
||||
r.onsuccess=()=>res(r.result); r.onerror=()=>rej(r.error);
|
||||
});
|
||||
return all.map(x => ({id:x.id, name:x.name, dtitle:(x.data&&x.data.title)||null}));
|
||||
} catch(e){ return 'ERR:'+e; }
|
||||
}"""
|
||||
|
||||
|
||||
async def main():
|
||||
from playwright.async_api import async_playwright
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(args=["--ignore-certificate-errors"])
|
||||
ctx = await browser.new_context(ignore_https_errors=True,
|
||||
viewport={"width": 1600, "height": 900})
|
||||
page = await ctx.new_page()
|
||||
errs = []
|
||||
page.on("pageerror", lambda e: errs.append(str(e)))
|
||||
|
||||
# 首页 → 列表
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded", timeout=120000)
|
||||
await page.wait_for_timeout(4000)
|
||||
await page.evaluate(GUARD)
|
||||
await page.reload(wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(6000)
|
||||
|
||||
inputs = page.locator("input[class*='__name__']")
|
||||
if await inputs.count() == 0:
|
||||
btn = page.get_by_text("创建项目", exact=True).first
|
||||
await btn.click()
|
||||
await page.wait_for_timeout(6000)
|
||||
if "workspace/draft" not in page.url:
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(5000)
|
||||
inputs = page.locator("input[class*='__name__']")
|
||||
|
||||
print("列表初始:", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
|
||||
# 打开第一个项目(卡片是无 href 的 a[onClick],内部 .pic 区域)
|
||||
a = page.locator("div[class*='__item__'] a").first
|
||||
if await a.count() == 0:
|
||||
a = page.locator("a").filter(has=page.locator("div[class*='__pic__']")).first
|
||||
await a.click()
|
||||
await page.wait_for_timeout(10000)
|
||||
print("URL:", page.url)
|
||||
|
||||
inp = page.locator("#projectName")
|
||||
print("顶栏输入框存在:", await inp.count())
|
||||
if await inp.count():
|
||||
print("顶栏初始值:", repr(await inp.input_value()))
|
||||
await inp.click()
|
||||
await page.keyboard.press("Control+a")
|
||||
await page.keyboard.type("TOPBAR_RENAME_001")
|
||||
await page.wait_for_timeout(1500)
|
||||
print("输入后立即读:", repr(await inp.input_value()))
|
||||
# 等待自动保存(10s周期)+ 主动点云保存
|
||||
cloud = page.locator("a").filter(has=page.locator("svg")).first
|
||||
try:
|
||||
await page.locator("#projectName").press("Control+s")
|
||||
except Exception:
|
||||
pass
|
||||
await page.wait_for_timeout(12000)
|
||||
print("12s后读:", repr(await inp.input_value()))
|
||||
print("DB(编辑器内):", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
|
||||
# 刷新页面看是否保留
|
||||
await page.reload(wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(10000)
|
||||
inp2 = page.locator("#projectName")
|
||||
if await inp2.count():
|
||||
print("刷新后顶栏:", repr(await inp2.input_value()))
|
||||
print("DB(刷新后):", json.dumps(await page.evaluate(READ_META), ensure_ascii=False))
|
||||
|
||||
# 回列表看卡片名
|
||||
await page.goto(f"{BASE}/workspace/draft", wait_until="domcontentloaded")
|
||||
await page.wait_for_timeout(6000)
|
||||
inputs2 = page.locator("input[class*='__name__']")
|
||||
if await inputs2.count():
|
||||
print("列表卡片名:", repr(await inputs2.first.input_value()))
|
||||
|
||||
print("JS errors:", errs[:6])
|
||||
await browser.close()
|
||||
|
||||
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -2,7 +2,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""AI 一键出片「自动封面」端到端:mock 掉对话/生图网关(无需真实 Key),
|
||||
真实跑完向导 4 步,断言:
|
||||
1. 确认页出现封面预览行且状态为「AI 按标题和图片生成」
|
||||
1. 确认页出现封面预览行且状态为「AI 封面文案 · 大字发光」
|
||||
2. 生成后时间轴第一个元素是「视频封面」图片、时长 3 秒、在片头
|
||||
3. 字幕从封面之后才开始(第一条字幕 BeginTime >= 3000ms)
|
||||
|
||||
@@ -59,7 +59,12 @@ COPY_JSON = json.dumps({
|
||||
{"text": "第三段测试口播内容收尾总结一下", "image": 3},
|
||||
]
|
||||
}, ensure_ascii=False)
|
||||
COVER_PROMPT = "A striking tech product cover, blue gradient, cinematic light, no text"
|
||||
# 封面文案请求(prompt 带固定标记「生成短视频封面文案」),渲染由本地 canvas 完成
|
||||
COVER_COPY_JSON = json.dumps({
|
||||
"main": "三步搞定封面",
|
||||
"sub": "AI 文案加大字发光描边",
|
||||
"tag": "实测有效",
|
||||
}, ensure_ascii=False)
|
||||
|
||||
|
||||
def install_mock(page, cover_b64):
|
||||
@@ -76,9 +81,9 @@ def install_mock(page, cover_b64):
|
||||
body = req.post_data or ""
|
||||
headers = {"access-control-allow-origin": "*", "content-type": "application/json"}
|
||||
if "chat/completions" in url:
|
||||
# 封面提示词请求的 prompt 里有「做一张封面图」,文案请求有「只输出 JSON」
|
||||
if "做一张封面图" in body:
|
||||
content = COVER_PROMPT
|
||||
# 封面文案请求带固定标记「生成短视频封面文案」,其余是口播文案请求
|
||||
if "生成短视频封面文案" in body:
|
||||
content = COVER_COPY_JSON
|
||||
else:
|
||||
content = COPY_JSON
|
||||
payload = json.dumps({"choices": [{"message": {"content": content}}]})
|
||||
@@ -210,7 +215,7 @@ def main():
|
||||
|
||||
# 断言 1:确认页封面预览行
|
||||
body = page.inner_text(".semi-modal-body")
|
||||
has_cover_row = ("视频封面" in body) and ("AI 按标题和图片生成" in body)
|
||||
has_cover_row = ("视频封面" in body) and ("AI 封面文案" in body) and ("大字发光" in body)
|
||||
has_cover_thumb = page.evaluate("""() => {
|
||||
const img = [...document.querySelectorAll('.semi-modal img')].find(i => (i.alt||'') === '视频封面');
|
||||
return !!(img && img.src && img.src.startsWith('data:image/png'));
|
||||
@@ -243,6 +248,7 @@ def main():
|
||||
} catch (e) { resUrl = 'ERR:' + e; }
|
||||
}
|
||||
return {
|
||||
title: d.title,
|
||||
first: f,
|
||||
coverResourceUrl: resUrl.slice(0, 40),
|
||||
imgCount: imgs.length,
|
||||
@@ -302,7 +308,7 @@ def main():
|
||||
const d = (window.__editor && window.__editor.movie && window.__editor.movie.data) || {};
|
||||
const els = (d.elements || []).slice().sort((a,b) => (a.startTime||0) - (b.startTime||0));
|
||||
const f = els[0] || {};
|
||||
return { firstName: f.name, firstT: f.startTime, firstD: f.duration,
|
||||
return { title: d.title, firstName: f.name, firstT: f.startTime, firstD: f.duration,
|
||||
els: els.length, caps: (d.captions||[]).length };
|
||||
}""")
|
||||
log("刷新后: " + json.dumps(after, ensure_ascii=False))
|
||||
@@ -311,6 +317,27 @@ def main():
|
||||
and after.get("firstT") is not None and abs(float(after.get("firstT"))) < 0.01
|
||||
)
|
||||
|
||||
# 断言:用户输入的标题 → 项目文件名(顶栏 title + 刷新后持久化)
|
||||
res_title = res.get("title")
|
||||
log("构建后 title: %s" % res_title)
|
||||
# AI 出片项目文件名须带【AI】前缀
|
||||
checks["title_applied_after_build"] = res_title == "【AI】封面功能端到端验证"
|
||||
checks["title_persist_after_reload"] = after.get("title") == "【AI】封面功能端到端验证"
|
||||
# 项目列表卡片名(meta.name)
|
||||
meta_name = page.evaluate("""async () => {
|
||||
try {
|
||||
const rq = indexedDB.open('H5VideoLocalDB');
|
||||
const db = await new Promise((res, rej) => { rq.onsuccess = () => res(rq.result); rq.onerror = () => rej(rq.error); });
|
||||
const id = window.__editor && window.__editor.appid;
|
||||
const tx = db.transaction('projects', 'readonly');
|
||||
const g = tx.objectStore('projects').get(id);
|
||||
const rec = await new Promise((res, rej) => { g.onsuccess = () => res(g.result); g.onerror = () => rej(g.error); });
|
||||
return (rec && rec.name) || '';
|
||||
} catch (e) { return 'ERR:' + e; }
|
||||
}""")
|
||||
log("项目卡片名: %s" % meta_name)
|
||||
checks["project_card_name"] = meta_name == "【AI】封面功能端到端验证"
|
||||
|
||||
ok = all(checks.values())
|
||||
print(json.dumps({"ok": ok, "checks": checks, "errors": errors[-5:]}, ensure_ascii=False))
|
||||
browser.close()
|
||||
|
||||
@@ -116,6 +116,15 @@ const Header = (props: IProps) => {
|
||||
>
|
||||
MCP 使用说明
|
||||
</NavLink>
|
||||
{/* 更多素材:外部资源站(MinDoc 文档),新窗口打开 */}
|
||||
<a
|
||||
href="https://doc.88531.cn/docs/mrfx/mrfx-1g99qum57n5qk"
|
||||
className={styles.text}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
更多素材
|
||||
</a>
|
||||
{/* <a
|
||||
href={languageType === 'en-US' ? '/docs/en' : '/docs'}
|
||||
target="_blank"
|
||||
|
||||
@@ -20,7 +20,7 @@ import Project from './Project';
|
||||
import { language, Intl } from '@language/index';
|
||||
import KeyboardModal from './KeyboardModal';
|
||||
import { stores } from '@stores/index';
|
||||
import { saveProject, canUseLocalSave } from '@services/localStorageService';
|
||||
import { saveProject, canUseLocalSave, updateLocalProjectMeta } from '@services/localStorageService';
|
||||
import HubStatus from '@components/hub';
|
||||
import { AiSettingsButton } from '@components/ai-settings';
|
||||
import { reURL } from '@utils/util';
|
||||
@@ -242,6 +242,18 @@ function Header(props: IProps) {
|
||||
editor.data.title = e.target.value;
|
||||
forceUpdate();
|
||||
}}
|
||||
/* 顶栏改名即项目文件名:失焦立刻写入列表(不等自动保存),
|
||||
否则用户改完名回列表看不到变化,会以为"修改无效" */
|
||||
onBlur={async () => {
|
||||
const t = (editor.data.title || '').trim();
|
||||
if (!t || !editor.appid) return;
|
||||
if (!String(editor.appid).startsWith('local_')) return; // 远程项目由保存链路处理
|
||||
try {
|
||||
await updateLocalProjectMeta(editor.appid, { name: t });
|
||||
} catch (e) {
|
||||
console.warn('同步项目文件名失败:', e);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
{/* <section className={styles.center}></section> */}
|
||||
|
||||
@@ -562,17 +562,19 @@ export default function QuickVideo({
|
||||
setAudio({});
|
||||
setStep(1);
|
||||
Toast.success(`已生成 ${list.length} 段文案`);
|
||||
// 封面还没好就继续等(生图通常几秒到几十秒),失败则用本地标题封面兜底
|
||||
// 封面还没好就继续等(AI 文案 + 本地渲染通常几秒),文案失败则用标题模板兜底
|
||||
const [cv, cerr] = await coverTask;
|
||||
setCoverLoading(false);
|
||||
if (cv) {
|
||||
setCover(cv);
|
||||
Toast.success(cv.local ? '封面已生成(本地标题封面)' : 'AI 封面已生成');
|
||||
setCoverErr(cerr || null);
|
||||
if (cv.local) Toast.warning(`AI 封面文案未成功(${cerr || '未知原因'}),已用标题模板渲染`);
|
||||
else Toast.success('封面已生成(AI 文案 · 大字发光描边)');
|
||||
} else {
|
||||
const fb = makeTitleCover(title.trim());
|
||||
setCover({ url: fb.url, w: fb.w, h: fb.h, local: true });
|
||||
setCoverErr(cerr || 'AI 生图失败');
|
||||
Toast.warning(`AI 封面生成失败,已用本地标题封面代替:${cerr || ''}`);
|
||||
setCoverErr(cerr || '封面文案生成失败');
|
||||
Toast.warning(`封面渲染失败,已用本地标题封面代替:${cerr || ''}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -770,6 +772,32 @@ export default function QuickVideo({
|
||||
if (captions.length) editor.setContorlAndSelectedElemenent?.([]);
|
||||
|
||||
const transCount = fxTrans === 'none' ? 0 : Math.max(0, segs.length - 1);
|
||||
|
||||
// 项目文件名 = 用户输入的标题:顶栏标题、工程数据、项目列表卡片名三处同步
|
||||
// AI 出片的项目文件名带【AI】标识(已带前缀则不重复叠加)
|
||||
const rawTitle = title.trim();
|
||||
const projTitle = rawTitle ? (rawTitle.startsWith('【AI】') ? rawTitle : `【AI】${rawTitle}`) : '';
|
||||
if (projTitle) {
|
||||
editor.data.title = projTitle;
|
||||
// movie.data 若是独立引用,一并改掉(保存走 sortZIndexNewData)
|
||||
const md: any = (editor as any).movie?.data;
|
||||
if (md && md !== editor.data) md.title = projTitle;
|
||||
try {
|
||||
if (typeof (editor as any).saveApp === 'function') {
|
||||
await (editor as any).saveApp();
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[qv] 保存标题失败', e);
|
||||
}
|
||||
try {
|
||||
// 本地模式:项目卡片名存的是 meta.name(saveProject 不会用 title 覆盖),需单独同步
|
||||
const { updateLocalProjectMeta } = await import('@services/localStorageService');
|
||||
await updateLocalProjectMeta(editor.appid, { name: projTitle }).catch(() => {});
|
||||
} catch (e) {
|
||||
console.warn('[qv] 同步项目名失败', e);
|
||||
}
|
||||
}
|
||||
|
||||
Toast.success(
|
||||
(cover ? '封面 + ' : '') +
|
||||
`已生成 ${segs.length} 段:图片${fxMotion === 'none' ? '' : '(带动效)'}、配音、字幕已就位` +
|
||||
@@ -1256,19 +1284,19 @@ export default function QuickVideo({
|
||||
<div>
|
||||
{coverLoading ? (
|
||||
<>
|
||||
<Spin size="small" /> AI 正在根据标题和图片生成封面…
|
||||
<Spin size="small" /> AI 正在生成封面文案与大字封面…
|
||||
</>
|
||||
) : cover ? (
|
||||
<>
|
||||
视频封面 · 片头 <b>{COVER_DUR}</b> 秒 ·{' '}
|
||||
<b>{cover.local ? '本地标题封面' : 'AI 按标题和图片生成'}</b>
|
||||
<b>{cover.local ? '本地标题模板' : 'AI 封面文案 · 大字发光'}</b>
|
||||
</>
|
||||
) : (
|
||||
'未生成封面'
|
||||
)}
|
||||
</div>
|
||||
{coverErr && !coverLoading && (
|
||||
<div style={{ color: '#d4380d' }}>AI 生图失败({coverErr}),已用本地封面代替</div>
|
||||
<div style={{ color: '#d4380d' }}>封面文案生成失败({coverErr}),已用标题模板渲染</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -115,9 +115,16 @@ export default function Draft(props: IProps) {
|
||||
</a>
|
||||
<input
|
||||
title={language.val('draft_name_input')}
|
||||
placeholder={language.val('draft_name_input')}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
e.stopPropagation();
|
||||
}}
|
||||
onFocus={e => {
|
||||
currentName.current = e.target.value;
|
||||
e.currentTarget.select();
|
||||
}}
|
||||
onClick={e => e.stopPropagation()}
|
||||
onBlur={async e => {
|
||||
if (e.target.value === currentName.current) return;
|
||||
item.name = e.target.value;
|
||||
|
||||
@@ -18,10 +18,32 @@
|
||||
|
||||
.name {
|
||||
margin-top: 10px;
|
||||
border: none;
|
||||
border: 1px solid transparent;
|
||||
width: 100%;
|
||||
background: transparent;
|
||||
color: var(--theme-text);
|
||||
cursor: text;
|
||||
border-radius: 6px;
|
||||
padding: 4px 6px;
|
||||
font-size: 14px;
|
||||
line-height: 1.4;
|
||||
transition: background 0.2s, border-color 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: var(--theme-wateritem);
|
||||
border-color: var(--theme-main);
|
||||
}
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
background: var(--theme-wateritem);
|
||||
border-color: var(--theme-main);
|
||||
}
|
||||
|
||||
&::placeholder {
|
||||
color: var(--theme-text);
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
.pic {
|
||||
|
||||
@@ -651,9 +651,12 @@ const projectFileQueue = new Map<string, Promise<void>>();
|
||||
/** 保存项目数据 */
|
||||
export async function saveProject(appId: string, data: any): Promise<void> {
|
||||
const existing = await localDB.projects.get(appId);
|
||||
/* 项目文件名跟随工程标题:顶栏改的是 data.title,此前保存时 name 恒取旧值,
|
||||
导致顶栏改名对列表文件名完全无效。title 为空则沿用原名。 */
|
||||
const titleName = typeof data?.title === 'string' && data.title.trim() ? data.title : '';
|
||||
await localDB.projects.put({
|
||||
id: appId,
|
||||
name: existing?.name || data?.name || 'Untitled',
|
||||
name: titleName || existing?.name || data?.name || 'Untitled',
|
||||
categoryId: existing?.categoryId || data?.categoryId || '0',
|
||||
thumb: existing?.thumb || data?.thumb || '',
|
||||
description: existing?.description || data?.description || '',
|
||||
@@ -826,7 +829,14 @@ export async function updateLocalProjectMeta(
|
||||
): Promise<[any, string | null]> {
|
||||
const record = await localDB.projects.get(id);
|
||||
if (!record) return [null, '项目不存在'];
|
||||
if (params.name !== undefined) record.name = params.name;
|
||||
if (params.name !== undefined) {
|
||||
record.name = params.name;
|
||||
/* 文件名与工程标题双向一致:列表改名时同步 data.title,
|
||||
否则打开编辑器顶栏仍显示旧标题(两处各存各的会分叉) */
|
||||
if (params.name && record.data && typeof record.data === 'object') {
|
||||
(record.data as any).title = params.name;
|
||||
}
|
||||
}
|
||||
if (params.category_id !== undefined) record.categoryId = String(params.category_id);
|
||||
if (params.thumb !== undefined) record.thumb = params.thumb;
|
||||
if (params.description !== undefined) record.description = params.description;
|
||||
|
||||
+265
-86
@@ -4,7 +4,7 @@
|
||||
* - 文案:用户在「AI 设置」填的对话模型(带图时直接用该模型,需其支持图片输入)
|
||||
* - 配音:本机 unicut-tts(edge-tts),走同源 /localtts 反代,无需登录、无需密钥
|
||||
*/
|
||||
import { aiVisionAvailable, localChatCompletion, localGenerateImage } from '@utils/localAi';
|
||||
import { aiVisionAvailable, localChatCompletion } from '@utils/localAi';
|
||||
|
||||
/** 一段口播 = 一句文案 + 对应第几张图(1 基) */
|
||||
export interface QvSegment {
|
||||
@@ -205,124 +205,303 @@ export async function generateQuickVideoCopy(params: {
|
||||
return [{ title: params.title, segments }, null];
|
||||
}
|
||||
|
||||
/** 封面图:AI 根据标题 + 素材(图片/正文)写提示词再文生图 */
|
||||
/** 封面文案:AI 根据标题 + 素材写吸引人的封面文字(主标题 / 副标题 / 角标) */
|
||||
export interface QvCoverCopy {
|
||||
/** 主标题:突出重点、抓眼球,≤12 字 */
|
||||
main: string;
|
||||
/** 副标题 / 钩子句,写出特色,≤18 字 */
|
||||
sub?: string;
|
||||
/** 角标短词,≤6 字(如「实测有效」「保姆级教程」) */
|
||||
tag?: string;
|
||||
/** true = AI 生成;false = 本地标题模板兜底 */
|
||||
ai?: boolean;
|
||||
}
|
||||
|
||||
export interface QvCover {
|
||||
url: string;
|
||||
w: number;
|
||||
h: number;
|
||||
/** true = 本地标题封面兜底(AI 生图失败时),false = AI 生成 */
|
||||
/** true = AI 文案失败,用标题模板兜底渲染 */
|
||||
local?: boolean;
|
||||
/** 渲染进封面的文案 */
|
||||
copy?: QvCoverCopy;
|
||||
}
|
||||
|
||||
/** 量图片真实尺寸(加载失败抛错,调用方兜底) */
|
||||
function measureImage(url: string): Promise<{ w: number; h: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
const timer = setTimeout(() => reject(new Error('封面图片加载超时')), 15000);
|
||||
img.onload = () => {
|
||||
clearTimeout(timer);
|
||||
resolve({ w: img.naturalWidth || 1280, h: img.naturalHeight || 720 });
|
||||
};
|
||||
img.onerror = () => {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('封面图片加载失败'));
|
||||
};
|
||||
img.src = url;
|
||||
});
|
||||
/** 封面文案请求的固定标记(E2E mock 按它区分请求) */
|
||||
export const COVER_COPY_MARK = '生成短视频封面文案';
|
||||
|
||||
/** 量图片尺寸(取不到按 16:9 兜底) */
|
||||
function measureImage(img: HTMLImageElement): { w: number; h: number } {
|
||||
const w = Number(img.naturalWidth) || 0;
|
||||
const h = Number(img.naturalHeight) || 0;
|
||||
return { w: w > 0 ? w : 1280, h: h > 0 ? h : 720 };
|
||||
}
|
||||
|
||||
/** 远程图片尽量转 data URL,避免工程保存后生图链接过期导致封面裂图;失败保持原地址 */
|
||||
/** 远程图片转 data URL(失败返回空串,调用方退回无背景渲染) */
|
||||
async function toDataUrl(url: string): Promise<string> {
|
||||
if (!url || url.startsWith('data:')) return url;
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) return url;
|
||||
if (!res.ok) return '';
|
||||
const blob = await res.blob();
|
||||
if (!blob.size || blob.size > 8 * 1024 * 1024) return url;
|
||||
return await new Promise<string>((resolve, reject) => {
|
||||
return await new Promise<string>(resolve => {
|
||||
const fr = new FileReader();
|
||||
fr.onload = () => resolve(String(fr.result));
|
||||
fr.onerror = () => reject(new Error('read fail'));
|
||||
fr.onload = () => resolve(String(fr.result || ''));
|
||||
fr.onerror = () => resolve('');
|
||||
fr.readAsDataURL(blob);
|
||||
});
|
||||
} catch (e) {
|
||||
return url;
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/** 本地模板兜底文案:标题直接当主标题,素材首句当副标题 */
|
||||
function templateCoverCopy(params: { title: string; sourceText?: string }): QvCoverCopy {
|
||||
const main = params.title.trim().slice(0, 14) || '未命名视频';
|
||||
const first = (params.sourceText || '').split(/[。!?!?.\n]/).map(s => s.trim()).find(s => s.length > 4);
|
||||
return { main, sub: first ? first.slice(0, 18) : undefined, ai: false };
|
||||
}
|
||||
|
||||
/**让模型根据标题/素材写封面文案(可带首图帮助理解画面),失败返回 [null, 错误] */
|
||||
async function askCoverCopy(params: {
|
||||
title: string;
|
||||
images?: string[];
|
||||
sourceText?: string;
|
||||
}): Promise<[QvCoverCopy | null, string | null]> {
|
||||
const useVision = !!params.images?.length && (await aiVisionAvailable());
|
||||
const text =
|
||||
`${COVER_COPY_MARK}。视频标题:${params.title}。\n` +
|
||||
(params.sourceText ? `素材正文节选:${params.sourceText.slice(0, 800)}。\n` : '') +
|
||||
'要求:写出现在最吸引人点击的封面文字,突出重点、有特色、口语化有钩子。\n' +
|
||||
'输出 JSON:{"main":"主标题,≤12字,必须突出重点","sub":"副标题/钩子句,≤18字,写出特色","tag":"角标短词,≤6字,可留空"}\n' +
|
||||
'只输出 JSON,不要任何解释。';
|
||||
const content: any[] = [{ type: 'text', text }];
|
||||
if (useVision) {
|
||||
content.push({ type: 'image_url', image_url: { url: await shrinkImageForVision(params.images![0], 640) } });
|
||||
}
|
||||
const [res, err] = await localChatCompletion({
|
||||
messages: [
|
||||
{ role: 'system', content: '你是短视频封面文案专家,只输出 JSON。' },
|
||||
{ role: 'user', content: useVision ? content : text },
|
||||
],
|
||||
});
|
||||
if (err) return [null, err];
|
||||
const raw = res?.choices?.[0]?.message?.content;
|
||||
const json = parseJsonLoose<{ main?: any; sub?: any; tag?: any }>(typeof raw === 'string' ? raw : raw?.content || '');
|
||||
const main = String(json?.main || '').replace(/\s+/g, '').trim().slice(0, 16);
|
||||
if (!main) return [null, '模型没有返回封面文案'];
|
||||
const sub = String(json?.sub || '').replace(/\s+/g, '').trim().slice(0, 24) || undefined;
|
||||
const tag = String(json?.tag || '').replace(/\s+/g, '').trim().slice(0, 8) || undefined;
|
||||
return [{ main, sub, tag, ai: true }, null];
|
||||
}
|
||||
|
||||
/** 加载图片(失败 resolve null) */
|
||||
function loadImage(src: string): Promise<HTMLImageElement | null> {
|
||||
return new Promise(resolve => {
|
||||
try {
|
||||
const img = new Image();
|
||||
img.onload = () => resolve(img);
|
||||
img.onerror = () => resolve(null);
|
||||
img.src = src;
|
||||
} catch (e) {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 按最大宽度缩字号(保证文字不出画) */
|
||||
function fitFont(ctx: CanvasRenderingContext2D, text: string, maxW: number, start: number, min: number, weight = '900'): number {
|
||||
let size = start;
|
||||
ctx.font = `${weight} ${size}px "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`;
|
||||
while (size > min && ctx.measureText(text).width > maxW) {
|
||||
size -= 4;
|
||||
ctx.font = `${weight} ${size}px "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成视频封面(根据标题和素材图片,AI 自动生成一张封面图)
|
||||
*
|
||||
* 三级降级,保证封面永远能出:
|
||||
* 1. 视觉模型看图 + 标题/正文 → 输出英文生图提示词
|
||||
* 2. 纯文本模型(按标题/正文)→ 输出提示词
|
||||
* 3. 都失败 → 用标题拼一条模板提示词
|
||||
* 生图也降级:先试 16:9(1280x720),失败回退网关默认尺寸;再失败返回 null,
|
||||
* 由调用方用本地 makeTitleCover 兜底。
|
||||
* 大字发光描边绘制:先画发光层(shadowBlur),再描边,最后实心填充,文字突出重点
|
||||
*/
|
||||
function drawGlowStrokeText(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
text: string,
|
||||
x: number,
|
||||
y: number,
|
||||
size: number,
|
||||
fill: string,
|
||||
stroke: string,
|
||||
glow: string,
|
||||
weight = '900',
|
||||
) {
|
||||
ctx.font = `${weight} ${size}px "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.lineJoin = 'round';
|
||||
// 发光层:同色文字带大模糊阴影画两遍,亮度更足
|
||||
ctx.save();
|
||||
ctx.shadowColor = glow;
|
||||
ctx.shadowBlur = Math.max(18, size * 0.35);
|
||||
ctx.fillStyle = fill;
|
||||
ctx.fillText(text, x, y);
|
||||
ctx.fillText(text, x, y);
|
||||
ctx.restore();
|
||||
// 描边层
|
||||
ctx.strokeStyle = stroke;
|
||||
ctx.lineWidth = Math.max(4, size * 0.14);
|
||||
ctx.strokeText(text, x, y);
|
||||
// 实心填充
|
||||
ctx.fillStyle = fill;
|
||||
ctx.fillText(text, x, y);
|
||||
}
|
||||
|
||||
/** 本地渲染封面:素材图背景(暗化)或渐变底 + AI 文案大字发光描边 */
|
||||
async function renderCover(copy: QvCoverCopy, bgDataUrl?: string): Promise<{ url: string; w: number; h: number }> {
|
||||
const W = 1280;
|
||||
const H = 720;
|
||||
const cv = document.createElement('canvas');
|
||||
cv.width = W;
|
||||
cv.height = H;
|
||||
const ctx = cv.getContext('2d');
|
||||
if (!ctx) throw new Error('canvas 不可用');
|
||||
|
||||
const bg = bgDataUrl ? await loadImage(bgDataUrl) : null;
|
||||
if (bg && (bg.naturalWidth || bg.width)) {
|
||||
const { w: iw, h: ih } = measureImage(bg);
|
||||
const scale = Math.max(W / iw, H / ih);
|
||||
const dw = iw * scale;
|
||||
const dh = ih * scale;
|
||||
ctx.drawImage(bg, (W - dw) / 2, (H - dh) / 2, dw, dh);
|
||||
// 暗化渐变蒙版,保证文字可读
|
||||
const veil = ctx.createLinearGradient(0, 0, 0, H);
|
||||
veil.addColorStop(0, 'rgba(8,10,30,0.42)');
|
||||
veil.addColorStop(0.5, 'rgba(8,10,30,0.58)');
|
||||
veil.addColorStop(1, 'rgba(8,10,30,0.78)');
|
||||
ctx.fillStyle = veil;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
} else {
|
||||
// 无背景:深色渐变 + 光斑,质感不输生图
|
||||
const g = ctx.createLinearGradient(0, 0, W, H);
|
||||
g.addColorStop(0, '#101a4d');
|
||||
g.addColorStop(0.55, '#25124f');
|
||||
g.addColorStop(1, '#0b1030');
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
const blob = (cx: number, cy: number, r: number, c: string) => {
|
||||
const rg = ctx.createRadialGradient(cx, cy, 0, cx, cy, r);
|
||||
rg.addColorStop(0, c);
|
||||
rg.addColorStop(1, 'rgba(0,0,0,0)');
|
||||
ctx.fillStyle = rg;
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, r, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
};
|
||||
blob(220, 160, 380, 'rgba(88,120,255,0.35)');
|
||||
blob(1080, 560, 420, 'rgba(255,95,140,0.28)');
|
||||
blob(640, 360, 460, 'rgba(255,196,64,0.14)');
|
||||
}
|
||||
|
||||
const main = copy.main || '视频封面';
|
||||
const sub = (copy.sub || '').slice(0, 24);
|
||||
const tag = (copy.tag || '').slice(0, 8);
|
||||
|
||||
// 主标题:可拆两行,字号尽量大
|
||||
let lines = [main];
|
||||
if (main.length > 9) {
|
||||
const cut = Math.ceil(main.length / 2);
|
||||
lines = [main.slice(0, cut), main.slice(cut)];
|
||||
}
|
||||
const mainSize = fitFont(ctx, lines.reduce((a, b) => (a.length > b.length ? a : b)), W - 180, lines.length > 1 ? 132 : 168, 72);
|
||||
const lineH = mainSize * 1.2;
|
||||
|
||||
const tagH = tag ? 66 : 0;
|
||||
const subSize = sub ? fitFont(ctx, sub, W - 240, 62, 36, '800') : 0;
|
||||
const subGap = sub ? 40 : 0;
|
||||
const totalH = tagH + 34 + lines.length * lineH + subGap + (sub ? subSize : 0);
|
||||
let cursorY = (H - totalH) / 2 + tagH / 2;
|
||||
|
||||
// 角标胶囊
|
||||
if (tag) {
|
||||
const tagSize = 40;
|
||||
ctx.font = `900 ${tagSize}px "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif`;
|
||||
const tw = ctx.measureText(tag).width;
|
||||
const pw = tw + 80;
|
||||
const ph = 66;
|
||||
const px = W / 2 - pw / 2;
|
||||
const py = cursorY - ph / 2;
|
||||
const r = ph / 2;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(px + r, py);
|
||||
ctx.arcTo(px + pw, py, px + pw, py + ph, r);
|
||||
ctx.arcTo(px + pw, py + ph, px, py + ph, r);
|
||||
ctx.arcTo(px, py + ph, px, py, r);
|
||||
ctx.arcTo(px, py, px + pw, py, r);
|
||||
ctx.closePath();
|
||||
ctx.save();
|
||||
ctx.shadowColor = 'rgba(255,196,64,0.85)';
|
||||
ctx.shadowBlur = 26;
|
||||
const bgg = ctx.createLinearGradient(px, py, px + pw, py + ph);
|
||||
bgg.addColorStop(0, '#ffd166');
|
||||
bgg.addColorStop(1, '#ff9f43');
|
||||
ctx.fillStyle = bgg;
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
ctx.fillStyle = '#3a1d00';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(tag, W / 2, cursorY + 2);
|
||||
cursorY += ph / 2 + 34;
|
||||
}
|
||||
|
||||
// 主标题(发光 + 描边 + 实心,突出重点)
|
||||
const mainFill = '#ffffff';
|
||||
const mainStroke = 'rgba(6,8,24,0.92)';
|
||||
lines.forEach((ln, i) => {
|
||||
drawGlowStrokeText(ctx, ln, W / 2, cursorY + lineH / 2 + i * lineH, mainSize, mainFill, mainStroke, 'rgba(120,170,255,0.95)');
|
||||
});
|
||||
cursorY += lines.length * lineH + subGap;
|
||||
|
||||
// 副标题(暖色发光描边,次级重点)
|
||||
if (sub) {
|
||||
drawGlowStrokeText(ctx, sub, W / 2, cursorY + subSize / 2, subSize, '#ffe9a8', 'rgba(6,8,24,0.9)', 'rgba(255,196,64,0.9)', '800');
|
||||
}
|
||||
|
||||
const url = cv.toDataURL('image/png');
|
||||
if (!url || !url.startsWith('data:image/')) throw new Error('封面画布导出失败');
|
||||
return { url, w: W, h: H };
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动封面:AI 根据标题/素材写吸引人的封面文案(主标题+副标题+角标),
|
||||
* 再本地渲染成大字发光描边封面(素材图作背景),不再依赖文生图。
|
||||
* @param params 标题 / 素材图 / 素材正文
|
||||
* @returns [封面, 错误];文案生成失败时仍返回模板兜底封面(local=true)
|
||||
*/
|
||||
export async function generateQuickVideoCover(params: {
|
||||
title: string;
|
||||
images: string[];
|
||||
images?: string[];
|
||||
sourceText?: string;
|
||||
}): Promise<[QvCover | null, string | null]> {
|
||||
const title = (params.title || '').trim() || '我的短视频';
|
||||
const images = params.images || [];
|
||||
const sourceText = (params.sourceText || '').trim();
|
||||
|
||||
const askPrompt = async (withImages: boolean): Promise<string> => {
|
||||
const lines = [
|
||||
`我要给短视频《${title}》做一张封面图。`,
|
||||
sourceText ? `素材正文开头:${sourceText.slice(0, 400)}` : '',
|
||||
'请输出一条给文生图模型的英文提示词(一句话):描述封面画面的主体、构图、风格与色调,要贴合标题和素材内容,画面有吸引力;',
|
||||
'画面里不要出现任何文字、字母、数字、水印、logo。',
|
||||
'只输出提示词本身,不要引号、不要解释、不要换行。',
|
||||
].filter(Boolean);
|
||||
const content: any[] = [{ type: 'text', text: lines.join('\n') }];
|
||||
if (withImages) {
|
||||
for (const img of images.slice(0, 4)) {
|
||||
try {
|
||||
content.push({ type: 'image_url', image_url: { url: await shrinkImageForVision(img, 640) } });
|
||||
} catch (e) {
|
||||
// 单张图压缩失败不影响其余
|
||||
}
|
||||
}
|
||||
}
|
||||
const [r, e] = await localChatCompletion({
|
||||
messages: [{ role: 'user', content }],
|
||||
});
|
||||
if (e || !r) throw new Error(e || '提示词生成失败');
|
||||
const raw = r?.choices?.[0]?.message?.content;
|
||||
const text = String(typeof raw === 'string' ? raw : raw?.content || '').trim();
|
||||
if (!text) throw new Error('模型没有返回提示词');
|
||||
return text.replace(/^["'「]+|["'」]+$/g, '').slice(0, 600);
|
||||
};
|
||||
|
||||
let prompt = '';
|
||||
try {
|
||||
prompt = await askPrompt(images.length > 0 && (await aiVisionAvailable()));
|
||||
} catch (e1) {
|
||||
let copy: QvCoverCopy | null = null;
|
||||
let copyErr: string | null = null;
|
||||
if (params.title.trim()) {
|
||||
try {
|
||||
prompt = await askPrompt(false);
|
||||
} catch (e2) {
|
||||
prompt = `A striking short video cover about "${title}", clean composition, vibrant colors, cinematic lighting, no text`;
|
||||
console.warn('[qv] 封面提示词三级降级到模板:', e1, e2);
|
||||
[copy, copyErr] = await askCoverCopy(params);
|
||||
} catch (e: any) {
|
||||
copyErr = e?.message || String(e);
|
||||
}
|
||||
}
|
||||
if (!copy) copy = templateCoverCopy(params);
|
||||
|
||||
let [img, err] = await localGenerateImage({ prompt, size: '1280x720' });
|
||||
if (err || !img) {
|
||||
console.warn('[qv] 封面 16:9 生图失败,回退默认尺寸:', err);
|
||||
[img, err] = await localGenerateImage({ prompt });
|
||||
}
|
||||
if (err || !img) return [null, err || '封面生成失败'];
|
||||
// 背景优先用第一张素材图(转 data URL 避免画布跨域污染)
|
||||
let bg = '';
|
||||
const first = params.images?.length ? params.images[0] : '';
|
||||
if (first) bg = first.startsWith('data:') ? first : await toDataUrl(first);
|
||||
|
||||
try {
|
||||
const url = await toDataUrl(img.url);
|
||||
const dim = await measureImage(url);
|
||||
return [{ url, w: dim.w, h: dim.h }, null];
|
||||
const out = await renderCover(copy, bg || undefined);
|
||||
return [{ ...out, local: !copy.ai, copy }, copyErr];
|
||||
} catch (e: any) {
|
||||
// 尺寸量不到也照样能插时间轴(用 16:9 默认值)
|
||||
return [{ url: img.url, w: 1280, h: 720 }, null];
|
||||
return [null, copyErr || e?.message || String(e)];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user