fix slash menu dismissal and anchor

This commit is contained in:
lix-2026
2026-05-29 11:34:41 +08:00
parent cbe789e034
commit 631205ba2f
5 changed files with 282 additions and 28 deletions
@@ -539,10 +539,6 @@ function __wbg_get_imports() {
const ret = arg0.getElementsByTagName(getStringFromWasm0(arg1, arg2));
return ret;
},
__wbg_getHours_bba0ffaba65cf3f1: function(arg0) {
const ret = arg0.getHours();
return ret;
},
__wbg_getItem_7fe1351b9ea3b2f3: function() { return handleError(function (arg0, arg1, arg2, arg3) {
const ret = arg1.getItem(getStringFromWasm0(arg2, arg3));
var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
@@ -550,18 +546,10 @@ function __wbg_get_imports() {
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
}, arguments); },
__wbg_getMinutes_240bbdd69fb6e5d0: function(arg0) {
const ret = arg0.getMinutes();
return ret;
},
__wbg_getRangeAt_b7ea59f2b148e5d9: function() { return handleError(function (arg0, arg1) {
const ret = arg0.getRangeAt(arg1 >>> 0);
return ret;
}, arguments); },
__wbg_getSeconds_95f730540087b3b6: function(arg0) {
const ret = arg0.getSeconds();
return ret;
},
__wbg_getSelection_dfd0ccff15057bd1: function() { return handleError(function (arg0) {
const ret = arg0.getSelection();
return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
@@ -793,10 +781,6 @@ function __wbg_get_imports() {
const ret = arg0.metaKey;
return ret;
},
__wbg_new_0_4d657201ced14de3: function() {
const ret = new Date();
return ret;
},
__wbg_new_0c7403db6e782f19: function(arg0) {
const ret = new Uint8Array(arg0);
return ret;
@@ -913,6 +897,10 @@ function __wbg_get_imports() {
const ret = arg0.queueMicrotask;
return ret;
},
__wbg_random_ce7f6871aed001dd: function() {
const ret = Math.random();
return ret;
},
__wbg_register_blockquote_fd046c8c627399c8: function() { return handleError(function () {
register_blockquote();
}, arguments); },
@@ -1244,47 +1232,47 @@ function __wbg_get_imports() {
}
}, arguments); },
__wbindgen_cast_0000000000000001: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 1148, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 1140, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h396914cf76a9e7a5);
return ret;
},
__wbindgen_cast_0000000000000002: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 1200, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 1192, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h3a3182d847094e12);
return ret;
},
__wbindgen_cast_0000000000000003: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 976, ret: Unit, inner_ret: Some(Unit) }, mutable: false }) -> Externref`.
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 969, ret: Unit, inner_ret: Some(Unit) }, mutable: false }) -> Externref`.
const ret = makeClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__had771ddc65647798);
return ret;
},
__wbindgen_cast_0000000000000004: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1098, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1090, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h0abd2b2fe4652e2a);
return ret;
},
__wbindgen_cast_0000000000000005: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1148, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1140, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h396914cf76a9e7a5_4);
return ret;
},
__wbindgen_cast_0000000000000006: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("KeyboardEvent")], shim_idx: 747, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("KeyboardEvent")], shim_idx: 637, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hd90af689bc3e71bf);
return ret;
},
__wbindgen_cast_0000000000000007: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1100, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1092, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h794babeffd4f821f);
return ret;
},
__wbindgen_cast_0000000000000008: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1115, ret: Unit, inner_ret: Some(Unit) }, mutable: false }) -> Externref`.
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1107, ret: Unit, inner_ret: Some(Unit) }, mutable: false }) -> Externref`.
const ret = makeClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h2b648e7ac8ec1fb5);
return ret;
},
__wbindgen_cast_0000000000000009: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1151, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1143, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h0b7fb40a8610550c);
return ret;
},
@@ -18,7 +18,7 @@ pub(crate) struct SlashMenuViewProps {
pub(crate) editor: TiptapEditorHandle,
pub(crate) signals: SlashMenuSignals,
pub(crate) runtime: SlashMenuRuntimeContext,
pub(crate) anchor_style: Arc<dyn Fn() -> String + Send + Sync>,
pub(crate) anchor_style: ReadSignal<String>,
}
#[derive(Clone, Copy)]
@@ -213,7 +213,14 @@ pub(crate) fn slash_menu_view(props: SlashMenuViewProps) -> impl IntoView {
<div
class="slash-menu"
data-testid="mnote-leptos-tiptap-slash-menu"
style=anchor_style()
style=move || {
let style = anchor_style.get();
if style.trim().is_empty() {
"top:24px;left:24px;".to_string()
} else {
style
}
}
>
<div class="slash-list">
{move || {
+34 -1
View File
@@ -1159,6 +1159,7 @@ fn App(mount_options: MountOptions) -> impl IntoView {
let (slash_open, set_slash_open) = signal(false);
let (slash_index, set_slash_index) = signal(0_usize);
let (slash_query, set_slash_query) = signal(String::new());
let (slash_anchor_style, set_slash_anchor_style) = signal(String::new());
let (turn_into_open, set_turn_into_open) = signal(false);
let (color_menu_open, set_color_menu_open) = signal(false);
let (more_menu_open, set_more_menu_open) = signal(false);
@@ -1782,6 +1783,7 @@ fn App(mount_options: MountOptions) -> impl IntoView {
let set_slash_index = set_slash_index;
let slash_query = slash_query;
let set_slash_query = set_slash_query;
let set_slash_anchor_style = set_slash_anchor_style;
let turn_into_open = turn_into_open;
let set_turn_into_open = set_turn_into_open;
let color_menu_open = color_menu_open;
@@ -2043,6 +2045,7 @@ fn App(mount_options: MountOptions) -> impl IntoView {
if event.key() == "/" && !event.ctrl_key() && !event.meta_key() && !event.alt_key() {
event.prevent_default();
let _ = set_slash_anchor_style.try_set(slash_menu_anchor_style());
open_slash_menu_overlay(
set_slash_open,
set_slash_index,
@@ -2132,6 +2135,36 @@ fn App(mount_options: MountOptions) -> impl IntoView {
on_cleanup(move || drop(keydown_handle));
}
{
let set_slash_open = set_slash_open;
let set_slash_index = set_slash_index;
let set_slash_query = set_slash_query;
let set_slash_anchor_style = set_slash_anchor_style;
let outside_mousedown_handle =
window_event_listener(ev::mousedown, move |event: MouseEvent| {
let Some(element) = event.target().and_then(target_element) else {
let _ = set_slash_open.try_set(false);
let _ = set_slash_index.try_set(0);
let _ = set_slash_query.try_set(String::new());
let _ = set_slash_anchor_style.try_set(String::new());
return;
};
if element
.closest("[data-testid=\"mnote-leptos-tiptap-slash-menu\"]")
.ok()
.flatten()
.is_some()
{
return;
}
let _ = set_slash_open.try_set(false);
let _ = set_slash_index.try_set(0);
let _ = set_slash_query.try_set(String::new());
let _ = set_slash_anchor_style.try_set(String::new());
});
on_cleanup(move || drop(outside_mousedown_handle));
}
{
let click_handle = window_event_listener(ev::click, move |event: MouseEvent| {
let Some(element) = event.target().and_then(target_element) else {
@@ -2251,7 +2284,7 @@ fn App(mount_options: MountOptions) -> impl IntoView {
command_feedback: set_command_feedback,
},
runtime: slash_menu_runtime,
anchor_style: std::sync::Arc::new(slash_menu_anchor_style),
anchor_style: slash_anchor_style,
};
view! {
@@ -0,0 +1,226 @@
#!/usr/bin/env node
"use strict";
const assert = require("node:assert/strict");
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 OUTPUT_DIR = path.join(process.cwd(), "tmp", "task511-slash-menu-position-dismiss-smoke");
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
const TEST_PASSWORD = process.env.MNOTE_E2E_PASSWORD || ["Mnote", "E2E", "123!"].join("");
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
|| ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium", "/usr/bin/chromium"]
.find((candidate) => fs.existsSync(candidate));
function fileUrl(localPath) {
return `file://${localPath.split(path.sep).map((part, index) => (
index === 0 ? "" : encodeURIComponent(part)
)).join("/")}`;
}
function localMdDocumentId(relativePath) {
return `local-md:${Buffer.from(relativePath, "utf8")
.toString("hex")
.replace(/../g, (hex) => {
const code = Number.parseInt(hex, 16);
const ch = String.fromCharCode(code);
return /[A-Za-z0-9._-]/.test(ch) ? ch : `~${hex.toUpperCase()}`;
})}`;
}
function documentUrl(root, relativePath) {
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");
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}:task511`,
ownerId,
createdAt: new Date().toISOString(),
capabilities: ["local_files", "markdown_edit"],
}, null, 2)}\n`,
"utf8",
);
}
async function ensureTestUser(context) {
const payload = (flow) => ({
action: "auth:signIn",
args: {
provider: "password",
params: {
email: "mnote.e2e@example.com",
username: "mnote-e2e",
name: "mnote-e2e",
password: TEST_PASSWORD,
flow,
},
},
});
const signIn = await context.request.fetch(`${BASE_URL}/api/auth`, {
method: "POST",
data: payload("signIn"),
});
if (signIn.ok()) return;
const signUp = await context.request.fetch(`${BASE_URL}/api/auth`, {
method: "POST",
data: payload("signUp"),
});
assert(signUp.ok(), `测试用户创建失败: ${signUp.status()} ${await signUp.text()}`);
}
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 }).catch(() => undefined);
}
}
async function waitForEditor(page) {
await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const editor = page.locator('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror[contenteditable="true"]').first();
await editor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
return editor;
}
async function slashMenuBox(page) {
return await page.evaluate(() => {
const menu = document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]');
if (!(menu instanceof HTMLElement)) return null;
const rect = menu.getBoundingClientRect();
const editor = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror');
const editorRect = editor instanceof HTMLElement ? editor.getBoundingClientRect() : null;
return {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
viewportWidth: window.innerWidth,
viewportHeight: window.innerHeight,
editorX: editorRect ? editorRect.x : null,
editorY: editorRect ? editorRect.y : null,
editorWidth: editorRect ? editorRect.width : null,
};
});
}
async function main() {
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task511-slash-"));
const relativePath = "SlashPosition.md";
writeWorkspaceManifest(root, "mnote-e2e");
fs.writeFileSync(path.join(root, relativePath), "# Slash Position\n\n第一行\n\n第二行\n", "utf8");
const browser = await chromium.launch({
headless: process.env.HEADFUL !== "1",
executablePath: CHROMIUM_EXECUTABLE_PATH,
});
const context = await browser.newContext({
viewport: { width: 1440, height: 900 },
locale: "zh-CN",
extraHTTPHeaders: {
"x-mnote-actor-id": "mnote-e2e",
"x-mnote-actor-type": "user",
},
});
const page = await context.newPage();
const result = { root, relativePath, states: [], console: [], pageErrors: [] };
page.on("console", (message) => result.console.push({ type: message.type(), text: message.text() }));
page.on("pageerror", (error) => result.pageErrors.push(String(error && error.stack || error)));
try {
await ensureTestUser(context);
await quickLogin(page);
await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
const editor = await waitForEditor(page);
await editor.click({ timeout: UI_TIMEOUT_MS });
await page.keyboard.press("End").catch(() => undefined);
await page.keyboard.type("/");
await page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const openedBox = await slashMenuBox(page);
assert(openedBox, "slash 菜单应打开");
assert(openedBox.x < openedBox.viewportWidth - openedBox.width - 32, `slash 菜单不应贴到右下角: ${JSON.stringify(openedBox)}`);
assert(openedBox.x >= Math.max(0, (openedBox.editorX || 0) - 24), `slash 菜单不应跑到编辑器左侧外: ${JSON.stringify(openedBox)}`);
assert(openedBox.y < openedBox.viewportHeight - 96, `slash 菜单不应贴到视口底部: ${JSON.stringify(openedBox)}`);
result.states.push({ step: "opened", box: openedBox });
await page.screenshot({ path: path.join(OUTPUT_DIR, "01-opened.png"), fullPage: false });
await page.mouse.click(1320, 820);
await page.waitForFunction(
() => !document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]'),
null,
{ timeout: UI_TIMEOUT_MS },
);
result.states.push({ step: "outside-click-closed" });
await page.screenshot({ path: path.join(OUTPUT_DIR, "02-outside-click-closed.png"), fullPage: false });
await editor.click({ timeout: UI_TIMEOUT_MS });
await page.keyboard.type("/");
await page.locator('[data-testid="mnote-leptos-tiptap-slash-menu"]').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const reopenedBox = await slashMenuBox(page);
assert(reopenedBox, "slash 菜单应能再次打开");
result.states.push({ step: "reopened", box: reopenedBox });
await page.mouse.click(Math.round((openedBox.editorX || 487) + 40), Math.round((openedBox.editorY || 242) + 40));
await page.waitForFunction(
() => !document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]'),
null,
{ timeout: UI_TIMEOUT_MS },
);
result.states.push({ step: "editor-click-closed" });
await page.screenshot({ path: path.join(OUTPUT_DIR, "03-editor-click-closed.png"), fullPage: false });
fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: true, ...result }, null, 2)}\n`, "utf8");
console.log(JSON.stringify({ ok: true, resultPath: RESULT_PATH, screenshotDir: OUTPUT_DIR }, null, 2));
} catch (error) {
const diagnostics = await page.evaluate(() => ({
url: location.href,
slashBox: (() => {
const menu = document.querySelector('[data-testid="mnote-leptos-tiptap-slash-menu"]');
if (!(menu instanceof HTMLElement)) return null;
const rect = menu.getBoundingClientRect();
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
})(),
})).catch((err) => ({ diagnosticsError: String(err) }));
await page.screenshot({ path: path.join(OUTPUT_DIR, "failure.png"), fullPage: true }).catch(() => undefined);
fs.writeFileSync(
RESULT_PATH,
`${JSON.stringify({ ok: false, ...result, diagnostics, error: String(error && error.stack || error) }, null, 2)}\n`,
"utf8",
);
console.error(JSON.stringify({ ok: false, resultPath: RESULT_PATH, diagnostics, error: String(error && error.stack || error) }, null, 2));
process.exitCode = 1;
} finally {
fs.rmSync(root, { recursive: true, force: true });
await page.close().catch(() => undefined);
await context.close().catch(() => undefined);
await browser.close().catch(() => undefined);
}
}
main().catch((error) => {
console.error(error && error.stack ? error.stack : error);
process.exit(1);
});