Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Restore mobile lite editor insertion menus https://github.com/siyuan-note/siyuan/issues/19696

Danielb275dc7d0967
diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scss
index 909641d23e..979944b0f2 100644
--- a/app/src/assets/scss/main/_mobile.scss
+++ b/app/src/assets/scss/main/_mobile.scss
@@ -1327,6 +1327,15 @@ body.mobile-topbar--merged {
flex: 1;
overflow: auto;
background-color: var(--b3-theme-surface);
+
+ > .protyle-hint {
+ position: static;
+ width: auto !important;
+ min-width: 0;
+ max-width: none;
+ max-height: none !important;
+ box-shadow: none;
+ }
}
&__split {
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 5707e3bdba..93ac477944 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -81,11 +81,13 @@ import {applyMobileToolbarEntries} from "./toolbarEntries";
import {getEntryOrder, isEntryVisible} from "../../config/entryVisibility/runtime";
import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";
import {getKeyboardPanelHeight} from "./keyboardPanelHeight";
+import {mountLiteSlashMenu} from "./liteSlashMenu";
const getCurrentEditor = () => getMobileToolbarProtyle()?.getInstance() || getDocumentEditor();
const getKeyboardPaddingElement = (protyle: IProtyle) =>
protyle.lite ? protyle.contentElement : protyle.element.parentElement;
let toolbarProtyle: IProtyle;
+let unmountLiteSlashMenu: (() => void) | undefined;
const applyKeyboardToolbarEntries = (element: HTMLElement, toolbar: Array<string | IMenuItem>) => {
applyMobileToolbarEntries(element, toolbar, {
@@ -694,19 +696,7 @@ const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {
protyle.hint.lastIndex = -1;
if (protyle.lite) {
// 轻量编辑器沿用自己的插入候选,保留单元格内容限制和智能体技能入口。
- const items = protyle.options.hint.extend.find(item => item.key === "/")?.hint?.("", protyle, "hint") || [];
- protyle.hint.genHTML(items, protyle, true, "hint");
- const utilElement = toolbarElement.querySelector(".keyboard__util");
- utilElement.replaceChildren();
- if (items.length > 0) {
- Array.from(protyle.hint.element.children).forEach((element: HTMLElement, index) => {
- element.classList.add("keyboard__slash-item");
- element.setAttribute("data-focus", items[index]?.focus === false ? "false" : "true");
- utilElement.appendChild(element);
- });
- }
- protyle.hint.element.classList.add("fn__none");
- protyle.hint.bindUploadEvent(protyle, utilElement as HTMLElement);
+ unmountLiteSlashMenu = mountLiteSlashMenu(protyle, toolbarElement.querySelector(".keyboard__util"));
return;
}
let pluginHTML = "";
@@ -832,6 +822,8 @@ export const showKeyboardToolbarUtil = (oldScrollTop: number) => {
};
const resetKeyboardToolbarUtilButtons = () => {
+ unmountLiteSlashMenu?.();
+ unmountLiteSlashMenu = undefined;
const toolbarElement = document.getElementById("keyboardToolbar");
toolbarElement.querySelectorAll('[data-type="add"], [data-type="text"], [data-type="font-family"], [data-type="font-size"]')
.forEach(item => item.classList.remove("protyle-toolbar__item--current"));
@@ -1525,7 +1517,8 @@ export const initKeyboardToolbar = () => {
}
const protyle = getCurrentEditor()?.protyle;
const target = event.target as HTMLElement;
- const slashBtnElement = hasClosestByClassName(event.target as HTMLElement, "keyboard__slash-item");
+ const liteSlashBtnElement = target.closest<HTMLElement>(".keyboard__util .protyle-hint .b3-list-item[data-value]");
+ const slashBtnElement = liteSlashBtnElement || hasClosestByClassName(target, "keyboard__slash-item");
if (slashBtnElement && slashBtnElement.dataset.action === "fontFamilyMenu") {
const range = protyle.toolbar.range.cloneRange();
const nodeElements = getFontNodeElements(protyle);
@@ -1575,6 +1568,14 @@ export const initKeyboardToolbar = () => {
if (dataValue === Constants.ZWSP + 3) {
return;
}
+ if (liteSlashBtnElement) {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!dataValue) {
+ return;
+ }
+ hideKeyboardToolbarUtil();
+ }
protyle.hint.fill(dataValue, protyle, false); // 点击后 range 会改变
event.preventDefault();
event.stopPropagation();
@@ -1586,7 +1587,8 @@ export const initKeyboardToolbar = () => {
if (isInHarmony() || isInAndroid()) {
setTimeout(() => focusByRange(protyle.toolbar.range), Constants.TIMEOUT_TRANSITION);
}
- } else if (slashBtnElement.getAttribute("data-focus") === "true") {
+ } else if (slashBtnElement.getAttribute("data-focus") === "true" ||
+ liteSlashBtnElement && slashBtnElement.getAttribute("data-focus") !== "false") {
focusByRange(protyle.toolbar.range);
}
return;
diff --git a/app/src/mobile/util/liteSlashMenu.test.ts b/app/src/mobile/util/liteSlashMenu.test.ts
new file mode 100644
index 0000000000..969ad5477d
--- /dev/null
+++ b/app/src/mobile/util/liteSlashMenu.test.ts
@@ -0,0 +1,113 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {test} from "node:test";
+import {promisify} from "node:util";
+import {ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (source: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ const mount: typeof import("./liteSlashMenu").mountLiteSlashMenu = new Function(source +
+ "\nreturn mountLiteSlashMenu;")();
+ window.siyuan = {languages: {emptyContent: "Empty"}} as unknown as typeof window.siyuan;
+ const element = document.createElement("div");
+ element.className = "protyle-hint fn__none";
+ document.body.appendChild(element);
+ const next = document.createElement("div");
+ document.body.appendChild(next);
+ const panel = document.createElement("div");
+ document.body.appendChild(panel);
+ let finishRequest: () => void;
+ const hint = {
+ element,
+ enableExtend: false,
+ genHTML: (items: IHintData[]) => {
+ element.innerHTML = '<div style="flex:1;overflow:auto"></div>';
+ items.forEach(item => {
+ const button = document.createElement("button");
+ button.className = "b3-list-item";
+ button.dataset.value = item.value;
+ button.innerHTML = item.html;
+ element.firstElementChild.appendChild(button);
+ });
+ element.classList.remove("fn__none");
+ },
+ };
+ const provider = {key: "/", hint: () => [{value: "```", html: "Code"}, {value: "$$", html: "Math", focus: false}]};
+ const protyle = {hint, options: {hint: {extend: [provider]}}} as unknown as IProtyle;
+ let unmount = mount(protyle, panel);
+ check.equal(panel.querySelectorAll("button[data-value]").length, 2);
+ check.equal(panel.querySelector('[data-value="$$"]').getAttribute("data-focus"), "false");
+ check.equal(hint.enableExtend, true);
+ unmount();
+ check.equal(element.parentElement, document.body);
+ check.equal(element.nextSibling, next);
+ check.equal(element.classList.contains("fn__none"), true);
+ provider.hint = () => {
+ element.classList.remove("fn__none");
+ element.textContent = "Loading";
+ finishRequest = () => {
+ if (hint.enableExtend && !element.classList.contains("fn__none")) {
+ hint.genHTML([{value: "skill", html: "Skill"}]);
+ }
+ };
+ return [];
+ };
+ unmount = mount(protyle, panel);
+ check.equal(panel.textContent, "Loading");
+ await Promise.resolve();
+ finishRequest();
+ check.equal(panel.querySelector('[data-value="skill"]').textContent, "Skill");
+ unmount();
+ unmount = mount(protyle, panel);
+ unmount();
+ finishRequest();
+ check.equal(element.classList.contains("fn__none"), true);
+ check.equal(panel.children.length, 0);
+ provider.hint = () => [];
+ unmount = mount(protyle, panel);
+ check.equal(panel.textContent, "Empty");
+ unmount();
+ return "Mobile slash cases passed";
+};
+
+test("mobile slash panel retains synchronous and asynchronous candidates and releases its owner", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const source = transpileModule(readFileSync(path.join(__dirname, "liteSlashMenu.ts"), "utf8")
+ .replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-mobile-slash-test-"));
+ const script = path.join(temporary, "run.cjs");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +
+ browserCases.toString() + ")(" + JSON.stringify(source) + ")")}));
+ win.destroy();
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win.destroy();
+ app.exit(1);
+ }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],
+ {env, timeout: 40000, windowsHide: true});
+ assert.match(result.stdout, /Mobile slash cases passed/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&
+ path.basename(temporary).startsWith("siyuan-mobile-slash-test-")) {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});
diff --git a/app/src/mobile/util/liteSlashMenu.ts b/app/src/mobile/util/liteSlashMenu.ts
new file mode 100644
index 0000000000..e63a86475f
--- /dev/null
+++ b/app/src/mobile/util/liteSlashMenu.ts
@@ -0,0 +1,25 @@
+export const mountLiteSlashMenu = (protyle: IProtyle, container: Element) => {
+ const hint = protyle.hint;
+ const parent = hint.element.parentElement;
+ const next = hint.element.nextSibling;
+ hint.enableExtend = true;
+ hint.element.replaceChildren();
+ hint.element.classList.add("fn__none");
+ // 保留候选面板本身,异步技能结果和附件事件继续使用同一节点。
+ container.replaceChildren(hint.element);
+ const items = protyle.options.hint.extend.find(item => item.key === "/")?.hint?.("", protyle, "hint") || [];
+ if (items.length > 0 || hint.element.classList.contains("fn__none")) {
+ hint.genHTML(items.length > 0 ? items : [{value: "", html: window.siyuan.languages.emptyContent}],
+ protyle, false, "hint");
+ hint.element.querySelectorAll<HTMLElement>(".b3-list-item[data-value]").forEach((element, index) => {
+ element.dataset.focus = items[index]?.focus === false ? "false" : "true";
+ });
+ }
+ return () => {
+ hint.enableExtend = false;
+ hint.element.classList.add("fn__none");
+ if (hint.element.parentElement === container) {
+ parent.insertBefore(hint.element, next?.parentNode === parent ? next : null);
+ }
+ };
+};
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 8341b6333c..932e4419c8 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -134,6 +134,9 @@ export class Hint {
this.element.setAttribute("data-close", "false");
this.element.className = "protyle-hint b3-list b3-list--background fn__none";
this.element.addEventListener("click", (event) => {
+ if (this.element.closest("#keyboardToolbar")) {
+ return;
+ }
const eventTarget = event.target as HTMLElement;
if (eventTarget.tagName === "INPUT") {
event.stopPropagation();