An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Use mobile insertion menu layout in lite editors https://github.com/siyuan-note/siyuan/issues/19696
Danielacf8cd1a6005
diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex 979944b0f2..d334482127 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -1335,6 +1335,14 @@ body.mobile-topbar--merged {max-width: none;max-height: none !important;box-shadow: none;+ border: 0;+ padding: 0;+ background-color: transparent;++ .keyboard__slash-text {+ min-width: 0;+ overflow-wrap: anywhere;+ }}}@@ -1439,6 +1447,12 @@ body.mobile-topbar--merged {&-text {margin-left: 6px;}++ &-description {+ display: block;+ color: var(--b3-theme-on-surface);+ font-size: .75rem;+ }}&__font-size {diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex e52f29cf03..3781f70658 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -1515,7 +1515,7 @@ export const initKeyboardToolbar = () => {}const protyle = getCurrentEditor()?.protyle;const target = event.target as HTMLElement;- const liteSlashBtnElement = target.closest<HTMLElement>(".keyboard__util .protyle-hint .b3-list-item[data-value]");+ const liteSlashBtnElement = target.closest<HTMLElement>(".keyboard__util .protyle-hint .keyboard__slash-item[data-value]");const slashBtnElement = liteSlashBtnElement || hasClosestByClassName(target, "keyboard__slash-item");if (slashBtnElement && slashBtnElement.dataset.action === "fontFamilyMenu") {const range = protyle.toolbar.range.cloneRange();diff --git a/app/src/mobile/util/liteSlashMenu.test.ts b/app/src/mobile/util/liteSlashMenu.test.tsindex 969ad5477d..d4a9c4fcea 100644--- a/app/src/mobile/util/liteSlashMenu.test.ts+++ b/app/src/mobile/util/liteSlashMenu.test.ts@@ -5,12 +5,15 @@ 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";+import {createSourceFile, isClassDeclaration, isMethodDeclaration, ScriptTarget, transpileModule} from "typescript";-const browserCases = async (source: string) => {+const browserCases = async (source: string, hintSource: string) => {const check: typeof assert = require("node:assert/strict");- const mount: typeof import("./liteSlashMenu").mountLiteSlashMenu = new Function(source +- "\nreturn mountLiteSlashMenu;")();+ const {mount, render} = new Function(source + hintSource ++ "\nreturn {mount: mountLiteSlashMenu, render: Hint.prototype.getHTMLByData};")() as {+ mount: typeof import("./liteSlashMenu").mountLiteSlashMenu,+ render: (data: IHintData[]) => string,+ };window.siyuan = {languages: {emptyContent: "Empty"}} as unknown as typeof window.siyuan;const element = document.createElement("div");element.className = "protyle-hint fn__none";@@ -18,39 +21,67 @@ const browserCases = async (source: string) => {const next = document.createElement("div");document.body.appendChild(next);const panel = document.createElement("div");- document.body.appendChild(panel);+ panel.className = "keyboard__util";+ const toolbar = document.createElement("div");+ toolbar.id = "keyboardToolbar";+ toolbar.className = "keyboard";+ toolbar.style.height = "500px";+ toolbar.appendChild(panel);+ document.body.appendChild(toolbar);let finishRequest: () => void;const hint = {element,+ source: "hint",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.innerHTML = render.call(hint, items);element.classList.remove("fn__none");},};- const provider = {key: "/", hint: () => [{value: "```", html: "Code"}, {value: "$$", html: "Math", focus: false}]};+ const itemHTML = (name: string) => '<div class="b3-list-item__first">' ++ '<svg class="b3-list-item__graphic"><use xlink:href="#iconCode"></use></svg>' ++ `<span class="b3-list-item__text">${name}</span><span class="b3-list-item__meta">Markdown</span>` ++ '<span class="b3-menu__accelerator">Ctrl+K</span></div>';+ const items: IHintData[] = [{value: "```", html: itemHTML("代码块")},+ {value: "$$", html: itemHTML("公式块"), focus: false},+ {value: "", html: "separator"}, {value: "", html: "separator"},+ {value: "upload", html: itemHTML("插入图片或文件") + '<input class="b3-form__upload" type="file" data-upload-mode="html-iframe">'},+ {value: "", html: "separator"}];+ const provider = {key: "/", hint: (): IHintData[] => items};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(panel.querySelectorAll("button.keyboard__slash-item[data-value]").length, 3);+ check.equal(panel.querySelectorAll(".keyboard__slash-block").length, 2);+ check.equal(panel.querySelector(".b3-list-item, .b3-menu__accelerator, .b3-list-item__meta"), null);+ check.equal(panel.querySelector(".keyboard__slash-icon use").getAttribute("xlink:href"), "#iconCode");+ check.equal(panel.querySelectorAll('input[type="file"][data-upload-mode="html-iframe"]').length, 1);+ check.equal(panel.querySelector('[data-value="%24%24"]').getAttribute("data-focus"), "false");+ for (const width of [320, 390, 768]) {+ toolbar.style.width = `${width}px`;+ const buttons = panel.querySelectorAll<HTMLElement>("button");+ const first = buttons[0].getBoundingClientRect();+ const second = buttons[1].getBoundingClientRect();+ check.equal(first.top, second.top);+ check.ok(second.left > first.right);+ check.ok(first.width < width / 2);+ check.ok(first.height >= 50);+ check.equal(panel.scrollWidth, panel.clientWidth);+ }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);+ hint.genHTML(items.slice(0, 2));+ check.equal(element.querySelectorAll(".b3-list-item").length, 2);+ check.equal(element.querySelector(".keyboard__slash-block"), null);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"}]);+ hint.genHTML([{value: "skill", html: itemHTML("Skill") ++ '<div class="b3-list-item__meta b3-list-item__showall">Skill description</div>'}]);}};return [];@@ -59,7 +90,9 @@ const browserCases = async (source: string) => {check.equal(panel.textContent, "Loading");await Promise.resolve();finishRequest();- check.equal(panel.querySelector('[data-value="skill"]').textContent, "Skill");+ check.equal(panel.querySelector('[data-value="skill"]').className, "keyboard__slash-item");+ check.equal(panel.querySelector(".keyboard__slash-description").textContent, "Skill description");+ check.equal(panel.querySelector(".b3-list-item"), null);unmount();unmount = mount(protyle, panel);unmount();@@ -70,6 +103,9 @@ const browserCases = async (source: string) => {unmount = mount(protyle, panel);check.equal(panel.textContent, "Empty");unmount();+ provider.hint = () => items;+ mount(protyle, panel);+ toolbar.style.width = "390px";return "Mobile slash cases passed";};@@ -79,17 +115,34 @@ test("mobile slash panel retains synchronous and asynchronous candidates and rel}, async () => {const source = transpileModule(readFileSync(path.join(__dirname, "liteSlashMenu.ts"), "utf8").replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;+ const hintFile = createSourceFile("hint.ts", readFileSync(path.join(__dirname, "../../protyle/hint/index.ts"), "utf8"),+ ScriptTarget.Latest, true);+ const hintClass = hintFile.statements.find(isClassDeclaration);+ const render = hintClass.members.find(member => isMethodDeclaration(member) && member.name.getText(hintFile) === "getHTMLByData");+ const hintSource = transpileModule("class Hint {" + render.getText(hintFile) + "}", {+ 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}});+ const win = new BrowserWindow({show: false, width: 390, height: 500, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});try {await win.loadURL("data:text/html,<html><body></body></html>");+ await win.webContents.insertCSS(require("node:fs").readFileSync(+ ${JSON.stringify(path.resolve(__dirname, "../../../appearance/themes/daylight/theme.css"))}, "utf8"));+ await win.webContents.executeJavaScript(require("node:fs").readFileSync(+ ${JSON.stringify(path.resolve(__dirname, "../../../appearance/icons/litheness/icon.js"))}, "utf8"));+ await win.webContents.insertCSS(require(${JSON.stringify(require.resolve("sass"))}).compile(+ ${JSON.stringify(path.resolve(__dirname, "../../assets/scss/mobile.scss"))}, {logger: {warn() {}}}).css);console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +- browserCases.toString() + ")(" + JSON.stringify(source) + ")")}));+ browserCases.toString() + ")(" + JSON.stringify(source) + "," + JSON.stringify(hintSource) + ")")}));+ if (process.env.SIYUAN_MOBILE_SLASH_SCREENSHOT) {+ await new Promise(resolve => setTimeout(resolve, 200));+ require("node:fs").writeFileSync(process.env.SIYUAN_MOBILE_SLASH_SCREENSHOT, (await win.webContents.capturePage()).toPNG());+ }win.destroy();app.exit(0);} catch (error) {diff --git a/app/src/mobile/util/liteSlashMenu.ts b/app/src/mobile/util/liteSlashMenu.tsindex e63a86475f..28f60493d6 100644--- a/app/src/mobile/util/liteSlashMenu.ts+++ b/app/src/mobile/util/liteSlashMenu.ts@@ -1,3 +1,51 @@+export const getLiteSlashMenuHTML = (items: IHintData[]) => {+ const menu = document.createElement("div");+ let group: HTMLElement;+ items.forEach(item => {+ if (item.html === "separator") {+ group = undefined;+ return;+ }+ if (!group) {+ const space = document.createElement("div");+ space.className = "keyboard__slash-title";+ group = document.createElement("div");+ group.className = "keyboard__slash-block";+ menu.append(space, group);+ }+ const button = document.createElement("button");+ button.className = "keyboard__slash-item";+ button.dataset.id = item.id || "";+ button.dataset.value = encodeURIComponent(item.value);+ button.dataset.focus = item.focus === false ? "false" : "true";+ const content = document.createElement("div");+ content.innerHTML = item.html;+ const uploads = Array.from(content.querySelectorAll('input[type="file"]'));+ uploads.forEach(input => input.remove());+ const label = content.querySelector(".b3-list-item__text");+ const icon = content.querySelector(".b3-list-item__graphic, .color__square");+ if (icon) {+ icon.setAttribute("class", "keyboard__slash-icon");+ button.appendChild(icon);+ }+ const text = document.createElement("span");+ text.className = "keyboard__slash-text";+ text.innerHTML = label ? label.innerHTML : content.innerHTML;+ const description = content.querySelector(".b3-list-item__showall");+ if (label && description) {+ const detail = document.createElement("span");+ detail.className = "keyboard__slash-description";+ detail.textContent = description.textContent;+ text.appendChild(detail);+ }+ button.appendChild(text);+ // 附件控件保留在按钮内,继续由候选面板绑定上传事件。+ button.append(...uploads);+ group.appendChild(button);+ });+ return menu.innerHTML;+};+export const mountLiteSlashMenu = (protyle: IProtyle, container: Element) => {const hint = protyle.hint;const parent = hint.element.parentElement;@@ -11,9 +59,6 @@ export const mountLiteSlashMenu = (protyle: IProtyle, container: Element) => {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;diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex 932e4419c8..6d2c99cee3 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -75,6 +75,7 @@ import {shouldIgnoreHintTrigger,} from "./blockHintRange";import {getMobileHintPosition} from "./mobileHintPosition";+import {getLiteSlashMenuHTML} from "../../mobile/util/liteSlashMenu";import {getVisibleViewportBounds} from "../../mobile/util/visibleViewport";import {getTopBarHeight} from "../../layout/getTopBarHeight";import {getSemanticInlineVisibleText, stripSemanticMarkersFromRangeText} from "../util/inlineElementMarker";@@ -537,6 +538,9 @@ export class Hint {}private getHTMLByData(data: IHintData[]) {+ if (this.source === "hint" && this.element.closest("#keyboardToolbar")) {+ return getLiteSlashMenuHTML(data);+ }let hintsHTML = '<div style="flex: 1;overflow:auto;">';if (this.source !== "hint") {hintsHTML = '<input spellcheck="false" style="margin:0 8px 4px 8px" class="b3-text-field"><div style="flex: 1;overflow:auto;">';