Files
mnote/scripts/task472-side-target-secondary-pane-smoke.js
T

250 lines
12 KiB
JavaScript
Raw Normal View History

#!/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}:task472`,
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 waitForPrimaryReady(page) {
await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
}
async function waitForSecondaryDocument(page, expectedDocumentId) {
await page.waitForFunction(
({ expected }) => {
const pane = document.querySelector('.document-pane[data-pane-role="secondary"]');
const editor = pane?.querySelector(".editor-surface .ProseMirror");
return pane instanceof HTMLElement
&& pane.getAttribute("data-pane-visible") === "true"
&& pane.getAttribute("data-pane-document-id") === expected
&& editor instanceof HTMLElement
&& editor.isContentEditable;
},
{ expected: expectedDocumentId },
{ timeout: UI_TIMEOUT_MS },
);
}
async function readSideTargetState(page) {
return await page.evaluate(() => {
const url = new URL(window.location.href);
const pane = document.querySelector('.document-pane[data-pane-role="secondary"]');
const activeTab = document.querySelector(".mnote-main-tab.is-active");
const placeholder = document.querySelector("[data-mnote-side-target-placeholder=\"true\"]");
return {
resourceTab: url.searchParams.get("resourceTab") || "",
secondaryDocumentId: url.searchParams.get("secondaryDocumentId"),
secondarySourceKind: url.searchParams.get("secondarySourceKind"),
secondaryRootUri: url.searchParams.get("secondaryRootUri"),
secondaryVisible: pane instanceof HTMLElement && pane.getAttribute("data-pane-visible") === "true" && !pane.hidden,
secondaryDocumentDomId: pane?.getAttribute("data-pane-document-id") || "",
secondarySideTarget: pane?.getAttribute("data-mnote-side-target") || "",
activeTabKind: activeTab?.getAttribute("data-mnote-tab-kind") || "",
activeTabText: activeTab?.textContent || "",
placeholderText: placeholder?.textContent || "",
unsupportedFlag: document.documentElement.getAttribute("data-mnote-side-target-unsupported") || "",
popupCount: window.__mnoteSideTargetPopupCount || 0,
};
});
}
async function main() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task472-side-target-"));
const relativePath = "README.md";
const firstSideRelativePath = "Side.md";
const secondSideRelativePath = "Second.md";
const documentId = localMdDocumentId(relativePath);
const firstSideDocumentId = localMdDocumentId(firstSideRelativePath);
const secondSideDocumentId = localMdDocumentId(secondSideRelativePath);
writeWorkspaceManifest(root, "user_real");
fs.writeFileSync(path.join(root, relativePath), "# Page\n\n主页面\n", "utf8");
fs.writeFileSync(path.join(root, firstSideRelativePath), "# Side\n\n第一侧栏\n", "utf8");
fs.writeFileSync(path.join(root, secondSideRelativePath), "# Second\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",
},
});
await context.addInitScript(() => {
window.__mnoteSideTargetPopupCount = 0;
const originalOpen = window.open;
window.open = function(...args) {
window.__mnoteSideTargetPopupCount += 1;
return originalOpen.apply(window, args);
};
});
const page = await context.newPage();
try {
await quickLogin(page);
await page.goto(documentUrl(root, relativePath, firstSideRelativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForPrimaryReady(page);
await waitForSecondaryDocument(page, firstSideDocumentId);
const asset = await uploadLocalAsset(
page,
root,
documentId,
"side-target-resource.md",
"text/markdown",
Buffer.from("# Resource\n\n资源正文\n", "utf8"),
"attachment",
);
await page.evaluate(({ asset, documentId }) => {
window.dispatchEvent(new CustomEvent("tree.asset.open", {
detail: {
assetId: asset.id,
documentId,
title: asset.file_name || "side-target-resource.md",
assetType: asset.asset_type || "attachment",
},
}));
}, { asset, documentId });
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]').waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const activeResourceBeforeSide = await readSideTargetState(page);
assert(activeResourceBeforeSide.resourceTab.includes("side-target-resource.md"), `active resource tab 应写入 URL: ${JSON.stringify(activeResourceBeforeSide)}`);
assert.equal(activeResourceBeforeSide.secondaryDocumentId, firstSideDocumentId, `资源 tab 不应清理既有 secondaryDocumentId: ${JSON.stringify(activeResourceBeforeSide)}`);
await page.evaluate(({ documentId }) => {
window.dispatchEvent(new CustomEvent("tree.page.open", {
detail: {
documentId,
openTarget: "side",
},
}));
}, { documentId: secondSideDocumentId });
await waitForSecondaryDocument(page, secondSideDocumentId);
const afterDocumentSideOpen = await readSideTargetState(page);
assert.equal(afterDocumentSideOpen.secondaryDocumentId, secondSideDocumentId, `document openTarget=side 应更新 secondaryDocumentId: ${JSON.stringify(afterDocumentSideOpen)}`);
assert.equal(afterDocumentSideOpen.secondarySourceKind, "local_folder", `document openTarget=side 应维护 secondarySourceKind: ${JSON.stringify(afterDocumentSideOpen)}`);
assert.equal(afterDocumentSideOpen.secondaryRootUri, fileUrl(root), `document openTarget=side 应维护 secondaryRootUri: ${JSON.stringify(afterDocumentSideOpen)}`);
assert(afterDocumentSideOpen.resourceTab.includes("side-target-resource.md"), `更新 secondary pane 不应清空 active resource tab URL: ${JSON.stringify(afterDocumentSideOpen)}`);
assert.equal(afterDocumentSideOpen.activeTabKind, "markdown", `active resource tab 与 secondary pane 应同时存在: ${JSON.stringify(afterDocumentSideOpen)}`);
await page.locator('[data-mnote-pane-close="secondary"]').first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForTimeout(250);
const afterCloseSecondary = await readSideTargetState(page);
assert.equal(afterCloseSecondary.secondaryDocumentId, null, `关闭 secondary pane 应清理 secondaryDocumentId: ${JSON.stringify(afterCloseSecondary)}`);
assert.equal(afterCloseSecondary.secondarySourceKind, null, `关闭 secondary pane 应清理 secondarySourceKind: ${JSON.stringify(afterCloseSecondary)}`);
assert.equal(afterCloseSecondary.secondaryRootUri, null, `关闭 secondary pane 应清理 secondaryRootUri: ${JSON.stringify(afterCloseSecondary)}`);
assert(afterCloseSecondary.resourceTab.includes("side-target-resource.md"), `关闭 secondary pane 不应清空 active resource tab URL: ${JSON.stringify(afterCloseSecondary)}`);
assert.equal(afterCloseSecondary.activeTabKind, "markdown", `关闭 secondary pane 不应切走 active resource tab: ${JSON.stringify(afterCloseSecondary)}`);
await page.evaluate(({ asset, documentId }) => {
window.dispatchEvent(new CustomEvent("tree.asset.open", {
detail: {
assetId: asset.id,
documentId,
title: asset.file_name || "side-target-resource.md",
assetType: asset.asset_type || "attachment",
openTarget: "side",
},
}));
}, { asset, documentId });
await page.waitForFunction(() => document.querySelector("[data-mnote-side-target-placeholder=\"true\"]"), {}, { timeout: UI_TIMEOUT_MS });
const afterResourceSideOpen = await readSideTargetState(page);
assert.equal(afterResourceSideOpen.secondaryDocumentId, null, `资源 openTarget=side placeholder 不应保留旧 secondaryDocumentId: ${JSON.stringify(afterResourceSideOpen)}`);
assert.equal(afterResourceSideOpen.secondarySideTarget, "unsupported-resource", `资源 openTarget=side 应标记 unsupported side target: ${JSON.stringify(afterResourceSideOpen)}`);
assert.match(afterResourceSideOpen.placeholderText, /暂不支持在侧栏打开此资源/, `资源 side placeholder 应可观测: ${JSON.stringify(afterResourceSideOpen)}`);
assert(afterResourceSideOpen.resourceTab.includes("side-target-resource.md"), `资源 side placeholder 不应清空 active resource tab URL: ${JSON.stringify(afterResourceSideOpen)}`);
assert.equal(afterResourceSideOpen.activeTabKind, "markdown", `资源 side placeholder 不应切走 active resource tab: ${JSON.stringify(afterResourceSideOpen)}`);
assert.equal(afterResourceSideOpen.popupCount, 0, `资源 openTarget=side 不应误开新窗口: ${JSON.stringify(afterResourceSideOpen)}`);
console.log(JSON.stringify({ ok: true, root, assetId: asset.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);
});