An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Add mobile insert actions to command panel https://github.com/siyuan-note/siyuan/issues/19811
Daniel1d769e48cc34
diff --git a/app/src/boot/globalEvent/command/panel.ts b/app/src/boot/globalEvent/command/panel.tsindex e885e277e9..a549e2e909 100644--- a/app/src/boot/globalEvent/command/panel.ts+++ b/app/src/boot/globalEvent/command/panel.ts@@ -17,6 +17,7 @@ import {import type {ICommandContextSnapshot, ICommandDefinition} from "../../../command/types";/// #if MOBILEimport {activeBlur} from "../../../mobile/util/keyboardToolbar";+import {ensureMobileInsertCommands} from "../../../mobile/util/mobileInsertCommands";/// #endifconst renderCommands = (listElement: HTMLElement, commands: ICommandDefinition[]) => {@@ -66,6 +67,9 @@ export const commandPanel = (app: App) => {}const context = captureCommandContext({app, source: "commandPanel"});const registry = ensureCommandSystem(app);+ /// #if MOBILE+ ensureMobileInsertCommands(app);+ /// #endifconst restoreFocusAfterCancel = !isMobile() || document.body.classList.contains("mobile-keyboard--open");const focusLifecycle = createPaletteFocusLifecycle(() => {if (context.range?.startContainer.isConnected) {diff --git a/app/src/mobile/util/mobileInsertCommands.test.ts b/app/src/mobile/util/mobileInsertCommands.test.tsnew file mode 100644index 0000000000..6ce0e06057--- /dev/null+++ b/app/src/mobile/util/mobileInsertCommands.test.ts@@ -0,0 +1,93 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {join} from "node:path";+import test from "node:test";+import {runInNewContext} from "node:vm";+import * as ts from "typescript";+import {getCommandRegistry} from "../../command/service";+import {queryCommandPalette, recordPaletteCommand} from "../../command/paletteCore";+import type {ICommandContextSnapshot} from "../../command/types";++const source = ts.transpileModule(readFileSync(join(process.cwd(), "src/mobile/util/mobileInsertCommands.ts"), "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},+}).outputText;++test("mobile insert commands search and execute the existing insertion actions at the saved cursor", async () => {+ const languages = new Proxy({template: "模板", assets: "资源", callout: "提示"} as Record<string, string>, {+ get: (target, key: string) => target[key] || key,+ });+ const siyuan = {config: {readonly: false}, isPublish: false, languages};+ const fills: string[] = [];+ const focused: unknown[] = [];+ let keyboards = 0;+ let picked = false;+ let uploadBound = false;+ const input = {+ type: "", className: "", multiple: false, accept: "", capture: "",+ addEventListener() {}, click() { picked = true; },+ };+ const uploadHost = {hidden: false, append() {}, remove() {}};+ const document = {createElement: (tag: string) => tag === "input" ? input : uploadHost,+ body: {append: (host: unknown) => assert.equal(host, uploadHost)}};+ const module = {exports: {}};+ const mocks: Record<string, unknown> = {+ "../../command/service": {getCommandRegistry},+ "../../command/english": {getEnglishCommandLabel: (key: string) => key},+ "../../protyle/hint/extend": {getBuiltinSlashMenuItems: () => [+ {id: "template", value: "template-value"}, {id: "ref", value: "(("},+ ]},+ "../../protyle/toolbar/inlineStyle": {isBuiltinInlineStyleVisible: () => true},+ "../../protyle/util/selection": {focusByRange: (range: unknown) => focused.push(range)},+ "../../protyle/util/compatibility": {isDisabledFeature: () => false, isInAndroid: () => false},+ "../../util/hostCapabilities": {getHostCapabilities: () => ({widgets: true, remoteKernel: false})},+ "./mobileAppUtil": {callMobileAppShowKeyboard: () => keyboards++},+ };+ runInNewContext(source, {module, exports: module.exports, require: (id: string) => mocks[id] || {},+ window: {siyuan}, document});+ const {ensureMobileInsertCommands} = module.exports as typeof import("./mobileInsertCommands");+ const app = {};+ ensureMobileInsertCommands(app);+ const registry = getCommandRegistry(app);+ const container = {isConnected: true};+ const range = {startContainer: container, endContainer: container, cloneRange() { return {...this}; }};+ const protyle = {+ lite: false, disabled: false, wysiwyg: {element: {contains: (node: unknown) => node === container}},+ options: {upload: {accept: "image/*"}}, toolbar: {range: undefined as unknown},+ hint: {splitChar: "", lastIndex: 2, fill: (value: string) => fills.push(value),+ bindUploadEvent: (_protyle: unknown, host: unknown) => { uploadBound = host === uploadHost; }},+ };+ const context = {+ app, source: "commandPanel", environment: "mobile", focus: "editor", selectedBlocks: [], protyle, range,+ } as unknown as ICommandContextSnapshot;+ const visible = registry.list(context).map(command => command.id);+ assert.ok(visible.includes("core.mobile.insert.template"));+ assert.ok(visible.includes("core.mobile.insert.insertAsset"));+ assert.ok(visible.includes("core.mobile.insert.mindmap"));+ assert.ok(!visible.includes("core.mobile.insert.insertPhoto"));+ assert.equal(queryCommandPalette(registry, context, "模板")[0].id, "core.mobile.insert.template");+ const recent = recordPaletteCommand([], "core.mobile.insert.assets");+ assert.equal(queryCommandPalette(registry, context, "", recent)[0].id, "core.mobile.insert.assets");+ assert.equal((await registry.execute("core.mobile.insert.template", context)).status, "executed");+ assert.deepEqual(fills, ["template-value"]);+ assert.equal(protyle.hint.splitChar, "/");+ assert.equal(protyle.hint.lastIndex, -1);+ assert.equal(focused.length, 1);+ assert.ok(protyle.toolbar.range);+ await registry.execute("core.mobile.insert.ref", context);+ assert.deepEqual(fills, ["template-value", "(("]);+ assert.equal(keyboards, 1);+ await registry.execute("core.mobile.insert.insertAsset", context);+ assert.equal(uploadBound, true);+ assert.equal(picked, true);+ assert.equal(input.accept, "image/*");+ assert.equal(uploadHost.hidden, true);+ assert.equal(registry.list({...context, environment: "desktop"}).length, 0);+ siyuan.config.readonly = true;+ assert.equal(registry.list(context).length, 0);+ siyuan.config.readonly = false;+ siyuan.isPublish = true;+ assert.equal(registry.list(context).length, 0);+ siyuan.isPublish = false;+ container.isConnected = false;+ assert.equal(registry.list(context).length, 0);+});diff --git a/app/src/mobile/util/mobileInsertCommands.ts b/app/src/mobile/util/mobileInsertCommands.tsnew file mode 100644index 0000000000..4fef2feaa4--- /dev/null+++ b/app/src/mobile/util/mobileInsertCommands.ts@@ -0,0 +1,145 @@+import {getCommandRegistry} from "../../command/service";+import {getEnglishCommandLabel} from "../../command/english";+import type {ICommandContextSnapshot, ICommandDefinition} from "../../command/types";+import {getBuiltinSlashMenuItems} from "../../protyle/hint/extend";+import {isBuiltinInlineStyleVisible, type TBuiltinInlineStyleID} from "../../protyle/toolbar/inlineStyle";+import {focusByRange} from "../../protyle/util/selection";+import {isDisabledFeature, isInAndroid} from "../../protyle/util/compatibility";+import {getHostCapabilities} from "../../util/hostCapabilities";+import {callMobileAppShowKeyboard} from "./mobileAppUtil";++const initializedApps = new WeakSet<object>();++// 与移动端加号菜单的内置插入项保持一致,具体插入值仍由斜杠菜单提供。+const INSERT_IDS = [+ "template", "widget", "assets", "ref", "blockEmbed", "aiWriting", "database", "newSubDocRef",+ "insertAsset", "insertIframeURL", "insertImgURL", "insertVideoURL", "insertAudioURL", "emoji",+ "heading1", "heading2", "heading3", "heading4", "heading5", "heading6",+ "list", "orderedList", "check", "quote", "tabs", "mindmap",+ "calloutNote", "calloutTip", "calloutImportant", "calloutWarning", "calloutCaution",+ "code", "table", "line", "math", "html", "staff", "chart", "flowChart", "graph", "mermaid", "UML",+ "infoStyle", "successStyle", "warningStyle", "errorStyle", "clearFontStyle",+] as const;+const BUILTIN_STYLES: Record<string, TBuiltinInlineStyleID> = {+ infoStyle: "info", successStyle: "success", warningStyle: "warning", errorStyle: "error",+};+const SPECIAL_LABELS: Record<string, string> = {+ html: "HTML", flowChart: "Flow Chart", graph: "Graph", mermaid: "Mermaid", UML: "UML",+};++const labelKey = (id: string) => id === "orderedList" ? "ordered-list" : id;+const label = (id: string, english = false) => {+ if (id.startsWith("callout")) {+ const kind = id.slice("callout".length);+ const callout = english ? getEnglishCommandLabel("callout") : window.siyuan.languages.callout;+ return `${callout || window.siyuan.languages.callout} - ${kind}`;+ }+ return SPECIAL_LABELS[id] || (english ? getEnglishCommandLabel(labelKey(id)) : window.siyuan.languages[labelKey(id)]) || id;+};++const available = (context: ICommandContextSnapshot, id: string) => {+ const protyle = context.protyle;+ const range = context.range;+ if (!protyle || protyle.lite || protyle.disabled || window.siyuan.isPublish || window.siyuan.config.readonly ||+ !range?.startContainer.isConnected || !range.endContainer.isConnected ||+ !protyle.wysiwyg.element.contains(range.startContainer) ||+ !protyle.wysiwyg.element.contains(range.endContainer)) {+ return false;+ }+ if (id === "widget") {+ return getHostCapabilities().widgets;+ }+ if (id === "aiWriting") {+ return !isDisabledFeature("ai");+ }+ if (id === "insertIframeURL") {+ return !getHostCapabilities().remoteKernel;+ }+ if (id === "insertImage" || id === "insertPhoto") {+ return Boolean(isInAndroid());+ }+ if (BUILTIN_STYLES[id]) {+ return isBuiltinInlineStyleVisible("style1", BUILTIN_STYLES[id]);+ }+ return true;+};++const openUpload = (context: ICommandContextSnapshot, id: string) => {+ const protyle = context.protyle;+ const host = document.createElement("div");+ const input = document.createElement("input");+ host.hidden = true;+ input.type = "file";+ input.className = "b3-form__upload";+ input.multiple = id !== "insertPhoto";+ if (id === "insertImage") {+ input.accept = "image/*,application/x-siyuan-image-picker";+ } else if (id === "insertPhoto") {+ input.accept = "image/*";+ input.capture = "user";+ } else if (protyle.options.upload.accept) {+ input.accept = protyle.options.upload.accept;+ }+ host.append(input);+ document.body.append(host);+ protyle.toolbar.range = context.range.cloneRange();+ protyle.hint.lastIndex = -1;+ protyle.hint.bindUploadEvent(protyle, host);+ const cleanup = () => host.remove();+ input.addEventListener("change", cleanup, {once: true});+ input.addEventListener("cancel", cleanup, {once: true});+ input.click();+};++const executeInsert = (context: ICommandContextSnapshot, id: string) => {+ if (!available(context, id)) {+ return;+ }+ if (["insertAsset", "insertImage", "insertPhoto"].includes(id)) {+ openUpload(context, id);+ return;+ }+ const protyle = context.protyle;+ const item = getBuiltinSlashMenuItems(protyle).find(candidate => candidate.id === id);+ if (!item) {+ return;+ }+ protyle.toolbar.range = context.range.cloneRange();+ protyle.hint.splitChar = "/";+ protyle.hint.lastIndex = -1;+ focusByRange(protyle.toolbar.range);+ protyle.hint.fill(item.value, protyle, false);+ if (id === "ref" || id === "blockEmbed") {+ callMobileAppShowKeyboard();+ }+};++export const ensureMobileInsertCommands = (app: object) => {+ if (initializedApps.has(app)) {+ return;+ }+ const registry = getCommandRegistry(app);+ const owner = {};+ const disposers: Array<() => boolean> = [];+ try {+ [...INSERT_IDS, "insertImage", "insertPhoto"].forEach((id, order) => {+ const command: ICommandDefinition = {+ id: `core.mobile.insert.${id}`,+ category: "core",+ label: () => label(id),+ englishLabel: () => label(id, true),+ keywords: () => [id],+ surfaces: ["commandPanel"],+ platform: environment => environment === "mobile" || environment === "browser-mobile",+ order: 2000 + order,+ when: context => available(context, id),+ execute: context => executeInsert(context, id),+ };+ disposers.push(registry.register(command, owner));+ });+ initializedApps.add(app);+ } catch (error) {+ disposers.reverse().forEach(dispose => dispose());+ throw error;+ }+};