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 batch converting heading levels from the outline https://github.com/siyuan-note/siyuan/issues/19138
Daniel90df35c36966
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 208092a5f9..a0be9da291 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,11 @@{+ "headingBatch": "تحويل مستويات العناوين دفعة واحدة",+ "headingBatchSource": "المستوى الأصلي",+ "headingBatchTarget": "المستوى المستهدف",+ "headingBatchTip": "تحويل المستوى المحدد فقط مع إبقاء مستويات العناوين الأخرى دون تغيير",+ "headingBatchConvert": "تحويل العناوين ({count})",+ "headingBatchScope": "المستند الحالي: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "جميع سجلات التغييرات","changelog": "سجل التغييرات","checkBlockRef": "التحقق من مراجع الكتل قبل الحذف أو القص",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex a4ba17a00c..3f029d69c2 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,11 @@{+ "headingBatch": "Überschriftenebenen gesammelt umwandeln",+ "headingBatchSource": "Ausgangsebene",+ "headingBatchTarget": "Zielebene",+ "headingBatchTip": "Nur die angegebene Ebene umwandeln; andere Überschriftenebenen bleiben unverändert",+ "headingBatchConvert": "{count} Überschriften umwandeln",+ "headingBatchScope": "Aktuelles Dokument: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Alle Änderungsprotokolle","changelog": "Änderungsprotokoll","checkBlockRef": "Blockreferenzen vor dem Löschen oder Ausschneiden prüfen",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 0bae90cf55..cca23ddc1e 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,11 @@{+ "headingBatch": "Batch convert heading levels",+ "headingBatchSource": "Source level",+ "headingBatchTarget": "Target level",+ "headingBatchTip": "Only convert the specified level; leave other heading levels unchanged",+ "headingBatchConvert": "Convert {count} headings",+ "headingBatchScope": "Current document: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "All changelogs","changelog": "Changelog","checkBlockRef": "Check block references before deleting or cutting",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex f89a1397e0..67e5cf539d 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,11 @@{+ "headingBatch": "Convertir niveles de encabezado en lote",+ "headingBatchSource": "Nivel original",+ "headingBatchTarget": "Nivel de destino",+ "headingBatchTip": "Convertir solo el nivel indicado; los demás niveles de encabezado no cambian",+ "headingBatchConvert": "Convertir {count} encabezados",+ "headingBatchScope": "Documento actual: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Todos los registros de cambios","changelog": "Registro de cambios","checkBlockRef": "Comprobar referencias de bloques antes de eliminar o cortar",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex a71a62f239..56014e4a7e 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,11 @@{+ "headingBatch": "Convertir les niveaux de titre par lot",+ "headingBatchSource": "Niveau d’origine",+ "headingBatchTarget": "Niveau cible",+ "headingBatchTip": "Convertir uniquement le niveau indiqué ; les autres niveaux de titre restent inchangés",+ "headingBatchConvert": "Convertir {count} titres",+ "headingBatchScope": "Document actuel : {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Tous les journaux des modifications","changelog": "Journal des modifications","checkBlockRef": "Vérifier les références de blocs avant de supprimer ou couper",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex a2bd4629eb..340dd3a07e 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,11 @@{+ "headingBatch": "המרת רמות כותרת באצווה",+ "headingBatchSource": "רמת המקור",+ "headingBatchTarget": "רמת היעד",+ "headingBatchTip": "המרת הרמה שנבחרה בלבד, ללא שינוי ברמות הכותרת האחרות",+ "headingBatchConvert": "המרת {count} כותרות",+ "headingBatchScope": "המסמך הנוכחי: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "כל יומני השינויים","changelog": "יומן שינויים","checkBlockRef": "בדיקת הפניות לבלוקים לפני מחיקה או גזירה",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 6bd855c30f..bcc1e3882b 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,11 @@{+ "headingBatch": "शीर्षक स्तरों को एक साथ बदलें",+ "headingBatchSource": "मूल स्तर",+ "headingBatchTarget": "लक्षित स्तर",+ "headingBatchTip": "केवल चुने गए स्तर को बदलें, अन्य शीर्षक स्तर अपरिवर्तित रहेंगे",+ "headingBatchConvert": "{count} शीर्षक बदलें",+ "headingBatchScope": "वर्तमान दस्तावेज़: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "सभी बदलाव सूचियाँ","changelog": "बदलाव सूची","checkBlockRef": "हटाने या काटने से पहले ब्लॉक संदर्भों की जाँच करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex ab42ff2586..19da86b7fa 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,11 @@{+ "headingBatch": "Konversi tingkat judul secara massal",+ "headingBatchSource": "Tingkat asal",+ "headingBatchTarget": "Tingkat tujuan",+ "headingBatchTip": "Hanya konversi tingkat yang ditentukan; tingkat judul lainnya tidak berubah",+ "headingBatchConvert": "Konversi {count} judul",+ "headingBatchScope": "Dokumen saat ini: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Semua catatan perubahan","changelog": "Catatan perubahan","checkBlockRef": "Periksa referensi blok sebelum menghapus atau memotong",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 9f9bd76414..bd210d6e71 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,11 @@{+ "headingBatch": "Converti i livelli dei titoli in blocco",+ "headingBatchSource": "Livello originale",+ "headingBatchTarget": "Livello di destinazione",+ "headingBatchTip": "Converti solo il livello specificato; gli altri livelli dei titoli restano invariati",+ "headingBatchConvert": "Converti {count} titoli",+ "headingBatchScope": "Documento corrente: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Tutti i registri delle modifiche","changelog": "Registro delle modifiche","checkBlockRef": "Controlla i riferimenti ai blocchi prima di eliminare o tagliare",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex dd0869f460..1118f391db 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,11 @@{+ "headingBatch": "見出しレベルを一括変換",+ "headingBatchSource": "元のレベル",+ "headingBatchTarget": "変換先のレベル",+ "headingBatchTip": "指定したレベルのみ変換し、他の見出しレベルは変更しません",+ "headingBatchConvert": "{count} 件の見出しを変換",+ "headingBatchScope": "現在のドキュメント:{title}",+ "headingBatchOption": "{heading}({count} 件)","allChangelogs": "すべての更新履歴","changelog": "更新履歴","checkBlockRef": "削除または切り取り前にブロック参照を確認",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 4190fe167d..26a5cda4b1 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,11 @@{+ "headingBatch": "제목 수준 일괄 변환",+ "headingBatchSource": "원본 수준",+ "headingBatchTarget": "대상 수준",+ "headingBatchTip": "지정한 수준만 변환하며 다른 제목 수준은 변경하지 않습니다",+ "headingBatchConvert": "제목 {count}개 변환",+ "headingBatchScope": "현재 문서: {title}",+ "headingBatchOption": "{heading} ({count}개)","allChangelogs": "모든 변경 로그","changelog": "변경 로그","checkBlockRef": "삭제하거나 잘라내기 전에 블록 참조 확인",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 7a043b18de..c64c51fff2 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,11 @@{+ "headingBatch": "Kopniveaus in één keer omzetten",+ "headingBatchSource": "Oorspronkelijk niveau",+ "headingBatchTarget": "Doelniveau",+ "headingBatchTip": "Alleen het opgegeven niveau omzetten; andere kopniveaus blijven ongewijzigd",+ "headingBatchConvert": "{count} koppen omzetten",+ "headingBatchScope": "Huidig document: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Alle wijzigingslogboeken","changelog": "Wijzigingslogboek","checkBlockRef": "Blokverwijzingen controleren vóór verwijderen of knippen",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 0ceee6b20e..5f66382d15 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,11 @@{+ "headingBatch": "Zbiorcza zmiana poziomów nagłówków",+ "headingBatchSource": "Poziom źródłowy",+ "headingBatchTarget": "Poziom docelowy",+ "headingBatchTip": "Zmień tylko wskazany poziom; pozostałe poziomy nagłówków pozostaną bez zmian",+ "headingBatchConvert": "Zmień nagłówki ({count})",+ "headingBatchScope": "Bieżący dokument: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Wszystkie dzienniki zmian","changelog": "Dziennik zmian","checkBlockRef": "Sprawdzaj odwołania do bloków przed usunięciem lub wycięciem",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 0af8675d26..c9507ced4f 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,11 @@{+ "headingBatch": "Converter níveis de título em lote",+ "headingBatchSource": "Nível original",+ "headingBatchTarget": "Nível de destino",+ "headingBatchTip": "Converter apenas o nível especificado; os outros níveis de título permanecem inalterados",+ "headingBatchConvert": "Converter {count} títulos",+ "headingBatchScope": "Documento atual: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Todos os registros de alterações","changelog": "Registro de alterações","checkBlockRef": "Verificar referências de blocos antes de excluir ou recortar",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex ec14b22547..bfb4f48065 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,11 @@{+ "headingBatch": "Массовое изменение уровней заголовков",+ "headingBatchSource": "Исходный уровень",+ "headingBatchTarget": "Целевой уровень",+ "headingBatchTip": "Изменить только указанный уровень; остальные уровни заголовков останутся без изменений",+ "headingBatchConvert": "Изменить заголовки ({count})",+ "headingBatchScope": "Текущий документ: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Все журналы изменений","changelog": "Журнал изменений","checkBlockRef": "Проверять ссылки на блоки перед удалением или вырезанием",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 8aedd9ced6..2ac2ea4cfb 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,11 @@{+ "headingBatch": "Hromadná zmena úrovní nadpisov",+ "headingBatchSource": "Pôvodná úroveň",+ "headingBatchTarget": "Cieľová úroveň",+ "headingBatchTip": "Zmeniť iba zadanú úroveň; ostatné úrovne nadpisov zostanú nezmenené",+ "headingBatchConvert": "Zmeniť nadpisy ({count})",+ "headingBatchScope": "Aktuálny dokument: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Všetky denníky zmien","changelog": "Denník zmien","checkBlockRef": "Kontrolovať odkazy na bloky pred odstránením alebo vystrihnutím",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex a1be2ce3aa..089ff89503 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,11 @@{+ "headingBatch": "แปลงระดับหัวเรื่องพร้อมกัน",+ "headingBatchSource": "ระดับเดิม",+ "headingBatchTarget": "ระดับเป้าหมาย",+ "headingBatchTip": "แปลงเฉพาะระดับที่ระบุ โดยไม่เปลี่ยนระดับหัวเรื่องอื่น",+ "headingBatchConvert": "แปลงหัวเรื่อง {count} รายการ",+ "headingBatchScope": "เอกสารปัจจุบัน: {title}",+ "headingBatchOption": "{heading} ({count} รายการ)","allChangelogs": "บันทึกการเปลี่ยนแปลงทั้งหมด","changelog": "บันทึกการเปลี่ยนแปลง","checkBlockRef": "ตรวจสอบการอ้างอิงบล็อกก่อนลบหรือตัด",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 9028882084..f1c80b6f16 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,11 @@{+ "headingBatch": "Başlık düzeylerini toplu dönüştür",+ "headingBatchSource": "Kaynak düzey",+ "headingBatchTarget": "Hedef düzey",+ "headingBatchTip": "Yalnızca belirtilen düzeyi dönüştür; diğer başlık düzeyleri değişmez",+ "headingBatchConvert": "{count} başlığı dönüştür",+ "headingBatchScope": "Geçerli belge: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Tüm değişiklik günlükleri","changelog": "Değişiklik günlüğü","checkBlockRef": "Silmeden veya kesmeden önce blok başvurularını denetle",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 5ac2433cb6..4e1d270c0e 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,11 @@{+ "headingBatch": "Масова зміна рівнів заголовків",+ "headingBatchSource": "Початковий рівень",+ "headingBatchTarget": "Цільовий рівень",+ "headingBatchTip": "Змінити лише вказаний рівень; інші рівні заголовків залишаться без змін",+ "headingBatchConvert": "Змінити заголовки ({count})",+ "headingBatchScope": "Поточний документ: {title}",+ "headingBatchOption": "{heading} ({count})","allChangelogs": "Усі журнали змін","changelog": "Журнал змін","checkBlockRef": "Перевіряти посилання на блоки перед видаленням або вирізанням",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 4be7782ea6..ff7daffdca 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,11 @@{+ "headingBatch": "批量转换标题级别",+ "headingBatchSource": "原级别",+ "headingBatchTarget": "目标级别",+ "headingBatchTip": "仅转换指定级别,其他标题级别保持不变",+ "headingBatchConvert": "转换 {count} 个标题",+ "headingBatchScope": "当前文档:{title}",+ "headingBatchOption": "{heading}({count} 个)","allChangelogs": "所有日志","changelog": "更新日志","checkBlockRef": "删除或剪切前检查块引用",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex ad29c0051b..3d5583001a 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,11 @@{+ "headingBatch": "批次轉換標題層級",+ "headingBatchSource": "原層級",+ "headingBatchTarget": "目標層級",+ "headingBatchTip": "僅轉換指定層級,其他標題層級保持不變",+ "headingBatchConvert": "轉換 {count} 個標題",+ "headingBatchScope": "目前文件:{title}",+ "headingBatchOption": "{heading}({count} 個)","allChangelogs": "所有日誌","changelog": "更新日誌","checkBlockRef": "刪除或剪下前檢查區塊引用",diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex a148c49bd9..b2cc8b2924 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -219,6 +219,11 @@ body.mobile-keyboard--open {color: var(--b3-theme-on-surface);background: transparent;+ &[disabled] {+ opacity: .38;+ cursor: not-allowed;+ }+svg {width: 20px;height: 20px;diff --git a/app/src/layout/dock/Outline.ts b/app/src/layout/dock/Outline.tsindex a3da4d1cbb..a2ec1baeb8 100644--- a/app/src/layout/dock/Outline.ts+++ b/app/src/layout/dock/Outline.ts@@ -35,6 +35,7 @@ import {} from "../../protyle/util/headingNumberCore";import {applyHeadingLevelUpdates, getHeadingLevelUpdateOperations} from "../../protyle/util/headingTransform";import {syncDocTitleIAL} from "../../protyle/util/docTitleIAL";+import {canBatchConvertHeadings, showHeadingBatchDialog, updateHeadingBatchButton} from "../../protyle/util/headingBatch";export class Outline extends Model {public tree: Tree;@@ -91,6 +92,8 @@ export class Outline extends Model {<svg><use xlink:href="#iconContract"></use></svg></span><span class="${this.type === "local" ? "fn__none " : ""}fn__space"></span>+ <button data-type="headingBatch" disabled class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.headingBatch}"><svg><use xlink:href="#iconRefresh"></use></svg></button>+ <span class="fn__space"></span><span data-type="min" class="${this.type === "local" ? "fn__none " : ""}block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.min}${updateHotkeyAfterTip(window.siyuan.config.keymap.general.closeTab.custom)}"><svg><use xlink:href='#iconMin'></use></svg></span>@@ -261,6 +264,16 @@ export class Outline extends Model {if (target.classList.contains("block__icon")) {const type = target.getAttribute("data-type");switch (type) {+ case "headingBatch": {+ const protyle = getAllModels().editor.find(item =>+ item.editor.protyle.block.rootID === this.blockId)?.editor.protyle;+ if (canBatchConvertHeadings(protyle, this.blockId, this.isPreview)) {+ void showHeadingBatchDialog(protyle, () =>+ canBatchConvertHeadings(protyle, this.blockId, this.isPreview) && protyle.element.isConnected);+ }+ isFocus = false;+ break;+ }case "min":getDockByType("outline").toggleModel("outline", false, true);isFocus = false;@@ -694,6 +707,11 @@ export class Outline extends Model {this.notebookId = typeof notebookId === "undefined" ? "" : notebookId;}this.tree.updateData(data.data);+ const protyle = getAllModels().editor.find(item =>+ item.editor.protyle.block.rootID === this.blockId)?.editor.protyle;+ const rootID = this.blockId;+ updateHeadingBatchButton(this.headerElement.querySelector('[data-type="headingBatch"]'), protyle,+ !!data.data?.length, () => rootID === this.blockId && canBatchConvertHeadings(protyle, rootID, this.isPreview));if (this.isPreview) {this.tree.element.querySelectorAll(".popover__block").forEach(item => {diff --git a/app/src/mobile/dock/MobileOutline.ts b/app/src/mobile/dock/MobileOutline.tsindex 4db4d4d934..fd7cd478c8 100644--- a/app/src/mobile/dock/MobileOutline.ts+++ b/app/src/mobile/dock/MobileOutline.ts@@ -20,6 +20,7 @@ import {dragOverScroll, stopScrollAnimation} from "../../boot/globalEvent/dragovimport {escapeHtml} from "../../util/escape";import {getFileTreeIconHTML} from "../../emoji/fileTreeIcon";import {syncDocTitleIAL} from "../../protyle/util/docTitleIAL";+import {canBatchConvertHeadings, showHeadingBatchDialog, updateHeadingBatchButton} from "../../protyle/util/headingBatch";import {bindMousePointerTouchBridge, isMousePointerTouchEvent} from "../util/mousePointerTouchBridge";import {operationsMayChangeOutline,@@ -71,10 +72,18 @@ export class MobileOutline extends Model {<svg data-type="expandLevel" class="toolbar__icon"><use xlink:href="#iconList"></use></svg><svg data-type="expand" class="toolbar__icon"><use xlink:href="#iconExpand"></use></svg><svg data-type="collapse" class="toolbar__icon"><use xlink:href="#iconContract"></use></svg>+ <button data-type="headingBatch" disabled class="toolbar__button" aria-label="${window.siyuan.languages.headingBatch}"><svg><use xlink:href="#iconRefresh"></use></svg></button></div><div class="b3-list-item fn__none" data-type="doc-title"></div><div class="fn__flex-1" style="padding: 3px 0 8px"></div>`;const inputElement = this.element.querySelector("input.b3-text-field.search__label") as HTMLInputElement;+ this.element.querySelector('[data-type="headingBatch"]').addEventListener("click", () => {+ const protyle = window.siyuan.mobile.editor?.protyle;+ if (canBatchConvertHeadings(protyle, this.blockId, this.isPreview)) {+ void showHeadingBatchDialog(protyle, () => window.siyuan.mobile.editor?.protyle === protyle &&+ canBatchConvertHeadings(protyle, this.blockId, this.isPreview));+ }+ });inputElement.addEventListener("blur", () => {inputElement.classList.add("fn__none");const filterIconElement = inputElement.nextElementSibling as HTMLElement; // search 图标@@ -567,6 +576,11 @@ export class MobileOutline extends Model {}const scrollTop = this.tree.element.scrollTop;this.tree.updateData(data.data);+ const protyle = window.siyuan.mobile.editor?.protyle;+ const rootID = this.blockId;+ updateHeadingBatchButton(this.element.querySelector('[data-type="headingBatch"]'), protyle,+ !!data.data?.length, () => rootID === this.blockId && window.siyuan.mobile.editor?.protyle === protyle &&+ canBatchConvertHeadings(protyle, rootID, this.isPreview));if (this.isPreview) {this.tree.element.querySelectorAll(".popover__block").forEach(item => {diff --git a/app/src/protyle/util/headingBatch.ts b/app/src/protyle/util/headingBatch.tsnew file mode 100644index 0000000000..28fae465c8--- /dev/null+++ b/app/src/protyle/util/headingBatch.ts@@ -0,0 +1,156 @@+import {Dialog} from "../../dialog";+import {fetchPost} from "../../util/fetch";+import {escapeHtml} from "../../util/escape";+import {isMobile} from "../../util/functions";+import {transaction} from "../wysiwyg/transaction";+import {reloadProtyle} from "./reload";+import {waitForPendingTransactions} from "./transactionQueue";++export const canBatchConvertHeadings = (protyle: IProtyle, rootID: string, preview: boolean) => {+ return !!rootID && !!protyle && protyle.block.rootID === rootID && !preview && !protyle.disabled &&+ !protyle.lite && !window.siyuan.config.readonly && !window.siyuan.isPublish;+};++export const updateHeadingBatchButton = (button: HTMLButtonElement, protyle: IProtyle,+ hasHeadings: boolean, isCurrent: () => boolean) => {+ button.disabled = !isCurrent();+ if (button.disabled || hasHeadings) {+ return;+ }+ button.disabled = true;+ // 大纲不展示引述块等容器内的标题,空大纲仍需按完整文档判断。+ fetchPost("/api/block/getDocHeadingLevelTransaction", {+ id: protyle.block.rootID,+ notebook: protyle.notebookId,+ }, response => {+ if (button.isConnected && isCurrent()) {+ button.disabled = !response.data?.counts?.some((count: number) => count > 0);+ }+ });+};++export const showHeadingBatchDialog = async (protyle: IProtyle, isCurrent: () => boolean) => {+ const rootID = protyle.block.rootID;+ const available = () => isCurrent() && canBatchConvertHeadings(protyle, rootID, false);+ if (!available()) {+ return;+ }+ await protyle.wysiwyg.flushPendingInput();+ await waitForPendingTransactions(protyle);+ if (!available()) {+ return;+ }+ fetchPost("/api/block/getDocHeadingLevelTransaction", {+ id: rootID,+ notebook: protyle.notebookId,+ }, response => {+ if (!available() || !response.data) {+ return;+ }+ const languages = window.siyuan.languages;+ let counts: number[] = response.data.counts;+ let closed = false;+ const dialog = new Dialog({+ title: languages.headingBatch,+ width: isMobile() ? "92vw" : "420px",+ content: `<div class="b3-dialog__content">+ <div class="ft__on-surface">${escapeHtml(languages.headingBatchScope.replace("{title}", response.data.title))}</div>+ <div class="fn__hr--b"></div>+ <label>${languages.headingBatchSource}<div class="fn__hr"></div><select class="b3-select fn__block" data-type="source"></select></label>+ <div class="fn__hr--b"></div>+ <label>${languages.headingBatchTarget}<div class="fn__hr"></div><select class="b3-select fn__block" data-type="target"></select></label>+ <div class="fn__hr--b"></div>+ <div class="ft__on-surface">${languages.headingBatchTip}</div>+</div>+<div class="b3-dialog__action">+ <button class="b3-button b3-button--cancel">${languages.cancel}</button><div class="fn__space"></div>+ <button class="b3-button b3-button--text" data-type="convert"></button>+</div>`,+ destroyCallback() {+ closed = true;+ }+ });+ const source = dialog.element.querySelector('[data-type="source"]') as HTMLSelectElement;+ const target = dialog.element.querySelector('[data-type="target"]') as HTMLSelectElement;+ const convert = dialog.element.querySelector('[data-type="convert"]') as HTMLButtonElement;+ const update = () => {+ Array.from(target.options).forEach(option => {+ option.disabled = option.value === source.value;+ });+ if (target.value === source.value) {+ target.value = String(Number(source.value) === 6 ? 5 : Number(source.value) + 1);+ }+ const count = counts[Number(source.value) - 1] || 0;+ convert.textContent = languages.headingBatchConvert.replace("{count}", String(count));+ convert.disabled = !count || !available();+ };+ const populate = () => {+ const previous = source.value;+ source.replaceChildren();+ counts.forEach((count, index) => {+ if (count) {+ source.add(new Option(languages.headingBatchOption+ .replace("{heading}", languages["heading" + (index + 1)])+ .replace("{count}", String(count)), String(index + 1)));+ }+ });+ if (counts[Number(previous) - 1]) {+ source.value = previous;+ }+ source.disabled = source.options.length === 0;+ target.disabled = source.disabled;+ update();+ };+ for (let level = 1; level <= 6; level++) {+ target.add(new Option(languages["heading" + level], String(level)));+ }+ populate();+ source.addEventListener("change", update);+ target.addEventListener("change", update);+ dialog.element.querySelector(".b3-button--cancel").addEventListener("click", () => dialog.destroy());+ convert.addEventListener("click", async () => {+ if (convert.disabled || !available()) {+ return;+ }+ convert.disabled = true;+ source.disabled = true;+ target.disabled = true;+ await protyle.wysiwyg.flushPendingInput();+ await waitForPendingTransactions(protyle);+ if (closed || !available()) {+ dialog.destroy();+ return;+ }+ void fetchPost("/api/block/getDocHeadingLevelTransaction", {+ id: rootID,+ notebook: protyle.notebookId,+ source: Number(source.value),+ target: Number(target.value),+ }, result => {+ if (closed || !available() || !result.data) {+ return;+ }+ const operations = result.data.transaction;+ if (!operations?.doOperations?.length) {+ counts = result.data.counts;+ populate();+ return;+ }+ transaction(protyle, operations.doOperations, operations.undoOperations, {+ callback() {+ if (protyle.block.rootID === rootID && protyle.element.isConnected) {+ reloadProtyle(protyle, false);+ }+ }+ });+ dialog.destroy();+ }).finally(() => {+ if (!closed) {+ source.disabled = source.options.length === 0;+ target.disabled = source.disabled;+ update();+ }+ });+ });+ });+};diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 19b5e8e764..7cf529b4de 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -1389,6 +1389,9 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd});});queueHeadingNumberRefresh(protyle, operations);+ if (operations.some(operation => operation.context?.headingBatchRootID === protyle.block.rootID)) {+ reloadProtyle(protyle, false);+ }};export const turnsIntoOneTransaction = async (options: {diff --git a/kernel/api/block.go b/kernel/api/block.goindex af2e86567f..17b47e9570 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -458,6 +458,31 @@ func getHeadingInsertTransaction(c *gin.Context) {ret.Data = transaction}+func getDocHeadingLevelTransaction(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)+ var arg struct {+ ID string `json:"id"`+ Notebook string `json:"notebook"`+ Source int `json:"source"`+ Target int `json:"target"`+ }+ if err := c.ShouldBindJSON(&arg); err != nil || arg.ID == "" ||+ arg.Source < 0 || arg.Source > 6 || arg.Target < 0 || arg.Target > 6 ||+ (arg.Source == 0) != (arg.Target == 0) {+ ret.Code = -1+ ret.Msg = "invalid heading conversion parameters"+ return+ }+ counts, title, transaction, err := model.GetDocHeadingLevelTransaction(arg.ID, arg.Notebook, arg.Source, arg.Target)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ ret.Data = map[string]any{"counts": counts, "title": title, "transaction": transaction}+}+func getHeadingLevelTransaction(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/router.go b/kernel/api/router.goindex ed25c65c7d..dcd7333478 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -299,6 +299,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/block/unfoldBlock", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, unfoldBlock)ginServer.Handle("POST", "/api/block/setBlockReminder", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setBlockReminder)ginServer.Handle("POST", "/api/block/getHeadingLevelTransaction", model.CheckAuth, model.CheckAdminRole, getHeadingLevelTransaction)+ ginServer.Handle("POST", "/api/block/getDocHeadingLevelTransaction", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getDocHeadingLevelTransaction)ginServer.Handle("POST", "/api/block/getHeadingFoldTransaction", model.CheckAuth, model.CheckAdminRole, getHeadingFoldTransaction)ginServer.Handle("POST", "/api/block/getHeadingDeleteTransaction", model.CheckAuth, model.CheckAdminRole, getHeadingDeleteTransaction)ginServer.Handle("POST", "/api/block/getHeadingInsertTransaction", model.CheckAuth, model.CheckAdminRole, getHeadingInsertTransaction)diff --git a/kernel/model/heading_batch.go b/kernel/model/heading_batch.gonew file mode 100644index 0000000000..fa9ae2131d--- /dev/null+++ b/kernel/model/heading_batch.go@@ -0,0 +1,50 @@+package model++import (+ "github.com/88250/lute/ast"+)++// GetDocHeadingLevelTransaction 按完整文档中的原始标题级别收集目标,不联动子标题。+func GetDocHeadingLevelTransaction(id, notebook string, source, target int) (counts [6]int, title string, transaction *Transaction, err error) {+ FlushTxQueue()+ tree, err := LoadTreeByBlockIDInExactBox(id, notebook)+ if err != nil {+ return+ }+ if tree.Root.ID != id {+ err = ErrTreeNotFound+ return+ }+ title = tree.Root.IALAttr("title")+ headings, counts := collectDocHeadingLevelNodes(tree.Root, source)+ if source < 1 || source > 6 || target < 1 || target > 6 || source == target || len(headings) == 0 {+ return counts, title, nil, nil+ }+ fillBlockRefCount(headings, tree.Box)+ transaction = buildDocHeadingLevelTransaction(headings, target-source, id)+ return+}++func collectDocHeadingLevelNodes(root *ast.Node, source int) (headings []*ast.Node, counts [6]int) {+ ast.Walk(root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && node.Type == ast.NodeHeading && node.HeadingLevel >= 1 && node.HeadingLevel <= 6 {+ counts[node.HeadingLevel-1]+++ if node.HeadingLevel == source {+ headings = append(headings, node)+ }+ }+ return ast.WalkContinue+ })+ return+}++func buildDocHeadingLevelTransaction(headings []*ast.Node, diff int, rootID string) *Transaction {+ transaction := buildHeadingLevelTransaction(headings, nil, diff)+ for _, operations := range [][]*Operation{transaction.DoOperations, transaction.UndoOperations} {+ for _, operation := range operations {+ // 完整文档转换保留折叠属性,界面在事务完成后按新层级重新加载。+ operation.Context = map[string]any{"headingBatchRootID": rootID}+ }+ }+ return transaction+}diff --git a/kernel/model/heading_level_test.go b/kernel/model/heading_level_test.goindex 55154fe061..586b164896 100644--- a/kernel/model/heading_level_test.go+++ b/kernel/model/heading_level_test.go@@ -148,6 +148,47 @@ func newHeadingLevelTestNode(id string, level int) *ast.Node {return heading}+func TestDocHeadingLevelConversionMatchesOriginalLevelAcrossContainers(t *testing.T) {+ root := &ast.Node{Type: ast.NodeDocument, ID: "document"}+ first := newHeadingLevelTestNode("first", 3)+ child := newHeadingLevelTestNode("child", 4)+ nested := newHeadingLevelTestNode("nested", 3)+ quote := &ast.Node{Type: ast.NodeBlockquote}+ root.AppendChild(first)+ root.AppendChild(child)+ root.AppendChild(quote)+ quote.AppendChild(nested)+ first.SetIALAttr("custom-test", "preserved")+ treenode.SetSelfFolded(first, true)++ headings, counts := collectDocHeadingLevelNodes(root, 3)+ assertHeadingLevelNodeIDs(t, headings, first.ID, nested.ID)+ if counts != [6]int{0, 0, 2, 1, 0, 0} {+ t.Fatalf("unexpected heading counts: %v", counts)+ }+ tx := buildDocHeadingLevelTransaction(headings, 1, root.ID)+ if len(tx.DoOperations) != 2 || len(tx.UndoOperations) != 2 || child.HeadingLevel != 4 {+ t.Fatal("conversion must update only matching headings")+ }+ if !treenode.IsSelfFolded(first) || first.IALAttr("custom-test") != "preserved" || nested.Parent != quote {+ t.Fatal("conversion must preserve folds, attributes and containers")+ }+ for i, id := range []string{first.ID, nested.ID} {+ for _, operations := range [][]*Operation{tx.DoOperations, tx.UndoOperations} {+ if operations[i].ID != id || operations[i].Action != "update" || operations[i].Context["headingBatchRootID"] != root.ID {+ t.Fatal("conversion and undo must preserve block identity and document context")+ }+ }+ if !strings.Contains(tx.DoOperations[i].Data.(string), `data-subtype="h4"`) ||+ !strings.Contains(tx.UndoOperations[i].Data.(string), `data-subtype="h3"`) {+ t.Fatal("undo must restore the original heading level")+ }+ }+ if headings, counts := collectDocHeadingLevelNodes(root, 6); len(headings) != 0 || counts[3] != 3 {+ t.Fatal("an absent source level must match no headings")+ }+}+func assertHeadingLevelNodeIDs(t *testing.T, nodes []*ast.Node, expected ...string) {t.Helper()if len(nodes) != len(expected) {diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 03e653dfb6..51cda9e338 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -1949,14 +1949,16 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {oldNode.InsertAfter(updatedNode)oldNode.Unlink()- if needUnfoldParentHeading {+ batchRootID, _ := operation.Context["headingBatchRootID"].(string)+ preserveHeadingFold := batchRootID == tree.Root.ID && oldNode.Type == ast.NodeHeading && updatedNode.Type == ast.NodeHeading+ if needUnfoldParentHeading && !preserveHeadingFold {newParentFoldedHeading := treenode.GetParentFoldedHeading(updatedNode)if nil == oldParentFoldedHeading || (nil != newParentFoldedHeading && oldParentFoldedHeading.ID != newParentFoldedHeading.ID) {unfoldHeading(newParentFoldedHeading, updatedNode)}}- if needInsertAfterParentHeading {+ if needInsertAfterParentHeading && !preserveHeadingFold {insertDom := dataif 2 == len(tx.DoOperations) && "foldHeading" == tx.DoOperations[1].Action {treenode.SetSelfFolded(updatedNode, true)diff --git a/kernel/model/transaction_fold_fts5_test.go b/kernel/model/transaction_fold_fts5_test.goindex 15d4f2047e..32de546312 100644--- a/kernel/model/transaction_fold_fts5_test.go+++ b/kernel/model/transaction_fold_fts5_test.go@@ -120,6 +120,69 @@ func TestCancelFoldedHeadingSuperBlockKeepsUndoBoundary(t *testing.T) {assertCancelledFoldedSuperBlock(t, fixture.sourceID, superBlockID, headingID, paragraphID, outsideID)}+func TestDocHeadingBatchPreservesFoldedParentOnUndoRedo(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ tree, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ for tree.Root.FirstChild != nil {+ tree.Root.FirstChild.Unlink()+ }+ parent := newHeadingLevelTestNode("20260905000001-parent0", 4)+ child := newHeadingLevelTestNode("20260905000002-child00", 3)+ other := newHeadingLevelTestNode("20260905000003-other00", 3)+ for _, node := range []*ast.Node{parent, child, other} {+ node.SetIALAttr("id", node.ID)+ node.SetIALAttr("custom-test", "preserved")+ tree.Root.AppendChild(node)+ }+ treenode.SetSelfFolded(parent, true)+ treenode.SetSelfFolded(child, true)+ treenode.SetSelfFolded(other, true)+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.IndexTreeQueue(tree)+ sql.FlushQueue()++ counts, _, tx, err := GetDocHeadingLevelTransaction(tree.Root.ID, tree.Box, 3, 5)+ if err != nil || counts[2] != 2 || tx == nil {+ t.Fatalf("prepare conversion: counts %v, error %v", counts, err)+ }+ for i, operations := range [][]*Operation{tx.DoOperations, tx.UndoOperations, tx.DoOperations} {+ if err = PerformTxSync(&Transaction{DoOperations: cloneOperations(operations)}); err != nil {+ t.Fatal(err)+ }+ actual, loadErr := LoadTreeByBlockID(tree.Root.ID)+ if loadErr != nil {+ t.Fatal(loadErr)+ }+ level := 5+ if i == 1 {+ level = 3+ }+ for _, id := range []string{child.ID, other.ID} {+ node := treenode.GetNodeInTree(actual, id)+ if node == nil || node.HeadingLevel != level || !treenode.IsSelfFolded(node) || node.IALAttr("custom-test") != "preserved" {+ t.Fatalf("step %d did not preserve heading %s", i, id)+ }+ }+ actualParent := treenode.GetNodeInTree(actual, parent.ID)+ if actualParent.HeadingLevel != 4 || !treenode.IsSelfFolded(actualParent) {+ t.Fatal("nonmatching parent headings must retain their level and fold state")+ }+ }+ for _, levels := range [][2]int{{5, 5}, {6, 1}, {0, 0}, {1, 7}} {+ _, _, noOp, err := GetDocHeadingLevelTransaction(tree.Root.ID, tree.Box, levels[0], levels[1])+ if err != nil || noOp != nil {+ t.Fatalf("expected no transaction for levels %v, got %v", levels, err)+ }+ }+}+func TestReplayFoldedHeadingMoveUsesOriginalChildren(t *testing.T) {const (anchorID = "20260819000000-anchor0"