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: Support shortcuts for callout presets https://github.com/siyuan-note/siyuan/issues/20588
Daniel60f2f63e410f
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.syindex 3cd07e5a59..8a2ea9777b 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy@@ -7,7 +7,7 @@"id": "20200924100950-9op5xi1","title": "Shortcuts","type": "doc",- "updated": "20261012014930"+ "updated": "20261015193140"},"Children": [{@@ -16,7 +16,7 @@"HeadingLevel": 2,"Properties": {"id": "20260928091747-wub2unw",- "updated": "20261002013053"+ "updated": "20261015193140"},"Children": [{@@ -66,6 +66,56 @@}]},+ {+ "ID": "20261015193140-bd3r41i",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261015193140-bd3r41i",+ "updated": "20261015193140"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "In "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Settings"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Keymap"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Editor"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Element"+ },+ {+ "Type": "NodeText",+ "Data": " you can assign separate shortcuts to the Note, Tip, Important, Warning, and Caution callout blocks. All five are unassigned by default and also work with an external keyboard on mobile. Like the blockquote shortcut, they convert the current or selected blocks, or insert an empty callout when conversion is unavailable. Inside a callout, a different type changes its type; the same type removes the wrapper when it has one unfolded child, or inserts an empty callout after the current child when it has multiple children or a folded child."+ }+ ]+ },{"ID": "20261011091952-wqpp0rc","Type": "NodeParagraph",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.syindex 2631e56f37..32aea9ce64 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy@@ -7,7 +7,7 @@"id": "20200813004551-gm0pbn1","title": "快捷键","type": "doc",- "updated": "20261012014930"+ "updated": "20261015193140"},"Children": [{@@ -16,7 +16,7 @@"HeadingLevel": 2,"Properties": {"id": "20260928091747-w9nonqj",- "updated": "20261002013053"+ "updated": "20261015193140"},"Children": [{@@ -66,6 +66,56 @@}]},+ {+ "ID": "20261015193140-2q8kvoa",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261015193140-2q8kvoa",+ "updated": "20261015193140"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "可在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "设置"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "快捷键"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "编辑器"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "元素"+ },+ {+ "Type": "NodeText",+ "Data": " 中为 Note、Tip、Important、Warning、Caution 五种提示块分别设置快捷键,默认均未绑定,移动端连接外接键盘后也可使用。行为参考引述块快捷键:转换当前块或选中的块,无法转换时插入空提示块。在提示块内,使用不同类型的快捷键会切换类型;使用相同类型的快捷键时,若仅有一个未折叠子块则取消提示块,若有多个子块或子块已折叠则在当前子块后插入空提示块。"+ }+ ]+ },{"ID": "20261011091952-vdfybuu","Type": "NodeParagraph",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.syindex 2dac71df06..49f4bd6881 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy@@ -7,7 +7,7 @@"id": "20211226122549-jktxego","title": "快捷鍵","type": "doc",- "updated": "20261012014930"+ "updated": "20261015193140"},"Children": [{@@ -16,7 +16,7 @@"HeadingLevel": 2,"Properties": {"id": "20260928091747-a3qlogr",- "updated": "20261002013053"+ "updated": "20261015193140"},"Children": [{@@ -66,6 +66,56 @@}]},+ {+ "ID": "20261015193140-98at8pv",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261015193140-98at8pv",+ "updated": "20261015193140"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "可在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "快捷鍵"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "編輯器"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "元素"+ },+ {+ "Type": "NodeText",+ "Data": " 中為 Note、Tip、Important、Warning、Caution 五種提示區塊分別設定快捷鍵,預設均未綁定,行動端連接外接鍵盤後也可使用。行為參考引述區塊快捷鍵:轉換目前區塊或選取的區塊,無法轉換時插入空提示區塊。在提示區塊內,使用不同類型的快捷鍵會切換類型;使用相同類型的快捷鍵時,若僅有一個未摺疊子區塊則取消提示區塊,若有多個子區塊或子區塊已摺疊則在目前子區塊後插入空提示區塊。"+ }+ ]+ },{"ID": "20261011091952-z1utga6","Type": "NodeParagraph",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.syindex d0ddb7ac4a..b4a96d3b6a 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy@@ -9,7 +9,7 @@"id": "20240530101000-xsbxokr","title": "ショートカット","type": "doc",- "updated": "20261012014930"+ "updated": "20261015193140"},"Children": [{@@ -18,7 +18,7 @@"HeadingLevel": 2,"Properties": {"id": "20260928091747-t67pljp",- "updated": "20261002013053"+ "updated": "20261015193140"},"Children": [{@@ -64,6 +64,52 @@}]},+ {+ "ID": "20261015193140-d0uhm3q",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261015193140-d0uhm3q",+ "updated": "20261015193140"+ },+ "Children": [+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "ショートカット"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "エディタ"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "要素"+ },+ {+ "Type": "NodeText",+ "Data": " で、Note、Tip、Important、Warning、Caution の各コールアウトブロックに個別のショートカットを設定できます。初期状態ではすべて未割り当てで、モバイル端末でも外付けキーボードで使用できます。引用ブロックと同様に、現在または選択中のブロックを変換し、変換できない場合は空のコールアウトを挿入します。コールアウト内で別の種類のショートカットを押すと種類を切り替えます。同じ種類の場合、折りたたまれていない子ブロックが一つだけならコールアウトを解除し、子ブロックが複数あるか折りたたまれている場合は現在の子ブロックの後に空のコールアウトを挿入します。"+ }+ ]+ },{"ID": "20261011091952-yanstq2","Type": "NodeParagraph",diff --git a/app/src/command/insertCommands.test.ts b/app/src/command/insertCommands.test.tsindex e50d781252..37a7358de8 100644--- a/app/src/command/insertCommands.test.ts+++ b/app/src/command/insertCommands.test.ts@@ -74,6 +74,10 @@ test("insert commands search and execute existing insertion actions at the savedassert.deepEqual(Array.from(registry.get("core.mobile.insert.orderedList")?.keymapPath || []), ["editor", "insert", "ordered-list"]);assert.deepEqual(Array.from(registry.get("core.mobile.insert.mindmap")?.keymapPath || []), ["editor", "insert", "mindmap"]);assert.deepEqual(Array.from(registry.get("core.mobile.insert.ref")?.keymapPath || []), ["editor", "insert", "ref"]);+ for (const type of ["Note", "Tip", "Important", "Warning", "Caution"]) {+ assert.deepEqual(Array.from(registry.get(`core.mobile.insert.callout${type}`)?.keymapPath || []),+ ["editor", "insert", `callout${type}`]);+ }assert.equal(registry.get("core.mobile.insert.template")?.keymapPath, undefined);assert.equal(queryCommandPalette(registry, context, "模板")[0].id, "core.mobile.insert.template");const recent = recordPaletteCommand([], "core.mobile.insert.assets");diff --git a/app/src/command/insertCommands.ts b/app/src/command/insertCommands.tsindex d8d5c1e272..1010d1d8ad 100644--- a/app/src/command/insertCommands.ts+++ b/app/src/command/insertCommands.ts@@ -28,7 +28,8 @@ const BUILTIN_STYLES: Record<string, TBuiltinInlineStyleID> = {const SPECIAL_LABELS: Record<string, string> = {html: "HTML", flowChart: "Flow Chart", graph: "Graph", mermaid: "Mermaid", UML: "UML",};-const INSERT_KEYMAP_IDS = new Set(["ref", "list", "orderedList", "check", "mindmap", "quote", "code", "table"]);+const INSERT_KEYMAP_IDS = new Set(["ref", "list", "orderedList", "check", "mindmap", "quote", "code", "table",+ "calloutNote", "calloutTip", "calloutImportant", "calloutWarning", "calloutCaution"]);const keymapPath = (id: string): TCommandKeymapPath | undefined => {if (/^heading[1-6]$/.test(id)) {diff --git a/app/src/config/tabs/keymapUi.test.ts b/app/src/config/tabs/keymapUi.test.tsindex 296dbbd531..f8a64f2151 100644--- a/app/src/config/tabs/keymapUi.test.ts+++ b/app/src/config/tabs/keymapUi.test.ts@@ -3,6 +3,23 @@ import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {CALLOUT_PRESETS} from "../../protyle/wysiwyg/calloutType";++test("callout shortcut rows use localized labels without requiring separate translation keys", () => {+ const source = createSourceFile("keymapUi.ts", readFileSync("src/config/tabs/keymapUi.ts", "utf8"), ScriptTarget.ES2021, true);+ const declaration = source.statements.find(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(item => item.name.getText(source) === "getKeymapLabel"));+ assert.ok(declaration);+ const code = transpileModule(declaration.getText(source) + "\nexports.label = getKeymapLabel;", {+ compilerOptions: {module: ModuleKind.CommonJS},+ }).outputText;+ const exports = {} as {label: (key: string) => string};+ runInNewContext(code, {exports, CALLOUT_PRESETS, window: {siyuan: {languages: {callout: "提示块", quote: "引述块"}}}});+ for (const preset of CALLOUT_PRESETS) {+ assert.equal(exports.label(preset.id), `提示块 - ${preset.title}`);+ }+ assert.equal(exports.label("quote"), "引述块");+});test("settings keymap search keeps undeclared owner plugins visible", () => {const source = createSourceFile("keymapUi.ts", readFileSync("src/config/tabs/keymapUi.ts", "utf8"), ScriptTarget.ES2021, true);diff --git a/app/src/config/tabs/keymapUi.ts b/app/src/config/tabs/keymapUi.tsindex 65565a98b8..e74ae86761 100644--- a/app/src/config/tabs/keymapUi.ts+++ b/app/src/config/tabs/keymapUi.ts@@ -21,6 +21,12 @@ import {Menu} from "../../plugin/Menu";import {trackSettingSave} from "../setting/pending";import {getSettingsOwnerApp} from "../setting/windowContext";import type {App} from "../../index";+import {CALLOUT_PRESETS} from "../../protyle/wysiwyg/calloutType";++const getKeymapLabel = (key: string) => {+ const callout = CALLOUT_PRESETS.find(item => item.id === key);+ return callout ? `${window.siyuan.languages.callout} - ${callout.title}` : window.siyuan.languages[key];+};const keymapToolbarSearchStrings = (): string[] => [window.siyuan.languages.keymapTip,@@ -155,7 +161,7 @@ const buildKeymapKeywords = (): string[] => [const buildKeymapCommandTexts = (): string[] => {const out: string[] = [];const pushKey = (key: string) => {- const text = window.siyuan.languages[key];+ const text = getKeymapLabel(key);if (text) {out.push(text);}@@ -271,11 +277,12 @@ const genKeymapItem = (keys: string) => {// 使用固定的 Constants.SIYUAN_KEYMAP 来保证每次生成的选项顺序一致// 避免在设置快捷键之后关闭设置重新打开设置之后选项顺序改变for (const key of Object.keys(template)) {- if (!window.siyuan.languages[key]) {+ const label = getKeymapLabel(key);+ if (!label) {continue;}const item = config[key] ?? template[key];- html.push(genKeymapRowHtml(window.siyuan.languages[key], keys + Constants.ZWSP + key, item));+ html.push(genKeymapRowHtml(label, keys + Constants.ZWSP + key, item));}return html.join("");};diff --git a/app/src/constants.ts b/app/src/constants.tsindex 6df45b17f0..8ee193fa6e 100644--- a/app/src/constants.ts+++ b/app/src/constants.ts@@ -675,6 +675,11 @@ export abstract class Constants {table: {default: "⌘O", custom: "⌘O"},code: {default: "⇧⌘K", custom: "⇧⌘K"},quote: {default: "", custom: ""},+ calloutNote: {default: "", custom: ""},+ calloutTip: {default: "", custom: ""},+ calloutImportant: {default: "", custom: ""},+ calloutWarning: {default: "", custom: ""},+ calloutCaution: {default: "", custom: ""},clearInline: {default: "⌘\\", custom: "⌘\\"},},heading: {diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex 570b831cf8..cc38d8cb62 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -1017,6 +1017,7 @@ export class Gutter {const menus: IMenu[] = CALLOUT_PRESETS.map(item => ({id: item.id,iconHTML: `<span class="b3-menu__icon">${item.icon}</span>`,+ accelerator: window.siyuan.config.keymap.editor.insert[item.id]?.custom,label: `<span style="color: ${item.color}">${window.siyuan.languages.callout} - ${item.title}</span>`,current: currentType === item.type,click() {diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.tsindex 69f364b356..5e54998412 100644--- a/app/src/protyle/hint/extend.ts+++ b/app/src/protyle/hint/extend.ts@@ -206,27 +206,27 @@ export const getBuiltinSlashMenuItems = (protyle: IProtyle): IHintData[] => {filter: [window.siyuan.languages.callout, "callout", "ts", "提示", "tishi", "note"],id: "calloutNote",value: `> [!NOTE]\n> ${Lute.Caret}`,- html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">✏️</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-note)">Note</span></span></div>`,+ html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">✏️</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-note)">Note</span></span>${getHotkeyOrMarker(window.siyuan.config.keymap.editor.insert.calloutNote?.custom, "")}</div>`,}, {filter: [window.siyuan.languages.callout, "callout", "ts", "提示", "tishi", "tip"],id: "calloutTip",value: `> [!TIP]\n> ${Lute.Caret}`,- html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">💡</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-tip)">Tip</span></span></div>`,+ html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">💡</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-tip)">Tip</span></span>${getHotkeyOrMarker(window.siyuan.config.keymap.editor.insert.calloutTip?.custom, "")}</div>`,}, {filter: [window.siyuan.languages.callout, "callout", "ts", "提示", "tishi", "important"],id: "calloutImportant",value: `> [!IMPORTANT]\n> ${Lute.Caret}`,- html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">❗</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-important)">Important</span></span></div>`,+ html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">❗</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-important)">Important</span></span>${getHotkeyOrMarker(window.siyuan.config.keymap.editor.insert.calloutImportant?.custom, "")}</div>`,}, {filter: [window.siyuan.languages.callout, "callout", "ts", "提示", "tishi", "warning"],id: "calloutWarning",value: `> [!WARNING]\n> ${Lute.Caret}`,- html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">⚠️</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-warning)">Warning</span></span></div>`,+ html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">⚠️</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-warning)">Warning</span></span>${getHotkeyOrMarker(window.siyuan.config.keymap.editor.insert.calloutWarning?.custom, "")}</div>`,}, {filter: [window.siyuan.languages.callout, "callout", "ts", "提示", "tishi", "caution"],id: "calloutCaution",value: `> [!CAUTION]\n> ${Lute.Caret}`,- html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">🚨</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-caution)">Caution</span></span></div>`,+ html: `<div class="b3-list-item__first"><span class="b3-list-item__graphic">🚨</span><span class="b3-list-item__text">${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-caution)">Caution</span></span>${getHotkeyOrMarker(window.siyuan.config.keymap.editor.insert.calloutCaution?.custom, "")}</div>`,}, {filter: [window.siyuan.languages.code, "code block", "代码块", "daimakuai", "dmk"],id: "code",diff --git a/app/src/protyle/wysiwyg/callout.test.ts b/app/src/protyle/wysiwyg/callout.test.tsindex 346b370d85..aa9ed0d20b 100644--- a/app/src/protyle/wysiwyg/callout.test.ts+++ b/app/src/protyle/wysiwyg/callout.test.ts@@ -14,7 +14,8 @@ const browserCases = async (sources: string[], luteSource: string) => {lute.SetKramdownIAL(true);lute.SetProtyleWYSIWYG(true);lute.SetCallout(true);- Object.assign(window, {siyuan: {languages: {callout: "Callout", custom: "Custom", type: "Type"}}});+ Object.assign(window, {siyuan: {languages: {callout: "Callout", custom: "Custom", type: "Type"},+ config: {editor: {spellcheck: false}, keymap: {editor: {insert: {}}}}}});const root = document.createElement("div");root.dataset.nodeId = "document";document.body.append(root);@@ -22,13 +23,15 @@ const browserCases = async (sources: string[], luteSource: string) => {let transactions: Array<{doOperations: IOperation[], undoOperations: IOperation[]}> = [];let inputOptions: Parameters<typeof import("../../dialog/inputDialog").openInputDialog>[0];let destroyed = false;+ let selectedBlocks: HTMLElement[] = [];+ let rangeBlocks: HTMLElement[] = [];const dialog = {destroy: () => {destroyed = true;inputOptions.destroyCallback?.();}} as Parameters<typeof inputOptions.onConfirm>[1];const identity = (html: string) => html;const dependencies = {- Constants: {ATTRIBUTE_EDITING: "data-editing"},+ Constants: {ATTRIBUTE_EDITING: "data-editing", ZWSP: "\u200b"},transaction: (_protyle: IProtyle, doOperations: IOperation[], undoOperations: IOperation[]) => {transactions.push({doOperations, undoOperations});},@@ -36,7 +39,17 @@ const browserCases = async (sources: string[], luteSource: string) => {isListMindmapListConversion: () => false,getPreviousBlockSibling: (element: Element) => element.previousElementSibling,getEmbedChildOperationParentID: (): undefined => undefined,- getParentBlock: (element: Element) => element.parentElement,+ getParentBlock: (element: Element) => element.parentElement.classList.contains("callout-content") ?+ element.parentElement.parentElement : element.parentElement,+ getNextBlockSibling: (element: Element) => element.nextElementSibling,+ getBlockOperationElements: () => [...selectedBlocks],+ getBlockElementsByRange: () => rangeBlocks,+ getUndoFocusContext: (): undefined => undefined,+ restoreFocusContext: () => {},+ isInEmbedBlock: (element: Element) => !!element.closest('[data-type="NodeBlockQueryEmbed"]'),+ setFold: () => ({}),+ unfoldListHeadings: (): IOperation[] => [],+ focusBlock: () => {}, hideElements: () => {},isTabsListConversion: () => false,convertListMindmapToList: (): undefined => undefined,cleanListMindmapHTML: identity,@@ -54,12 +67,15 @@ const browserCases = async (sources: string[], luteSource: string) => {},focusByRange: () => {},};- const conversions = new Function(...Object.keys(dependencies), sources[0] + "\nreturn {turnsOneInto};")(- ...Object.values(dependencies));const presets = {} as typeof import("./calloutType");new Function("exports", sources[1])(presets);+ const conversions = new Function(...Object.keys(dependencies), "CALLOUT_PRESETS", sources[0] ++ "\nreturn {turnsOneInto, turnsIntoOneTransaction, turnsIntoGroupsTransaction, insertEmptyCallout};")(+ ...Object.values(dependencies), presets.CALLOUT_PRESETS);const callouts = {} as typeof import("./callout");new Function("exports", "require", sources[2])(callouts, () => ({...dependencies, ...conversions, ...presets}));+ const shortcuts = {} as typeof import("./calloutShortcut");+ new Function("exports", "require", sources[4])(shortcuts, () => ({...dependencies, ...conversions, ...callouts}));const menu = new Function("CALLOUT_PRESETS", "updateCalloutType", "updateCustomCalloutType",sources[3] + "\nreturn new CalloutMenu();")(presets.CALLOUT_PRESETS,callouts.updateCalloutType, callouts.updateCustomCalloutType) as {@@ -167,6 +183,72 @@ const browserCases = async (sources: string[], luteSource: string) => {check.equal(root.querySelector(".callout-title").textContent, "My title");check.equal(root.querySelector(".callout-icon").textContent, icon);check.equal((root.firstElementChild as HTMLElement).dataset.subtype, "CUSTOM");++ const shortcut = async (preset: typeof presets.CALLOUT_PRESETS[number], target: HTMLElement) => {+ const range = document.createRange();+ range.selectNodeContents(target.querySelector('[contenteditable="true"]') || target);+ range.collapse(true);+ await shortcuts.handleCalloutShortcut(protyle, target, range, preset);+ };+ for (const preset of presets.CALLOUT_PRESETS) {+ // 转换保留原块 ID,类型、标题和图标在同一次事务内生成。+ setup("text\n");+ const paragraph = root.firstElementChild as HTMLElement;+ paragraph.removeAttribute("fold");+ const id = paragraph.dataset.nodeId;+ await shortcut(preset, paragraph);+ const callout = root.firstElementChild as HTMLElement;+ check.equal(callout.dataset.subtype, preset.type);+ check.equal(callout.querySelector(".callout-icon").textContent, preset.icon);+ check.equal(callout.querySelector(".callout-title").textContent, preset.title);+ check.equal(callout.querySelector(".callout-content").firstElementChild.getAttribute("data-node-id"), id);+ check.equal(transactions.length, 1);+ check.equal(transactions[0].undoOperations.at(-1).action, "delete");+ transactions = [];+ await shortcut(preset, paragraph);+ check.equal(root.firstElementChild.getAttribute("data-type"), "NodeParagraph");+ check.ok(root.querySelector(`[data-node-id="${id}"]`));+ check.equal(transactions.length, 1);++ // 多子块和折叠子块沿用引述块的插入规则,插入锚点指向提示块而非内容包装元素。+ for (const folded of [false, true]) {+ const block = setup(`> [!${preset.type}]\n> first\n${folded ? "" : ">\n> second\n"}`);+ block.removeAttribute("fold");+ const child = block.querySelector<HTMLElement>(".callout-content > [data-node-id]");+ if (folded) {+ child.setAttribute("fold", "1");+ }+ await shortcut(preset, child);+ check.equal(transactions.length, 1);+ check.equal(transactions[0].doOperations[0].action, "insert");+ check.equal(transactions[0].doOperations[0].parentID, block.dataset.nodeId);+ check.equal(child.nextElementSibling.getAttribute("data-subtype"), preset.type);+ }+ }+ const existing = setup("> [!NOTE] Custom title\n> content\n");+ existing.removeAttribute("fold");+ await shortcut(presets.CALLOUT_PRESETS[1], existing.querySelector(".callout-content > [data-node-id]"));+ check.equal(existing.dataset.subtype, "TIP");+ check.equal(existing.querySelector(".callout-title").textContent, "Custom title");+ check.equal(transactions.length, 1);++ setup("first\n\nsecond\n");+ selectedBlocks = Array.from(root.children) as HTMLElement[];+ await shortcut(presets.CALLOUT_PRESETS[2], selectedBlocks[0]);+ check.equal(transactions.length, 1);+ check.equal(root.firstElementChild.getAttribute("data-subtype"), "IMPORTANT");+ check.equal(root.querySelector(".callout-content").childElementCount, 2);+ selectedBlocks = [];++ setup("first\n\n> second\n");+ rangeBlocks = [root.firstElementChild as HTMLElement, root.querySelector(".bq > [data-node-id]")];+ const crossRange = document.createRange();+ crossRange.setStart(rangeBlocks[0].firstElementChild.firstChild, 0);+ crossRange.setEnd(rangeBlocks[1].firstElementChild.firstChild, 3);+ await shortcuts.handleCalloutShortcut(protyle, rangeBlocks[0], crossRange, presets.CALLOUT_PRESETS[3]);+ check.equal(transactions.length, 1);+ check.equal(root.querySelectorAll('[data-subtype="WARNING"]').length, 2);+ rangeBlocks = [];return "Callout conversion cases passed";};@@ -177,14 +259,16 @@ test("shared block menus convert blockquotes to callout types in a single undoabconst source = createSourceFile("transaction.ts", readFileSync(path.join(__dirname, "transaction.ts"), "utf8"),ScriptTarget.ES2021, true);const conversionSource = source.statements.filter(statement => isVariableStatement(statement) &&- statement.declarationList.declarations.some(item => ["turnsOneInto", "updateTransaction"].includes(item.name.getText(source))))+ statement.declarationList.declarations.some(item => ["turnsOneInto", "updateTransaction", "turnsIntoOneTransaction",+ "turnsIntoGroupsTransaction", "insertEmptyQuoteBlock", "insertEmptyCallout"].includes(item.name.getText(source)))).map(statement => statement.getText(source).replace(/^export /, "")).join("\n");const gutter = createSourceFile("index.ts", readFileSync(path.join(__dirname, "../gutter/index.ts"), "utf8"),ScriptTarget.ES2021, true);const menuSource = gutter.statements.filter(isClassDeclaration).find(item => item.name?.text === "Gutter").members.find(item => item.name?.getText(gutter) === "calloutTypeMenus").getText(gutter);const sources = [conversionSource, readFileSync(path.join(__dirname, "calloutType.ts"), "utf8"),- readFileSync(path.join(__dirname, "callout.ts"), "utf8"), `class CalloutMenu { ${menuSource} }`]+ readFileSync(path.join(__dirname, "callout.ts"), "utf8"), `class CalloutMenu { ${menuSource} }`,+ readFileSync(path.join(__dirname, "calloutShortcut.ts"), "utf8")].map(text => transpileModule(text, {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021}}).outputText);const luteSource = readFileSync("stage/protyle/js/lute/lute.min.js", "utf8");const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-callout-test-"));diff --git a/app/src/protyle/wysiwyg/calloutShortcut.ts b/app/src/protyle/wysiwyg/calloutShortcut.tsnew file mode 100644index 0000000000..fada19ff4f--- /dev/null+++ b/app/src/protyle/wysiwyg/calloutShortcut.ts@@ -0,0 +1,81 @@+import {getBlockOperationElements} from "./blockSelection";+import {getNextBlockSibling} from "./getBlock";+import {isInEmbedBlock} from "../util/hasClosest";+import {getBlockElementsByRange, getUndoFocusContext, restoreFocusContext} from "../util/selection";+import {insertEmptyCallout, turnsIntoGroupsTransaction, turnsIntoOneTransaction, turnsOneInto} from "./transaction";+import {updateCalloutType} from "./callout";+import type {ICalloutPreset} from "./calloutType";++export const handleCalloutShortcut = async (protyle: IProtyle, nodeElement: HTMLElement, range: Range,+ preset: ICalloutPreset, selectionModeElement?: HTMLElement) => {+ if (isInEmbedBlock(nodeElement)) {+ return;+ }+ const rangeElements = !range.collapsed && range.toString() !== "" ? getBlockElementsByRange(range) : [];+ if (rangeElements.length > 1 && !rangeElements.some(item => item.classList.contains("li"))) {+ const groups: Element[][] = [];+ rangeElements.forEach(item => {+ const group = groups[groups.length - 1];+ const previous = group?.[group.length - 1];+ if (previous?.parentElement === item.parentElement && getNextBlockSibling(previous) === item) {+ group.push(item);+ } else {+ groups.push([item]);+ }+ });+ const focusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);+ await turnsIntoGroupsTransaction({protyle, selectsElementGroups: groups, type: "Blocks2Callout", callout: preset});+ if (focusContext) {+ restoreFocusContext(protyle, focusContext);+ }+ return;+ }+ const selected = getBlockOperationElements(protyle.wysiwyg.element, selectionModeElement);+ const hasBlockSelection = selected.length > 0;+ if (!hasBlockSelection) {+ selected.push(nodeElement);+ }+ if (selected.length > 1) {+ if (selected.some((item, index) => item.classList.contains("li") ||+ index > 0 && getNextBlockSibling(selected[index - 1]) !== item)) {+ return;+ }+ await turnsIntoOneTransaction({protyle, selectsElement: selected, type: "Blocks2Callout", callout: preset});+ return;+ }+ const target = selected[0];+ let callout = target;+ if (!hasBlockSelection) {+ while (callout && callout !== protyle.wysiwyg.element && callout.dataset.type !== "NodeCallout") {+ callout = callout.parentElement;+ }+ }+ if (callout?.dataset.type === "NodeCallout" && callout !== protyle.wysiwyg.element) {+ if (callout.dataset.subtype !== preset.type) {+ updateCalloutType([callout], protyle, preset);+ return;+ }+ const content = callout.querySelector<HTMLElement>(":scope > .callout-content");+ const children = Array.from(content.children).filter(item => item.hasAttribute("data-node-id"));+ let child = target;+ while (child.parentElement && child.parentElement !== content && child !== callout) {+ child = child.parentElement;+ }+ if (hasBlockSelection || target === callout || children.length === 1 && child.getAttribute("fold") !== "1") {+ if (!hasBlockSelection) {+ const focusRange = range.cloneRange();+ focusRange.collapse(true);+ focusRange.insertNode(document.createElement("wbr"));+ }+ await turnsOneInto({protyle, nodeElement: callout, id: callout.dataset.nodeId, type: "CancelCallout"});+ } else {+ insertEmptyCallout(protyle, child, preset);+ }+ } else if (target.dataset.type === "NodeBlockquote") {+ updateCalloutType([target], protyle, preset);+ } else if (["NodeHeading", "NodeParagraph", "NodeList"].includes(target.dataset.type)) {+ await turnsIntoOneTransaction({protyle, selectsElement: selected, type: "Blocks2Callout", callout: preset});+ } else {+ protyle.hint.fillCommand(`> [!${preset.type}]\n> ${Lute.Caret}`, protyle);+ }+};diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex 46e46002eb..5eaf6a1ced 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -83,6 +83,8 @@ import {isEmptyParagraph} from "./emptyTextBlock";import {isListHeadingContainer} from "./headingConversion";import {turnParagraphIntoCode} from "./turnIntoCode";import {getBlockquoteContext, shouldCancelBlockquote} from "./blockquote";+import {CALLOUT_PRESETS} from "./calloutType";+import {handleCalloutShortcut} from "./calloutShortcut";import {fontEvent} from "../toolbar/Font";import {applyTableCellStyleHotkey} from "../toolbar/tableCell";import {formatPainter} from "../toolbar/FormatPainter";@@ -2258,6 +2260,14 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}return;}+ const calloutPreset = CALLOUT_PRESETS.find(item =>+ matchHotKey(window.siyuan.config.keymap.editor.insert[item.id], event));+ if (calloutPreset && !isInEmbedBlock(nodeElement)) {+ event.preventDefault();+ event.stopPropagation();+ await handleCalloutShortcut(protyle, nodeElement, range, calloutPreset, blockSelectionModeElement);+ return;+ }const isMatchList = matchHotKey(window.siyuan.config.keymap.editor.insert.list, event);const isMatchCheck = matchHotKey(window.siyuan.config.keymap.editor.insert.check, event);const isMatchOList = matchHotKey(window.siyuan.config.keymap.editor.insert["ordered-list"], event);diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex be021ec741..5a17635df4 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -23,6 +23,7 @@ import {getTopAloneElement} from "./getBlock";import {Constants} from "../../constants";+import {CALLOUT_PRESETS, type ICalloutPreset} from "./calloutType";import {blockRender} from "../render/blockRender";import {renderBlockDirection, syncBlockDirection} from "../render/blockDirection";import {renderEmbedHeadings} from "../render/embedHeading";@@ -92,7 +93,6 @@ import type {TransactionListConversionResult} from "../../types/api";import {getProtyleTransactionOwner} from "../runtimeCapabilities";import {completeTabsListSource, convertTabsList, isTabsListConversion} from "./tabsList";import {preserveTabTask} from "../util/tabsCopy";-import type {ICalloutPreset} from "./calloutType";import {waitForPendingTransactions} from "../util/transactionQueue";import {replayListMindmap} from "../render/listMindmap/render";import {@@ -1598,6 +1598,7 @@ export const turnsIntoOneTransaction = async (options: {getOperations?: boolean,parentID?: string,widthSourceElement?: HTMLElement,+ callout?: ICalloutPreset,}) => {let parentElement: Element;let widthSourceOldStyle: string;@@ -1624,12 +1625,13 @@ export const turnsIntoOneTransaction = async (options: {parentElement.setAttribute("data-type", "NodeBlockquote");parentElement.innerHTML = `<div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div>`;} else if (options.type === "Blocks2Callout") {+ const preset = options.callout || CALLOUT_PRESETS[0];parentElement = document.createElement("div");parentElement.classList.add("callout");parentElement.setAttribute("data-node-id", id);parentElement.setAttribute("data-type", "NodeCallout");- parentElement.setAttribute("data-subtype", "NOTE");- parentElement.innerHTML = `<div class="callout-info" contenteditable="false"><span class="callout-icon">✏️</span><span contenteditable="true" spellcheck="${window.siyuan.config.editor.spellcheck}" class="callout-title">Note</span></div><div class="callout-content"></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div>`;+ parentElement.setAttribute("data-subtype", preset.type);+ parentElement.innerHTML = `<div class="callout-info" contenteditable="false"><span class="callout-icon">${preset.icon}</span><span contenteditable="true" spellcheck="${window.siyuan.config.editor.spellcheck}" class="callout-title">${preset.title}</span></div><div class="callout-content"></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div>`;} else if (options.type.endsWith("Ls")) {parentElement = document.createElement("div");parentElement.classList.add("list");@@ -1758,7 +1760,7 @@ export const turnsIntoOneTransaction = async (options: {hideElements(["gutter"], options.protyle);};-export const insertEmptyBlockquote = (protyle: IProtyle, previousElement: HTMLElement, options?: {+const insertEmptyQuoteBlock = (protyle: IProtyle, previousElement: HTMLElement, options?: {updateElement: HTMLElement,oldHTML: string,undoContext?: Record<string, string>,@@ -1766,13 +1768,13 @@ export const insertEmptyBlockquote = (protyle: IProtyle, previousElement: HTMLEldoOperations: IOperation[],undoOperations: IOperation[],},-}) => {+}, callout?: ICalloutPreset) => {const range = getEditorRange(protyle.wysiwyg.element);const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);const template = document.createElement("template");- template.innerHTML = protyle.lute.SpinBlockDOM(">" + Lute.Caret);+ template.innerHTML = protyle.lute.SpinBlockDOM(callout ? `> [!${callout.type}]\n> ${Lute.Caret}` : ">" + Lute.Caret);const blockquoteElement = template.content.firstElementChild as HTMLElement;- if (!blockquoteElement || blockquoteElement.getAttribute("data-type") !== "NodeBlockquote") {+ if (!blockquoteElement || blockquoteElement.getAttribute("data-type") !== (callout ? "NodeCallout" : "NodeBlockquote")) {return;}@@ -1787,7 +1789,8 @@ export const insertEmptyBlockquote = (protyle: IProtyle, previousElement: HTMLElid,data: blockquoteElement.outerHTML,previousID: previousElement.getAttribute("data-node-id"),- parentID: previousElement.parentElement.getAttribute("data-node-id"),+ parentID: previousElement.parentElement.getAttribute("data-node-id") ||+ getParentBlock(previousElement).getAttribute("data-node-id"),}];const undoOperations: IOperation[] = [{action: "delete",@@ -1822,6 +1825,15 @@ export const insertEmptyBlockquote = (protyle: IProtyle, previousElement: HTMLElhideElements(["gutter"], protyle);};+export const insertEmptyBlockquote = (protyle: IProtyle, previousElement: HTMLElement,+ options?: Parameters<typeof insertEmptyQuoteBlock>[2]) => {+ insertEmptyQuoteBlock(protyle, previousElement, options);+};++export const insertEmptyCallout = (protyle: IProtyle, previousElement: HTMLElement, preset: ICalloutPreset) => {+ insertEmptyQuoteBlock(protyle, previousElement, undefined, preset);+};+export const wrapBlockInBlockquote = async (protyle: IProtyle, blockElement: HTMLElement, options?: {oldHTML: string,undoContext?: Record<string, string>,@@ -1870,6 +1882,7 @@ export const turnsIntoGroupsTransaction = async (options: {protyle: IProtyle,selectsElementGroups: Element[][],type: Exclude<TTurnIntoOne, "BlocksMergeSuperBlock">,+ callout?: ICalloutPreset,}) => {const firstElement = options.selectsElementGroups[0]?.[0];if (!firstElement) {@@ -1886,6 +1899,7 @@ export const turnsIntoGroupsTransaction = async (options: {protyle: options.protyle,selectsElement,type: options.type,+ callout: options.callout,getOperations: true,});doOperations.push(...groupOperations.doOperations);