Checkpoint current workspace

This commit is contained in:
lix-2026
2026-05-02 06:25:26 +08:00
parent 015ad5bedd
commit 98b6360595
88 changed files with 40217 additions and 178 deletions
+181
View File
@@ -0,0 +1,181 @@
#!/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/task144-e19-indent-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 = `task144-e19-indent-${Date.now().toString(36)}`;
const result = await postTreeCommand({ action: "create", title }, "创建 E19 临时文档");
assert(result.documentId, "创建 E19 临时文档缺少 documentId");
assert(result.workspaceId, "创建 E19 临时文档缺少 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 }, "清理 E19 临时文档");
}
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 collectTypes(value, out = []) {
if (Array.isArray(value)) {
value.forEach((item) => collectTypes(item, out));
return out;
}
if (!value || typeof value !== "object") return out;
if (typeof value.type === "string") out.push(value.type);
collectTypes(value.content, out);
return out;
}
function hasNestedBulletList(value) {
if (!value || typeof value !== "object") return false;
if (Array.isArray(value)) return value.some(hasNestedBulletList);
if (value.type === "listItem" && Array.isArray(value.content)) {
return value.content.some((item) => item?.type === "bulletList" || item?.type === "orderedList" || item?.type === "taskList");
}
if ((value.type === "bullet_list_item" || value.type === "numbered_list_item" || value.type === "todo") && Array.isArray(value.children)) {
return value.children.length > 0;
}
return hasNestedBulletList(value.content);
}
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 });
await page.keyboard.type("/");
const slashBullet = page.locator('[data-testid="slash-item-bullet"]').first();
await slashBullet.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await slashBullet.click({ timeout: UI_TIMEOUT_MS });
await page.keyboard.type("E19 parent");
await page.keyboard.press("Enter");
await page.keyboard.type("E19 child");
await waitForSavedText(page, "E19 child");
await screenshot(page, "01-before-indent");
await page.keyboard.press("Tab");
await page.waitForFunction(() => !!document.querySelector('.editor-surface .ProseMirror ul li ul li'), null, { timeout: UI_TIMEOUT_MS });
await waitForSavedText(page, "E19 child");
await screenshot(page, "02-after-tab-indent");
const lastSave = saveRequests.at(-1);
assert(lastSave?.tiptapDocument, `Tab 缩进后必须走 /api/documents/save 并提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
assert(hasNestedBulletList(lastSave.tiptapDocument), `保存请求里的 Tiptap JSON 必须包含真实嵌套列表结构: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
assert(collectTypes(lastSave.tiptapDocument).filter((type) => type === "bulletList").length >= 2, "保存请求应包含父/子两层 bulletList");
await page.keyboard.press("Shift+Tab");
await page.waitForFunction(() => !document.querySelector('.editor-surface .ProseMirror ul li ul li'), null, { timeout: UI_TIMEOUT_MS });
await waitForSavedText(page, "E19 child");
await screenshot(page, "03-after-shift-tab-outdent");
await page.keyboard.press("Tab");
await page.waitForFunction(() => !!document.querySelector('.editor-surface .ProseMirror ul li ul li'), null, { timeout: UI_TIMEOUT_MS });
await waitForSavedText(page, "E19 child");
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForRuntimeIsland(page);
await page.waitForFunction(() => !!document.querySelector('.editor-surface .ProseMirror ul li ul li'), null, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "04-after-reload-nested-list");
const contentAfterReload = await loadDocumentContent(target, "读取缩进保存后的正文");
const savedContent = contentAfterReload?.result?.content;
assert(hasNestedBulletList(savedContent), `刷新后的 /api/documents/content 必须保留嵌套列表真源: ${JSON.stringify(savedContent).slice(0, 1600)}`);
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);
});
}
+179
View File
@@ -0,0 +1,179 @@
#!/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);
});
}
+180
View File
@@ -0,0 +1,180 @@
#!/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/task150-e22-folding-blocks-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 = `task150-e22-folding-${Date.now().toString(36)}`;
const result = await postTreeCommand({ action: "create", title }, "创建 E22 临时文档");
assert(result.documentId, "创建 E22 临时文档缺少 documentId");
assert(result.workspaceId, "创建 E22 临时文档缺少 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 }, "清理 E22 临时文档");
}
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 findCollapsedHeading(value) {
if (!value || typeof value !== "object") return null;
if (Array.isArray(value)) return value.map(findCollapsedHeading).find(Boolean) || null;
const isHeading = value.type === "heading" || value.blockType === "heading";
const attrs = value.attrs || value.props || {};
if (isHeading && (attrs.collapsed === true || value.collapsed === true)) return value;
return findCollapsedHeading(value.content) || findCollapsedHeading(value.children) || 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 = `E22 folded heading ${Date.now().toString(36)}`;
await page.keyboard.type(text);
await waitForSavedText(page, text);
await screenshot(page, "01-before-folded-title");
const firstBlock = page.locator('.editor-surface .ProseMirror > *').filter({ hasText: text }).first();
await firstBlock.hover({ timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="mnote-leptos-tiptap-handle"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="block-drag-handle-trigger"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="block-drag-menu"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="block-drag-menu-item-turn-into"]').first().hover({ timeout: UI_TIMEOUT_MS });
const transformMenu = page.locator('[data-testid="block-transform-submenu"]').first();
await transformMenu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await screenshot(page, "02-transform-submenu-before-e22");
const foldedTitle = page.locator('[data-testid="block-transform-item-folded-title"]').first();
assert.equal(await foldedTitle.isDisabled(), false, "折叠标题不能是 disabled 静态文案");
await foldedTitle.hover({ timeout: UI_TIMEOUT_MS });
const foldedTitleSubmenu = page.locator('[data-testid="block-transform-folded-title-submenu"]').first();
await foldedTitleSubmenu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const labels = await foldedTitleSubmenu.locator('[data-testid^="block-transform-folded-heading-"]').evaluateAll((nodes) => nodes.map((node) => (node.textContent || "").trim()));
for (const expected of ["折叠主标题", "折叠大标题", "折叠中标题", "折叠小标题"]) {
assert(labels.some((label) => label.includes(expected)), `折叠标题三级菜单缺少 ${expected}: ${labels.join(" | ")}`);
}
await screenshot(page, "03-folded-title-tertiary-submenu");
await page.locator('[data-testid="block-transform-folded-heading-1"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction((expected) => {
const heading = Array.from(document.querySelectorAll('.editor-surface .ProseMirror h1')).find((node) => (node.textContent || '').includes(expected));
return heading instanceof HTMLElement && heading.getAttribute('data-collapsed') === 'true';
}, text, { timeout: UI_TIMEOUT_MS });
await waitForSavedText(page, text);
await screenshot(page, "04-after-folded-heading-click");
const lastSave = saveRequests.at(-1);
assert(lastSave?.tiptapDocument, `折叠标题后必须提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
assert(findCollapsedHeading(lastSave.tiptapDocument), `保存请求 Tiptap JSON 必须包含 heading attrs.collapsed=true: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
const contentAfterFold = await loadDocumentContent(target, "读取折叠标题保存后的正文");
const savedContent = contentAfterFold?.result?.content;
assert(findCollapsedHeading(savedContent), `/api/documents/content 必须保留折叠标题语义: ${JSON.stringify(savedContent).slice(0, 1600)}`);
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForRuntimeIsland(page);
await page.waitForFunction((expected) => {
const heading = Array.from(document.querySelectorAll('.editor-surface .ProseMirror h1')).find((node) => (node.textContent || '').includes(expected));
return heading instanceof HTMLElement && heading.getAttribute('data-collapsed') === 'true';
}, text, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "05-after-reload-folded-heading");
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);
});
}
+439
View File
@@ -0,0 +1,439 @@
#!/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/task151-e23-table-local-smoke";
const TABLE_EXTENSION_SOURCE = "/mnt/Data1T/mnote/design/05-editor-mainline/reference-code/leptos-tiptap/tiptap/src/extensions/tiptap_table.ts";
const LEPTOS_SPIKE_SOURCE = "/mnt/Data1T/mnote/rust/spikes/leptos-tiptap-spike/src/lib.rs";
function assertOfficialTableSelectionBridge() {
const source = fs.readFileSync(TABLE_EXTENSION_SOURCE, "utf8");
assert(
source.includes("CellSelection.rowSelection") && source.includes("CellSelection.colSelection"),
"E23 表格行/列选择必须复用 @tiptap/pm/tables 的 CellSelection.rowSelection/colSelection",
);
assert(
!source.includes("setCellSelection"),
"E23 表格行/列选择不能绕过官方 CellSelection 静态选择逻辑",
);
}
function assertOfficialTableInsertBridge() {
const source = fs.readFileSync(LEPTOS_SPIKE_SOURCE, "utf8");
assert(
source.includes("editor.insert_table(4, 3, false)"),
"E23 简单表格必须通过 bridge 调用 Tiptap 官方 insertTable(rows=4, cols=3, withHeaderRow=false)",
);
assert(
!source.includes(`insert_content(
TiptapContent::json(simple_table_node())`),
"E23 简单表格不能再通过手写 JSON simple_table_node() 走 insert_content",
);
}
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 = `task151-e23-table-${Date.now().toString(36)}`;
const result = await postTreeCommand({ action: "create", title }, "创建 E23 临时文档");
assert(result.documentId, "创建 E23 临时文档缺少 documentId");
assert(result.workspaceId, "创建 E23 临时文档缺少 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 }, "清理 E23 临时文档");
}
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 waitForSavedTable(page, minRows = 2, minCells = 4) {
await page.waitForFunction(({ minRows, minCells }) => {
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
const table = host?.querySelector('.editor-surface .ProseMirror table');
return host?.getAttribute("data-runtime-editor-status") === "saved"
&& table instanceof HTMLTableElement
&& table.querySelectorAll('tr').length >= minRows
&& table.querySelectorAll('td,th').length >= minCells;
}, { minRows, minCells }, { timeout: UI_TIMEOUT_MS });
}
async function waitForSavedWithoutTable(page) {
await page.waitForFunction(() => {
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
return host?.getAttribute("data-runtime-editor-status") === "saved"
&& !host.querySelector('.editor-surface .ProseMirror table');
}, null, { 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 });
}
async function clickTableCell(page, { row = 0, col = 0, text = null } = {}) {
const point = await page.locator('.editor-surface .ProseMirror table').first().evaluate((table, options) => {
const rows = Array.from(table.querySelectorAll('tr'));
let cell = null;
if (options.text) {
cell = Array.from(table.querySelectorAll('td,th')).find((candidate) => (candidate.textContent || '').includes(options.text));
} else {
const rowIndex = options.row < 0 ? rows.length + options.row : options.row;
const targetRow = rows[rowIndex];
const cells = targetRow ? Array.from(targetRow.querySelectorAll('td,th')) : [];
const colIndex = options.col < 0 ? cells.length + options.col : options.col;
cell = cells[colIndex] || null;
}
if (!(cell instanceof HTMLElement)) return null;
const rect = cell.getBoundingClientRect();
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
}, { row, col, text });
assert(point, `找不到可点击的表格单元格: ${JSON.stringify({ row, col, text })}`);
await page.mouse.click(point.x, point.y);
}
function findTable(value) {
if (!value || typeof value !== "object") return null;
if (Array.isArray(value)) return value.map(findTable).find(Boolean) || null;
if (value.type === "table" || value.blockType === "table") return value;
return findTable(value.content) || findTable(value.children) || findTable(value.props?.tiptapTable);
}
function tableText(value) {
if (!value || typeof value !== "object") return "";
if (Array.isArray(value)) return value.map(tableText).join("");
if (typeof value.text === "string") return value.text;
if (typeof value.content === "string") return value.content;
return `${tableText(value.content)}${tableText(value.children)}${tableText(value.props?.tiptapTable)}`;
}
function countNodeType(value, type) {
if (!value || typeof value !== "object") return 0;
if (Array.isArray(value)) return value.reduce((sum, item) => sum + countNodeType(item, type), 0);
const own = value.type === type || value.blockType === type ? 1 : 0;
return own + countNodeType(value.content, type) + countNodeType(value.children, type) + countNodeType(value.props?.tiptapTable, type);
}
function findColwidth(value) {
if (!value || typeof value !== "object") return null;
if (Array.isArray(value)) return value.map(findColwidth).find(Boolean) || null;
const colwidth = value.attrs?.colwidth;
if (Array.isArray(colwidth) && colwidth.some((width) => typeof width === "number" && width > 0)) {
return colwidth;
}
return findColwidth(value.content) || findColwidth(value.children) || findColwidth(value.props?.tiptapTable);
}
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 });
}
});
assertOfficialTableSelectionBridge();
assertOfficialTableInsertBridge();
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 });
await page.keyboard.type("/");
const slash = page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first();
await slash.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const slashText = await slash.innerText();
assert(slashText.includes("进阶块列表"), `slash 菜单缺少进阶块列表: ${slashText}`);
assert(slashText.includes("简单表格"), `slash 菜单缺少简单表格: ${slashText}`);
assert(slashText.includes("/jdbg"), `slash 菜单缺少简单表格快捷码 /jdbg: ${slashText}`);
const simpleTableItem = page.locator('[data-testid="slash-item-simple-table"]').first();
await simpleTableItem.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
await screenshot(page, "01-slash-simple-table-entry");
await simpleTableItem.click({ timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 4, 12);
await screenshot(page, "02-after-simple-table-insert");
const tableShape = await page.locator('.editor-surface .ProseMirror table').first().evaluate((table) => ({
rows: table.querySelectorAll('tr').length,
cells: table.querySelectorAll('td,th').length,
text: table.textContent || "",
}));
assert.equal(tableShape.rows, 4, `简单表格应按 Wolai 基线插入 4 行: ${JSON.stringify(tableShape)}`);
assert.equal(tableShape.cells, 12, `简单表格应按 Wolai 基线插入 3 列共 12 个单元格: ${JSON.stringify(tableShape)}`);
const firstCell = page.locator('.editor-surface .ProseMirror table td, .editor-surface .ProseMirror table th').first();
await firstCell.click({ timeout: UI_TIMEOUT_MS });
const tableToolbar = page.locator('[data-testid="mnote-leptos-tiptap-table-toolbar"]').first();
await tableToolbar.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const tableControls = page.locator('[data-testid="mnote-leptos-tiptap-table-controls"]').first();
await tableControls.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
assert(await page.locator('[data-testid="table-row-aux-0"]').first().isVisible(), "表格应显示首行左侧 aux 选择手柄");
assert(await page.locator('[data-testid="table-col-aux-0"]').first().isVisible(), "表格应显示首列顶部 aux 选择手柄");
await page.locator('[data-testid="table-row-aux-0"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const selection = document.querySelector('[data-testid="table-selection-overlay"]');
const table = document.querySelector('.editor-surface .ProseMirror table');
return selection?.getAttribute('data-selection-kind') === 'row'
&& selection?.getAttribute('data-selection-index') === '0'
&& table?.querySelectorAll('tr').length === 5
&& table?.querySelectorAll('td,th').length === 15;
}, null, { timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 5, 15);
await page.waitForFunction(() => {
const table = document.querySelector('.editor-surface .ProseMirror table');
if (!(table instanceof HTMLTableElement)) return false;
const rows = Array.from(table.querySelectorAll('tr'));
const targetRow = rows[0];
const selectedCells = Array.from(table.querySelectorAll('.selectedCell'));
const targetCells = targetRow ? Array.from(targetRow.querySelectorAll('td,th')) : [];
return targetCells.length > 0
&& selectedCells.length === targetCells.length
&& selectedCells.every((cell) => targetCells.includes(cell));
}, null, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "03a-table-row-aux-insert");
await page.locator('[data-testid="table-col-aux-0"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const selection = document.querySelector('[data-testid="table-selection-overlay"]');
const table = document.querySelector('.editor-surface .ProseMirror table');
return selection?.getAttribute('data-selection-kind') === 'column'
&& selection?.getAttribute('data-selection-index') === '0'
&& table?.querySelectorAll('tr').length === 5
&& table?.querySelectorAll('td,th').length === 20;
}, null, { timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 5, 20);
await page.waitForFunction(() => {
const table = document.querySelector('.editor-surface .ProseMirror table');
if (!(table instanceof HTMLTableElement)) return false;
const rows = Array.from(table.querySelectorAll('tr'));
const selectedCells = Array.from(table.querySelectorAll('.selectedCell'));
const firstColumnCells = rows
.map((row) => row.querySelector('td,th'))
.filter((cell) => cell instanceof HTMLTableCellElement);
return firstColumnCells.length === rows.length
&& selectedCells.length === firstColumnCells.length
&& selectedCells.every((cell) => firstColumnCells.includes(cell));
}, null, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "03b-table-column-aux-insert");
await clickTableCell(page, { row: -1, col: 0 });
for (const testid of [
"table-toolbar-add-row-after",
"table-toolbar-add-column-after",
"table-toolbar-clear-cell",
"table-toolbar-delete-row",
"table-toolbar-delete-column",
"table-toolbar-delete-table",
"table-toolbar-options",
]) {
assert(await page.locator(`[data-testid="${testid}"]`).first().isVisible(), `表格 toolbar 缺少 ${testid}`);
}
await screenshot(page, "03-table-toolbar-visible");
const initialColumnMetrics = await page.locator('.editor-surface .ProseMirror table td, .editor-surface .ProseMirror table th').first().evaluate((cell) => {
const rect = cell.getBoundingClientRect();
return { left: rect.left, right: rect.right, top: rect.top, height: rect.height, width: rect.width };
});
await page.mouse.move(initialColumnMetrics.right - 2, initialColumnMetrics.top + initialColumnMetrics.height / 2);
await page.waitForFunction(() => {
const editor = document.querySelector('.editor-surface .ProseMirror');
return editor?.classList.contains('resize-cursor')
|| document.querySelectorAll('.editor-surface .ProseMirror .column-resize-handle').length > 0;
}, null, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "03c-table-column-resize-handle");
await page.mouse.down();
await page.mouse.move(initialColumnMetrics.right + 86, initialColumnMetrics.top + initialColumnMetrics.height / 2, { steps: 8 });
await page.mouse.up();
await page.waitForFunction((initialWidth) => {
const firstCell = document.querySelector('.editor-surface .ProseMirror table td, .editor-surface .ProseMirror table th');
const firstCol = document.querySelector('.editor-surface .ProseMirror table col');
const domWidth = firstCell instanceof HTMLElement ? firstCell.getBoundingClientRect().width : 0;
const styleWidth = firstCol instanceof HTMLTableColElement ? parseFloat(firstCol.style.width || '0') : 0;
const attrWidth = firstCell instanceof HTMLElement ? Number((firstCell.getAttribute('data-colwidth') || '').split(',')[0]) : 0;
return domWidth >= initialWidth + 40 || styleWidth >= initialWidth + 40 || attrWidth >= initialWidth + 40;
}, initialColumnMetrics.width, { timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 5, 20);
await screenshot(page, "03d-after-column-resize");
await page.keyboard.type("A1");
await page.locator('[data-testid="table-toolbar-add-row-after"]').first().click({ timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 6, 24);
await page.locator('[data-testid="table-toolbar-add-column-after"]').first().click({ timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 6, 30);
await screenshot(page, "04-after-row-column-ops");
await clickTableCell(page, { text: "A1" });
await page.locator('[data-testid="table-toolbar-clear-cell"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => !(document.querySelector('.editor-surface .ProseMirror table')?.textContent || '').includes('A1'), null, { timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 6, 30);
await screenshot(page, "05-after-clear-cell");
await page.locator('[data-testid="table-toolbar-options"]').first().click({ timeout: UI_TIMEOUT_MS });
const optionsMenu = page.locator('[data-testid="table-toolbar-options-menu"]').first();
await optionsMenu.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
for (const testid of [
"table-option-toggle-header-row",
"table-option-toggle-header-column",
"table-option-toggle-hidden-borders",
]) {
const option = page.locator(`[data-testid="${testid}"]`).first();
assert(await option.isVisible(), `表格选项菜单缺少 ${testid}`);
assert.equal(await option.getAttribute("role"), "switch", `${testid} 应使用 switch 语义`);
assert.equal(await option.getAttribute("aria-checked"), "false", `${testid} 初始应为关闭态`);
}
await screenshot(page, "06-table-options-menu");
await page.locator('[data-testid="table-option-toggle-header-row"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => document.querySelector('[data-testid="table-option-toggle-header-row"]')?.getAttribute('aria-checked') === 'true', null, { timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const table = document.querySelector('.editor-surface .ProseMirror table');
const firstRowCells = [...(table?.querySelectorAll('tr:first-child > td, tr:first-child > th') || [])];
return firstRowCells.length >= 4 && firstRowCells.every((cell) => cell.tagName === 'TH');
}, null, { timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 5, 20);
await page.locator('[data-testid="table-option-toggle-header-column"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => document.querySelector('[data-testid="table-option-toggle-header-column"]')?.getAttribute('aria-checked') === 'true', null, { timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const rows = [...document.querySelectorAll('.editor-surface .ProseMirror table tr')];
return rows.length >= 5 && rows.every((row) => row.firstElementChild?.tagName === 'TH');
}, null, { timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 5, 20);
await page.locator('[data-testid="table-option-toggle-hidden-borders"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => document.querySelector('[data-testid="table-option-toggle-hidden-borders"]')?.getAttribute('aria-checked') === 'true', null, { timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const table = document.querySelector('.editor-surface .ProseMirror table');
const firstCell = table?.querySelector('td,th');
return table?.getAttribute('data-hidden-borders') === 'true'
&& firstCell instanceof HTMLElement
&& getComputedStyle(firstCell).borderTopWidth === '0px';
}, null, { timeout: UI_TIMEOUT_MS });
await waitForSavedTable(page, 5, 20);
await screenshot(page, "07-after-table-options");
const lastSave = saveRequests.at(-1);
assert(lastSave?.tiptapDocument, `表格操作后必须提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
const savedTable = findTable(lastSave.tiptapDocument);
assert(savedTable, `保存请求 Tiptap JSON 必须包含 table: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
assert(!tableText(savedTable).includes("A1"), `清空单元格后保存请求不应保留 A1: ${JSON.stringify(savedTable).slice(0, 1600)}`);
assert.equal(savedTable.attrs?.hiddenBorders, true, `隐藏边框应写入 table attrs.hiddenBorders: ${JSON.stringify(savedTable).slice(0, 1600)}`);
assert(countNodeType(savedTable, "tableHeader") >= 8, `标题行/标题列应写入 tableHeader 节点: ${JSON.stringify(savedTable).slice(0, 1600)}`);
const savedColwidth = findColwidth(savedTable);
assert(savedColwidth?.some((width) => width >= initialColumnMetrics.width + 40), `列宽拖拽应写入保存请求 attrs.colwidth: ${JSON.stringify(savedTable).slice(0, 1600)}`);
const contentAfterTable = await loadDocumentContent(target, "读取表格保存后的正文");
const savedContent = contentAfterTable?.result?.content;
const contentTable = findTable(savedContent);
const contentTiptapTable = findTable(contentTable?.props?.tiptapTable) || contentTable;
assert(contentTable, `/api/documents/content 必须保留 table 语义: ${JSON.stringify(savedContent).slice(0, 1600)}`);
assert(!tableText(contentTiptapTable).includes("A1"), `/api/documents/content 清空单元格后不应保留 A1: ${JSON.stringify(savedContent).slice(0, 1600)}`);
assert.equal(contentTiptapTable.attrs?.hiddenBorders, true, `/api/documents/content 应保留隐藏边框属性: ${JSON.stringify(savedContent).slice(0, 1600)}`);
assert(countNodeType(contentTiptapTable, "tableHeader") >= 8, `/api/documents/content 应保留标题行/列语义: ${JSON.stringify(savedContent).slice(0, 1600)}`);
const contentColwidth = findColwidth(contentTiptapTable);
assert(contentColwidth?.some((width) => width >= initialColumnMetrics.width + 40), `/api/documents/content 应保留列宽 attrs.colwidth: ${JSON.stringify(savedContent).slice(0, 1600)}`);
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForRuntimeIsland(page);
await page.waitForFunction((initialWidth) => {
const table = document.querySelector('.editor-surface .ProseMirror table');
return table instanceof HTMLTableElement
&& table.querySelectorAll('tr').length >= 5
&& table.querySelectorAll('td,th').length >= 20
&& table.getAttribute('data-hidden-borders') === 'true'
&& [...table.querySelectorAll('tr:first-child > td, tr:first-child > th')].every((cell) => cell.tagName === 'TH')
&& [...table.querySelectorAll('tr')].every((row) => row.firstElementChild?.tagName === 'TH')
&& (() => {
const firstCell = table.querySelector('td,th');
const firstCol = table.querySelector('col');
const domWidth = firstCell instanceof HTMLElement ? firstCell.getBoundingClientRect().width : 0;
const styleWidth = firstCol instanceof HTMLTableColElement ? parseFloat(firstCol.style.width || firstCol.style.minWidth || '0') : 0;
const attrWidth = firstCell instanceof HTMLElement ? Number((firstCell.getAttribute('data-colwidth') || '').split(',')[0]) : 0;
return domWidth >= initialWidth + 40 || styleWidth >= initialWidth + 40 || attrWidth >= initialWidth + 40;
})()
&& !(table.textContent || '').includes('A1');
}, initialColumnMetrics.width, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "08-after-reload-table-ops");
await page.locator('.editor-surface .ProseMirror table td, .editor-surface .ProseMirror table th').first().click({ timeout: UI_TIMEOUT_MS });
await tableToolbar.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="table-toolbar-delete-table"]').first().click({ timeout: UI_TIMEOUT_MS });
await waitForSavedWithoutTable(page);
const contentAfterDelete = await loadDocumentContent(target, "读取删除表格后的正文");
assert(!findTable(contentAfterDelete?.result?.content), `删除表格后 content API 不应保留 table: ${JSON.stringify(contentAfterDelete).slice(0, 1600)}`);
await screenshot(page, "09-after-delete-table");
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);
});
}
+280
View File
@@ -0,0 +1,280 @@
#!/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/task152-e24-image-local-smoke";
const IMAGE_SRC = "/api/editor/image-placeholder.svg";
const LEPTOS_SPIKE_SOURCE = "/mnt/Data1T/mnote/rust/spikes/leptos-tiptap-spike/src/lib.rs";
function assertOfficialImageBridge() {
const source = fs.readFileSync(LEPTOS_SPIKE_SOURCE, "utf8");
assert(
source.includes("editor.set_image(TiptapImageResource"),
"E24 图片入口必须通过 leptos-tiptap 的 set_image / TiptapImageResource bridge",
);
assert(
!source.includes('TiptapContent::json(json!({ "type": "image"'),
"E24 图片入口不能手写 image JSON 绕过 Tiptap setImage",
);
const imageExtension = fs.readFileSync("/mnt/Data1T/mnote/design/05-editor-mainline/reference-code/leptos-tiptap/tiptap/src/extensions/tiptap_image.ts", "utf8");
assert(
imageExtension.includes("Image.extend") && imageExtension.includes('"data-align"'),
"E24 图片对齐必须复用 Tiptap Image.extend/addAttributes,而不是在 UI 里伪造样式",
);
}
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 = `task152-e24-image-${Date.now().toString(36)}`;
const result = await postTreeCommand({ action: "create", title }, "创建 E24 临时文档");
assert(result.documentId, "创建 E24 临时文档缺少 documentId");
assert(result.workspaceId, "创建 E24 临时文档缺少 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 }, "清理 E24 临时文档");
}
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 waitForSavedImage(page) {
await page.waitForFunction((expectedSrc) => {
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
const image = host?.querySelector('.editor-surface .ProseMirror img[src]');
return host?.getAttribute("data-runtime-editor-status") === "saved"
&& image instanceof HTMLImageElement
&& image.getAttribute("src") === expectedSrc
&& image.naturalWidth > 0
&& image.naturalHeight > 0;
}, IMAGE_SRC, { 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 });
}
async function waitForCondition(label, predicate, timeoutMs = UI_TIMEOUT_MS) {
const started = Date.now();
let lastError = null;
while (Date.now() - started < timeoutMs) {
try {
if (predicate()) return;
} catch (error) {
lastError = error;
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(`${label} 超时${lastError ? `: ${lastError.message || lastError}` : ""}`);
}
function findImage(value) {
if (!value || typeof value !== "object") return null;
if (Array.isArray(value)) return value.map(findImage).find(Boolean) || null;
if (value.type === "image" || value.blockType === "image") return value;
return findImage(value.content) || findImage(value.children) || findImage(value.props?.tiptapImage);
}
function imageSrc(value) {
const image = findImage(value);
return image?.attrs?.src || image?.props?.src || image?.src || null;
}
function imageAlign(value) {
const image = findImage(value);
return image?.attrs?.["data-align"]
|| image?.props?.["data-align"]
|| image?.props?.tiptapImage?.attrs?.["data-align"]
|| null;
}
async function main() {
assertOfficialImageBridge();
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: { width: 1440, height: 960 }, acceptDownloads: true });
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 });
await page.keyboard.type("/");
const slash = page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first();
await slash.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const slashText = await slash.innerText();
assert(slashText.includes("媒体与附件"), `slash 菜单缺少媒体与附件分组: ${slashText}`);
assert(slashText.includes("图片"), `slash 菜单缺少图片入口: ${slashText}`);
assert(slashText.includes("/tp"), `slash 菜单缺少图片快捷码 /tp: ${slashText}`);
const imageItem = page.locator('[data-testid="slash-item-image"]').first();
await imageItem.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
await screenshot(page, "01-slash-image-entry");
await imageItem.click({ timeout: UI_TIMEOUT_MS });
await waitForSavedImage(page);
await screenshot(page, "02-after-image-insert");
const image = page.locator('.editor-surface .ProseMirror img[src]').first();
await image.click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const selectedImage = document.querySelector('.editor-surface .ProseMirror img.ProseMirror-selectednode[src]');
const toolbar = document.querySelector('[data-testid="image-floating-toolbar"]');
return selectedImage instanceof HTMLImageElement
&& toolbar instanceof HTMLElement
&& getComputedStyle(toolbar).display !== "none"
&& toolbar.getBoundingClientRect().width > 0
&& toolbar.getBoundingClientRect().height > 0;
}, null, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "03-image-floating-toolbar");
const imageToolbar = page.locator('[data-testid="image-floating-toolbar"]').first();
await imageToolbar.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
for (const testid of [
"image-align-left",
"image-align-center",
"image-align-right",
"image-download",
"image-delete",
]) {
await imageToolbar.locator(`[data-testid="${testid}"]`).first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
}
assert.equal(await imageToolbar.locator('[data-testid="image-download"]').first().isDisabled(), false, "同源图片下载入口应可用");
assert.equal(await imageToolbar.locator('[data-testid="image-delete"]').first().isDisabled(), true, "删除图片入口本切片应保持禁用,真实删除保存链后续单列");
const currentUrlAfterImageSelect = page.url();
const downloadPromise = page.waitForEvent("download", { timeout: UI_TIMEOUT_MS });
await imageToolbar.locator('[data-testid="image-download"]').first().click({ timeout: UI_TIMEOUT_MS });
const download = await downloadPromise;
const suggestedFilename = download.suggestedFilename();
assert(suggestedFilename.includes("E24"), `图片下载文件名应来自图片 title/alt: ${suggestedFilename}`);
assert(/\.svg$/i.test(suggestedFilename), `图片下载文件名应保留 SVG 扩展名: ${suggestedFilename}`);
await download.delete().catch(() => undefined);
assert.equal(page.url(), currentUrlAfterImageSelect, "下载图片不应触发页面跳转");
await imageToolbar.locator('[data-testid="image-align-center"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
const image = document.querySelector('.editor-surface .ProseMirror img[src]');
const toolbar = document.querySelector('[data-testid="image-floating-toolbar"]');
return host?.getAttribute("data-runtime-editor-status") === "saved"
&& image instanceof HTMLImageElement
&& image.getAttribute("data-align") === "center"
&& toolbar instanceof HTMLElement
&& toolbar.getAttribute("data-align") === "center";
}, null, { timeout: UI_TIMEOUT_MS });
await waitForCondition("等待图片对齐保存请求", () => saveRequests.some((request) => imageAlign(request.tiptapDocument) === "center"));
await screenshot(page, "03-image-floating-toolbar");
const imgAttrs = await image.evaluate((img) => ({
src: img.getAttribute("src"),
alt: img.getAttribute("alt"),
title: img.getAttribute("title"),
dataAlign: img.getAttribute("data-align"),
}));
assert.equal(imgAttrs.src, IMAGE_SRC, `图片 src 应保持稳定测试 URL: ${JSON.stringify(imgAttrs)}`);
assert.equal(imgAttrs.alt, "E24 图片占位", `图片 alt 应由 setImage 写入: ${JSON.stringify(imgAttrs)}`);
assert.equal(imgAttrs.title, "E24 图片", `图片 title 应由 setImage 写入: ${JSON.stringify(imgAttrs)}`);
assert.equal(imgAttrs.dataAlign, "center", `图片居中应通过 data-align 写入 DOM: ${JSON.stringify(imgAttrs)}`);
assert.equal(page.url(), currentUrlAfterImageSelect, "点击图片打开工具条不应触发页面跳转");
const lastSave = [...saveRequests].reverse().find((request) => imageAlign(request.tiptapDocument) === "center") || saveRequests.at(-1);
assert(lastSave?.tiptapDocument, `图片插入后必须提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
assert.equal(imageSrc(lastSave.tiptapDocument), IMAGE_SRC, `保存请求 Tiptap JSON 必须包含 image attrs.src: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
assert.equal(imageAlign(lastSave.tiptapDocument), "center", `保存请求 Tiptap JSON 必须保留 image data-align: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
const contentAfterImage = await loadDocumentContent(target, "读取图片保存后的正文");
const savedContent = contentAfterImage?.result?.content;
assert.equal(imageSrc(savedContent), IMAGE_SRC, `/api/documents/content 必须保留 image 真源: ${JSON.stringify(savedContent).slice(0, 1600)}`);
assert.equal(imageAlign(savedContent), "center", `/api/documents/content 必须保留 image data-align: ${JSON.stringify(savedContent).slice(0, 1600)}`);
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForRuntimeIsland(page);
await page.waitForFunction((expectedSrc) => {
const image = document.querySelector('.editor-surface .ProseMirror img[src]');
return image instanceof HTMLImageElement
&& image.getAttribute("src") === expectedSrc
&& image.getAttribute("data-align") === "center"
&& image.naturalWidth > 0
&& image.naturalHeight > 0;
}, IMAGE_SRC, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "04-after-reload-image");
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);
});
}
+233
View File
@@ -0,0 +1,233 @@
#!/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/task153-e25-toc-local-smoke";
const TOC_EXTENSION_SOURCE = "/mnt/Data1T/mnote/design/05-editor-mainline/reference-code/leptos-tiptap/tiptap/src/extensions/tiptap_toc_node.ts";
const LEPTOS_SPIKE_SOURCE = "/mnt/Data1T/mnote/rust/spikes/leptos-tiptap-spike/src/lib.rs";
function assertTocBridgeSource() {
const extension = fs.readFileSync(TOC_EXTENSION_SOURCE, "utf8");
assert(extension.includes('name: "tocNode"'), "E25 必须注册真实 Tiptap tocNode schema");
assert(extension.includes("Node.create"), "E25 tocNode 必须基于 Tiptap Node.create");
assert(extension.includes("insertTocNode"), "E25 必须提供 insertTocNode 命令入口");
assert(extension.includes("editor.state.doc.descendants"), "E25 TOC 列表必须从当前 Tiptap doc headings 派生,不能写死静态列表");
const spike = fs.readFileSync(LEPTOS_SPIKE_SOURCE, "utf8");
assert(spike.includes("editor.insert_toc_node(TiptapTocNodeAttrs"), "E25 /toc 必须通过 leptos-tiptap insert_toc_node bridge");
assert(!spike.includes('TiptapContent::json(json!({ "type": "tocNode"'), "E25 /toc 不能在 spike 中手写 tocNode JSON 绕过 bridge 命令");
}
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 = `task153-e25-toc-${Date.now().toString(36)}`;
const result = await postTreeCommand({ action: "create", title }, "创建 E25 临时文档");
assert(result.documentId, "创建 E25 临时文档缺少 documentId");
assert(result.workspaceId, "创建 E25 临时文档缺少 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 }, "清理 E25 临时文档");
}
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 screenshot(page, name) {
fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
await page.screenshot({ path: `${SCREENSHOT_DIR}/${name}.png`, fullPage: true });
}
function findToc(value) {
if (!value || typeof value !== "object") return null;
if (Array.isArray(value)) return value.map(findToc).find(Boolean) || null;
if (value.type === "tocNode" || value.blockType === "toc" || value.type === "toc") return value;
return findToc(value.content) || findToc(value.children) || findToc(value.props?.tiptapTocNode) || findToc(value.props?.tiptapToc);
}
function tocShowTitle(value) {
const toc = findToc(value);
return toc?.attrs?.showTitle ?? toc?.props?.tiptapTocNode?.attrs?.showTitle ?? null;
}
async function setHeadingFixture(page) {
await page.evaluate(() => {
const editor = document.querySelector('.editor-surface .ProseMirror')?.editor;
if (!editor) throw new Error('找不到 Tiptap editor');
editor.commands.setContent({
type: 'doc',
content: [
{ type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: 'E25 主标题' }] },
{ type: 'paragraph', content: [{ type: 'text', text: 'E25 正文' }] },
{ type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'E25 子标题' }] },
{ type: 'paragraph' },
],
});
editor.commands.focus('end');
});
await page.waitForFunction(() => {
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
return host?.getAttribute("data-runtime-editor-status") !== "error"
&& document.querySelectorAll('.editor-surface .ProseMirror h1, .editor-surface .ProseMirror h2').length >= 2;
}, null, { timeout: UI_TIMEOUT_MS });
}
async function main() {
assertTocBridgeSource();
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 setHeadingFixture(page);
await editor.click({ timeout: UI_TIMEOUT_MS });
await page.keyboard.type("/");
const slash = page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first();
await slash.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const slashText = await slash.innerText();
assert(slashText.includes("页面目录"), `slash 菜单缺少页面目录: ${slashText}`);
assert(slashText.includes("/toc"), `slash 菜单缺少页面目录快捷码 /toc: ${slashText}`);
const tocItem = page.locator('[data-testid="slash-item-toc"]').first();
await tocItem.scrollIntoViewIfNeeded({ timeout: UI_TIMEOUT_MS });
await screenshot(page, "01-slash-toc-entry");
await tocItem.click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
const toc = document.querySelector('.editor-surface .ProseMirror [data-type="toc-node"]');
const items = Array.from(document.querySelectorAll('.tiptap-table-of-contents-item')).map((item) => item.textContent || '');
return host?.getAttribute("data-runtime-editor-status") === "saved"
&& toc instanceof HTMLElement
&& toc.getAttribute("data-show-title") === "true"
&& items.includes("E25 主标题")
&& items.includes("E25 子标题");
}, null, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "02-after-toc-insert");
await page.evaluate(() => {
const editor = document.querySelector('.editor-surface .ProseMirror')?.editor;
if (!editor) throw new Error('找不到 Tiptap editor');
const doc = editor.getJSON();
const content = Array.isArray(doc.content) ? [...doc.content] : [];
content.push({ type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'E25 动态标题' }] });
editor.commands.setContent({ ...doc, content });
});
await page.waitForFunction(() => Array.from(document.querySelectorAll('.tiptap-table-of-contents-item')).some((item) => (item.textContent || '').includes('E25 动态标题')), null, { timeout: UI_TIMEOUT_MS });
const firstTocItem = page.locator('.tiptap-table-of-contents-item', { hasText: 'E25 主标题' }).first();
await firstTocItem.click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => window.location.hash.startsWith('#heading-'), null, { timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="toc-show-title-toggle"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => {
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
const toc = document.querySelector('.editor-surface .ProseMirror [data-type="toc-node"]');
return host?.getAttribute("data-runtime-editor-status") === "saved"
&& toc instanceof HTMLElement
&& toc.getAttribute("data-show-title") === "false"
&& !document.querySelector('.tiptap-table-of-contents-title');
}, null, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "03-toc-title-hidden");
const lastSave = [...saveRequests].reverse().find((request) => findToc(request.tiptapDocument));
assert(lastSave?.tiptapDocument, `TOC 插入后必须提交 tiptapDocument: ${JSON.stringify(lastSave).slice(0, 1200)}`);
assert.equal(findToc(lastSave.tiptapDocument)?.type, "tocNode", `保存请求必须包含 tocNode: ${JSON.stringify(lastSave.tiptapDocument).slice(0, 1600)}`);
const contentAfterToc = await loadDocumentContent(target, "读取 TOC 保存后的正文");
const savedContent = contentAfterToc?.result?.content;
assert(findToc(savedContent), `/api/documents/content 必须保留 tocNode 真源: ${JSON.stringify(savedContent).slice(0, 1600)}`);
assert.equal(tocShowTitle(savedContent), false, `/api/documents/content 必须保留 showTitle=false: ${JSON.stringify(savedContent).slice(0, 1600)}`);
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForRuntimeIsland(page);
await page.waitForFunction(() => {
const toc = document.querySelector('.editor-surface .ProseMirror [data-type="toc-node"]');
const items = Array.from(document.querySelectorAll('.tiptap-table-of-contents-item')).map((item) => item.textContent || '');
return toc instanceof HTMLElement
&& toc.getAttribute("data-show-title") === "false"
&& items.includes("E25 主标题")
&& items.includes("E25 动态标题");
}, null, { timeout: UI_TIMEOUT_MS });
await screenshot(page, "04-after-reload-toc");
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);
});
}