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 converting between lists and tabbed containers https://github.com/siyuan-note/siyuan/issues/17642
Daniel9907c87699aa
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.tsindex 1e3cd7cd18..867187f860 100644--- a/app/src/config/entryVisibility/catalog.test.ts+++ b/app/src/config/entryVisibility/catalog.test.ts@@ -623,6 +623,15 @@ test("callout presets stay aligned across block menu scopes", () => {});});+test("tab conversion belongs to the single block conversion menu", () => {+ const keys = getEntryCatalogChildren("gutter.single.turnInto").map(item => item.key);+ assert.equal(keys[keys.indexOf("tabs") - 1], "calloutCustom");+ assert.equal(keys[keys.indexOf("tabs") + 1], "list");+ assert.equal(getEntryCatalogNode("gutter.single.turnInto.tabs")?.simple, true);+ assert.equal(getEntryCatalogNode("gutter.single.turnInto.tabs")?.type, "entry");+ assert.equal(getEntryCatalogNode("gutter.multi.turnInto.tabs"), undefined);+});+test("conditional block resource menus have distinct configuration labels", () => {const windowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window");Object.defineProperty(globalThis, "window", {diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 4c01b8be24..f104d21d1f 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -201,7 +201,7 @@ const gutterCopyChildren = (includeCopyAsPNG = false) => [node("duplicateCompletely", lang("duplicateCompletely")),];-const gutterTurnInto = () => node("turnInto", lang("turnInto"), true, [+const gutterTurnInto = (multi: boolean) => node("turnInto", lang("turnInto"), true, [node("paragraph", lang("paragraph")),node("heading1", lang("heading1")),node("heading2", lang("heading2")),@@ -217,6 +217,7 @@ const gutterTurnInto = () => node("turnInto", lang("turnInto"), true, [node("calloutWarning", location(lang("callout"), literal("Warning"))),node("calloutCaution", location(lang("callout"), literal("Caution"))),node("calloutCustom", location(lang("callout"), () => `${window.siyuan.languages.custom}...`)),+ ...(!multi ? [node("tabs", lang("tabs"))] : []),node("list", lang("list")),node("orderedList", lang("ordered-list")),node("check", lang("check")),@@ -325,7 +326,7 @@ const gutterTable = () => node("table", lang("table"), true, []);const gutterBase = (multi: boolean) => [- gutterTurnInto(),+ gutterTurnInto(multi),...(multi ? [gutterHeadingTransform(), node("mergeSuperBlock", () => `${window.siyuan.languages.merge} ${window.siyuan.languages.superBlock}`, true, [node("hLayout", lang("hLayout")),node("vLayout", lang("vLayout")),diff --git a/app/src/config/entryVisibility/order.test.ts b/app/src/config/entryVisibility/order.test.tsindex 626df6e691..236870e46e 100644--- a/app/src/config/entryVisibility/order.test.ts+++ b/app/src/config/entryVisibility/order.test.ts@@ -32,6 +32,17 @@ test("entry order ignores unknown and duplicate keys", () => {assert.deepEqual(mergeEntryOrder(["a", "b", "c"], ["missing", "c", "c", "a"]), ["c", "a", "b"]);});+test("tab conversion merges into saved block menus without moving plugin slots", () => {+ const entries = getEntryCatalogChildren("gutter.single.turnInto");+ const defaults = entries.map(item => item.key);+ const saved = defaults.filter(key => key !== "tabs");+ saved.splice(1, 0, "plugin:example:item");+ const merged = mergeEntryOrderPreservingUnknown(defaults, saved);+ assert.deepEqual(merged.filter(key => key !== "tabs"), saved);+ assert.equal(merged[1], "plugin:example:item");+ assert.equal(merged[merged.indexOf("tabs") + 1], "list");+});+test("document tree profiles merge sibling creation while preserving custom order and plugin slots", () => {const entries = getEntryCatalogChildren("docTree.document");const defaults = entries.map((item) => item.key);diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex c05b512621..e45aa0ab11 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -1885,6 +1885,15 @@ export class Gutter {selectsElement: [nodeElement],type: "Blocks2Callout"}));+ turnIntoSubmenu.push(this.turnsOneInto({+ menuId: "tabs",+ id,+ icon: "iconTabs",+ label: window.siyuan.languages.tabs,+ protyle,+ nodeElement,+ type: "List2Tabs"+ }));const listSubtype = nodeElement.getAttribute("data-subtype");if (listSubtype === "o") {turnIntoSubmenu.push(this.turnsOneInto({@@ -1953,6 +1962,18 @@ export class Gutter {if (this.hasSublist([nodeElement])) {turnIntoSubmenu.push(this.recursiveListMenu(protyle, [nodeElement]));}+ } else if (type === "NodeTabs" && allowStructuralMutation) {+ [+ {menuId: "list", icon: "iconList", label: "list", type: "Tabs2UL"},+ {menuId: "orderedList", icon: "iconOrderedList", label: "ordered-list", type: "Tabs2OL"},+ {menuId: "check", icon: "iconCheck", label: "check", type: "Tabs2TL"},+ ].forEach(target => turnIntoSubmenu.push(this.turnsOneInto({+ ...target,+ id,+ label: window.siyuan.languages[target.label],+ protyle,+ nodeElement,+ })));} else if (type === "NodeBlockquote" && allowStructuralMutation) {turnIntoSubmenu.push(this.turnsOneInto({menuId: "paragraph",diff --git a/app/src/protyle/wysiwyg/tabsList.test.ts b/app/src/protyle/wysiwyg/tabsList.test.tsnew file mode 100644index 0000000000..df360b7411--- /dev/null+++ b/app/src/protyle/wysiwyg/tabsList.test.ts@@ -0,0 +1,11 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {tabsListTitle} from "./tabsList";++test("tab summaries count twelve runes and append an extra ellipsis only when truncated", () => {+ assert.equal(tabsListTitle(""), "");+ assert.equal(tabsListTitle("abcdefghijkl"), "abcdefghijkl");+ assert.equal(tabsListTitle("abcdefghijklm"), "abcdefghijkl...");+ assert.equal(tabsListTitle("这是一个超过十二个字符的长段落"), "这是一个超过十二个字符的...");+ assert.equal(tabsListTitle("😀".repeat(13)), "😀".repeat(12) + "...");+});diff --git a/app/src/protyle/wysiwyg/tabsList.ts b/app/src/protyle/wysiwyg/tabsList.tsnew file mode 100644index 0000000000..f89aa91e72--- /dev/null+++ b/app/src/protyle/wysiwyg/tabsList.ts@@ -0,0 +1,157 @@+export type TTabsListConversion = "List2Tabs" | "Tabs2UL" | "Tabs2OL" | "Tabs2TL";++export const isTabsListConversion = (type: string): type is TTabsListConversion =>+ ["List2Tabs", "Tabs2UL", "Tabs2OL", "Tabs2TL"].includes(type);++const blockChildren = (element: Element): Element[] => Array.from(+ (element.getAttribute("data-type") === "NodeTabItem" ?+ element.querySelector(":scope > .tab-item-content") : element)?.children || [],+).filter(child => child.hasAttribute("data-node-id"));++// 补齐折叠隐藏的块,同时保留编辑器中已有的正文、属性和光标。+export const completeTabsListSource = (visible: Element, full: Element): Element => {+ const result = visible.cloneNode(true) as Element;+ const complete = (target: Element, source: Element) => {+ const container = target.getAttribute("data-type") === "NodeTabItem" ?+ target.querySelector(":scope > .tab-item-content") : target;+ const children = blockChildren(target);+ const byID = new Map(children.map(child => [child.getAttribute("data-node-id"), child]));+ let next = container.querySelector(":scope > .protyle-attr");+ blockChildren(source).reverse().forEach(child => {+ const existing = byID.get(child.getAttribute("data-node-id"));+ if (existing) {+ complete(existing, child);+ next = existing;+ } else {+ const added = child.cloneNode(true) as Element;+ container.insertBefore(added, next);+ next = added;+ }+ });+ };+ complete(result, full);+ return result;+};++export const tabsListText = (element: Element): string => {+ if (!element) {+ return "";+ }+ const clone = element.cloneNode(true) as Element;+ clone.querySelectorAll("wbr, .protyle-attr, .protyle-action").forEach(item => item.remove());+ clone.querySelectorAll("br").forEach(item => item.replaceWith(" "));+ clone.querySelectorAll('[data-type="inline-math"]').forEach(item => item.replaceWith(item.getAttribute("data-content") || ""));+ clone.querySelectorAll("img").forEach(item => item.replaceWith(item.getAttribute("alt") || ""));+ return (clone.textContent || "").replace(/[\u200b\ufeff]/g, "").replace(/\s+/gu, " ").trim();+};++export const tabsListTitle = (text: string): string => {+ const runes = Array.from(text);+ return runes.slice(0, 12).join("") + (runes.length > 12 ? "..." : "");+};++const isRepeatedTitle = (title: Element, paragraph: Element): boolean => {+ if (!paragraph || tabsListText(title) !== tabsListText(paragraph)) {+ return false;+ }+ const clean = (element: Element) => {+ const clone = element.cloneNode(true) as Element;+ clone.querySelectorAll("wbr").forEach(caret => caret.remove());+ return clone;+ };+ const titleContent = clean(title);+ // 普通摘要可复用原正文,富格式标题只有内容完全一致时才省略,避免丢失引用等行级信息。+ return titleContent.childElementCount === 0 || titleContent.innerHTML === clean(paragraph).innerHTML;+};++const skeleton = (lute: Lute, markdown: string): HTMLElement => {+ const template = document.createElement("template");+ template.innerHTML = lute.Md2BlockDOM(markdown);+ return template.content.firstElementChild as HTMLElement;+};++const newParagraph = (lute: Lute): HTMLElement => {+ const paragraph = skeleton(lute, "x\n");+ paragraph.querySelector("[contenteditable]").replaceChildren();+ return paragraph;+};++const convertContainer = (source: Element, target: HTMLElement): HTMLElement => {+ const result = source.cloneNode(false) as HTMLElement;+ ["data-subtype", "data-marker", "data-task", "data-tight", "fold", "data-tabs-hidden", "data-tabs-editing",+ "tabs-active-id", "tabs-position", "data-sb-layout", "data-list-index", "aria-hidden", "hidden"].forEach(name =>+ result.removeAttribute(name));+ Array.from(target.attributes).forEach(attr => {+ if (!["data-node-id", "updated"].includes(attr.name)) {+ result.setAttribute(attr.name, attr.value);+ }+ });+ result.replaceChildren(...Array.from(target.childNodes));+ const oldIAL = source.querySelector(":scope > .protyle-attr");+ if (oldIAL) {+ result.querySelector(":scope > .protyle-attr")?.replaceWith(oldIAL.cloneNode(true));+ }+ return result;+};++// 仅改当前容器及直属项的类型,正文和嵌套容器保持原有块身份。+export const convertTabsList = (source: Element, type: TTabsListConversion, lute: Lute): HTMLElement => {+ const toTabs = type === "List2Tabs";+ if (source.getAttribute("data-type") !== (toTabs ? "NodeList" : "NodeTabs")) {+ return;+ }+ const items = blockChildren(source);+ if (items.length === 0) {+ return;+ }+ const listMarker = type === "Tabs2OL" ? "1." : type === "Tabs2TL" ? "* [ ]" : "*";+ const target = skeleton(lute, toTabs ? "::: tabs\n@tab\n\n:::\n" : `${listMarker} \n`);+ const itemTemplate = target.querySelector(toTabs ? ":scope > .tab-item" : ":scope > .li") as HTMLElement;+ const result = convertContainer(source, target);+ result.querySelector(toTabs ? ":scope > .tab-item" : ":scope > .li").remove();+ items.forEach((item, index) => {+ const converted = convertContainer(item, itemTemplate.cloneNode(true) as HTMLElement);+ const blocks = blockChildren(item).map(child => child.cloneNode(true) as Element);+ const first = blocks[0];+ const paragraph = first?.getAttribute("data-type") === "NodeParagraph" ?+ first.querySelector(":scope > [contenteditable]") : undefined;+ if (toTabs) {+ converted.querySelector(".tab-item-title").textContent = tabsListTitle(tabsListText(paragraph));+ const body = converted.querySelector(".tab-item-content");+ body.replaceChildren(...(blocks.length > 0 ? blocks : [newParagraph(lute)]));+ } else {+ const title = item.querySelector(":scope > .tab-item-info > .tab-item-title");+ const text = tabsListText(title);+ if (text && !isRepeatedTitle(title, paragraph)) {+ const titleBlock = newParagraph(lute);+ titleBlock.querySelector("[contenteditable]").innerHTML = title.innerHTML;+ titleBlock.querySelectorAll("wbr").forEach(caret => caret.remove());+ blocks.unshift(titleBlock);+ }+ converted.querySelectorAll(":scope > [data-node-id]").forEach(child => child.remove());+ if (blocks.length === 0) {+ blocks.push(newParagraph(lute));+ }+ const ial = converted.querySelector(":scope > .protyle-attr");+ blocks.forEach(block => converted.insertBefore(block, ial));+ if (type === "Tabs2OL") {+ converted.dataset.marker = `${index + 1}.`;+ converted.querySelector(":scope > .protyle-action").textContent = `${index + 1}.`;+ }+ }+ result.insertBefore(converted, result.querySelector(":scope > .protyle-attr"));+ });+ if (toTabs) {+ result.setAttribute("tabs-active-id", result.querySelector(":scope > .tab-item").getAttribute("data-node-id"));+ }+ if (source.querySelector("wbr")) {+ if (toTabs) {+ result.querySelectorAll("wbr").forEach(caret => caret.remove());+ }+ if (!result.querySelector("wbr")) {+ result.querySelector(toTabs ? ".tab-item-content [contenteditable=\"true\"]" : "[contenteditable=\"true\"]")+ ?.insertAdjacentHTML("afterbegin", "<wbr>");+ }+ }+ return result;+};diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 0740744c7b..326b710884 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -67,6 +67,8 @@ import {restoreBlockSelectionModeState} from "./blockSelection";import {isEmptyParagraph} from "./emptyTextBlock";+import {completeTabsListSource, convertTabsList, isTabsListConversion} from "./tabsList";+import {waitForPendingTransactions} from "../util/transactionQueue";import {invalidateTrackedRangesByOperations,type ITrackedRangeInsertion,@@ -2136,8 +2138,37 @@ export const turnsOneInto = async (options: {}const parentId = getEmbedChildOperationParentID(options.nodeElement) ||getParentBlock(options.nodeElement).getAttribute("data-node-id") || options.protyle.block.parentID;- // @ts-ignore- const newHTML = options.protyle.lute[options.type](options.nodeElement.outerHTML, options.level);+ let newHTML: string;+ if (isTabsListConversion(options.type)) {+ let source = options.nodeElement;+ if (!options.protyle.lite && source.querySelector('[fold="1"]')) {+ await waitForPendingTransactions(options.protyle);+ const snapshot = source.outerHTML;+ const response = await fetchSyncPost("/api/block/getBlockDOM", {+ id: options.id,+ notebook: options.protyle.notebookId,+ });+ if (!source.isConnected || source.outerHTML !== snapshot) {+ return;+ }+ const template = document.createElement("template");+ template.innerHTML = normalizeHTMLAssetIFrameBlockDOM(response.data?.dom || "");+ const full = template.content.firstElementChild;+ if (full?.getAttribute("data-node-id") !== options.id) {+ return;+ }+ source = completeTabsListSource(source, full);+ oldHTML = source.outerHTML;+ }+ const converted = convertTabsList(source, options.type, options.protyle.lute);+ if (!converted) {+ return;+ }+ newHTML = converted.outerHTML;+ } else {+ // @ts-ignore+ newHTML = options.protyle.lute[options.type](options.nodeElement.outerHTML, options.level);+ }disposeCustomBlocksInElement(options.nodeElement);options.nodeElement.insertAdjacentHTML("afterend", newHTML);options.nodeElement = options.nodeElement.nextElementSibling as HTMLElement;diff --git a/docs/TABS.md b/docs/TABS.mdindex 62109dd79c..03cebd1352 100644--- a/docs/TABS.md+++ b/docs/TABS.md@@ -68,6 +68,12 @@ Linux 下的说明。## 渲染与编辑+通过块标菜单的 `转换为` 可以将当前列表转为页签,或者将当前页签转为无序、有序、任务列表。只转换当前层级,正文中的子列表和嵌套页签保持原样。列表容器、列表项及正文块沿用原 ID 和属性;类型专属状态随转换重置,整个操作支持一次撤销。++列表转页签时,从每个直属列表项首个正文块提取标题;仅当该块为段落时使用其可见文字,将换行和连续空白合并为空格,取前 12 个 rune,超出时追加不计入长度的 `...`。标题使用独立的纯文本摘要,原段落及其行级格式完整保留在正文中;没有可用文字时保留空标题。标题只在转换时生成,之后独立编辑。转换后默认选择第一页。++页签转列表时,将非空页签标题作为列表项首段落,原正文接在后面;普通文字标题与原正文首段落的可见文字相同时,不重复插入。富格式标题还需行级内容完全一致才省略,避免丢失标题中的引用等信息。新插入的标题段落获得新 ID,保留标题行级格式。截断标题可能与原正文部分重复,以保留用户修改后的标题。有序列表从 1 开始,任务列表全部未完成;不保留原列表编号、勾选状态或页签布局、选中状态用于后续反向转换。+- 页签容器使用 `.tabs`,导航控件位于 `.tabs-header.protyle-action`,控件不持有内容块 ID。- 直属页签项使用 `.tab-item`,标题保存在项内唯一的 `.tab-item-title.callout-title`,正文位于 `.tab-item-content`。正文不复用 `.callout-content`,避免提示块退出行为破坏页签父子关系。- 导航栏只是标题的展示,反向解析以页签项中的原始标题为唯一来源。嵌套查找必须限制到直属结构。