Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support batch heading conversion for list items https://github.com/siyuan-note/siyuan/issues/19827

Daniela0272646f01b
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.sy
index 72af47e9f1..0ad247f99f 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": "20260924145647"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -4064,7 +4064,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210106154056-koo4wdj",
- "updated": "20260924145647"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -11299,7 +11299,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20210106154319-6lhdzmm",
- "updated": "20260811122156"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -11967,6 +11967,47 @@
}
]
},
+ {
+ "ID": "20260924173802-6zzgsf2",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260924173802-6zzgsf2",
+ "updated": "20260924173802"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Select a list or one or more list items, then use the heading shortcuts above or choose "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Block menu"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Turn into"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Heading 1 block"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " (or another heading level) to convert the first paragraph of each item. Existing headings are set to the chosen level. Selecting an entire list affects only its immediate items; other paragraphs, nested lists, numbering, and task states are preserved. Items whose first block is neither a paragraph nor a heading are skipped. On mobile, select the list items and use the same block menu. When only the caret is inside a paragraph, the shortcut converts that paragraph."
+ }
+ ]
+ },
{
"ID": "20210106154319-ans1gna",
"Type": "NodeHeading",
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.sy
index f50b8f9a21..181f89dfca 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": "20260924145647"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -4062,7 +4062,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20201227133317-rkh4bji",
- "updated": "20260924145647"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -11287,7 +11287,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20201227133317-n64nfza",
- "updated": "20260811122156"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -11955,6 +11955,47 @@
}
]
},
+ {
+ "ID": "20260924173802-r3fq7uc",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260924173802-r3fq7uc",
+ "updated": "20260924173802"
+ },
+ "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": "(或其他标题级别)转换各项的首个段落。已有标题会调整到目标级别。选中整个列表时仅处理当前层的列表项,保留其他段落、子列表、编号和任务状态。首块不是段落或标题的列表项会被跳过。移动端可选中列表项后使用相同的块菜单。仅将光标放在段落内时,快捷键转换当前段落。"
+ }
+ ]
+ },
{
"ID": "20201227133317-x02vhoh",
"Type": "NodeHeading",
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.sy
index 02cd53429a..bb0188967f 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": "20260924145647"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -4056,7 +4056,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20211226122652-htptsmh",
- "updated": "20260924145647"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -11299,7 +11299,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20211226122652-wez4zj6",
- "updated": "20260811122156"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -11967,6 +11967,47 @@
}
]
},
+ {
+ "ID": "20260924173802-11vvysw",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260924173802-11vvysw",
+ "updated": "20260924173802"
+ },
+ "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": "(或其他標題層級)轉換各項目的第一個段落。已有標題會調整至目標層級。選取整個列表時僅處理目前層級的列表項目,保留其他段落、子列表、編號和任務狀態。第一個區塊不是段落或標題的列表項目會被略過。行動端可選取列表項目後使用相同的區塊選單。僅將游標放在段落內時,快捷鍵轉換目前段落。"
+ }
+ ]
+ },
{
"ID": "20211226122652-td76oes",
"Type": "NodeHeading",
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.sy
index 565109efdb..3e04431b2c 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": "20260924145647"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -4022,7 +4022,7 @@
"Properties": {
"ID": "20240530101000-twmuxke",
"id": "20240530101000-675gu9g",
- "updated": "20260924145647"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -11232,7 +11232,7 @@
"Properties": {
"ID": "20240530101000-xpeqztf",
"id": "20240530101000-emapwbq",
- "updated": "20260811122156"
+ "updated": "20260924173802"
},
"Children": [
{
@@ -11910,6 +11910,47 @@
}
]
},
+ {
+ "ID": "20260924173802-3l46zgy",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260924173802-3l46zgy",
+ "updated": "20260924173802"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "リストまたは1つ以上のリスト項目を選択し、上の見出しショートカットを使うか、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "ブロックメニュー"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "変換"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "見出し1ブロック"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "(または別の見出しレベル)を選ぶと、各項目の最初の段落を変換できます。既存の見出しは選択したレベルに変更されます。リスト全体を選択した場合は、その直下の項目だけが対象となり、他の段落、子リスト、番号、タスクの状態は保持されます。最初のブロックが段落でも見出しでもない項目はスキップされます。モバイルでもリスト項目を選択し、同じブロックメニューを利用できます。段落内にカーソルを置くだけの場合、ショートカットはその段落を変換します。"
+ }
+ ]
+ },
{
"ID": "20240530101000-yl0e0sq",
"Type": "NodeHeading",
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index 63b0db785d..7d51343608 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -674,6 +674,11 @@ test("heading conversions follow list conversions across block menu scopes", ()
const headingIndex = keys.indexOf("heading1");
assert.equal(headingIndex, keys.indexOf(path === "gutter.single.turnInto" ? "listMindmap" : "check") + 1);
assert.deepEqual(keys.slice(headingIndex, headingIndex + headingKeys.length), headingKeys);
+ headingKeys.forEach(key => {
+ const entry = getEntryCatalogNode(`${path}.${key}`);
+ assert.equal(entry?.type, "entry");
+ assert.equal(entry?.simple, true);
+ });
});
});
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index 007de55b61..df9378f405 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -226,6 +226,7 @@ const gutterTurnInto = (multi: boolean) => node("turnInto", lang("turnInto"), tr
node("orderedList", lang("ordered-list")),
node("check", lang("check")),
...(!multi ? [node("listMindmap", lang("mindmap"))] : []),
+ // 列表及列表项的首块转换复用标题入口,保持单选、多选的配置标识和默认顺序一致。
node("heading1", lang("heading1")),
node("heading2", lang("heading2")),
node("heading3", lang("heading3")),
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index c4f0ed3c28..2cbdf1fc39 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -1859,7 +1859,9 @@ export const initKeyboardToolbar = () => {
window.siyuan.menus.menu.fullscreen("all", restoreMenuKeyboard);
return;
}
- protyle.gutter?.renderMenu(protyle, nodeElement);
+ // 多选时以已选块打开共享块菜单,使列表项转换作用于整个选区。
+ const selectedBlock = protyle.wysiwyg.element.querySelector<HTMLElement>(".protyle-wysiwyg--select");
+ protyle.gutter?.renderMenu(protyle, selectedBlock || nodeElement);
window.siyuan.menus.menu.fullscreen("all", restoreMenuKeyboard);
return;
} else if (type === "outdent") {
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 79cd249c78..95a8d52573 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -38,6 +38,7 @@ import {
import {isEmptyParagraph} from "../wysiwyg/emptyTextBlock";
import {removeBlockPreservingSelectionMode} from "../wysiwyg/remove";
import {focusBlock, focusByRange, getBlockElementsByRange, getEditorRange, selectBlocksByRange} from "../util/selection";
+import {getHeadingConversionElements} from "../wysiwyg/headingConversion";
import {hideElements} from "../ui/hideElements";
import {markGutterForFoldRestore} from "../ui/gutterVisibility";
import {highlightRender} from "../render/highlightRender";
@@ -1018,6 +1019,22 @@ export class Gutter {
};
}
+ private headingTurnIntoMenu(protyle: IProtyle, selectsElement: Element[]): IMenu[] {
+ if (getHeadingConversionElements(selectsElement).length === 0) {
+ return [];
+ }
+ return [1, 2, 3, 4, 5, 6].map(level => this.turnsInto({
+ menuId: `heading${level}`,
+ icon: `iconH${level}`,
+ label: window.siyuan.languages[`heading${level}`],
+ accelerator: window.siyuan.config.keymap.editor.heading[`heading${level}`].custom,
+ protyle,
+ selectsElement,
+ level,
+ type: "Blocks2Hs",
+ }));
+ }
+
private emptyParagraphTurnIntoMenu(protyle: IProtyle, nodeElements: Element[]): IMenu[] {
if (!nodeElements.every(isEmptyParagraph)) {
return [];
@@ -1161,72 +1178,7 @@ export class Gutter {
type: "Blocks2Ps",
isContinue
}));
- turnIntoSubmenu.push(this.turnsInto({
- menuId: "heading1",
- icon: "iconH1",
- label: window.siyuan.languages.heading1,
- accelerator: window.siyuan.config.keymap.editor.heading.heading1.custom,
- protyle,
- selectsElement,
- level: 1,
- type: "Blocks2Hs",
- isContinue
- }));
- turnIntoSubmenu.push(this.turnsInto({
- menuId: "heading2",
- icon: "iconH2",
- label: window.siyuan.languages.heading2,
- accelerator: window.siyuan.config.keymap.editor.heading.heading2.custom,
- protyle,
- selectsElement,
- level: 2,
- type: "Blocks2Hs",
- isContinue
- }));
- turnIntoSubmenu.push(this.turnsInto({
- menuId: "heading3",
- icon: "iconH3",
- label: window.siyuan.languages.heading3,
- accelerator: window.siyuan.config.keymap.editor.heading.heading3.custom,
- protyle,
- selectsElement,
- level: 3,
- type: "Blocks2Hs",
- isContinue
- }));
- turnIntoSubmenu.push(this.turnsInto({
- menuId: "heading4",
- icon: "iconH4",
- label: window.siyuan.languages.heading4,
- accelerator: window.siyuan.config.keymap.editor.heading.heading4.custom,
- protyle,
- selectsElement,
- level: 4,
- type: "Blocks2Hs",
- isContinue
- }));
- turnIntoSubmenu.push(this.turnsInto({
- menuId: "heading5",
- icon: "iconH5",
- label: window.siyuan.languages.heading5,
- accelerator: window.siyuan.config.keymap.editor.heading.heading5.custom,
- protyle,
- selectsElement,
- level: 5,
- type: "Blocks2Hs",
- isContinue
- }));
- turnIntoSubmenu.push(this.turnsInto({
- menuId: "heading6",
- icon: "iconH6",
- label: window.siyuan.languages.heading6,
- accelerator: window.siyuan.config.keymap.editor.heading.heading6.custom,
- protyle,
- selectsElement,
- level: 6,
- type: "Blocks2Hs",
- isContinue
- }));
+ turnIntoSubmenu.push(...this.headingTurnIntoMenu(protyle, selectsElement));
turnIntoSubmenu.push(...this.emptyParagraphTurnIntoMenu(protyle, selectsElement));
window.siyuan.menus.menu.append(new MenuItem({
id: "turnInto",
@@ -1280,6 +1232,18 @@ export class Gutter {
}).element);
}
}
+ if (isList && !protyle.disabled) {
+ const submenu = this.headingTurnIntoMenu(protyle, selectsElement);
+ if (submenu.length > 0) {
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "turnInto",
+ icon: "iconTurnInto",
+ label: window.siyuan.languages.turnInto,
+ type: "submenu",
+ submenu,
+ }).element);
+ }
+ }
if (!protyle.disabled && !isDisabledFeature("ai")) {
window.siyuan.menus.menu.append(new MenuItem({
id: "ai",
@@ -1920,9 +1884,14 @@ export class Gutter {
},
});
}
+ if (!isMindmap) {
+ turnIntoSubmenu.push(...this.headingTurnIntoMenu(protyle, [nodeElement]));
+ }
if (!isMindmap && this.hasSublist([nodeElement])) {
turnIntoSubmenu.push(this.recursiveListMenu(protyle, [nodeElement]));
}
+ } else if (type === "NodeListItem" && allowStructuralMutation) {
+ turnIntoSubmenu.push(...this.headingTurnIntoMenu(protyle, [nodeElement]));
} else if (type === "NodeTabs" && allowStructuralMutation) {
[
{menuId: "list", icon: "iconList", label: "list", type: "Tabs2UL"},
diff --git a/app/src/protyle/wysiwyg/headingConversion.test.ts b/app/src/protyle/wysiwyg/headingConversion.test.ts
new file mode 100644
index 0000000000..8df9a75f12
--- /dev/null
+++ b/app/src/protyle/wysiwyg/headingConversion.test.ts
@@ -0,0 +1,260 @@
+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, isMethodDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+import type {Node} from "typescript";
+
+const browserCases = (source: string, menuSource: string, rangeSource: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ const lute = Lute.New();
+ const editor = document.createElement("div");
+ document.body.append(editor);
+ const batches: Array<{doOperations: IOperation[], undoOperations: IOperation[]}> = [];
+ let disconnects = 0;
+ const noop = (): void => undefined;
+ const dependencies = {
+ Constants: {ATTRIBUTE_EDITING: "data-editing", ZWSP: "\u200b"},
+ transaction: (_protyle: IProtyle, doOperations: IOperation[], undoOperations: IOperation[]) => {
+ batches.push({doOperations, undoOperations});
+ },
+ hideElements: (panels: string[]) => {
+ if (panels.includes("select")) {
+ editor.querySelectorAll(".protyle-wysiwyg--select, .protyle-wysiwyg--select-mode").forEach(item => {
+ item.classList.remove("protyle-wysiwyg--select", "protyle-wysiwyg--select-mode");
+ item.removeAttribute("select-start");
+ item.removeAttribute("select-end");
+ });
+ }
+ },
+ processRender: noop,
+ highlightRender: noop,
+ avRender: noop,
+ blockRender: noop,
+ disposeCustomBlocksInElement: noop,
+ focusBlock: noop,
+ focusByRange: (range: Range) => {
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ },
+ getSemanticMarkerPrefixLengthForNode: () => 0,
+ hasPreviousSibling: (element: Element) => element.previousSibling,
+ setFold: () => check.fail("List folding must not unfold unrelated content"),
+ };
+ const api = new Function(...Object.keys(dependencies), source +
+ "\nreturn {turnsIntoTransaction, getHeadingConversionElements, isListHeadingContainer};")(...Object.values(dependencies)) as
+ typeof import("./transaction") & typeof import("./headingConversion");
+ const protyle = {wysiwyg: {element: editor}, lute, observerLoad: {disconnect: () => disconnects++}} as unknown as IProtyle;
+ const Gutter = new Function("turnsIntoTransaction", "getHeadingConversionElements", menuSource + "\nreturn Gutter;")(
+ api.turnsIntoTransaction, api.getHeadingConversionElements);
+ const gutter = new Gutter() as {
+ headingTurnIntoMenu: (protyle: IProtyle, elements: Element[]) => Array<{id: string, click: () => void}>,
+ };
+ window.siyuan = {languages: {}, config: {keymap: {editor: {heading: {}}}}} as typeof window.siyuan;
+ for (let level = 1; level <= 6; level++) {
+ window.siyuan.languages[`heading${level}`] = `Heading ${level}`;
+ window.siyuan.config.keymap.editor.heading[`heading${level}`] = {custom: `Alt+Ctrl+${level}`};
+ }
+ const reset = (subtype = "u") => {
+ const marker = {u: "-", o: "1.", t: "- [x]"}[subtype];
+ editor.innerHTML = lute.Md2BlockDOM(`${marker} **one**\n\n tail\n\n - nested\n\n${marker} two\n\n${marker} three`);
+ batches.length = 0;
+ return editor.querySelector('[data-type="NodeList"]');
+ };
+ const items = (list: Element) => Array.from(list.querySelectorAll(':scope > [data-type="NodeListItem"]'));
+ const first = (item: Element) => item.querySelector(":scope > [data-node-id]");
+ const id = (element: Element) => element.getAttribute("data-node-id");
+ const cleanHTML = () => {
+ const clone = editor.cloneNode(true) as Element;
+ clone.querySelectorAll("[data-editing]").forEach(item => item.removeAttribute("data-editing"));
+ clone.querySelectorAll("wbr").forEach(item => item.remove());
+ return clone.innerHTML;
+ };
+ const replay = (operations: IOperation[]) => {
+ operations.forEach(operation => {
+ check.equal(operation.action, "update");
+ editor.querySelector(`[data-node-id="${operation.id}"]`).outerHTML = operation.data as string;
+ });
+ };
+ const setCaret = (element: Element) => {
+ const range = document.createRange();
+ range.selectNodeContents(element.querySelector('[contenteditable="true"]'));
+ range.collapse(true);
+ dependencies.focusByRange(range);
+ };
+
+ for (const subtype of ["u", "o", "t"]) {
+ for (let level = 1; level <= 6; level++) {
+ const list = reset(subtype);
+ const listItems = items(list);
+ listItems[0].setAttribute("fold", "1");
+ listItems[0].setAttribute("data-task", "x");
+ const targets = listItems.map(first);
+ targets[0].setAttribute("custom-test", "retained");
+ const targetIDs = targets.map(id);
+ const before = cleanHTML();
+ const nested = listItems[0].querySelector('[data-type="NodeList"]').outerHTML;
+ const tail = listItems[0].querySelectorAll(':scope > [data-type="NodeParagraph"]')[1].outerHTML;
+ const menu = gutter.headingTurnIntoMenu(protyle, [list]);
+ check.deepEqual(menu.map(item => item.id), [1, 2, 3, 4, 5, 6].map(value => `heading${value}`));
+ menu[level - 1].click();
+ check.equal(batches.length, 1);
+ check.deepEqual(batches[0].doOperations.map(operation => operation.id), targetIDs);
+ listItems.forEach(item => check.equal(first(item).getAttribute("data-subtype"), `h${level}`));
+ check.equal(first(listItems[0]).getAttribute("custom-test"), "retained");
+ check.ok(first(listItems[0]).querySelector('[data-type="strong"]'));
+ check.equal(listItems[0].getAttribute("fold"), "1");
+ check.equal(listItems[0].getAttribute("data-task"), "x");
+ check.equal(listItems[0].querySelector('[data-type="NodeList"]').outerHTML, nested);
+ check.equal(listItems[0].querySelector(':scope > [data-type="NodeParagraph"]').outerHTML, tail);
+ const after = cleanHTML();
+ replay(batches[0].undoOperations);
+ check.equal(cleanHTML(), before);
+ replay(batches[0].doOperations);
+ check.equal(cleanHTML(), after);
+ }
+ }
+
+ for (const selectList of [false, true]) {
+ const list = reset();
+ const selected = selectList ? [list] : items(list).slice(0, 2);
+ const event = new KeyboardEvent("keydown", {cancelable: true});
+ const rangeDependencies = {
+ isCrossBlock: true,
+ selectText: "one two",
+ range: document.createRange(),
+ getBlockElementsByRange: () => selected,
+ getUndoFocusContext: noop,
+ turnsIntoTransaction: api.turnsIntoTransaction,
+ isListHeadingContainer: api.isListHeadingContainer,
+ protyle,
+ event,
+ };
+ const convertRange = new Function(...Object.keys(rangeDependencies), rangeSource +
+ "\nreturn turnCrossBlockRangeInto;")(...Object.values(rangeDependencies)) as (type: TTurnInto, level?: number) => boolean;
+ check.equal(convertRange("Blocks2Ps"), false);
+ check.equal(convertRange("Blocks2Hs", 5), true);
+ check.equal(batches.length, 1);
+ check.equal(batches[0].doOperations.length, selectList ? 3 : 2);
+ check.equal(event.defaultPrevented, true);
+ }
+
+ for (const selectList of [false, true]) {
+ const list = reset();
+ const listItems = items(list);
+ const selected = selectList ? [list] : [listItems[0], listItems[2]];
+ selected.forEach(item => item.classList.add("protyle-wysiwyg--select"));
+ setCaret(first(listItems[0]));
+ api.turnsIntoTransaction({protyle, nodeElement: first(listItems[0]), type: "Blocks2Hs", level: 2});
+ check.equal(first(listItems[0]).getAttribute("data-type"), "NodeHeading");
+ check.equal(first(listItems[1]).getAttribute("data-type"), selectList ? "NodeHeading" : "NodeParagraph");
+ check.equal(first(listItems[2]).getAttribute("data-type"), "NodeHeading");
+ check.equal(editor.querySelector("wbr, .protyle-wysiwyg--select"), null);
+ check.ok(first(listItems[0]).contains(getSelection().anchorNode));
+ }
+
+ let list = reset();
+ let listItems = items(list);
+ let targets = listItems.map(first);
+ check.deepEqual(api.getHeadingConversionElements([list, listItems[0], targets[0]]), targets);
+ api.turnsIntoTransaction({protyle, selectsElement: [listItems[0], listItems[2]], type: "Blocks2Hs", level: 3});
+ check.equal(first(listItems[1]).getAttribute("data-type"), "NodeParagraph");
+ listItems[0].classList.add("protyle-wysiwyg--select");
+ setCaret(first(listItems[0]));
+ api.turnsIntoTransaction({protyle, nodeElement: first(listItems[0]), type: "Blocks2Hs", level: 3});
+ check.equal(first(listItems[0]).getAttribute("data-type"), "NodeHeading");
+ api.turnsIntoTransaction({protyle, nodeElement: first(listItems[0]), type: "Blocks2Hs", level: 3});
+ check.equal(first(listItems[0]).getAttribute("data-type"), "NodeParagraph");
+
+ list = reset();
+ listItems = items(list);
+ targets = listItems.map(first);
+ targets[0].setAttribute("data-type", "NodeCodeBlock");
+ check.equal(gutter.headingTurnIntoMenu(protyle, [listItems[0]]).length, 0);
+ listItems[0].classList.add("protyle-wysiwyg--select");
+ setCaret(targets[0]);
+ const unchanged = editor.innerHTML;
+ const previousDisconnects = disconnects;
+ api.turnsIntoTransaction({protyle, nodeElement: targets[0], type: "Blocks2Hs", level: 1});
+ check.equal(editor.innerHTML, unchanged);
+ check.equal(batches.length, 0);
+ check.equal(disconnects, previousDisconnects);
+
+ list = reset();
+ editor.insertAdjacentHTML("beforeend", lute.Md2BlockDOM("outside"));
+ const outside = editor.lastElementChild;
+ api.turnsIntoTransaction({protyle, selectsElement: [list, outside], type: "Blocks2Hs", level: 4});
+ check.equal(batches[0].doOperations.length, 4);
+ check.equal(editor.lastElementChild.getAttribute("data-type"), "NodeHeading");
+ check.equal(editor.querySelectorAll('[data-type="NodeList"]').length, 2);
+ editor.remove();
+ return "List heading conversion cases passed";
+};
+
+test("list heading menus and shortcuts preserve containers, content, IDs and undo operations", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const read = (file: string) => readFileSync(path.join(__dirname, file), "utf8");
+ const compile = (source: string) => transpileModule(source.replace(/^export /gm, ""), {
+ compilerOptions: {target: ScriptTarget.ES2021},
+ }).outputText;
+ const extract = (file: string, name: string) => {
+ const parsed = createSourceFile(file, read(file), ScriptTarget.Latest, true);
+ let result: string;
+ const visit = (node: Node) => {
+ if (isVariableStatement(node) && node.declarationList.declarations.some(item => item.name.getText(parsed) === name)) {
+ result = node.getText(parsed);
+ return;
+ }
+ node.forEachChild(visit);
+ };
+ visit(parsed);
+ assert.ok(result, name);
+ return result;
+ };
+ const source = compile(read("headingConversion.ts") + "\n" + extract("transaction.ts", "turnsIntoTransaction") +
+ "\n" + extract("getBlock.ts", "getNextBlockSibling") + "\n" + extract("../util/selection.ts", "focusByWbr"));
+ const rangeSource = compile(extract("keydown.ts", "turnCrossBlockRangeInto"));
+ const parsed = createSourceFile("gutter.ts", read("../gutter/index.ts"), ScriptTarget.Latest, true);
+ const gutter = parsed.statements.find(isClassDeclaration);
+ const methods = gutter.members.filter(member => isMethodDeclaration(member) &&
+ ["headingTurnIntoMenu", "turnsInto"].includes(member.name.getText(parsed)));
+ const menuSource = compile("class Gutter {\n" + methods.map(member => member.getText(parsed)).join("\n") + "\n}");
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-list-heading-test-"));
+ const script = path.join(temporary, "run.cjs");
+ const lutePath = path.resolve(__dirname, "../../../stage/protyle/js/lute/lute.min.js");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +
+ browserCases.toString() + ")(" + [source, menuSource, rangeSource].map(value => JSON.stringify(value)).join(",") + ")")}));
+ win.destroy();
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win.destroy();
+ 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, timeout: 40000, windowsHide: true});
+ assert.match(result.stdout, /List heading conversion cases passed/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&
+ path.basename(temporary).startsWith("siyuan-list-heading-test-")) {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});
diff --git a/app/src/protyle/wysiwyg/headingConversion.ts b/app/src/protyle/wysiwyg/headingConversion.ts
new file mode 100644
index 0000000000..f4bed3d2bd
--- /dev/null
+++ b/app/src/protyle/wysiwyg/headingConversion.ts
@@ -0,0 +1,30 @@
+export const isListHeadingContainer = (element: Element) =>
+ ["NodeList", "NodeListItem"].includes(element.getAttribute("data-type"));
+
+export const getHeadingConversionElements = (elements: Element[]) => {
+ const targets = new Set<Element>();
+ const addListItem = (item: Element) => {
+ // 只转换列表项的直接首块,保留后续段落及子列表。
+ const firstBlock = Array.from(item.children).find(child => child.hasAttribute("data-node-id"));
+ if (firstBlock && ["NodeParagraph", "NodeHeading"].includes(firstBlock.getAttribute("data-type"))) {
+ targets.add(firstBlock);
+ }
+ };
+ elements.forEach(element => {
+ const type = element.getAttribute("data-type");
+ if (type === "NodeList") {
+ Array.from(element.children).forEach(child => {
+ if (child.getAttribute("data-type") === "NodeListItem") {
+ addListItem(child);
+ }
+ });
+ } else if (type === "NodeListItem") {
+ addListItem(element);
+ } else {
+ targets.add(element);
+ }
+ });
+ const result = Array.from(targets);
+ return result.filter(target => !result.some(parent =>
+ parent !== target && parent.contains(target)));
+};
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 86927295da..f26ed53406 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -78,6 +78,7 @@ import {
updateTransaction
} from "./transaction";
import {isEmptyParagraph} from "./emptyTextBlock";
+import {isListHeadingContainer} from "./headingConversion";
import {turnParagraphIntoCode} from "./turnIntoCode";
import {getBlockquoteContext, shouldCancelBlockquote} from "./blockquote";
import {fontEvent} from "../toolbar/Font";
@@ -1249,7 +1250,8 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
return false;
}
const selectsElement = getBlockElementsByRange(range);
- if (selectsElement.length < 2 || selectsElement.some(item => item.classList.contains("li"))) {
+ const listHeading = type === "Blocks2Hs" && selectsElement.some(isListHeadingContainer);
+ if (!listHeading && (selectsElement.length < 2 || selectsElement.some(item => item.classList.contains("li")))) {
return false;
}
const focusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 48a543d0b1..cccf0e79d9 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -74,6 +74,7 @@ import {
restoreBlockSelectionModeState
} from "./blockSelection";
import {isEmptyParagraph} from "./emptyTextBlock";
+import {getHeadingConversionElements, isListHeadingContainer} from "./headingConversion";
import {cleanTableCellRichHTML, retainTableCellRichMetadata} from "../util/tableCellRich";
import {cleanListMindmapHTML, convertListMindmapToList, listMindmapConversionSource} from "../render/listMindmap/model";
import {getProtyleTransactionOwner} from "../runtimeCapabilities";
@@ -1834,25 +1835,25 @@ export const turnsIntoTransaction = (options: {
range?: Range,
unfocus?: boolean,
}) => {
- // https://github.com/siyuan-note/siyuan/issues/14505
- options.protyle.observerLoad?.disconnect();
let selectsElement: Element[] = options.selectsElement;
let range: Range;
// 通过快捷键触发
if (options.nodeElement) {
- range = getSelection().getRangeAt(0);
- range.insertNode(document.createElement("wbr"));
selectsElement = Array.from(options.protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
if (selectsElement.length === 0) {
selectsElement = [options.nodeElement];
}
+ }
+ const hasListHeadingTargets = options.type === "Blocks2Hs" && selectsElement.some(isListHeadingContainer);
+ if (hasListHeadingTargets) {
+ selectsElement = getHeadingConversionElements(selectsElement);
+ }
+ if (selectsElement.length === 0 || options.nodeElement && selectsElement.some(item => item.classList.contains("li"))) {
+ return;
+ }
+ if (options.nodeElement) {
let isContinue = false;
- let isList = false;
selectsElement.find((item, index) => {
- if (item.classList.contains("li")) {
- isList = true;
- return true;
- }
if (selectsElement[index + 1] && getNextBlockSibling(item) === selectsElement[index + 1]) {
isContinue = true;
} else if (index !== selectsElement.length - 1) {
@@ -1860,16 +1861,20 @@ export const turnsIntoTransaction = (options: {
return true;
}
});
- if (isList) {
- return;
- }
- if (selectsElement.length === 1 && options.type === "Blocks2Hs" &&
+ if (!hasListHeadingTargets && selectsElement.length === 1 && options.type === "Blocks2Hs" &&
selectsElement[0].getAttribute("data-type") === "NodeHeading" &&
options.level === parseInt(selectsElement[0].getAttribute("data-subtype").substr(1))) {
// 快捷键同级转换,消除标题
options.type = "Blocks2Ps";
}
options.isContinue = isContinue;
+ range = getSelection().getRangeAt(0);
+ range.insertNode(document.createElement("wbr"));
+ }
+ // https://github.com/siyuan-note/siyuan/issues/14505
+ options.protyle.observerLoad?.disconnect();
+ if (hasListHeadingTargets) {
+ hideElements(["select"], options.protyle);
}
let html = "";