Files
mnote/scripts/task145-e20-alignment-smoke.js
2026-05-02 06:25:26 +08:00

180 lines
8.8 KiB
JavaScript

#!/usr/bin/env node
"use strict";
const assert = require("node:assert");
const fs = require("node:fs");
const { chromium } = require("playwright");
const { fetchWithTimeout } = require("./task114-rust-web-gateway-entry-smoke.js");
const BASE_URL = (process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const SCREENSHOT_DIR = process.env.MNOTE_PHASE_E_SCREENSHOT_DIR || "/mnt/Data1T/mnote/tmp/wolai-editor-parity/task145-e20-alignment-local-smoke";
async function readJsonResponse(response, label) {
const text = await response.text();
let payload = null;
try {
payload = text ? JSON.parse(text) : null;
} catch {
throw new Error(`${label} 返回了非 JSON 内容: ${text.slice(0, 1200)}`);
}
assert(response.ok, `${label} 请求失败: ${response.status}; body: ${text.slice(0, 1200)}`);
return payload;
}
async function postTreeCommand(body, label) {
const response = await fetchWithTimeout(`${BASE_URL}/api/tree/commands`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
const payload = await readJsonResponse(response, label);
assert(payload?.result, `${label} 缺少 result`);
return payload.result;
}
async function createTempDocument() {
const title = `task145-e20-align-${Date.now().toString(36)}`;
const result = await postTreeCommand({ action: "create", title }, "创建 E20 临时文档");
assert(result.documentId, "创建 E20 临时文档缺少 documentId");
assert(result.workspaceId, "创建 E20 临时文档缺少 workspaceId");
return { documentId: result.documentId, workspaceId: result.workspaceId, title };
}
async function purgeTempDocument(target) {
if (!target?.documentId || !target?.workspaceId) return;
await postTreeCommand({ action: "purge", workspaceId: target.workspaceId, documentId: target.documentId }, "清理 E20 临时文档");
}
async function loadDocumentContent(target, label) {
const url = `${BASE_URL}/api/documents/content?documentId=${encodeURIComponent(target.documentId)}&workspaceId=${encodeURIComponent(target.workspaceId)}`;
const response = await fetchWithTimeout(url, { method: "GET" });
return readJsonResponse(response, label);
}
async function waitForRuntimeIsland(page) {
const root = page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first();
await root.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const editor = page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .editor-surface .ProseMirror[contenteditable="true"]').first();
await editor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
const editorNode = host?.querySelector('.editor-surface .ProseMirror[contenteditable="true"]');
return host?.getAttribute("data-runtime-editor-status") !== "error" && editorNode instanceof HTMLElement && editorNode.isContentEditable;
}, null, { timeout: UI_TIMEOUT_MS });
return editor;
}
async function waitForSavedText(page, text) {
await page.waitForFunction((expected) => {
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
const editor = host?.querySelector('.editor-surface .ProseMirror');
return host?.getAttribute("data-runtime-editor-status") === "saved" && (editor?.textContent || "").includes(expected);
}, text, { timeout: UI_TIMEOUT_MS });
}
async function screenshot(page, name) {
fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
await page.screenshot({ path: `${SCREENSHOT_DIR}/${name}.png`, fullPage: true });
}
function findNodeWithTextAlign(value, align = "center") {
if (!value || typeof value !== "object") return null;
if (Array.isArray(value)) return value.map((item) => findNodeWithTextAlign(item, align)).find(Boolean) || null;
if (value.attrs?.textAlign === align || value.props?.textAlign === align) return value;
return findNodeWithTextAlign(value.content, align) || findNodeWithTextAlign(value.children, align) || null;
}
async function main() {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
const page = await context.newPage();
const saveRequests = [];
page.on("request", (request) => {
if (!request.url().includes("/api/documents/save")) return;
const body = request.postData();
if (!body) return;
try {
saveRequests.push(JSON.parse(body));
} catch {
saveRequests.push({ raw: body });
}
});
let target = null;
try {
target = await createTempDocument();
const url = `${BASE_URL}/documents/${encodeURIComponent(target.documentId)}?workspaceId=${encodeURIComponent(target.workspaceId)}`;
const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
assert(response, "文档页没有返回响应");
assert.equal(response.status(), 200, `文档页状态码异常: ${response.status()}`);
const editor = await waitForRuntimeIsland(page);
await editor.click({ timeout: UI_TIMEOUT_MS });
const text = `E20 align center ${Date.now().toString(36)}`;
await page.keyboard.type(text);
await waitForSavedText(page, text);
await screenshot(page, "01-before-align");
await page.keyboard.press("Control+Shift+U");
const layoutOutline = page.locator('[data-testid="block-layout-outline"]').first();
await layoutOutline.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const outlineStyle = await layoutOutline.evaluate((node) => {
const style = window.getComputedStyle(node);
return {
borderStyle: style.borderTopStyle,
borderColor: style.borderTopColor,
minHeight: style.minHeight,
};
});
assert.equal(outlineStyle.borderStyle, "dashed", `Ctrl+Shift+U 后块布局轮廓应为虚线: ${JSON.stringify(outlineStyle)}`);
await screenshot(page, "01a-after-layout-hotkey");
const firstBlock = page.locator('.editor-surface .ProseMirror > *').filter({ hasText: text }).first();
await firstBlock.hover({ timeout: UI_TIMEOUT_MS });
const handle = page.locator('[data-testid="mnote-leptos-tiptap-handle"]').first();
await handle.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="block-drag-handle-trigger"]').first().click({ timeout: UI_TIMEOUT_MS });
const menu = page.locator('[data-testid="block-drag-menu"]').first();
await menu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="block-drag-menu-item-align-center"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction((expected) => {
const block = Array.from(document.querySelectorAll('.editor-surface .ProseMirror > *')).find((node) => (node.textContent || '').includes(expected));
return block && window.getComputedStyle(block).textAlign === 'center';
}, text, { timeout: UI_TIMEOUT_MS });
await waitForSavedText(page, text);
await screenshot(page, "02-after-align-center");
const lastSave = saveRequests.at(-1);
assert(lastSave?.tiptapDocument, `居中后必须提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
assert(findNodeWithTextAlign(lastSave.tiptapDocument, "center"), `保存请求 Tiptap JSON 必须包含 attrs.textAlign=center: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
const contentAfterAlign = await loadDocumentContent(target, "读取对齐保存后的正文");
const savedContent = contentAfterAlign?.result?.content;
assert(findNodeWithTextAlign(savedContent, "center"), `/api/documents/content 必须保留 props.textAlign=center: ${JSON.stringify(savedContent).slice(0, 1600)}`);
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForRuntimeIsland(page);
await page.waitForFunction((expected) => {
const block = Array.from(document.querySelectorAll('.editor-surface .ProseMirror > *')).find((node) => (node.textContent || '').includes(expected));
return block && window.getComputedStyle(block).textAlign === 'center';
}, text, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "03-after-reload-align-center");
console.log(JSON.stringify({ ok: true, baseUrl: BASE_URL, documentId: target.documentId, screenshotDir: SCREENSHOT_DIR }, null, 2));
} finally {
if (target) await purgeTempDocument(target).catch(() => undefined);
await page.close().catch(() => undefined);
await context.close().catch(() => undefined);
await browser.close().catch(() => undefined);
}
}
if (require.main === module) {
main().catch((error) => {
console.error(error instanceof Error ? error.stack || error.message : String(error));
process.exit(1);
});
}