257 lines
12 KiB
JavaScript
257 lines
12 KiB
JavaScript
#!/usr/bin/env node
|
|
"use strict";
|
|
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const os = require("node:os");
|
|
const path = require("node:path");
|
|
const { chromium } = require("playwright");
|
|
|
|
const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
|
|
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
|
|
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
|
|
|| ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium"]
|
|
.find((candidate) => fs.existsSync(candidate));
|
|
|
|
function fileUrl(localPath) {
|
|
return `file://${localPath}`;
|
|
}
|
|
|
|
function localMdDocumentId(relativePath) {
|
|
return `local-md:${relativePath.replaceAll("/", "~2F")}`;
|
|
}
|
|
|
|
function documentUrl(root, relativePath, secondaryRelativePath = "") {
|
|
const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`);
|
|
url.searchParams.set("sourceKind", "local_folder");
|
|
url.searchParams.set("rootUri", fileUrl(root));
|
|
url.searchParams.set("treeView", "filetree");
|
|
if (secondaryRelativePath) {
|
|
url.searchParams.set("secondaryDocumentId", localMdDocumentId(secondaryRelativePath));
|
|
url.searchParams.set("secondarySourceKind", "local_folder");
|
|
url.searchParams.set("secondaryRootUri", fileUrl(root));
|
|
}
|
|
return url.toString();
|
|
}
|
|
|
|
function writeWorkspaceManifest(root, ownerId) {
|
|
const metadataDir = path.join(root, ".mnote");
|
|
fs.mkdirSync(metadataDir, { recursive: true });
|
|
fs.writeFileSync(
|
|
path.join(metadataDir, "workspace.json"),
|
|
`${JSON.stringify({
|
|
workspaceId: `local-ws:${ownerId}:task457`,
|
|
ownerId,
|
|
createdAt: new Date().toISOString(),
|
|
capabilities: ["local_files", "markdown_edit", "asset_upload"],
|
|
}, null, 2)}\n`,
|
|
"utf8",
|
|
);
|
|
}
|
|
|
|
async function quickLogin(page) {
|
|
await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
|
|
const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" });
|
|
if (await quickLoginButton.count()) {
|
|
await quickLoginButton.click({ timeout: UI_TIMEOUT_MS });
|
|
await page.waitForURL((url) => url.pathname === "/", { timeout: UI_TIMEOUT_MS });
|
|
}
|
|
}
|
|
|
|
async function uploadLocalAsset(page, root, documentId, fileName, mimeType, bytes, kind) {
|
|
return await page.evaluate(
|
|
async ({ rootUri, documentId, fileName, mimeType, bytes, kind }) => {
|
|
const form = new FormData();
|
|
form.append("rootUri", rootUri);
|
|
form.append("documentId", documentId);
|
|
form.append("kind", kind);
|
|
form.append("file", new File([new Uint8Array(bytes)], fileName, { type: mimeType }));
|
|
const response = await fetch("/api/local-folder/assets/upload", { method: "POST", body: form });
|
|
const payload = await response.json().catch(() => null);
|
|
if (!response.ok || !payload || payload.ok !== true) {
|
|
throw new Error(`upload_failed_${response.status}:${JSON.stringify(payload)}`);
|
|
}
|
|
return payload.asset;
|
|
},
|
|
{ rootUri: fileUrl(root), documentId, fileName, mimeType, bytes: Array.from(bytes), kind },
|
|
);
|
|
}
|
|
|
|
async function main() {
|
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task457-resource-tabs-"));
|
|
const relativePath = "README.md";
|
|
const documentId = localMdDocumentId(relativePath);
|
|
const sideRelativePath = "Side.md";
|
|
writeWorkspaceManifest(root, "user_real");
|
|
fs.writeFileSync(path.join(root, relativePath), "# Page\n\n页面正文保持不变\n", "utf8");
|
|
fs.writeFileSync(path.join(root, sideRelativePath), "# Side\n\n右侧栏保持打开\n", "utf8");
|
|
|
|
const browser = await chromium.launch({
|
|
headless: true,
|
|
executablePath: CHROMIUM_EXECUTABLE_PATH,
|
|
});
|
|
const context = await browser.newContext({
|
|
viewport: { width: 1360, height: 900 },
|
|
extraHTTPHeaders: {
|
|
"x-mnote-actor-id": "user_real",
|
|
"x-mnote-actor-type": "user",
|
|
},
|
|
});
|
|
const page = await context.newPage();
|
|
try {
|
|
await quickLogin(page);
|
|
await page.goto(documentUrl(root, relativePath, sideRelativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
|
|
await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
|
|
state: "visible",
|
|
timeout: UI_TIMEOUT_MS,
|
|
});
|
|
await page.locator('.document-pane[data-pane-role="secondary"][data-pane-visible="true"]').waitFor({
|
|
state: "visible",
|
|
timeout: UI_TIMEOUT_MS,
|
|
});
|
|
const asset = await uploadLocalAsset(
|
|
page,
|
|
root,
|
|
documentId,
|
|
"resource-note.md",
|
|
"text/markdown",
|
|
Buffer.from("# Resource Note\n\n旧资源正文\n", "utf8"),
|
|
"attachment",
|
|
);
|
|
const officeAsset = await uploadLocalAsset(
|
|
page,
|
|
root,
|
|
documentId,
|
|
"resource-office.docx",
|
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
Buffer.from("task457 office probe", "utf8"),
|
|
"attachment",
|
|
);
|
|
await page.goto(documentUrl(root, relativePath, sideRelativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
|
|
await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
|
|
state: "visible",
|
|
timeout: UI_TIMEOUT_MS,
|
|
});
|
|
await page.evaluate(({ asset, documentId }) => {
|
|
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
|
detail: {
|
|
assetId: asset.id,
|
|
documentId,
|
|
title: asset.file_name || "resource-note.md",
|
|
assetType: asset.asset_type || "attachment",
|
|
},
|
|
}));
|
|
}, { asset, documentId });
|
|
await page.locator('[data-testid="mnote-resource-tab-host"]:not([hidden])').waitFor({
|
|
state: "visible",
|
|
timeout: UI_TIMEOUT_MS,
|
|
});
|
|
await page.locator('.document-pane[data-pane-role="secondary"][data-pane-visible="true"]').waitFor({
|
|
state: "visible",
|
|
timeout: UI_TIMEOUT_MS,
|
|
});
|
|
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]').waitFor({
|
|
state: "visible",
|
|
timeout: UI_TIMEOUT_MS,
|
|
});
|
|
const markdownTabState = await page.evaluate(() => {
|
|
const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
|
|
const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]');
|
|
const badge = tab?.querySelector(".mnote-main-tab-badge");
|
|
return {
|
|
pageText: pageTab?.textContent || "",
|
|
resourceText: tab?.textContent || "",
|
|
badgeKind: tab?.getAttribute("data-mnote-tab-badge-kind") || "",
|
|
badgeColor: badge ? getComputedStyle(badge).backgroundColor : "",
|
|
};
|
|
});
|
|
assert(!/\b(description|article|notes)\b/i.test(markdownTabState.pageText), `页面 tab 不应显示 Material Symbols 文本: ${JSON.stringify(markdownTabState)}`);
|
|
assert(!/\b(description|article|notes)\b/i.test(markdownTabState.resourceText), `Markdown tab 不应显示 Material Symbols 文本: ${JSON.stringify(markdownTabState)}`);
|
|
assert.equal(markdownTabState.badgeKind, "code", `Markdown tab 应使用黑色 code 色块: ${JSON.stringify(markdownTabState)}`);
|
|
assert(markdownTabState.badgeColor === "rgb(17, 17, 17)", `Markdown tab 色块应为黑色: ${JSON.stringify(markdownTabState)}`);
|
|
const editor = page.locator('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]').first();
|
|
await editor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
|
|
await editor.click({ timeout: UI_TIMEOUT_MS });
|
|
await page.keyboard.press(process.platform === "darwin" ? "Meta+End" : "Control+End");
|
|
await page.keyboard.type("\n新增资源正文", { delay: 5 });
|
|
await page.waitForFunction(
|
|
() => document.querySelector('.mnote-resource-tab-panel:not([hidden]) [data-runtime-editor-status="saved"]'),
|
|
null,
|
|
{ timeout: UI_TIMEOUT_MS },
|
|
);
|
|
|
|
const assetPath = path.join(root, "README", "resource-note.md");
|
|
const pageMarkdown = fs.readFileSync(path.join(root, relativePath), "utf8");
|
|
const assetMarkdown = fs.readFileSync(assetPath, "utf8");
|
|
assert(assetMarkdown.includes("新增资源正文"), assetMarkdown);
|
|
assert(pageMarkdown.includes("页面正文保持不变"), pageMarkdown);
|
|
assert(!pageMarkdown.includes("新增资源正文"), pageMarkdown);
|
|
|
|
await page.evaluate(({ officeAsset, documentId }) => {
|
|
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
|
detail: {
|
|
assetId: officeAsset.id,
|
|
documentId,
|
|
title: officeAsset.file_name || "resource-office.docx",
|
|
assetType: officeAsset.asset_type || "attachment",
|
|
},
|
|
}));
|
|
}, { officeAsset, documentId });
|
|
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
|
|
state: "visible",
|
|
timeout: UI_TIMEOUT_MS,
|
|
});
|
|
const officeTabState = await page.evaluate(() => {
|
|
const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
|
const badge = tab?.querySelector(".mnote-main-tab-badge");
|
|
return {
|
|
resourceText: tab?.textContent || "",
|
|
badgeKind: tab?.getAttribute("data-mnote-tab-badge-kind") || "",
|
|
badgeColor: badge ? getComputedStyle(badge).backgroundColor : "",
|
|
};
|
|
});
|
|
assert(!/\b(description|article|notes)\b/i.test(officeTabState.resourceText), `Office tab 不应显示 Material Symbols 文本: ${JSON.stringify(officeTabState)}`);
|
|
assert.equal(officeTabState.badgeKind, "word", `docx tab 应使用 word 色块: ${JSON.stringify(officeTabState)}`);
|
|
assert(officeTabState.badgeColor === "rgb(79, 125, 243)", `docx tab 色块应与附件 word 蓝色一致: ${JSON.stringify(officeTabState)}`);
|
|
const officeFrameSrc = await page.locator('.mnote-resource-tab-panel:not([hidden]) iframe.mnote-resource-tab-frame').first().getAttribute("src", {
|
|
timeout: UI_TIMEOUT_MS,
|
|
});
|
|
assert(officeFrameSrc, "Office resource tab 应创建 iframe");
|
|
const officeFrameUrl = new URL(officeFrameSrc, BASE_URL);
|
|
assert(officeFrameUrl.pathname === "/onlyoffice", `Office resource tab iframe 应指向 /onlyoffice,实际为 ${officeFrameSrc}`);
|
|
assert(officeFrameUrl.searchParams.get("assetId") === officeAsset.id, "Office iframe URL 应携带当前资源 assetId");
|
|
assert(officeFrameUrl.searchParams.get("mode") === "view", "Office resource tab iframe 应使用 view 模式");
|
|
|
|
const [officePopup] = await Promise.all([
|
|
page.waitForEvent("popup", { timeout: UI_TIMEOUT_MS }),
|
|
page.evaluate(({ officeAsset, documentId }) => {
|
|
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
|
detail: {
|
|
assetId: officeAsset.id,
|
|
documentId,
|
|
title: officeAsset.file_name || "resource-office.docx",
|
|
assetType: officeAsset.asset_type || "attachment",
|
|
openTarget: "new-window",
|
|
},
|
|
}));
|
|
}, { officeAsset, documentId }),
|
|
]);
|
|
await officePopup.waitForLoadState("domcontentloaded", { timeout: UI_TIMEOUT_MS }).catch(() => undefined);
|
|
const officePopupUrl = new URL(officePopup.url());
|
|
assert(officePopupUrl.pathname === "/onlyoffice", `显式 new-window 应打开 /onlyoffice,实际为 ${officePopup.url()}`);
|
|
assert(officePopupUrl.searchParams.get("assetId") === officeAsset.id, "new-window URL 应携带当前资源 assetId");
|
|
assert(officePopupUrl.searchParams.get("mode") === "edit", "显式 new-window 应保留 edit 模式");
|
|
await officePopup.close().catch(() => undefined);
|
|
|
|
console.log(JSON.stringify({ ok: true, root, assetPath, assetId: asset.id, officeAssetId: officeAsset.id }, null, 2));
|
|
} finally {
|
|
await context.close().catch(() => undefined);
|
|
await browser.close().catch(() => undefined);
|
|
}
|
|
}
|
|
|
|
main().catch((error) => {
|
|
console.error(error && error.stack ? error.stack : error);
|
|
process.exit(1);
|
|
});
|