{{ message }}
Repository navigation
Expand file tree
/
Copy pathrun-video-subtitle-settings-test.cjs
More file actions
368 lines (347 loc) · 20.6 KB
/
Copy pathrun-video-subtitle-settings-test.cjs
File metadata and controls
368 lines (347 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#!/usr/bin/env node
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const {createRequire} = require('node:module');
function fail(message) { throw new Error(message); }
let newPageWithoutForeground;
function args(argv) {
const result = {
extensionDir: '',
artifactsDir: '/private/tmp/video-subtitle-settings-proof',
playwrightRoot: '',
browserPath: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
focusSafeHelper: '',
extensionInstall: 'cdp',
background: true,
};
for (let index = 0; index < argv.length; index += 1) {
const token = argv[index];
if (token === '--headed') { result.background = false; continue; }
if (!token.startsWith('--')) fail(`无法识别参数:${token}`);
const key = token.slice(2).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
const value = argv[index + 1];
if (!value || value.startsWith('--')) fail(`参数缺少值:${token}`);
result[key] = value;
index += 1;
}
if (!result.extensionDir) fail('必须传入 --extension-dir');
if (!result.focusSafeHelper) fail('必须传入 --focus-safe-helper');
return result;
}
function loadPlaywright(root) {
try { return require('playwright'); } catch (error) {
if (!root) throw error;
return createRequire(path.join(path.resolve(root), '__fluentread_settings_loader__.cjs'))('playwright');
}
}
async function waitWorker(context, manifest, timeout = 30000) {
const worker = await new Promise((resolve, reject) => {
let settled = false;
let timer;
const finish = (candidate, error = null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
context.off('serviceworker', onWorker);
error ? reject(error) : resolve(candidate);
};
const check = async candidate => {
if (settled) return;
try {
const loaded = await candidate.evaluate(() => chrome.runtime.getManifest());
if (loaded?.action?.default_popup === manifest.action?.default_popup
&& (loaded?.options_ui?.page || loaded?.options_page) === (manifest.options_ui?.page || manifest.options_page)) {
finish(candidate);
}
} catch {
// Ignore unrelated or already-destroyed workers.
}
};
const onWorker = candidate => { void check(candidate); };
try {
context.on('serviceworker', onWorker);
timer = setTimeout(() => finish(null, new Error('等待 FluentRead 扩展 worker 超时')), timeout);
const candidates = context.serviceWorkers();
const scan = async () => {
for (const candidate of candidates) {
if (settled) return;
await check(candidate);
}
};
void scan().catch(error => finish(null, error));
} catch (error) {
finish(null, error);
}
});
const match = worker.url().match(/^chrome-extension:\/\/([^/]+)/);
if (!match) fail(`扩展 worker URL 无法解析:${worker.url()}`);
return {worker, extensionId: match[1]};
}
async function openExtensionPage(context, url, viewport) {
const page = await newPageWithoutForeground(context, 10000);
await page.setViewportSize(viewport);
await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 30000});
return page;
}
async function screenshot(page, file) {
await page.screenshot({path: file, fullPage: true});
}
async function selectOptionsVideo(page) {
const nav = page.locator('button[data-section="settings-video"]');
await nav.waitFor({state: 'visible', timeout: 30000});
await nav.click();
await page.locator('#settings-video').waitFor({state: 'visible', timeout: 30000});
}
async function setRange(page, label, value) {
// 字号同时有滑块和数字输入框,两者共用可访问名称;这里操作滑块。
const input = page.locator(`input[type="range"][aria-label="${label}"]`);
const aligned = await input.evaluate((element, requested) => {
const min = Number(element.getAttribute('min') || requested);
const max = Number(element.getAttribute('max') || requested);
const step = Number(element.getAttribute('step') || 1);
return Math.min(max, Math.max(min, min + Math.round((requested - min) / step) * step));
}, value);
await input.fill(String(aligned));
await input.dispatchEvent('change');
}
async function selectVideoSourceLanguage(page, label) {
const combobox = page.getByRole('combobox', {name: '视频原语言'});
await combobox.click({force: true});
const option = page.locator('[role="option"]:visible').filter({hasText: label}).first();
await option.waitFor({state: 'visible', timeout: 30000});
await option.click();
}
async function selectedVideoSourceLanguage(page) {
return page.locator('#settings-video [role="combobox"][aria-label="视频原语言"]')
.evaluate(element => element.closest('.el-select')?.querySelector('.el-select__selected-item:not(.el-select__input-wrapper)')?.textContent?.trim() || '');
}
async function main() {
const options = args(process.argv.slice(2));
const playwright = loadPlaywright(options.playwrightRoot);
const focusSafeBrowser = require(path.resolve(options.focusSafeHelper));
const {launchFocusSafePersistentContext} = focusSafeBrowser;
newPageWithoutForeground = focusSafeBrowser.newPageWithoutForeground;
const extensionDir = path.resolve(options.extensionDir);
const manifest = JSON.parse(fs.readFileSync(path.join(extensionDir, 'manifest.json'), 'utf8'));
const popupPath = manifest.action?.default_popup || manifest.browser_action?.default_popup;
const optionsPath = manifest.options_ui?.page || manifest.options_page;
if (!popupPath || !optionsPath) fail('清单缺少 popup/options entrypoint');
fs.mkdirSync(options.artifactsDir, {recursive: true});
const profileDir = fs.mkdtempSync(path.join(os.tmpdir(), 'fluentread-video-settings-'));
const result = {
success: false,
extensionDir,
profileDir,
launchMode: null,
focusPolicy: null,
windowPlacement: null,
skinCases: [],
persistence: {},
popup: {},
screenshots: [],
consoleErrors: [],
};
let session;
let launchAttempted = false;
try {
launchAttempted = true;
session = await launchFocusSafePersistentContext({
chromium: playwright.chromium,
profileDir,
browserPath: options.browserPath,
headless: false,
background: options.background,
displayTarget: 'secondary',
viewport: {width: 1440, height: 1000},
browserArgs: [
...(options.extensionInstall === 'cdp'
? ['--enable-unsafe-extension-debugging']
: [`--disable-extensions-except=${extensionDir}`, `--load-extension=${extensionDir}`]),
'--no-first-run',
'--no-default-browser-check',
],
timeout: 30000,
});
result.launchMode = session.launchMode;
result.focusPolicy = session.focusPolicy;
result.windowPlacement = session.windowPlacement;
let extensionId;
if (options.extensionInstall === 'cdp') {
const extensionSession = await session.context.browser().newBrowserCDPSession();
extensionId = (await extensionSession.send('Extensions.loadUnpacked', {path: extensionDir})).id;
await extensionSession.detach();
}
extensionId ||= (await waitWorker(session.context, manifest)).extensionId;
const optionsUrl = `chrome-extension://${extensionId}/${optionsPath}`;
const popupUrl = `chrome-extension://${extensionId}/${popupPath}`;
const optionsPage = await openExtensionPage(session.context, optionsUrl, {width: 1440, height: 1000});
optionsPage.on('console', message => { if (message.type() === 'error') result.consoleErrors.push(message.text()); });
optionsPage.on('pageerror', error => result.consoleErrors.push(error.message));
await optionsPage.locator('.settings-app').waitFor({state: 'visible', timeout: 30000});
await selectOptionsVideo(optionsPage);
const translationToggle = optionsPage.locator('#settings-video [aria-label="视频字幕翻译"]');
if (await translationToggle.getAttribute('aria-checked') !== 'true') {
await translationToggle.locator('xpath=ancestor::*[contains(@class, "el-switch")]').click({force: true});
}
await optionsPage.evaluate(async () => {
await chrome.storage.local.set({fluentReadVideoLocalTranscriptionModels: ['tiny', 'base']});
await chrome.runtime.sendMessage({
type: 'fluentReadSetVideoAiSubtitleCache',
source: {statusUrl: 'https://x.com/settings-proof/status/123456789', mediaId: 'settings-proof-media'},
model: 'tiny',
videoSourceLanguage: 'ko',
cues: [{startMs: 0, durationMs: 1_200, spokenEndMs: 1_000, text: 'Settings cache proof.'}],
});
});
await optionsPage.reload({waitUntil: 'domcontentloaded'});
await optionsPage.locator('.settings-app').waitFor({state: 'visible', timeout: 30000});
await selectOptionsVideo(optionsPage);
const reloadedTranslationToggle = optionsPage.locator('#settings-video [aria-label="视频字幕翻译"]');
if (await reloadedTranslationToggle.getAttribute('aria-checked') !== 'true') {
await reloadedTranslationToggle.locator('xpath=ancestor::*[contains(@class, "el-switch")]').click({force: true});
}
// 模型状态由后台核对真实缓存文件;只有元数据而没有模型文件时不能显示为已下载。
await optionsPage.waitForFunction(() => {
const status = document.querySelector('.video-model-status')?.textContent || '';
return Boolean(status.trim()) && !status.includes('正在读取模型状态');
}, null, {timeout: 30000});
const modelStatus = (await optionsPage.locator('.video-model-status').textContent() || '').trim();
if (modelStatus.includes('当前模型已下载')) fail(`仅有元数据时不应显示模型已下载:${modelStatus}`);
result.modelState = {fixtureMetadata:true,status:modelStatus,managementCollapsed:false};
await screenshot(optionsPage, path.join(options.artifactsDir, 'options-model-downloaded.png'));
result.screenshots.push(path.join(options.artifactsDir, 'options-model-downloaded.png'));
const modelManagement = optionsPage.locator('.video-model-management');
await modelManagement.locator('.video-model-card').first().waitFor({state: 'visible'});
result.modelDescriptions = await modelManagement.locator('.video-model-description').allTextContents();
await screenshot(optionsPage, path.join(options.artifactsDir, 'options-model-descriptions.png'));
result.screenshots.push(path.join(options.artifactsDir, 'options-model-descriptions.png'));
const skinButtons = optionsPage.locator('[data-video-subtitle-appearance] button[data-skin]');
const skinIds = await skinButtons.evaluateAll(items => items.map(item => item.getAttribute('data-skin')).filter(Boolean));
if (skinIds.length !== 8) fail(`字幕皮肤数量应为 8,实际 ${skinIds.length}`);
for (const skinId of skinIds) {
await optionsPage.locator(`[data-video-subtitle-appearance] button[data-skin="${skinId}"]`).click();
const preview = optionsPage.locator('[data-video-subtitle-preview]');
const style = await preview.getAttribute('style');
if (!style || !style.includes('--fluent-read-video-subtitle-background')) fail(`皮肤 ${skinId} 未更新预览 CSS 变量`);
result.skinCases.push({skinId, style});
}
await setRange(optionsPage, '字幕字号', 130);
await setRange(optionsPage, '字幕底部偏移', 16);
if (await optionsPage.getByRole('checkbox', {name: '移动端 / X 自动贴底'}).isChecked()) fail('手动偏移应关闭移动端 / X 自动贴底');
await setRange(optionsPage, '字幕背景透明度', 44);
await setRange(optionsPage, '字幕行距', 1.45);
await setRange(optionsPage, '字幕最大宽度', 78);
// 位置已改用项目下拉组件,不再是原生 select。
await optionsPage.locator('[data-video-subtitle-appearance]').getByRole('combobox', {name: '字幕位置'}).click({force: true});
await optionsPage.locator('[role="option"]:visible').filter({hasText: '顶部'}).first().click();
if (await optionsPage.locator('[data-video-subtitle-preview-scene]').getAttribute('data-position') !== 'top') fail('字幕位置未切换到顶部');
const reset = optionsPage.getByRole('button', {name: '恢复默认'});
await reset.click();
if (!(await optionsPage.getByRole('checkbox', {name: '移动端 / X 自动贴底'}).isChecked())) fail('恢复默认应启用移动端 / X 自动贴底');
const resetState = await optionsPage.locator('[data-video-subtitle-appearance]').evaluate(element => ({
skin: element.querySelector('[data-skin].selected')?.getAttribute('data-skin'),
fontScale: element.querySelector('input[aria-label="字幕字号"]')?.value,
position: element.querySelector('[data-video-subtitle-preview-scene]')?.getAttribute('data-position'),
}));
if (resetState.skin !== 'classic' || resetState.fontScale !== '100' || resetState.position !== 'bottom') fail(`恢复默认状态不正确:${JSON.stringify(resetState)}`);
// 逐字高亮默认关闭;打开后预览立即出现循环扫光,恢复默认会一并关闭。
const karaokeSwitch = optionsPage.getByRole('switch', {name: '视频字幕逐字高亮'});
const readKaraokePreview = () => optionsPage.locator('[data-video-subtitle-preview]').evaluate(element => Array.from(element.children).map(line => ({
animated: getComputedStyle(line, '::after').animationName !== 'none' && getComputedStyle(line, '::after').content !== 'none',
dimmed: getComputedStyle(line).color.includes('/') || /rgba\(/.test(getComputedStyle(line).color),
})));
result.karaoke = {default: await karaokeSwitch.getAttribute('aria-checked'), defaultPreview: await readKaraokePreview()};
if (result.karaoke.default !== 'false' || result.karaoke.defaultPreview.some(line => line.animated)) fail(`逐字高亮应默认关闭:${JSON.stringify(result.karaoke)}`);
await optionsPage.locator('[data-video-subtitle-karaoke]').click();
result.karaoke.enabledPreview = await readKaraokePreview();
if (result.karaoke.enabledPreview.length !== 2 || result.karaoke.enabledPreview.some(line => !line.animated || !line.dimmed)) fail(`开启逐字高亮后预览没有扫光:${JSON.stringify(result.karaoke)}`);
await optionsPage.locator('[data-video-subtitle-karaoke]').scrollIntoViewIfNeeded();
await optionsPage.waitForTimeout(1300);
await screenshot(optionsPage, path.join(options.artifactsDir, 'options-video-karaoke.png'));
result.screenshots.push(path.join(options.artifactsDir, 'options-video-karaoke.png'));
await reset.click();
if (await karaokeSwitch.getAttribute('aria-checked') !== 'false') fail('恢复默认应关闭逐字高亮');
await optionsPage.locator('[data-video-subtitle-appearance] button[data-skin="terminal"]').click();
await setRange(optionsPage, '字幕字号', 130);
await selectVideoSourceLanguage(optionsPage, '한국어');
await optionsPage.waitForTimeout(500);
result.persistence.beforeClose = await optionsPage.locator('#settings-video').evaluate(element => ({
sourceLanguage: element.querySelector('[role="combobox"][aria-label="视频原语言"]')?.closest('.el-select')?.querySelector('.el-select__selected-item:not(.el-select__input-wrapper)')?.textContent?.trim(),
skin: element.querySelector('[data-video-subtitle-appearance] [data-skin].selected')?.getAttribute('data-skin'),
fontScale: element.querySelector('[data-video-subtitle-appearance] input[aria-label="字幕字号"]')?.value,
enabled: element.querySelector('[aria-label="视频字幕翻译"]')?.getAttribute('aria-checked'),
}));
const cachePanel = optionsPage.locator('[data-video-ai-cache]');
const cacheStatus = await cachePanel.locator('[role="status"]').textContent();
const clearCacheButton = cachePanel.getByRole('button', {name: '清除缓存'});
const cacheBeforeClear = {status: cacheStatus?.trim() || '', disabled: await clearCacheButton.isDisabled()};
if (!cacheBeforeClear.status || !/个视频|读取缓存状态/.test(cacheBeforeClear.status)) fail(`X 字幕缓存状态缺失:${JSON.stringify(cacheBeforeClear)}`);
if (!cacheBeforeClear.disabled) {
await clearCacheButton.click();
await optionsPage.waitForTimeout(250);
if (!(await cachePanel.locator('[role="status"]').textContent())?.includes('0 个视频')) fail('清除 X 字幕缓存后状态未归零');
}
result.persistence.cache = cacheBeforeClear;
await optionsPage.locator('[data-video-subtitle-preview-scene]').scrollIntoViewIfNeeded();
await screenshot(optionsPage, path.join(options.artifactsDir, 'options-video-settings.png'));
result.screenshots.push(path.join(options.artifactsDir, 'options-video-settings.png'));
await optionsPage.setViewportSize({width: 390, height: 844});
await optionsPage.waitForTimeout(100);
await optionsPage.locator('[data-video-subtitle-preview-scene]').scrollIntoViewIfNeeded();
const mobile = await optionsPage.evaluate(() => ({width: document.documentElement.clientWidth, scrollWidth: document.documentElement.scrollWidth}));
result.mobile = mobile;
if (mobile.scrollWidth > mobile.width + 1) fail(`视频设置窄屏横向溢出:${JSON.stringify(mobile)}`);
await screenshot(optionsPage, path.join(options.artifactsDir, 'options-video-settings-mobile.png'));
result.screenshots.push(path.join(options.artifactsDir, 'options-video-settings-mobile.png'));
await optionsPage.close();
const reopenedOptions = await openExtensionPage(session.context, optionsUrl, {width: 1440, height: 1000});
await reopenedOptions.locator('.settings-app').waitFor({state: 'visible', timeout: 30000});
await selectOptionsVideo(reopenedOptions);
const afterClose = await reopenedOptions.locator('#settings-video').evaluate(element => ({
sourceLanguage: element.querySelector('[role="combobox"][aria-label="视频原语言"]')?.closest('.el-select')?.querySelector('.el-select__selected-item:not(.el-select__input-wrapper)')?.textContent?.trim(),
skin: element.querySelector('[data-video-subtitle-appearance] [data-skin].selected')?.getAttribute('data-skin'),
fontScale: element.querySelector('[data-video-subtitle-appearance] input[aria-label="字幕字号"]')?.value,
enabled: element.querySelector('[aria-label="视频字幕翻译"]')?.getAttribute('aria-checked'),
}));
result.persistence.afterReopen = afterClose;
result.persistence.passed = afterClose.sourceLanguage === '한국어' && afterClose.skin === 'terminal' && afterClose.fontScale === '130' && afterClose.enabled === 'true';
if (!result.persistence.passed) fail(`配置重开后未保持:${JSON.stringify(result.persistence)}`);
await reopenedOptions.close();
const popup = await openExtensionPage(session.context, popupUrl, {width: 400, height: 600});
await popup.locator('.popup-shell').waitFor({state: 'visible', timeout: 30000});
const onboarding = popup.locator('[data-testid="ui-language-onboarding"]');
if (await onboarding.count()) {
await onboarding.locator('[data-testid="onboarding-language-step"]').waitFor();
await onboarding.locator('[data-language="zh-CN"]').click();
await onboarding.locator('.onboarding-confirm').click();
await onboarding.waitFor({state: 'hidden', timeout: 30000});
}
// Popup 的快捷功能里已没有视频字幕抽屉;视频设置集中在设置页,这里只记录入口列表。
result.popup = {
quickFeatures: await popup.locator('[data-popup-quick-feature]').evaluateAll(items => items.map(item => item.getAttribute('data-popup-quick-feature'))),
};
if (result.popup.quickFeatures.includes('video')) fail(`Popup 出现了未覆盖的视频入口:${JSON.stringify(result.popup)}`);
await screenshot(popup, path.join(options.artifactsDir, 'popup-video-settings.png'));
result.screenshots.push(path.join(options.artifactsDir, 'popup-video-settings.png'));
await popup.close();
if (result.consoleErrors.length) fail(`UI 控制台存在错误:${result.consoleErrors.join(' | ')}`);
result.success = true;
} catch (error) {
result.error = error instanceof Error ? error.stack || error.message : String(error);
throw error;
} finally {
if (session) {
await session.close();
fs.rmSync(profileDir, {recursive: true, force: true});
} else if (!launchAttempted) {
try {fs.rmdirSync(profileDir);} catch { /* No browser launch was attempted; only remove an empty initial profile. */ }
}
fs.writeFileSync(path.join(options.artifactsDir, 'report.json'), JSON.stringify(result, null, 2));
}
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
}
main().catch(error => {
process.stderr.write(`${error.stack || error}\n`);
process.exitCode = 1;
});
You can’t perform that action at this time.
