An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Improve blockquote conversion to callout types https://github.com/siyuan-note/siyuan/issues/20567
Daniel30ed90067b01
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 0876b2aed4..4705b227cd 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -2,6 +2,7 @@ import {IMAGE_OCR_MENU} from "../../menus/declarations/imageOCRMenu";import {declaredMenuCatalog} from "../../menus/declarations/menuDeclaration";import {CODE_TAB_SPACE_VALUES, getCodeTabSpacesLabel} from "../../protyle/wysiwyg/codeBlockUtil";import {orderGutterTurnIntoItems} from "../../protyle/gutter/turnIntoMenu";+import {CALLOUT_PRESETS} from "../../protyle/wysiwyg/calloutType";import {DESKTOP_TOOLBAR_ENTRIES,getToolbarEntryId,@@ -234,11 +235,7 @@ const gutterTurnInto = (multi: boolean) => node("turnInto", lang("turnInto"), trnode("paragraph", lang("paragraph")),node("quote", lang("quote")),node("callout", lang("callout")),- node("calloutNote", location(lang("callout"), literal("Note"))),- node("calloutTip", location(lang("callout"), literal("Tip"))),- node("calloutImportant", location(lang("callout"), literal("Important"))),- node("calloutWarning", location(lang("callout"), literal("Warning"))),- node("calloutCaution", location(lang("callout"), literal("Caution"))),+ ...CALLOUT_PRESETS.map(item => node(item.id, location(lang("callout"), literal(item.title)))),node("calloutCustom", location(lang("callout"), () => `${window.siyuan.languages.custom}...`)),...(!multi ? [node("tabs", lang("tabs"))] : []),node("heading1", lang("heading1")),diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex 7dff4a6d53..d45e62b602 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -139,7 +139,8 @@ import {closeSubElement} from "../toolbar/subElementLifecycle";import {canShowGutterInsert, genGutterBlockButtonHTML} from "./button";import {getViewFoldOccurrenceID, hasViewFoldContext} from "../util/viewFold";import {exportImage} from "../export/util";-import {CALLOUT_PRESETS, updateCalloutType, updateCustomCalloutType} from "../wysiwyg/callout";+import {updateCalloutType, updateCustomCalloutType} from "../wysiwyg/callout";+import {CALLOUT_PRESETS} from "../wysiwyg/calloutType";import {setTabsPosition, toggleTabsTasks, unwrapTabs} from "../wysiwyg/tabs";import {getTaskStatusItems} from "../wysiwyg/taskStatusDialog";import {hasTabsTasks} from "../render/tabsRender";@@ -1990,14 +1991,7 @@ export class Gutter {nodeElement,type: "CancelBlockquote"}));- turnIntoSubmenu.push(this.turnsOneInto({- id,- icon: "iconCallout",- label: window.siyuan.languages.callout,- protyle,- nodeElement,- type: "Blockquote2Callout"- }));+ turnIntoSubmenu.push(...this.calloutTypeMenus(protyle, [nodeElement as HTMLElement]));} else if (type === "NodeCallout" && allowStructuralMutation) {turnIntoSubmenu.push(this.turnsOneInto({menuId: "paragraph",diff --git a/app/src/protyle/gutter/turnIntoMenu.test.ts b/app/src/protyle/gutter/turnIntoMenu.test.tsindex 1799ad3df3..3f7f8f4712 100644--- a/app/src/protyle/gutter/turnIntoMenu.test.ts+++ b/app/src/protyle/gutter/turnIntoMenu.test.ts@@ -6,6 +6,7 @@ import {getEntryCatalogChildren} from "../../config/entryVisibility/catalog";import {mergeEntryOrderPreservingUnknown, reorderEntrySlots, resolveEntryOrder} from "../../config/entryVisibility/order";import {normalizeEntryVisibilityImportProfile} from "../../config/entryVisibility/profile";import {orderGutterTurnIntoItems} from "./turnIntoMenu";+import {CALLOUT_PRESETS} from "../wysiwyg/calloutType";const headings = ["heading1", "heading2", "heading3", "heading4", "heading5", "heading6"];const common = ["paragraph", ...headings, "list", "orderedList", "check", "quote", "callout"];@@ -46,6 +47,35 @@ test("partial paragraph and heading menus keep their candidates and callbacks",}});+test("blockquote callout types retain existing catalog identities and saved orders", () => {+ const path = "gutter.single.turnInto";+ const types = [...CALLOUT_PRESETS.map(item => item.id), "calloutCustom"];+ const catalog = getEntryCatalogChildren(path);+ assert.deepEqual(catalog.filter(item => types.includes(item.key)).map(item => item.key), types);+ types.forEach(key => {+ const entry = catalog.find(item => item.key === key);+ assert.equal(entry.type, "entry");+ assert.equal(entry.simple, true);+ });+ const defaults = catalog.map(item => item.key);+ const saved = ["calloutWarning", "plugin:example:item", "paragraph", "callout", "calloutNote"];+ const profile = normalizeEntryVisibilityImportProfile({name: "Custom", entries: {+ [`${path}.callout`]: false, [`${path}.calloutTip`]: false,+ }, orders: {[path]: saved}}, 6, {[path]: defaults});+ assert.equal(profile.entries[`${path}.callout`], false);+ assert.equal(profile.entries[`${path}.calloutTip`], false);+ assert.deepEqual(profile.orders[path], saved);+ const visible = ["paragraph", ...types].filter(key => profile.entries[`${path}.${key}`] !== false);+ const ordered = reorderEntrySlots(orderGutterTurnIntoItems(visible, key => key),+ resolveEntryOrder(defaults, saved, new Set()), key => key);+ assert.deepEqual(ordered.filter(key => saved.includes(key)), ["calloutWarning", "paragraph", "calloutNote"]);+ const source = readFileSync(resolve(process.cwd(), "src/protyle/gutter/index.ts"), "utf8");+ const quoteMenu = source.slice(source.indexOf('} else if (type === "NodeBlockquote" && allowStructuralMutation)'),+ source.indexOf('} else if (type === "NodeCallout" && allowStructuralMutation)'));+ assert.match(quoteMenu, /this\.calloutTypeMenus\(protyle, \[nodeElement as HTMLElement\]\)/);+ assert.doesNotMatch(quoteMenu, /Blockquote2Callout/);+});+test("saved conversion orders and visibility survive profile migration and default changes", () => {for (const multi of [false, true]) {const path = `gutter.${multi ? "multi" : "single"}.turnInto`;diff --git a/app/src/protyle/wysiwyg/callout.test.ts b/app/src/protyle/wysiwyg/callout.test.tsnew file mode 100644index 0000000000..346b370d85--- /dev/null+++ b/app/src/protyle/wysiwyg/callout.test.ts@@ -0,0 +1,216 @@+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 {createSourceFile, isClassDeclaration, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";++const browserCases = async (sources: string[], luteSource: string) => {+ const check: typeof assert = require("node:assert/strict");+ new Function(luteSource)();+ const lute = Lute.New();+ lute.SetKramdownIAL(true);+ lute.SetProtyleWYSIWYG(true);+ lute.SetCallout(true);+ Object.assign(window, {siyuan: {languages: {callout: "Callout", custom: "Custom", type: "Type"}}});+ const root = document.createElement("div");+ root.dataset.nodeId = "document";+ document.body.append(root);+ const protyle = {lute, wysiwyg: {element: root}, block: {showAll: false}, disabled: false} as unknown as IProtyle;+ let transactions: Array<{doOperations: IOperation[], undoOperations: IOperation[]}> = [];+ let inputOptions: Parameters<typeof import("../../dialog/inputDialog").openInputDialog>[0];+ let destroyed = false;+ 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"},+ transaction: (_protyle: IProtyle, doOperations: IOperation[], undoOperations: IOperation[]) => {+ transactions.push({doOperations, undoOperations});+ },+ getContenteditableElement: (element: Element) => element.querySelector('[contenteditable="true"]'),+ isListMindmapListConversion: () => false,+ getPreviousBlockSibling: (element: Element) => element.previousElementSibling,+ getEmbedChildOperationParentID: (): undefined => undefined,+ getParentBlock: (element: Element) => element.parentElement,+ isTabsListConversion: () => false,+ convertListMindmapToList: (): undefined => undefined,+ cleanListMindmapHTML: identity,+ cleanHeadingNumberHTML: identity,+ cleanTableCellRichHTML: identity,+ cleanBlockSelectionModeHTML: identity,+ disposeCustomBlocksInElement: () => {},+ focusByWbr: () => root.querySelector("wbr")?.remove(),+ getEditorRange: () => document.createRange(),+ blockRender: () => {}, processRender: () => {}, highlightRender: () => {}, avRender: () => {},+ openInputDialog: (options: typeof inputOptions) => {+ inputOptions = options;+ destroyed = false;+ return dialog;+ },+ 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 callouts = {} as typeof import("./callout");+ new Function("exports", "require", sources[2])(callouts, () => ({...dependencies, ...conversions, ...presets}));+ const menu = new Function("CALLOUT_PRESETS", "updateCalloutType", "updateCustomCalloutType",+ sources[3] + "\nreturn new CalloutMenu();")(presets.CALLOUT_PRESETS,+ callouts.updateCalloutType, callouts.updateCustomCalloutType) as {+ calloutTypeMenus: (protyle: IProtyle, elements: HTMLElement[]) => IMenu[];+ };+ const menus = () => menu.calloutTypeMenus(protyle, [root.firstElementChild as HTMLElement]);+ const setup = (markdown = "> # heading\n>\n> alpha\n>\n> - item\n>\n> > inner quote\n") => {+ transactions = [];+ protyle.disabled = false;+ root.innerHTML = lute.Md2BlockDOM(markdown);+ const block = root.firstElementChild as HTMLElement;+ block.setAttribute("custom-test", "kept");+ block.setAttribute("name", "sample");+ block.setAttribute("fold", "1");+ return block;+ };+ const ids = (element: Element) => [element, ...element.querySelectorAll("[data-node-id]")]+ .map(item => item.getAttribute("data-node-id"));+ const update = (operation: IOperation) => {+ check.equal(operation.action, "update");+ root.innerHTML = operation.data as string;+ root.querySelectorAll("wbr").forEach(item => item.remove());+ return root.firstElementChild as HTMLElement;+ };++ // 每种预设都直接转换引述块,内容和属性在一次撤销、重做后仍完整。+ for (const preset of presets.CALLOUT_PRESETS) {+ const source = setup();+ const originalIDs = ids(source);+ const originalHTML = source.outerHTML;+ const items = menus();+ check.deepEqual(items.map(item => item.id), [...presets.CALLOUT_PRESETS.map(item => item.id), "calloutCustom"]);+ check.ok(items.every(item => !item.current));+ items.find(item => item.id === preset.id).click(null, null);+ await Promise.resolve();+ const converted = root.firstElementChild as HTMLElement;+ check.equal(converted.dataset.type, "NodeCallout");+ check.equal(converted.dataset.subtype, preset.type);+ check.equal(converted.querySelector(".callout-title").textContent, preset.title);+ check.equal(converted.querySelector(".callout-icon").textContent, preset.icon);+ check.deepEqual(ids(converted), originalIDs);+ check.equal(converted.getAttribute("custom-test"), "kept");+ check.equal(converted.getAttribute("name"), "sample");+ check.equal(converted.getAttribute("fold"), "1");+ check.match(converted.textContent, /heading.*alpha.*item.*inner quote/s);+ check.equal(transactions.length, 1);+ const {doOperations, undoOperations} = transactions[0];+ check.equal(doOperations.length, 1);+ check.equal(undoOperations.length, 1);+ check.equal(doOperations[0].id, originalIDs[0]);+ check.equal(undoOperations[0].id, originalIDs[0]);+ const restored = update(undoOperations[0]);+ restored.querySelector("wbr")?.remove();+ check.equal(restored.outerHTML, originalHTML);+ check.equal(update(doOperations[0]).outerHTML, converted.outerHTML.replace(' data-editing="true"', ""));+ }++ // 自定义输入确认前不修改原块,空值和取消也不产生事务。+ const source = setup();+ const originalHTML = source.outerHTML;+ menus().find(item => item.id === "calloutCustom").click(null, null);+ check.equal(inputOptions.value, "");+ inputOptions.onConfirm(" ", dialog);+ check.equal(destroyed, false);+ check.equal(root.firstElementChild, source);+ check.equal(source.outerHTML, originalHTML);+ check.equal(transactions.length, 0);+ dialog.destroy();+ check.equal(root.firstElementChild, source);+ check.equal(source.outerHTML, originalHTML);+ menus().find(item => item.id === "calloutCustom").click(null, null);+ const customType = 'CUSTOM <type> " &';+ inputOptions.onConfirm(` ${customType} `, dialog);+ await Promise.resolve();+ check.equal(destroyed, true);+ check.equal((root.firstElementChild as HTMLElement).dataset.subtype, customType);+ check.equal(root.querySelector(".callout-title").textContent, "Note");+ check.equal(transactions.length, 1);+ check.equal((update(transactions[0].undoOperations[0])).dataset.type, "NodeBlockquote");++ // 弹窗期间原块被移除或编辑器变为只读时不再执行转换。+ for (const stale of ["removed", "disabled"]) {+ const block = setup();+ menus().find(item => item.id === "calloutCustom").click(null, null);+ if (stale === "removed") {+ block.remove();+ } else {+ protyle.disabled = true;+ }+ inputOptions.onConfirm("CUSTOM", dialog);+ await Promise.resolve();+ check.equal(transactions.length, 0);+ check.equal(block.dataset.type, "NodeBlockquote");+ }++ // 已有提示块仍保留用户自定义的标题,自定义类型也保留现有图标。+ setup("> [!TIP] My title\n> content\n");+ check.equal(menus().find(item => item.id === "calloutTip").current, true);+ menus().find(item => item.id === "calloutWarning").click(null, null);+ check.equal(root.querySelector(".callout-title").textContent, "My title");+ const icon = root.querySelector(".callout-icon").textContent;+ menus().find(item => item.id === "calloutCustom").click(null, null);+ check.equal(inputOptions.value, "WARNING");+ inputOptions.onConfirm("CUSTOM", dialog);+ 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");+ return "Callout conversion cases passed";+};++test("shared block menus convert blockquotes to callout types in a single undoable transaction", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+}, async () => {+ const 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))))+ .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} }`]+ .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-"));+ const script = path.join(temporary, "run.cjs");+ const code = "(async () => { try { const __name = value => value; return await (" + browserCases.toString() + ")(" ++ JSON.stringify(sources) + "," + JSON.stringify(luteSource) + "); } catch (error) { return error.stack; } })()";+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(code)}));+ app.exit(0);+ } catch (error) { console.error(error); 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, windowsHide: true, timeout: 40000});+ assert.match(result.stdout, /Callout conversion cases passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-callout-test-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});diff --git a/app/src/protyle/wysiwyg/callout.ts b/app/src/protyle/wysiwyg/callout.tsindex 495bd53f4b..cf62e54374 100644--- a/app/src/protyle/wysiwyg/callout.ts+++ b/app/src/protyle/wysiwyg/callout.ts@@ -1,49 +1,25 @@-import {transaction} from "./transaction";+import {transaction, turnsOneInto} from "./transaction";import {Constants} from "../../constants";import {openInputDialog} from "../../dialog/inputDialog";import {focusByRange} from "../util/selectionOffsets";+import {CALLOUT_PRESETS, ICalloutPreset} from "./calloutType";-export interface ICalloutPreset {- id: string;- icon: string;- type: string;- title: string;- color: string;-}--export const CALLOUT_PRESETS: ICalloutPreset[] = [{- id: "calloutNote",- icon: "✏️",- type: "NOTE",- title: "Note",- color: "var(--b3-callout-note)",-}, {- id: "calloutTip",- icon: "💡",- type: "TIP",- title: "Tip",- color: "var(--b3-callout-tip)",-}, {- id: "calloutImportant",- icon: "❗",- type: "IMPORTANT",- title: "Important",- color: "var(--b3-callout-important)",-}, {- id: "calloutWarning",- icon: "⚠️",- type: "WARNING",- title: "Warning",- color: "var(--b3-callout-warning)",-}, {- id: "calloutCaution",- icon: "🚨",- type: "CAUTION",- title: "Caution",- color: "var(--b3-callout-caution)",-}];+const turnBlockquoteIntoCallout = (blockElements: HTMLElement[], protyle: IProtyle,+ callout: Pick<ICalloutPreset, "type" | "title" | "icon">) => {+ if (blockElements.length !== 1 || blockElements[0].dataset.type !== "NodeBlockquote") {+ return false;+ }+ const nodeElement = blockElements[0];+ if (!protyle.disabled && protyle.wysiwyg.element.contains(nodeElement)) {+ void turnsOneInto({protyle, nodeElement, id: nodeElement.dataset.nodeId, type: "Blockquote2Callout", callout});+ }+ return true;+};export const updateCalloutType = (blockElements: HTMLElement[], protyle: IProtyle, preset: ICalloutPreset) => {+ if (turnBlockquoteIntoCallout(blockElements, protyle, preset)) {+ return;+ }const doOperations: IOperation[] = [];const undoOperations: IOperation[] = [];const ids = new Set<string>();@@ -97,6 +73,10 @@ export const updateCustomCalloutType = (blockElements: HTMLElement[], protyle: Iif (!type) {return;}+ if (turnBlockquoteIntoCallout(blockElements, protyle, {...CALLOUT_PRESETS[0], type})) {+ dialog.destroy();+ return;+ }const doOperations: IOperation[] = [];const undoOperations: IOperation[] = [];const ids = new Set<string>();diff --git a/app/src/protyle/wysiwyg/calloutType.ts b/app/src/protyle/wysiwyg/calloutType.tsnew file mode 100644index 0000000000..139b2bc4f3--- /dev/null+++ b/app/src/protyle/wysiwyg/calloutType.ts@@ -0,0 +1,39 @@+export interface ICalloutPreset {+ id: string;+ icon: string;+ type: string;+ title: string;+ color: string;+}++export const CALLOUT_PRESETS: ICalloutPreset[] = [{+ id: "calloutNote",+ icon: "✏️",+ type: "NOTE",+ title: "Note",+ color: "var(--b3-callout-note)",+}, {+ id: "calloutTip",+ icon: "💡",+ type: "TIP",+ title: "Tip",+ color: "var(--b3-callout-tip)",+}, {+ id: "calloutImportant",+ icon: "❗",+ type: "IMPORTANT",+ title: "Important",+ color: "var(--b3-callout-important)",+}, {+ id: "calloutWarning",+ icon: "⚠️",+ type: "WARNING",+ title: "Warning",+ color: "var(--b3-callout-warning)",+}, {+ id: "calloutCaution",+ icon: "🚨",+ type: "CAUTION",+ title: "Caution",+ color: "var(--b3-callout-caution)",+}];diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 3ac9834ae9..8422a520be 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -92,6 +92,7 @@ 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 {@@ -2318,6 +2319,7 @@ export const turnsOneInto = async (options: {id: string,type: string,level?: number,+ callout?: Pick<ICalloutPreset, "type" | "title" | "icon">,undoElement?: {id: string,html: string,@@ -2414,6 +2416,15 @@ export const turnsOneInto = async (options: {// @ts-ignorenewHTML = listHTML ?? options.protyle.lute[options.type](sourceHTML, options.level);}+ if (options.type === "Blockquote2Callout" && options.callout) {+ const template = document.createElement("template");+ template.innerHTML = newHTML;+ const calloutElement = template.content.firstElementChild as HTMLElement;+ calloutElement.dataset.subtype = options.callout.type;+ calloutElement.querySelector(".callout-title").textContent = options.callout.title;+ calloutElement.querySelector(".callout-icon").textContent = options.callout.icon;+ newHTML = calloutElement.outerHTML;+ }const cancelListOperations = options.type === "CancelList" &&options.nodeElement.getAttribute("data-type") === "NodeList" ? buildCancelListOperations(options.nodeElement, {previousID: previousId,