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 contextual commands to the command palette https://github.com/siyuan-note/siyuan/issues/19047
Vanessa1c72c65a3bbb
diff --git a/app/src/command/contextCommands.ts b/app/src/command/contextCommands.tsnew file mode 100644index 0000000000..716004084f--- /dev/null+++ b/app/src/command/contextCommands.ts@@ -0,0 +1,294 @@+import type {App} from "../index";+import type {ICommandContextSnapshot, ICommandDefinition, TCommandKeymapPath} from "./types";+import {getCommandRegistry} from "./service";+import {getEnglishCommandLabel} from "./english";+import {getCommandBlocks, getCommandDocument, hasCommandEditorTarget} from "./contextTargets";+import {isInEmbedBlock} from "../protyle/util/hasClosest";+import {focusByRange, getEditorRange} from "../protyle/util/selection";+import {getNextBlockSibling} from "../protyle/wysiwyg/getBlock";+import {turnsIntoGroupsTransaction, turnsIntoTransaction, turnsOneInto} from "../protyle/wysiwyg/transaction";+import {turnParagraphIntoCode} from "../protyle/wysiwyg/turnIntoCode";+import {getListConversionType, type TListSubtype} from "../protyle/wysiwyg/listContext";+import {removeBlockPreservingSelectionMode} from "../protyle/wysiwyg/remove";+import {foldBlocksRecursively, foldHeadingGroup, getFoldBlock, setFold} from "../protyle/util/blockFold";+import {pasteAsPlainText, pasteEscaped} from "../protyle/util/paste";+import {insertColumn, insertRow, insertRowAbove} from "../protyle/util/table";+import {tableMenu} from "../menus/protyle";+import {deleteFile} from "../editor/deleteFile";+import {newFileInTree} from "../util/newFile";+import {newNotebook} from "../util/mount";+import {pathPosix} from "../util/pathName";+import {isCustomFileTreeList} from "../util/fileTreeSort";+/// #if !MOBILE+import {Tab} from "../layout/Tab";+/// #endif++const initialized = new WeakSet<object>();+const editable = (context: ICommandContextSnapshot) => !window.siyuan.config.readonly &&+ !context.protyle?.disabled && hasCommandEditorTarget(context) &&+ getCommandBlocks(context).every(block => !isInEmbedBlock(block.element));+const documentWritable = (context: ICommandContextSnapshot) => {+ const doc = getCommandDocument(context);+ return Boolean(doc?.notebookId && doc.path?.endsWith(".sy") && !window.siyuan.config.readonly &&+ (context.focus === "fileTree" || !context.protyle.disabled));+};+const blocks = (context: ICommandContextSnapshot) => getCommandBlocks(context).map(block => block.element);+const label = (keys: string[], english = false) => keys.map(key =>+ (english ? getEnglishCommandLabel(key) : window.siyuan.languages[key]) || key).join(" - ");++const getTableMenus = (context: ICommandContextSnapshot) => {+ if (!editable(context) || context.selectedBlocks.length || !context.tableCell ||+ context.block?.element.getAttribute("data-type") !== "NodeTable") {+ return [];+ }+ const cell = context.tableCell.element;+ if (!cell.isConnected || !context.block.element.contains(cell) ||+ !cell.contains(context.range.startContainer) || !cell.contains(context.range.endContainer)) {+ return [];+ }+ return tableMenu(context.protyle, context.block.element, cell, context.range).menus;+};++const getFoldTargets = (context: ICommandContextSnapshot) => {+ let elements: Element[] = [];+ if (editable(context) && context.selectedBlocks.length <= 1) {+ getFoldBlock(context.protyle, context.block?.element || blocks(context)[0], targets => elements = targets);+ }+ return elements;+};++export const ensureContextCommands = (app: App) => {+ if (initialized.has(app)) {+ return;+ }+ const commands: ICommandDefinition[] = [];+ const add = (id: string, keys: string[], when: ICommandDefinition["when"],+ execute: ICommandDefinition["execute"], keymapPath?: TCommandKeymapPath) => {+ commands.push({+ id: `core.context.${id}`,+ category: "core",+ label: () => label(keys),+ englishLabel: () => label(keys, true),+ keywords: () => [id, ...keys],+ surfaces: ["commandPanel"],+ order: 1000 + commands.length,+ keymapPath,+ hotkey: keymapPath ? () => keymapPath[0] === "editor" ?+ window.siyuan.config.keymap.editor[keymapPath[1] as keyof Config.IKeymapEditor]?.[keymapPath[2]]?.custom || "" : "" : undefined,+ when,+ execute: context => {+ if (!when(context)) {+ return;+ }+ if (hasCommandEditorTarget(context)) {+ focusByRange(context.range);+ }+ return execute(context);+ },+ });+ };++ /// #if !MOBILE+ const getTab = (context: ICommandContextSnapshot) => {+ const tab = (context.activeTab?.model as {parent?: Tab})?.parent;+ return tab instanceof Tab && tab.id === context.activeTab.id && tab.headElement.isConnected ? tab : undefined;+ };+ ["pin", "unpin"].forEach(key => add(`tab.${key}`, ["mobileTabs", key], context => {+ const tab = getTab(context);+ return Boolean(tab && tab.headElement.classList.contains("item--pin") === (key === "unpin"));+ }, context => key === "pin" ? getTab(context).pin() : getTab(context).unpin()));+ /// #endif++ add("notebook.new", ["newNotebook"], () => !window.siyuan.config.readonly, () => newNotebook());+ ["newDocAbove", "newDocBelow"].forEach(key => add(`document.${key}`, ["doc", key], context => {+ if (!documentWritable(context)) {+ return false;+ }+ const doc = getCommandDocument(context);+ const element = context.fileTree?.elements[0] || document.querySelector(+ `.sy__file li[data-node-id="${doc.id}"]`);+ return Boolean(element && isCustomFileTreeList(element.parentElement));+ }, context => {+ const doc = getCommandDocument(context);+ newFileInTree(app, doc.notebookId, pathPosix().dirname(doc.path), {+ targetID: doc.id,+ position: key === "newDocAbove" ? "before" : "after",+ });+ }));+ add("document.delete", ["doc", "delete"], documentWritable, context => {+ const doc = getCommandDocument(context);+ return deleteFile(doc.notebookId, doc.path);+ });++ const convertible = (context: ICommandContextSnapshot) => editable(context) &&+ blocks(context).every(element => ["NodeParagraph", "NodeHeading"].includes(element.dataset.type));+ const selectedList = (context: ICommandContextSnapshot) => {+ const targets = blocks(context);+ if (targets.length !== 1) {+ return undefined;+ }+ if (targets[0].dataset.type === "NodeList") {+ return targets[0];+ }+ return undefined;+ };+ const groupedTypes: Array<[string, Exclude<TTurnIntoOne, "BlocksMergeSuperBlock">]> = [+ ["list", "Blocks2ULs"], ["ordered-list", "Blocks2OLs"], ["check", "Blocks2TLs"], ["quote", "Blocks2Blockquote"],+ ];+ groupedTypes.forEach(([key, type]) => add(`block.${key}`, ["turnInto", key], context => {+ if (!editable(context)) {+ return false;+ }+ const list = selectedList(context);+ if (list && key !== "quote") {+ const subtype = key === "list" ? "u" : key === "ordered-list" ? "o" : "t";+ return Boolean(getListConversionType(list.dataset.subtype as TListSubtype, subtype));+ }+ return convertible(context) || Boolean(list);+ }, context => {+ const list = selectedList(context);+ if (list && key !== "quote") {+ const subtype = key === "list" ? "u" : key === "ordered-list" ? "o" : "t";+ if (subtype !== list.dataset.subtype) {+ return turnsOneInto({protyle: context.protyle, nodeElement: list, id: list.dataset.nodeId,+ type: getListConversionType(list.dataset.subtype as TListSubtype, subtype)});+ }+ return;+ }+ const groups: Element[][] = [];+ blocks(context).forEach(element => {+ const group = groups[groups.length - 1];+ if (group && getNextBlockSibling(group[group.length - 1]) === element &&+ group[0].parentElement === element.parentElement) {+ group.push(element);+ } else {+ groups.push([element]);+ }+ });+ return turnsIntoGroupsTransaction({protyle: context.protyle, selectsElementGroups: groups, type});+ }, ["editor", "insert", key]));+ ["paragraph", "heading1", "heading2", "heading3", "heading4", "heading5", "heading6"].forEach(key =>+ add(`block.${key}`, ["turnInto", key], context => convertible(context) || key === "paragraph" &&+ editable(context) && (Boolean(selectedList(context)) || blocks(context).length === 1 &&+ blocks(context)[0].dataset.type === "NodeBlockquote"), context => {+ const list = key === "paragraph" && selectedList(context);+ if (list) {+ return turnsOneInto({protyle: context.protyle, nodeElement: list, id: list.dataset.nodeId, type: "CancelList"});+ }+ const blockquote = blocks(context)[0];+ if (key === "paragraph" && blockquote.dataset.type === "NodeBlockquote") {+ return turnsOneInto({protyle: context.protyle, nodeElement: blockquote,+ id: blockquote.dataset.nodeId, type: "CancelBlockquote"});+ }+ return turnsIntoTransaction({+ protyle: context.protyle,+ selectsElement: blocks(context),+ type: key === "paragraph" ? "Blocks2Ps" : "Blocks2Hs",+ level: key.startsWith("heading") ? Number(key.slice(-1)) : undefined,+ });+ }, ["editor", "heading", key]));+ add("block.code", ["turnInto", "code"], context => editable(context) && blocks(context).length === 1 &&+ blocks(context)[0].dataset.type === "NodeParagraph", context => turnParagraphIntoCode(context.protyle, blocks(context)[0]),+ ["editor", "insert", "code"]);++ const remove = async (context: ICommandContextSnapshot, targets: HTMLElement[]) => {+ const added = targets.filter(element => !element.classList.contains("protyle-wysiwyg--select"));+ added.forEach(element => element.classList.add("protyle-wysiwyg--select"));+ try {+ return await removeBlockPreservingSelectionMode(context.protyle, targets[0], getEditorRange(targets[0]), "Backspace");+ } finally {+ added.forEach(element => element.classList.remove("protyle-wysiwyg--select"));+ }+ };+ add("block.delete", ["blockCount", "delete"], editable, context => remove(context, blocks(context)));++ ["fold", "foldChildHeadings", "foldSiblingHeadings", "foldRecursive"].forEach(key =>+ add(`block.${key}`, ["blockCount", key], context => {+ const targets = getFoldTargets(context);+ if (!targets.length) {+ return false;+ }+ if (key === "foldChildHeadings" || key === "foldSiblingHeadings") {+ return targets[0].getAttribute("data-type") === "NodeHeading";+ }+ return targets[0].getAttribute("data-type") !== "NodeThematicBreak";+ }, context => {+ const targets = getFoldTargets(context);+ if (key === "foldRecursive") {+ return foldBlocksRecursively(context.protyle, targets);+ }+ if (key === "foldChildHeadings" || key === "foldSiblingHeadings") {+ return foldHeadingGroup(context.protyle, targets[0], key === "foldChildHeadings" ? "children" : "siblings");+ }+ return setFold(context.protyle, targets[0]).ready;+ }, key === "fold" ? undefined : ["editor", "general", key]));++ const tableKeys = ["insertRowAbove", "insertRowBelow", "insertColumnLeft", "insertColumnRight",+ "moveToUp", "moveToDown", "moveToLeft", "moveToRight", "delete-row", "delete-column"];+ tableKeys.forEach(key => {+ const menuId = key === "delete-row" ? "deleteRow" : key === "delete-column" ? "deleteColumn" : key;+ const keys = ["table"];+ if (key.startsWith("moveTo")) {+ keys.push(key === "moveToUp" || key === "moveToDown" ? "row" : "column");+ }+ keys.push(key);+ add(`table.${key}`, keys, context => {+ if (!getTableMenus(context).some(item => item.id === menuId)) {+ return false;+ }+ const cell = context.tableCell.element;+ const table = cell.closest("table");+ const row = cell.parentElement as HTMLTableRowElement;+ if (key === "moveToUp") {+ return row.rowIndex > 0;+ }+ if (key === "moveToDown") {+ return row.rowIndex < table.rows.length - 1;+ }+ if (key === "moveToLeft") {+ return cell.cellIndex > 0;+ }+ if (key === "moveToRight") {+ return cell.cellIndex < row.cells.length - 1;+ }+ return true;+ }, context => {+ const protyle = context.protyle;+ const range = context.range;+ const cell = context.tableCell.element;+ const node = context.block.element;+ if (key === "insertRowAbove") {+ return insertRowAbove(protyle, range, cell, node);+ }+ if (key === "insertRowBelow") {+ return insertRow(protyle, range, cell, node);+ }+ if (key === "insertColumnLeft" || key === "insertColumnRight") {+ return insertColumn(protyle, node, cell, key === "insertColumnLeft" ? "beforebegin" : "afterend", range);+ }+ getTableMenus(context).find(item => item.id === menuId)?.click?.(undefined, undefined);+ }, ["editor", "table", key]);+ });+ ["pasteAsPlainText", "pasteEscaped"].forEach(key => add(`editor.${key}`, [key], context =>+ editable(context) && !context.selectedBlocks.length, context => {+ const prepareInsertion = () => {+ if (!editable(context)) {+ return false;+ }+ focusByRange(context.range);+ return true;+ };+ return key === "pasteAsPlainText" ? pasteAsPlainText(context.protyle, prepareInsertion) :+ pasteEscaped(context.protyle, context.block.element, prepareInsertion);+ }));++ const registry = getCommandRegistry(app);+ const disposers: Array<() => boolean> = [];+ try {+ commands.forEach(command => disposers.push(registry.register(command, app)));+ initialized.add(app);+ } catch (error) {+ disposers.reverse().forEach(dispose => dispose());+ throw error;+ }+};diff --git a/app/src/command/contextTargets.test.ts b/app/src/command/contextTargets.test.tsnew file mode 100644index 0000000000..098fe7d6d2--- /dev/null+++ b/app/src/command/contextTargets.test.ts@@ -0,0 +1,109 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {getCommandBlocks, getCommandDocument, hasCommandEditorTarget} from "./contextTargets";+import type {ICommandContextSnapshot} from "./types";++const createEditorContext = () => {+ const first = {isConnected: true, getAttribute: () => "first"} as unknown as HTMLElement;+ const second = {isConnected: true, getAttribute: () => "second"} as unknown as HTMLElement;+ const state = {selected: [] as HTMLElement[], nodes: [first, second]};+ const element = {+ isConnected: true,+ contains: (node: HTMLElement) => state.nodes.includes(node),+ querySelectorAll: () => state.selected,+ } as unknown as HTMLElement;+ const context: ICommandContextSnapshot = {+ app: {}, source: "commandPanel", environment: "desktop", focus: "editor",+ selectedBlocks: [], block: {id: "first", element: first},+ range: {startContainer: first, endContainer: first} as unknown as Range,+ document: {rootId: "doc", notebookId: "box", path: "/doc.sy"},+ protyle: {+ element, wysiwyg: {element}, block: {rootID: "doc"}, notebookId: "box", path: "/doc.sy",+ } as unknown as IProtyle,+ };+ return {context, state, first, second};+};++describe("context command targets", () => {+ it("prioritizes selected blocks over the current block", () => {+ const {context, state, second} = createEditorContext();+ context.selectedBlocks = [{id: "second", element: second}];+ state.selected = [second];+ assert.equal(hasCommandEditorTarget(context), true);+ assert.deepEqual(getCommandBlocks(context), context.selectedBlocks);+ context.selectedBlocks = [];+ state.selected = [];+ assert.deepEqual(getCommandBlocks(context), [context.block]);+ });++ it("retains the captured editor target after palette focus changes", () => {+ const {context} = createEditorContext();+ context.activeElement = {} as HTMLElement;+ assert.equal(hasCommandEditorTarget(context), true);+ assert.deepEqual(getCommandDocument(context), {id: "doc", notebookId: "box", path: "/doc.sy"});+ assert.deepEqual(getCommandBlocks(context), [context.block]);+ });++ it("does not fall back to an editor when the file tree or dock owns focus", () => {+ const {context} = createEditorContext();+ for (const focus of ["fileTree", "dock", "global"] as const) {+ context.focus = focus;+ assert.equal(hasCommandEditorTarget(context), false);+ assert.equal(getCommandDocument(context), undefined);+ }+ });++ it("rejects detached, replaced, or cross-editor targets", () => {+ const {context, state, second} = createEditorContext();+ state.nodes = [second];+ assert.equal(hasCommandEditorTarget(context), false);+ state.nodes = [context.block.element, second];+ context.block.id = "replacement";+ assert.equal(hasCommandEditorTarget(context), false);+ context.block.id = "first";+ context.range = {startContainer: context.block.element, endContainer: {}} as unknown as Range;+ assert.equal(hasCommandEditorTarget(context), false);+ });++ it("requires the entire captured block selection to remain unchanged", () => {+ const {context, state, first, second} = createEditorContext();+ context.selectedBlocks = [{id: "first", element: first}, {id: "second", element: second}];+ state.selected = [first, second];+ assert.equal(hasCommandEditorTarget(context), true);+ assert.deepEqual(getCommandBlocks(context), context.selectedBlocks);+ state.selected = [first];+ assert.equal(hasCommandEditorTarget(context), false);+ context.selectedBlocks = [];+ assert.equal(hasCommandEditorTarget(context), false);+ });++ it("rejects an editor that has navigated to another document", () => {+ const {context} = createEditorContext();+ context.protyle.block.rootID = "other";+ assert.equal(hasCommandEditorTarget(context), false);+ assert.equal(getCommandDocument(context), undefined);+ context.protyle.block.rootID = "doc";+ context.protyle.path = "/moved/doc.sy";+ assert.equal(getCommandDocument(context), undefined);+ });++ it("uses only a single unchanged document tree item", () => {+ const {context} = createEditorContext();+ const attrs: Record<string, string> = {+ "data-type": "navigation-file", "data-node-id": "tree-doc",+ "data-path": "/tree-doc.sy", "data-notebook-id": "tree-box",+ };+ const item = {isConnected: true, getAttribute: (key: string) => attrs[key]} as unknown as HTMLElement;+ context.focus = "fileTree";+ context.fileTree = {elements: [item], ids: ["tree-doc"], paths: ["/tree-doc.sy"]};+ assert.deepEqual(getCommandDocument(context), {id: "tree-doc", path: "/tree-doc.sy", notebookId: "tree-box"});+ context.fileTree.elements.push(item);+ assert.equal(getCommandDocument(context), undefined);+ context.fileTree.elements.pop();+ attrs["data-path"] = "/moved.sy";+ assert.equal(getCommandDocument(context), undefined);+ attrs["data-path"] = "/tree-doc.sy";+ attrs["data-type"] = "navigation-root";+ assert.equal(getCommandDocument(context), undefined);+ });+});diff --git a/app/src/command/contextTargets.ts b/app/src/command/contextTargets.tsnew file mode 100644index 0000000000..21c8bfaba7--- /dev/null+++ b/app/src/command/contextTargets.ts@@ -0,0 +1,53 @@+import type {ICommandContextSnapshot} from "./types";++export const getCommandBlocks = (context: ICommandContextSnapshot) =>+ context.selectedBlocks.length ? context.selectedBlocks : context.block ? [context.block] : [];++export const hasCommandEditorTarget = (context: ICommandContextSnapshot) => {+ const editor = context.protyle?.wysiwyg?.element;+ const range = context.range;+ if (context.focus !== "editor" || !editor?.isConnected || !range ||+ !editor.contains(range.startContainer) || !editor.contains(range.endContainer)) {+ return false;+ }+ if (context.document && (context.document.rootId !== context.protyle.block.rootID ||+ context.document.notebookId !== context.protyle.notebookId)) {+ return false;+ }+ const blocks = getCommandBlocks(context);+ if (!blocks.length || blocks.some(block => !block.element.isConnected ||+ !editor.contains(block.element) || block.element.getAttribute("data-node-id") !== block.id)) {+ return false;+ }+ // 面板打开后选中集合发生变化时取消操作,避免底层函数使用新的选中目标。+ const selected = Array.from(editor.querySelectorAll(".protyle-wysiwyg--select"));+ return selected.length === context.selectedBlocks.length &&+ context.selectedBlocks.every(block => selected.includes(block.element));+};++export const getCommandDocument = (context: ICommandContextSnapshot) => {+ if (context.focus === "fileTree") {+ const elements = context.fileTree?.elements;+ if (elements?.length !== 1) {+ return undefined;+ }+ const element = elements[0];+ if (!element.isConnected || element.getAttribute("data-type") !== "navigation-file" ||+ element.getAttribute("data-node-id") !== context.fileTree.ids[0] ||+ element.getAttribute("data-path") !== context.fileTree.paths[0]) {+ return undefined;+ }+ return {+ id: context.fileTree.ids[0],+ path: context.fileTree.paths[0],+ notebookId: element.getAttribute("data-notebook-id") || element.closest("ul[data-url]")?.getAttribute("data-url"),+ };+ }+ const protyle = context.protyle;+ const doc = context.document;+ if (context.focus !== "editor" || !protyle?.element.isConnected || !doc?.rootId ||+ protyle.block.rootID !== doc.rootId || protyle.path !== doc.path || protyle.notebookId !== doc.notebookId) {+ return undefined;+ }+ return {id: doc.rootId, path: doc.path, notebookId: doc.notebookId};+};diff --git a/app/src/command/executor.ts b/app/src/command/executor.tsindex cb4f965605..c7e951363c 100644--- a/app/src/command/executor.ts+++ b/app/src/command/executor.ts@@ -3,6 +3,7 @@ import {captureCommandContext} from "./context";import {ensureNativeCommands, getNativeCommandId} from "./nativeCommands";import {executeLegacyNativeCommand} from "./nativeRuntime";import {getCommandRegistry} from "./service";+import {ensureContextCommands} from "./contextCommands";import type {ICommandContextSnapshot, TCommandSource} from "./types";interface IExecByCommandOptions {@@ -17,6 +18,7 @@ interface IExecByCommandOptions {export const ensureCommandSystem = (app: App) => {ensureNativeCommands(app, executeLegacyNativeCommand);+ ensureContextCommands(app);return getCommandRegistry(app);};diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex c6c5c5fcdd..cdf69cfc8a 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -209,9 +209,12 @@ export const getPlainText = (blockElement: HTMLElement, isNested = false) => {return text;};-export const pasteEscaped = async (protyle: IProtyle, nodeElement: Element) => {+export const pasteEscaped = async (protyle: IProtyle, nodeElement: Element, prepareInsertion?: () => boolean) => {try {let clipText = await readText() || "";+ if (prepareInsertion && !prepareInsertion()) {+ return;+ }// 删掉 <span data-type\="text".*>text</span> 标签,只保留文本clipText = clipText.replace(/<span data-type="text".*?>(.*?)<\/span>/g, "$1");@@ -250,11 +253,14 @@ export const pasteEscaped = async (protyle: IProtyle, nodeElement: Element) => {}};-export const pasteAsPlainText = async (protyle: IProtyle) => {+export const pasteAsPlainText = async (protyle: IProtyle, prepareInsertion?: () => boolean) => {let localFiles: ILocalFiles[] = [];/// #if !BROWSERlocalFiles = await getLocalFiles();if (localFiles.length > 0) {+ if (prepareInsertion && !prepareInsertion()) {+ return;+ }uploadLocalFiles(localFiles, protyle, false);return;}@@ -262,6 +268,9 @@ export const pasteAsPlainText = async (protyle: IProtyle) => {if (localFiles.length === 0) {// Inline-level elements support pasted as plain text https://github.com/siyuan-note/siyuan/issues/8010let textPlain = await readText() || "";+ if (prepareInsertion && !prepareInsertion()) {+ return;+ }if (getSelection().rangeCount > 0) {const range = getSelection().getRangeAt(0);if (hasClosestByAttribute(range.startContainer, "data-type", "code") || hasClosestByClassName(range.startContainer, "hljs")) {diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex 4761b4776c..cf5ed0871a 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -66,7 +66,6 @@ import {clearTableCell, fixTable, isIncludeCell} from "../util/table";import {transaction,insertEmptyBlockquote,- turnEmptyParagraphsIntoTransaction,turnsIntoGroupsTransaction,turnsIntoOneTransaction,turnsIntoTransaction,@@ -75,6 +74,7 @@ import {updateTransaction} from "./transaction";import {isEmptyParagraph} from "./emptyTextBlock";+import {turnParagraphIntoCode} from "./turnIntoCode";import {getBlockquoteContext, shouldCancelBlockquote} from "./blockquote";import {fontEvent} from "../toolbar/Font";import {applyTableCellStyleHotkey} from "../toolbar/tableCell";@@ -112,7 +112,6 @@ import {fetchPost} from "../../util/fetch";import {scrollCenter} from "../../util/highlightById";import {BlockPanel} from "../../block/Panel";import * as dayjs from "dayjs";-import {highlightRender} from "../render/highlightRender";import {countBlockWord, countSelectWord} from "../../layout/status";import {moveToDown, moveToUp} from "./move";import {beforePaste, pasteAsPlainText} from "../util/paste";@@ -2115,26 +2114,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {if (matchHotKey(window.siyuan.config.keymap.editor.insert.code.custom, event) &&!["NodeCodeBlock", "NodeHeading", "NodeTable"].includes(nodeType) &&!isInEmbedBlock(nodeElement)) {- if (isEmptyParagraph(nodeElement)) {- turnEmptyParagraphsIntoTransaction({- protyle,- nodeElements: [nodeElement],- type: "code",- });- event.preventDefault();- event.stopPropagation();- return true;- }- const editElement = getContenteditableElement(nodeElement);- if (editElement) {- const html = nodeElement.outerHTML;- // 需要 EscapeHTMLStr https://github.com/siyuan-note/siyuan/issues/11451- editElement.innerHTML = "```" + window.siyuan.storage[Constants.LOCAL_CODELANG] + "\n" + Lute.EscapeHTMLStr(editElement.textContent) + "<wbr>\n```";- nodeElement.insertAdjacentHTML("afterend", protyle.lute.SpinBlockDOM(nodeElement.outerHTML));- const newNodeElement = nodeElement.nextElementSibling;- nodeElement.remove();- updateTransaction(protyle, newNodeElement, html);- highlightRender(newNodeElement);+ if (turnParagraphIntoCode(protyle, nodeElement)) {event.preventDefault();event.stopPropagation();return true;diff --git a/app/src/protyle/wysiwyg/turnIntoCode.ts b/app/src/protyle/wysiwyg/turnIntoCode.tsnew file mode 100644index 0000000000..9878f6795f--- /dev/null+++ b/app/src/protyle/wysiwyg/turnIntoCode.ts@@ -0,0 +1,25 @@+import {Constants} from "../../constants";+import {highlightRender} from "../render/highlightRender";+import {isEmptyParagraph} from "./emptyTextBlock";+import {getContenteditableElement} from "./getBlock";+import {turnEmptyParagraphsIntoTransaction, updateTransaction} from "./transaction";++export const turnParagraphIntoCode = (protyle: IProtyle, nodeElement: HTMLElement) => {+ if (isEmptyParagraph(nodeElement)) {+ turnEmptyParagraphsIntoTransaction({protyle, nodeElements: [nodeElement], type: "code"});+ return true;+ }+ const editElement = getContenteditableElement(nodeElement);+ if (!editElement) {+ return false;+ }+ const html = nodeElement.outerHTML;+ editElement.innerHTML = "```" + window.siyuan.storage[Constants.LOCAL_CODELANG] + "\n" ++ Lute.EscapeHTMLStr(editElement.textContent) + "<wbr>\n```";+ nodeElement.insertAdjacentHTML("afterend", protyle.lute.SpinBlockDOM(nodeElement.outerHTML));+ const newNodeElement = nodeElement.nextElementSibling;+ nodeElement.remove();+ updateTransaction(protyle, newNodeElement, html);+ highlightRender(newNodeElement);+ return true;+};