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 dragging mind map relation paths and endpoints https://github.com/siyuan-note/siyuan/issues/19677
Vanessa8242dc6ea2a8
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex a3d69c04e3..cd1a812514 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "اسحب لتغيير عقدة البداية",+ "listMindmapRouteEnd": "اسحب لتغيير عقدة النهاية",+ "listMindmapRouteHandle": "اسحب لضبط المسار؛ انقر نقرًا مزدوجًا على مقبض السحب لاستعادة الحساب التلقائي",+ "listMindmapRouteFallback": "المسار المعدّل غير متاح في هذا التخطيط؛ يتم عرض المسار التلقائي","listView": "قائمة","databaseListView": "عرض قائمة قاعدة البيانات","copyRuntimeInfo": "نسخ معلومات التشغيل",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 0f9c079c9f..e5028a16ba 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Ziehen, um den Startknoten zu ändern",+ "listMindmapRouteEnd": "Ziehen, um den Zielknoten zu ändern",+ "listMindmapRouteHandle": "Ziehen, um den Verlauf anzupassen; Doppelklick auf den Ziehpunkt stellt die automatische Berechnung wieder her",+ "listMindmapRouteFallback": "Der angepasste Verlauf ist in diesem Layout nicht verfügbar; der automatische Verlauf wird angezeigt","listView": "Liste","databaseListView": "Datenbank-Listenansicht","copyRuntimeInfo": "Laufzeitinformationen kopieren",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 1c8a90e385..188a12eafc 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Drag to change the start node",+ "listMindmapRouteEnd": "Drag to change the end node",+ "listMindmapRouteHandle": "Drag to adjust the path; double-click the handle to reset",+ "listMindmapRouteFallback": "The adjusted path is unavailable in this layout; showing the automatic path","listView": "List","databaseListView": "Database list view","copyRuntimeInfo": "Copy runtime information",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 80246e62d4..6943242990 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Arrastra para cambiar el nodo inicial",+ "listMindmapRouteEnd": "Arrastra para cambiar el nodo final",+ "listMindmapRouteHandle": "Arrastra para ajustar el trazado; haz doble clic en el controlador para restablecerlo",+ "listMindmapRouteFallback": "El trazado ajustado no está disponible en esta disposición; se muestra el trazado automático","listView": "Lista","databaseListView": "Vista de lista de base de datos","copyRuntimeInfo": "Copiar información de ejecución",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex d2fe29d541..7b00781d22 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Faites glisser pour changer le nœud de départ",+ "listMindmapRouteEnd": "Faites glisser pour changer le nœud d’arrivée",+ "listMindmapRouteHandle": "Faites glisser pour ajuster le tracé ; double-cliquez sur la poignée pour rétablir le calcul automatique",+ "listMindmapRouteFallback": "Le tracé ajusté est indisponible dans cette disposition ; le tracé automatique est affiché","listView": "Liste","databaseListView": "Vue liste de base de données","copyRuntimeInfo": "Copier les informations d’exécution",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 62da906b66..30ca0a92f5 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "גררו כדי לשנות את צומת ההתחלה",+ "listMindmapRouteEnd": "גררו כדי לשנות את צומת הסיום",+ "listMindmapRouteHandle": "גררו כדי להתאים את הנתיב; לחצו פעמיים על ידית הגרירה כדי לשחזר חישוב אוטומטי",+ "listMindmapRouteFallback": "הנתיב המותאם אינו זמין בפריסה זו; מוצג הנתיב האוטומטי","listView": "רשימה","databaseListView": "תצוגת רשימה של מסד נתונים","copyRuntimeInfo": "העתקת מידע על סביבת הריצה",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 720839dcd9..79fdc3f13e 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "आरंभिक नोड बदलने के लिए खींचें",+ "listMindmapRouteEnd": "लक्ष्य नोड बदलने के लिए खींचें",+ "listMindmapRouteHandle": "पथ समायोजित करने के लिए खींचें; स्वचालित गणना बहाल करने के लिए ड्रैग हैंडल पर दो बार क्लिक करें",+ "listMindmapRouteFallback": "इस लेआउट में समायोजित पथ उपलब्ध नहीं है; स्वचालित पथ दिखाया जा रहा है","listView": "सूची","databaseListView": "डेटाबेस सूची दृश्य","copyRuntimeInfo": "रनटाइम की जानकारी कॉपी करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 4264c912c9..7a8b30e3b8 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Seret untuk mengganti simpul awal",+ "listMindmapRouteEnd": "Seret untuk mengganti simpul tujuan",+ "listMindmapRouteHandle": "Seret untuk menyesuaikan jalur; klik dua kali pada pegangan seret untuk mengembalikan perhitungan otomatis",+ "listMindmapRouteFallback": "Jalur yang disesuaikan tidak tersedia dalam tata letak ini; jalur otomatis ditampilkan","listView": "Daftar","databaseListView": "Tampilan daftar database","copyRuntimeInfo": "Salin informasi runtime",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex b29746a8e6..994bc41e25 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Trascina per cambiare il nodo iniziale",+ "listMindmapRouteEnd": "Trascina per cambiare il nodo di destinazione",+ "listMindmapRouteHandle": "Trascina per regolare il percorso; fai doppio clic sulla maniglia per ripristinare il calcolo automatico",+ "listMindmapRouteFallback": "Il percorso modificato non è disponibile in questa disposizione; viene mostrato il percorso automatico","listView": "Elenco","databaseListView": "Vista elenco del database","copyRuntimeInfo": "Copia informazioni di esecuzione",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 10b0879c68..fcadcfd40f 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "ドラッグして始点ノードを変更",+ "listMindmapRouteEnd": "ドラッグして終点ノードを変更",+ "listMindmapRouteHandle": "ドラッグして経路を調整、ハンドルをダブルクリックして自動計算に戻す",+ "listMindmapRouteFallback": "現在のレイアウトでは手動の経路を使用できないため、自動の経路を表示しています","listView": "リスト","databaseListView": "データベース リストビュー","copyRuntimeInfo": "実行環境情報をコピー",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex f6e09ba00c..51e51c6ffa 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "드래그하여 시작 노드 변경",+ "listMindmapRouteEnd": "드래그하여 대상 노드 변경",+ "listMindmapRouteHandle": "드래그하여 경로 조정, 드래그 핸들을 두 번 클릭하여 자동 계산으로 복원",+ "listMindmapRouteFallback": "현재 레이아웃에서는 수동 경로를 사용할 수 없어 자동 경로를 표시합니다","listView": "목록","databaseListView": "데이터베이스 목록 보기","copyRuntimeInfo": "실행 환경 정보 복사",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex bdb3160422..65d82900f5 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Sleep om het beginknooppunt te wijzigen",+ "listMindmapRouteEnd": "Sleep om het doelknooppunt te wijzigen",+ "listMindmapRouteHandle": "Sleep om het pad aan te passen; dubbelklik op de sleepgreep om de automatische berekening te herstellen",+ "listMindmapRouteFallback": "Het aangepaste pad is niet beschikbaar in deze indeling; het automatische pad wordt getoond","listView": "Lijst","databaseListView": "Lijstweergave van database","copyRuntimeInfo": "Runtime-informatie kopiëren",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 1e72ca11ba..a68ceb91a8 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Przeciągnij, aby zmienić węzeł początkowy",+ "listMindmapRouteEnd": "Przeciągnij, aby zmienić węzeł docelowy",+ "listMindmapRouteHandle": "Przeciągnij, aby dostosować przebieg; kliknij dwukrotnie uchwyt, aby przywrócić automatyczne wyznaczanie",+ "listMindmapRouteFallback": "Dostosowany przebieg jest niedostępny w tym układzie; wyświetlany jest przebieg automatyczny","listView": "Lista","databaseListView": "Widok listy bazy danych","copyRuntimeInfo": "Kopiuj informacje o środowisku uruchomieniowym",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 14cc613e1c..dd0a5bd74b 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Arraste para alterar o nó inicial",+ "listMindmapRouteEnd": "Arraste para alterar o nó de destino",+ "listMindmapRouteHandle": "Arraste para ajustar o trajeto; clique duas vezes na alça para restaurar o cálculo automático",+ "listMindmapRouteFallback": "O trajeto ajustado não está disponível neste leiaute; exibindo o trajeto automático","listView": "Lista","databaseListView": "Visualização de lista do banco de dados","copyRuntimeInfo": "Copiar informações de execução",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 4c9a938873..2a0884cb11 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Перетащите, чтобы изменить начальный узел",+ "listMindmapRouteEnd": "Перетащите, чтобы изменить конечный узел",+ "listMindmapRouteHandle": "Перетащите, чтобы изменить путь; дважды щёлкните маркер перетаскивания, чтобы восстановить автоматический расчёт",+ "listMindmapRouteFallback": "Изменённый путь недоступен в этой компоновке; показан автоматический путь","listView": "Список","databaseListView": "Представление базы данных в виде списка","copyRuntimeInfo": "Копировать информацию о среде выполнения",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 1a05757e03..d5881731f4 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Potiahnutím zmeníte počiatočný uzol",+ "listMindmapRouteEnd": "Potiahnutím zmeníte cieľový uzol",+ "listMindmapRouteHandle": "Potiahnutím upravíte trasu; dvojitým kliknutím na úchyt obnovíte automatický výpočet",+ "listMindmapRouteFallback": "Upravená trasa nie je v tomto rozložení dostupná; zobrazuje sa automatická trasa","listView": "Zoznam","databaseListView": "Zoznamové zobrazenie databázy","copyRuntimeInfo": "Kopírovať informácie o prostredí behu",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex f11fa1b31d..7e3bf5b23b 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Превуците да промените почетни чвор",+ "listMindmapRouteEnd": "Превуците да промените одредишни чвор",+ "listMindmapRouteHandle": "Превуците да подесите путању; двапут кликните на ручицу за превлачење да вратите аутоматско израчунавање",+ "listMindmapRouteFallback": "Подешена путања није доступна у овом распореду; приказује се аутоматска путања","listView": "Lista","databaseListView": "Prikaz baze - lista","copyRuntimeInfo": "Копирај информације о извршавању",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex dcb357e30f..89b50a9026 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "ลากเพื่อเปลี่ยนโหนดเริ่มต้น",+ "listMindmapRouteEnd": "ลากเพื่อเปลี่ยนโหนดปลายทาง",+ "listMindmapRouteHandle": "ลากเพื่อปรับเส้นทาง ดับเบิลคลิกที่จุดควบคุมเพื่อกลับไปคำนวณอัตโนมัติ",+ "listMindmapRouteFallback": "ไม่สามารถใช้เส้นทางที่ปรับไว้ในเค้าโครงนี้ได้ จึงแสดงเส้นทางอัตโนมัติชั่วคราว","listView": "รายการ","databaseListView": "มุมมองรายการฐานข้อมูล","copyRuntimeInfo": "คัดลอกข้อมูลสภาพแวดล้อมการทำงาน",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex e4b56f1552..dd1802216a 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Başlangıç düğümünü değiştirmek için sürükleyin",+ "listMindmapRouteEnd": "Hedef düğümü değiştirmek için sürükleyin",+ "listMindmapRouteHandle": "Yolu ayarlamak için sürükleyin; otomatik hesaplamayı geri yüklemek için sürükleme tutamacına çift tıklayın",+ "listMindmapRouteFallback": "Ayarlanan yol bu düzende kullanılamıyor; otomatik yol gösteriliyor","listView": "Liste","databaseListView": "Veritabanı liste görünümü","copyRuntimeInfo": "Çalışma zamanı bilgilerini kopyala",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex e0cc787390..6be782561e 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "Перетягніть, щоб змінити початковий вузол",+ "listMindmapRouteEnd": "Перетягніть, щоб змінити кінцевий вузол",+ "listMindmapRouteHandle": "Перетягніть, щоб змінити шлях; двічі клацніть маркер перетягування, щоб відновити автоматичний розрахунок",+ "listMindmapRouteFallback": "Змінений шлях недоступний у цьому компонуванні; показано автоматичний шлях","listView": "Список","databaseListView": "Подання бази даних у вигляді списку","copyRuntimeInfo": "Копіювати інформацію про середовище виконання",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 83c3e70a6c..90d9770cc4 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "拖动更换起始节点",+ "listMindmapRouteEnd": "拖动更换目标节点",+ "listMindmapRouteHandle": "拖动调整路径,双击拖拽手柄恢复自动计算",+ "listMindmapRouteFallback": "当前布局无法使用手动路径,暂时显示自动路径","listView": "列表","databaseListView": "数据库列表视图","copyRuntimeInfo": "复制运行信息",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 5618b02cd8..a7f6c69bd1 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,8 @@{+ "listMindmapRouteStart": "拖曳以變更起始節點",+ "listMindmapRouteEnd": "拖曳以變更目標節點",+ "listMindmapRouteHandle": "拖曳調整路徑,按兩下拖曳控制點恢復自動計算",+ "listMindmapRouteFallback": "目前配置無法使用手動路徑,暫時顯示自動路徑","listView": "列表","databaseListView": "資料庫列表檢視","copyRuntimeInfo": "複製執行資訊",diff --git a/app/src/assets/scss/protyle/_list-mindmap.scss b/app/src/assets/scss/protyle/_list-mindmap.scssindex 32d21c0080..07acf68f01 100644--- a/app/src/assets/scss/protyle/_list-mindmap.scss+++ b/app/src/assets/scss/protyle/_list-mindmap.scss@@ -594,6 +594,70 @@}}+ &__route-handle {+ position: absolute;+ z-index: 4;+ width: 20px;+ height: 20px;+ padding: 0;+ border: 0;+ transform: translate(-50%, -50%);+ background: transparent;+ touch-action: none;++ &::before {+ content: "";+ display: block;+ width: 8px;+ height: 8px;+ margin: auto;+ border: 1px solid var(--b3-theme-primary);+ border-radius: 2px;+ background: var(--b3-theme-background);+ box-sizing: border-box;+ }++ &:hover::before,+ &:focus-visible::before {+ background: var(--b3-theme-primary);+ }+ }++ &__viewport--route-invalid &__route-handle::before {+ border-color: var(--b3-theme-error);+ }++ &__route-endpoint {+ width: 12px;+ height: 12px;+ cursor: crosshair;++ &::before {+ width: 10px;+ height: 10px;+ border-radius: 50%;+ }++ &[data-endpoint="to"]::before {+ background: var(--b3-theme-primary);+ }+ }++ &__route-status {+ position: absolute;+ bottom: 40px;+ left: 50%;+ z-index: 6;+ transform: translateX(-50%);+ max-width: calc(100% - 32px);+ padding: 4px 8px;+ border-radius: var(--b3-border-radius);+ background: var(--b3-theme-background);+ color: var(--b3-theme-on-surface);+ font-size: 12px;+ pointer-events: none;+ }+&__inspector {@include protyle-toolbar-surface;position: absolute;@@ -679,6 +743,8 @@&__toolbar,&__inspector,&__tooltip,+ &__route-handle,+ &__route-status,&__add-bridge,&__fold,&__add-child {diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.tsindex c3dd34053c..c1868b2f09 100644--- a/app/src/protyle/render/listMindmap/index.ts+++ b/app/src/protyle/render/listMindmap/index.ts@@ -228,10 +228,24 @@ class ListMindmapController {metadata.relations.push({id: Lute.NewNodeID(), from, to, label: ""});}}),- onRelationChange: (id, patch) => this.metadata(metadata => {+ onRelationChange: (id, patch, expected) => this.metadata(metadata => {const relation = metadata.relations.find(item => item.id === id);- if (relation) {- Object.assign(relation, patch);+ if (!relation || (expected !== undefined && JSON.stringify(relation) !== expected)) {+ showMessage(window.siyuan.languages.listMindmapStale);+ return false;+ }+ if (patch.from !== undefined || patch.to !== undefined) {+ const from = patch.from ?? relation.from;+ const to = patch.to ?? relation.to;+ const nodes = readListMindmap(this.list).nodes;+ if (!nodes.has(from) || !nodes.has(to) || from === to || metadata.relations.some(item =>+ item.id !== id && item.from === from && item.to === to)) {+ return false;+ }+ }+ Object.assign(relation, patch);+ if ("route" in patch && patch.route === undefined) {+ delete relation.route;}}),onRelationDelete: id => this.metadata(metadata => {@@ -242,10 +256,12 @@ class ListMindmapController {this.snapshot = cleanListMindmapHTML(list.outerHTML);}- private metadata(change: (metadata: ListMindmapMetadata) => void) {+ private metadata(change: (metadata: ListMindmapMetadata) => void | false) {this.change(() => {const metadata = readListMindmap(this.list).metadata;- change(metadata);+ if (change(metadata) === false) {+ return false;+ }writeListMindmapMetadata(this.list, metadata);});}diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.tsindex 3765678a66..a4076590a6 100644--- a/app/src/protyle/render/listMindmap/model.test.ts+++ b/app/src/protyle/render/listMindmap/model.test.ts@@ -50,6 +50,21 @@ test("mindmap metadata rejects unknown formats and invalid values without replac}});+test("manual relation routes are optional, versioned and validated without dropping extension fields", () => {+ const route = {version: 1, points: [{x: -40, y: 25.5, t: .4, extension: "keep"}], extension: "keep"};+ const metadata = {version: 1, nodes: {}, relations: [{id: "r", from: "a", to: "b", label: "", route}]};+ const value = JSON.stringify(metadata);+ assert.equal(JSON.stringify(parseListMindmapMetadata(value)), value);+ for (const invalid of [null, {}, {...route, version: 2}, {...route, points: []},+ {...route, points: Array(65).fill(route.points[0])}, ...[+ {x: "0", y: 0, t: 0}, {x: 0, y: 0, t: -1}, {x: 0, y: 0, t: 1.1},+ {x: 1e7, y: 0, t: .5}, {x: 0, y: null, t: .5}, {x: 0, y: 0},+ ].map(point => ({version: 1, points: [point]}))]) {+ const data = JSON.stringify({...metadata, relations: [{...metadata.relations[0], route: invalid}]});+ assert.throws(() => parseListMindmapMetadata(data), /Invalid list mindmap metadata/);+ }+});+test("variable-size mindmap branches keep their order and never overlap", () => {const root = measured("root", 90, 55, [measured("a", 220, 200, [measured("a1", 150, 36), measured("a2", 90, 92)]),@@ -306,9 +321,10 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,check.ok(lute.BlockDOM2Md(cleaned).includes("New child"));// 复制后关系线与节点样式引用新块 ID,遇到任一损坏配置时不进行部分迁移。+ const copiedRoute = {version: 1, points: [{x: -35, y: 20, t: .5}], extension: "keep"};list.setAttribute("custom-sy-list-mindmap-data", JSON.stringify({version: 1, extension: "keep",nodes: {a: {bold: true}, b: {italic: true}, deleted: {bold: true}},- relations: [{id: "relation", from: "a", to: "b", label: "keep"},+ relations: [{id: "relation", from: "a", to: "b", label: "keep", route: copiedRoute},{id: "orphan", from: "a", to: "deleted", label: "remove"}]}));const copiedItems = list.querySelectorAll('[data-type="NodeListItem"]');copiedItems[0].setAttribute("data-node-id", "new-a");@@ -322,7 +338,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,api.remapListMindmapIDs(list, new Map([["a", "new-a"], ["b", "new-b"]]));const remapped = JSON.parse(list.getAttribute("custom-sy-list-mindmap-data"));check.deepEqual(remapped.nodes, {"new-a": {bold: true}, "new-b": {italic: true}});- check.deepEqual(remapped.relations, [{id: "relation", from: "new-a", to: "new-b", label: "keep"}]);+ check.deepEqual(remapped.relations, [{id: "relation", from: "new-a", to: "new-b", label: "keep", route: copiedRoute}]);check.equal(remapped.extension, "keep");check.equal(list.querySelector(".list-mindmap"), null);check.equal(list.hasAttribute("data-list-mindmap-rendered"), false);@@ -797,6 +813,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,relationLabel.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));check.deepEqual(relationChanges.pop(), ["relation-test", {label: "Renamed"}]);check.equal(host.querySelector(".list-mindmap__relation-editor"), null);+ check.equal(getComputedStyle(relationElement).visibility, "hidden", "finishing text editing returns to handle mode");host.querySelector<HTMLButtonElement>(".list-mindmap__relation").click();host.querySelector(".list-mindmap__relation").dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));const cancelledLabel = host.querySelector<HTMLInputElement>(".list-mindmap__relation-editor");@@ -815,6 +832,8 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,blank();check.equal(inspector.hidden, true);check.equal(host.querySelector(".list-mindmap__relation--selected"), null);+ await settle();+ check.equal(getComputedStyle(relationElement).visibility, "visible", "deselecting restores relation text");const savedRelations = model.metadata.relations;// 短连线文字撑开节点间距,文字仍位于所属连线上。@@ -847,6 +866,28 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,(point.y === previous.y && p.y === point.y && p.x >= Math.min(point.x, previous.x) &&p.x <= Math.max(point.x, previous.x));}), "the label stays on its own connection");+ const beforeHandleGap = siblingGap();+ const beforeHandleLabel = shortLabel.getBoundingClientRect();+ shortLabel.click();+ check.equal(getComputedStyle(shortLabel).visibility, "hidden", "selecting a relation hides its label before dragging");+ const midpointHandle = host.querySelector<HTMLElement>(".list-mindmap__route-handle:not(.list-mindmap__route-endpoint)");+ check.ok(midpointHandle, "text no longer suppresses the segment handle");+ const midpoint = centerPoint(midpointHandle);+ check.equal(document.elementFromPoint(midpoint.x, midpoint.y), midpointHandle, "the drag handle receives the pointer");+ view.refreshLayout();+ await settle();+ check.equal(siblingGap(), beforeHandleGap, "hidden text keeps its layout measurements");+ check.equal(shortLabel.getBoundingClientRect().width, beforeHandleLabel.width);+ view.setReadOnly(true);+ check.equal(getComputedStyle(shortLabel).visibility, "visible", "read-only rendering retains relation text");+ view.setReadOnly(false);+ check.equal(getComputedStyle(shortLabel).visibility, "hidden");+ window.dispatchEvent(new Event("beforeprint"));+ check.equal(getComputedStyle(shortLabel).visibility, "visible", "printing retains selected relation text");+ window.dispatchEvent(new Event("afterprint"));+ check.equal(getComputedStyle(shortLabel).visibility, "hidden");+ blank();+ check.equal(getComputedStyle(shortLabel).visibility, "visible");model.metadata.relations[0].label = "";view.update(model);await settle();@@ -872,15 +913,283 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,check.equal(view.selectedRelation, id, "overlapping reverse relations can be selected independently");viewport.dispatchEvent(new MouseEvent("dblclick", {clientX: x, clientY: y, bubbles: true}));const input = host.querySelector<HTMLInputElement>(".list-mindmap__relation-editor");- check.ok(input, "double-clicking either arrow edits that relation");- input.value = id;- input.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));- check.deepEqual(relationChanges[relationChanges.length - 1], [id, {label: id}]);+ check.ok(input, "double-clicking either arrow edits its relation label");+ input.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));pressDelete();check.equal(relationDeletions[relationDeletions.length - 1], id);}}+ // 短尾段仍绘制清晰的箭头,整体很短的双向直连则保留箭头间距。+ const arrowContext = host.querySelector("canvas").getContext("2d");+ const originalMoveTo = arrowContext.moveTo;+ const originalLineTo = arrowContext.lineTo;+ const originalFill = arrowContext.fill;+ let polygon: {x: number, y: number}[] = [];+ let arrows: {x: number, y: number}[][] = [];+ arrowContext.moveTo = (x, y) => { polygon = [{x, y}]; originalMoveTo.call(arrowContext, x, y); };+ arrowContext.lineTo = (x, y) => { polygon.push({x, y}); originalLineTo.call(arrowContext, x, y); };+ arrowContext.fill = () => { arrows.push(polygon); originalFill.call(arrowContext); };+ try {+ const straight = view.relationRoutes.get("forward");+ const start = straight[0];+ const end = straight[straight.length - 1];+ view.relationRoutes.set("forward", [start, {x: end.x + 100, y: start.y},+ {x: end.x + 100, y: end.y - 3}, {x: end.x, y: end.y - 3}, end]);+ view.selectedRelation = undefined;+ view.hoveredLine = undefined;+ for (const scale of [.5, 1, 2]) {+ view.scale = scale;+ arrows = [];+ view.draw();+ const width = (arrow: {x: number, y: number}[]) => Math.hypot(arrow[2].x - arrow[0].x, arrow[2].y - arrow[0].y) * scale;+ check.ok(width(arrows[0]) >= 6.9, "a three-unit tail retains a readable arrow at every zoom level");+ check.ok(width(arrows[1]) <= Math.hypot(end.x - start.x, end.y - start.y) * scale / 3 + .001,+ "short reverse connections retain space between arrowheads");+ }+ } finally {+ arrowContext.moveTo = originalMoveTo;+ arrowContext.lineTo = originalLineTo;+ arrowContext.fill = originalFill;+ }view.scale = 1;+ // 拖动短关系线只在松手时保存一次;取消、外部刷新和只读切换丢弃预览。+ model.metadata.relations = [{id: "drag-route", from: alpha, to: beta, label: ""}];+ view.update(model);+ await settle();+ view.selectedRelation = "drag-route";+ view.updateSelection();+ relationChanges.length = 0;+ const automaticRoute = JSON.stringify(view.relationRoutes.get("drag-route"));+ const screenNodes = () => [alpha, beta].map(id => {+ const bounds = nodeElement(id).getBoundingClientRect();+ return {x: bounds.x, y: bounds.y};+ });+ const dragHandle = async (offset: number) => {+ const handle = host.querySelector<HTMLElement>(".list-mindmap__route-handle:not(.list-mindmap__route-endpoint)");+ check.ok(handle, "short relations expose a drag handle");+ const point = centerPoint(handle);+ const horizontal = handle.style.cursor === "ns-resize";+ sendPointer(handle, "pointerdown", point.x, point.y);+ check.ok(view.pointer?.relation);+ sendPointer(viewport, "pointermove", point.x + (horizontal ? 0 : offset), point.y + (horizontal ? offset : 0));+ await settle();+ return {x: point.x + (horizontal ? 0 : offset), y: point.y + (horizontal ? offset : 0)};+ };+ const beforeDragNodes = screenNodes();+ const beforeDragScale = view.scale;+ const blockedEnd = await dragHandle(-35);+ check.equal(view.pointer.relation.valid, false, "a control inside another node's buttons is rejected");+ sendPointer(viewport, "pointerup", blockedEnd.x, blockedEnd.y);+ check.equal(relationChanges.length, 0, "an invalid preview never saves");+ let dragEnd = await dragHandle(110);+ check.equal(view.pointer.relation.valid, true, "dragging a short relation creates a valid path");+ check.notEqual(JSON.stringify(view.relationRoutes.get("drag-route")), automaticRoute);+ check.deepEqual(screenNodes(), beforeDragNodes);+ check.equal(relationChanges.length, 0, "previews do not create transactions");+ viewport.dispatchEvent(new WheelEvent("wheel", {deltaY: 100, ctrlKey: true, bubbles: true, cancelable: true}));+ check.equal(view.scale, beforeDragScale, "zoom stays fixed while dragging");+ sendPointer(viewport, "pointerup", dragEnd.x, dragEnd.y);+ check.equal(relationChanges.length, 1, "release saves exactly once");+ const savedRoute = (relationChanges[0] as any[])[1].route;+ check.equal((relationChanges[0] as any[])[2], JSON.stringify(model.metadata.relations[0]), "save guards against stale relations");+ check.ok(savedRoute.points.length);+ model.metadata.relations[0].route = savedRoute;+ view.update(model);+ await settle();+ check.deepEqual(screenNodes(), beforeDragNodes, "saving the path preserves the camera anchor");+ const savedGeometry = JSON.stringify(view.relationRoutes.get("drag-route"));+ const outwardPoints = view.relationRoutes.get("drag-route");+ const outwardColumn = JSON.parse(automaticRoute)[0].x + 110;+ const returningSegment = outwardPoints.findIndex((point: any, index: number) =>+ point.x === outwardColumn && outwardPoints[index + 1]?.x === outwardColumn);+ const returningHandle = view.routeHandles.get(`drag-route:${returningSegment}`);+ check.ok(returningHandle);+ const returningPoint = centerPoint(returningHandle);+ sendPointer(returningHandle, "pointerdown", returningPoint.x, returningPoint.y);+ sendPointer(viewport, "pointermove", returningPoint.x - 110 * view.scale, returningPoint.y);+ await settle();+ check.equal(view.pointer.relation.valid, true, "a saved outward path can be dragged back between its endpoints");+ check.equal(JSON.stringify(view.relationRoutes.get("drag-route")), automaticRoute);+ sendPointer(viewport, "pointerup", returningPoint.x - 110 * view.scale, returningPoint.y);+ check.equal(relationChanges.length, 2);+ model.metadata.relations[0].route = (relationChanges[1] as any[])[1].route;+ view.update(model);+ await settle();+ check.equal(JSON.stringify(view.relationRoutes.get("drag-route")), automaticRoute, "the returned route persists across refresh");+ model.metadata.relations[0].route = savedRoute;+ view.update(model);+ await settle();+ model.metadata.relations[0].route = {version: 1, points: [{x: 0, y: 0, t: 0}]};+ view.update(model);+ await settle();+ check.equal(view.fallbackRoutes.has("drag-route"), true);+ check.equal(host.querySelector<HTMLElement>(".list-mindmap__route-status").hidden, false);+ check.equal(model.metadata.relations[0].route.points.length, 1, "unavailable routes retain their saved controls");+ model.metadata.relations[0].route = savedRoute;+ view.update(model);+ await settle();+ check.equal(view.fallbackRoutes.has("drag-route"), false);+ check.equal(JSON.stringify(view.relationRoutes.get("drag-route")), savedGeometry);+ relationChanges.length = 0;+ await dragHandle(-15);+ host.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ check.equal(view.pointer, undefined);+ check.equal(JSON.stringify(view.relationRoutes.get("drag-route")), savedGeometry);+ check.equal(relationChanges.length, 0);+ dragEnd = await dragHandle(-15);+ viewport.dispatchEvent(new PointerEvent("pointercancel", {pointerId: 1, bubbles: true}));+ sendPointer(viewport, "pointerup", dragEnd.x, dragEnd.y);+ check.equal(relationChanges.length, 0, "pointer cancellation discards the preview");+ dragEnd = await dragHandle(-15);+ view.update(model);+ sendPointer(viewport, "pointerup", dragEnd.x, dragEnd.y);+ await settle();+ check.equal(relationChanges.length, 0, "remote refresh cancels a stale drag");+ dragEnd = await dragHandle(-15);+ view.setReadOnly(true);+ sendPointer(viewport, "pointerup", dragEnd.x, dragEnd.y);+ check.equal(relationChanges.length, 0);+ check.equal(host.querySelector(".list-mindmap__route-handle:not(.list-mindmap__route-endpoint)"), null, "read-only render has no drag handles");+ await settle();+ check.equal(JSON.stringify(view.relationRoutes.get("drag-route")), savedGeometry, "read-only rendering uses the saved path");+ view.setReadOnly(false);+ view.selectedRelation = "drag-route";+ view.updateSelection();+ await settle();+ const resetEnd = view.linePaths.find((line: any) => line.id === "drag-route").end;+ const resetBounds = viewport.getBoundingClientRect();+ viewport.dispatchEvent(new MouseEvent("dblclick", {clientX: resetBounds.left + view.offsetX + resetEnd.x * view.scale,+ clientY: resetBounds.top + view.offsetY + resetEnd.y * view.scale, bubbles: true}));+ const lineEditor = host.querySelector<HTMLInputElement>(".list-mindmap__relation-editor");+ check.ok(lineEditor, "double-clicking a manual path edits its text");+ check.equal(relationChanges.length, 0, "double-clicking a line does not reset its route");+ lineEditor.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ host.querySelector(".list-mindmap__route-handle:not(.list-mindmap__route-endpoint)").dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));+ check.deepEqual(relationChanges.map((change: any[]) => change.slice(0, 2)), [["drag-route", {route: undefined}]],+ "double-clicking the drag handle clears only its manual route");+ delete model.metadata.relations[0].route;+ view.update(model);+ await settle();+ check.equal(JSON.stringify(view.relationRoutes.get("drag-route")), automaticRoute);+ check.equal(host.querySelector(".list-mindmap__relation-editor"), null);+ // 线条本身也可拖动,手柄在不同缩放下保持相同的点击尺寸。+ relationChanges.length = 0;+ const directPoints = view.relationRoutes.get("drag-route");+ const directX = resetBounds.left + view.offsetX + (directPoints[0].x + directPoints[1].x) / 2 * view.scale;+ const directY = resetBounds.top + view.offsetY + (directPoints[0].y + directPoints[1].y) / 2 * view.scale;+ sendPointer(viewport, "pointerdown", directX, directY);+ sendPointer(viewport, "pointermove", directX + 110, directY);+ sendPointer(viewport, "pointerup", directX + 110, directY);+ check.equal(relationChanges.length, 1);+ for (const scale of [.5, 2]) {+ view.scale = scale;+ view.draw();+ const handle = host.querySelector<HTMLElement>(".list-mindmap__route-handle:not(.list-mindmap__route-endpoint)").getBoundingClientRect();+ check.equal(handle.width, 20);+ check.equal(handle.height, 20);+ }+ view.scale = 1;+ view.draw();+ HTMLElement.prototype.setPointerCapture = originalCapture;+ HTMLElement.prototype.hasPointerCapture = originalHasCapture;+ HTMLElement.prototype.releasePointerCapture = originalReleaseCapture;+ relationChanges.length = 0;+ const nativeHandle = centerPoint(host.querySelector<HTMLElement>(".list-mindmap__route-handle:not(.list-mindmap__route-endpoint)"));+ await nativeInput([+ {type: "mouseMove", ...nativeHandle},+ {type: "mouseDown", ...nativeHandle, button: "left", clickCount: 1},+ {type: "mouseMove", x: nativeHandle.x + 110, y: nativeHandle.y, button: "left"},+ {type: "mouseUp", x: nativeHandle.x + 110, y: nativeHandle.y, button: "left", clickCount: 1},+ ]);+ check.equal(relationChanges.length, 1, "native pointer capture saves a drag exactly once");+ model.metadata.relations[0].route = (relationChanges[0] as any[])[1].route;+ view.update(model);+ await settle();+ const nativeReset = centerPoint(host.querySelector<HTMLElement>(".list-mindmap__route-handle:not(.list-mindmap__route-endpoint)"));+ await nativeInput([+ {type: "mouseMove", ...nativeReset},+ {type: "mouseDown", ...nativeReset, button: "left", clickCount: 1},+ {type: "mouseUp", ...nativeReset, button: "left", clickCount: 1},+ {type: "mouseDown", ...nativeReset, button: "left", clickCount: 2},+ {type: "mouseUp", ...nativeReset, button: "left", clickCount: 2},+ ]);+ check.equal(relationChanges.length, 2, "native double click restores automatic routing despite pointer capture");+ check.deepEqual((relationChanges[1] as any[]).slice(0, 2), ["drag-route", {route: undefined}]);+ HTMLElement.prototype.setPointerCapture = () => undefined;+ HTMLElement.prototype.hasPointerCapture = () => false;+ HTMLElement.prototype.releasePointerCapture = () => undefined;+ // 首尾标识分别更换起点和终点,空白、自身、重复连接及取消操作均保留原数据。+ const endpointModel = api.readListMindmap(reset("* Start\n* End\n* Alternate\n"));+ const [startNode, endNode, alternateNode] = endpointModel.root.children;+ endpointModel.metadata.relations = [{id: "endpoint-test", from: startNode.id, to: endNode.id,+ label: "Keep label", color: "red", route: savedRoute}];+ view.update(endpointModel);+ await settle();+ view.selectedRelation = "endpoint-test";+ view.updateSelection();+ check.equal(host.querySelectorAll(".list-mindmap__route-endpoint").length, 2);+ const dragEndpoint = async (endpoint: string, targetId?: string) => {+ const handle = host.querySelector<HTMLElement>(`.list-mindmap__route-endpoint[data-endpoint="${endpoint}"]`);+ const point = centerPoint(handle);+ const target = targetId ? centerPoint(nodeElement(targetId)) : {x: point.x + 100, y: panelBounds.top + 10};+ sendPointer(handle, "pointerdown", point.x, point.y);+ sendPointer(viewport, "pointermove", target.x, target.y);+ await settle();+ check.equal(host.querySelectorAll(".list-mindmap__route-endpoint").length, 2, "both endpoints remain marked during a drag");+ return target;+ };+ for (const endpoint of ["from", "to"]) {+ relationChanges.length = 0;+ const target = await dragEndpoint(endpoint, alternateNode.id);+ check.equal(view.pointer.relation.valid, true);+ check.ok(nodeElement(alternateNode.id).classList.contains("list-mindmap__node--relation"));+ check.equal(relationChanges.length, 0);+ sendPointer(viewport, "pointerup", target.x, target.y);+ check.deepEqual((relationChanges[0] as any[]).slice(0, 2), ["endpoint-test", {[endpoint]: alternateNode.id, route: undefined}]);+ check.equal(relationChanges.length, 1);+ check.equal((relationChanges[0] as any[])[2], JSON.stringify(endpointModel.metadata.relations[0]));+ await settle();+ }+ relationChanges.length = 0;+ for (const targetId of [undefined, startNode.id, endpointModel.root.id]) {+ const target = await dragEndpoint("to", targetId);+ check.equal(view.pointer.relation.valid, false);+ sendPointer(viewport, "pointerup", target.x, target.y);+ check.equal(relationChanges.length, 0);+ await settle();+ }+ const cancelTarget = await dragEndpoint("to", alternateNode.id);+ host.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ sendPointer(viewport, "pointerup", cancelTarget.x, cancelTarget.y);+ check.equal(relationChanges.length, 0);+ await settle();+ HTMLElement.prototype.setPointerCapture = originalCapture;+ HTMLElement.prototype.hasPointerCapture = originalHasCapture;+ HTMLElement.prototype.releasePointerCapture = originalReleaseCapture;+ const nativeStart = centerPoint(host.querySelector<HTMLElement>('.list-mindmap__route-endpoint[data-endpoint="from"]'));+ const nativeTarget = centerPoint(nodeElement(alternateNode.id));+ await nativeInput([+ {type: "mouseMove", ...nativeStart},+ {type: "mouseDown", ...nativeStart, button: "left", clickCount: 1},+ {type: "mouseMove", ...nativeTarget, button: "left"},+ {type: "mouseUp", ...nativeTarget, button: "left", clickCount: 1},+ ]);+ check.equal(relationChanges.length, 1, "native endpoint capture reconnects the start node once");+ check.deepEqual((relationChanges[0] as any[]).slice(0, 2), ["endpoint-test", {from: alternateNode.id, route: undefined}]);+ relationChanges.length = 0;+ HTMLElement.prototype.setPointerCapture = () => undefined;+ HTMLElement.prototype.hasPointerCapture = () => false;+ HTMLElement.prototype.releasePointerCapture = () => undefined;+ endpointModel.metadata.relations.push({id: "existing", from: startNode.id, to: alternateNode.id, label: ""});+ view.update(endpointModel);+ await settle();+ const duplicateTarget = await dragEndpoint("to", alternateNode.id);+ check.equal(view.pointer.relation.valid, false);+ sendPointer(viewport, "pointerup", duplicateTarget.x, duplicateTarget.y);+ check.equal(relationChanges.length, 0);+ view.setReadOnly(true);+ check.equal(host.querySelectorAll(".list-mindmap__route-endpoint").length, 0);+ view.setReadOnly(false);model.metadata.relations = savedRelations;view.update(model);diff --git a/app/src/protyle/render/listMindmap/model.ts b/app/src/protyle/render/listMindmap/model.tsindex 3b3db1f91a..5d4da33ab1 100644--- a/app/src/protyle/render/listMindmap/model.ts+++ b/app/src/protyle/render/listMindmap/model.ts@@ -1,5 +1,6 @@import {Constants} from "../../../constants";import {getOrderedListMarkerUpdates} from "../../wysiwyg/listContext";+import type {MindmapManualRoute} from "./routing";export interface ListMindmapNodeStyle {textColor?: string;@@ -23,6 +24,7 @@ export interface ListMindmapRelation {color?: string;width?: number;dash?: boolean;+ route?: MindmapManualRoute;}export interface ListMindmapMetadata {@@ -114,6 +116,16 @@ export const parseListMindmapMetadata = (value: string | null): ListMindmapMetad("dash" in relation && typeof relation.dash !== "boolean")) {throw invalidMetadata();}+ if ("route" in relation) {+ const route = relation.route;+ if (!isRecord(route) || route.version !== 1 || !Array.isArray(route.points) ||+ !route.points.length || route.points.length > 64 || route.points.some(point =>+ !isRecord(point) || ["x", "y", "t"].some(key => typeof point[key] !== "number" ||+ !Number.isFinite(point[key]) || Math.abs(Number(point[key])) > 1000000) ||+ Number(point.t) < 0 || Number(point.t) > 1)) {+ throw invalidMetadata();+ }+ }relationIds.add(relation.id);}return data as unknown as ListMindmapMetadata;diff --git a/app/src/protyle/render/listMindmap/relation.test.ts b/app/src/protyle/render/listMindmap/relation.test.tsnew file mode 100644index 0000000000..0f5c2b867c--- /dev/null+++ b/app/src/protyle/render/listMindmap/relation.test.ts@@ -0,0 +1,84 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import test from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isClassDeclaration, isPropertyAssignment, ScriptTarget, transpileModule} from "typescript";++// 直接执行控制器中的保存入口,验证快照冲突不会进入文档事务。+const source = createSourceFile("index.ts", readFileSync("src/protyle/render/listMindmap/index.ts", "utf8"),+ ScriptTarget.ES2021, true);+const controller = source.statements.find(item => isClassDeclaration(item) && item.name?.text === "ListMindmapController");+assert.ok(controller && isClassDeclaration(controller));+let callback = "";+const visit = (node: import("typescript").Node) => {+ if (isPropertyAssignment(node) && node.name.getText(source) === "onRelationChange") {+ callback = node.initializer.getText(source);+ }+ node.forEachChild(visit);+};+visit(controller);+assert.ok(callback);+const methods = controller.members.filter(item => item.name && ["metadata", "change"].includes(item.name.getText(source)));+const compiled = transpileModule(`class Controller {+ ${methods.map(item => item.getText(source)).join("\n")}+ onRelationChange = ${callback};+}+globalThis.Controller = Controller;`, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;++test("manual route save and reset use one transaction and reject stale relation snapshots", async () => {+ let data = {version: 1, nodes: {}, relations: [{id: "r", from: "a", to: "b", label: "Keep", color: "red"}]};+ const original = JSON.stringify(data);+ const transactions: {before: string, after: string}[] = [];+ const messages: string[] = [];+ const list = {isConnected: true, get outerHTML() { return JSON.stringify(data); }};+ const context: any = {+ canEdit: () => true,+ readListMindmap: () => ({metadata: JSON.parse(JSON.stringify(data)), nodes: new Map(["a", "b", "c"].map(id => [id, {}]))}),+ writeListMindmapMetadata: (_list: unknown, next: typeof data) => data = next,+ cleanListMindmapHTML: (html: string) => html,+ updateTransaction: (_owner: unknown, _list: unknown, before: string) => transactions.push({before, after: list.outerHTML}),+ showMessage: (message: string) => messages.push(message),+ window: {siyuan: {languages: {listMindmapStale: "stale"}}}, console,+ };+ runInNewContext(compiled, context);+ const target = new context.Controller();+ Object.assign(target, {list, owner: {}, refresh: () => {}});+ const route = {version: 1, points: [{x: -40, y: 20, t: .5}]};+ const snapshot = JSON.stringify(data.relations[0]);+ target.onRelationChange("r", {route}, snapshot);+ assert.equal(transactions.length, 1);+ assert.equal(transactions[0].before, original);+ assert.deepEqual(JSON.parse(transactions[0].after).relations[0].route, route);+ const saved = JSON.stringify(data);+ target.onRelationChange("r", {route: undefined}, JSON.stringify(data.relations[0]));+ assert.equal(transactions.length, 2);+ assert.deepEqual(transactions[1], {before: saved, after: original});+ data = JSON.parse(saved);+ let finish: (value: boolean) => void;+ target.activeEditor = {finish: () => new Promise<boolean>(resolve => finish = resolve)};+ target.onRelationChange("r", {route: undefined}, JSON.stringify(data.relations[0]));+ data.relations[0].label = "Remote edit";+ finish(true);+ await new Promise(resolve => setImmediate(resolve));+ assert.equal(transactions.length, 2);+ assert.equal(messages.pop(), "stale");+ assert.equal(data.relations[0].label, "Remote edit");+ assert.deepEqual(JSON.parse(JSON.stringify(data)).relations[0].route, route);+ target.activeEditor = undefined;+ data.relations = [];+ target.onRelationChange("r", {route}, snapshot);+ assert.equal(transactions.length, 2, "a deleted relation cannot be recreated by a stale drag");+ data = JSON.parse(saved);+ target.onRelationChange("r", {from: "c", route: undefined}, JSON.stringify(data.relations[0]));+ assert.equal(transactions.length, 3);+ assert.equal(transactions[2].before, saved, "undo retains the previous endpoints and manual path");+ assert.deepEqual(JSON.parse(transactions[2].after).relations[0], {id: "r", from: "c", to: "b", label: "Keep", color: "red"});+ data = JSON.parse(saved);+ for (const from of ["missing", "b"]) {+ target.onRelationChange("r", {from}, JSON.stringify(data.relations[0]));+ assert.equal(transactions.length, 3, "missing endpoints and self-connections never enter a transaction");+ }+ data.relations.push({...data.relations[0], id: "existing", from: "c"});+ target.onRelationChange("r", {from: "c"}, JSON.stringify(data.relations[0]));+ assert.equal(transactions.length, 3, "duplicate connections are checked against the current source data");+});diff --git a/app/src/protyle/render/listMindmap/routing.test.ts b/app/src/protyle/render/listMindmap/routing.test.tsindex d676628c0a..02cd4a85cb 100644--- a/app/src/protyle/render/listMindmap/routing.test.ts+++ b/app/src/protyle/render/listMindmap/routing.test.ts@@ -1,6 +1,7 @@import * as assert from "node:assert/strict";import test from "node:test";-import {routeMindmapRelation, MindmapRouteBox, MindmapRoutePoint} from "./routing";+import {routeMindmapRelation, routeManualMindmapRelation, encodeMindmapRoute, moveMindmapRouteSegment, adjustMindmapRoute,+ MindmapRouteBox, MindmapRoutePoint} from "./routing";const validate = (route: MindmapRoutePoint[], nodes: MindmapRouteBox[]) => {assert.ok(route.length >= 2, "a route must exist");@@ -35,6 +36,88 @@ const validateDirection = (route: MindmapRoutePoint[], from: MindmapRouteBox, tooutward(route[route.length - 1], route[route.length - 2], to);};+test("dragging a straight relation preserves arrow direction and follows endpoint translation", () => {+ for (const vertical of [false, true]) {+ const nodes = [{x: 0, y: 0, width: 100, height: 40},+ {x: vertical ? 0 : 300, y: vertical ? 200 : 0, width: 100, height: 40}];+ const automatic = routeMindmapRelation(nodes[0], nodes[1], nodes);+ assert.equal(automatic.length, 2);+ const moved = moveMindmapRouteSegment(automatic, 0, -60);+ const saved = encodeMindmapRoute(moved, nodes[0], nodes[1]);+ const routed = routeManualMindmapRelation(nodes[0], nodes[1], nodes, saved);+ validate(routed, nodes);+ validateDirection(routed, nodes[0], nodes[1]);+ assert.notDeepEqual(routed, automatic);+ assert.ok(routed.some(point => vertical ? point.x === automatic[0].x - 60 : point.y === automatic[0].y - 60));+ const axis = vertical ? "x" : "y";+ const segment = routed.findIndex((point, index) => point[axis] === automatic[0][axis] - 60 &&+ routed[index + 1]?.[axis] === point[axis]);+ const returned = adjustMindmapRoute(routed, segment, 60, nodes[0], nodes[1], saved);+ assert.deepEqual(routeManualMindmapRelation(nodes[0], nodes[1], nodes, returned), automatic,+ "dragging either orientation back restores the straight path");+ const translated = nodes.map(node => ({...node, x: node.x + 57, y: node.y + 83}));+ const next = routeManualMindmapRelation(translated[0], translated[1], translated, saved);+ validate(next, translated);+ assert.equal(next.length, routed.length);+ next.forEach((point, index) => {+ assert.ok(Math.abs(point.x - routed[index].x - 57) < .001);+ assert.ok(Math.abs(point.y - routed[index].y - 83) < .001);+ });+ const resized = [nodes[0], {...nodes[1], x: nodes[1].x + 150, y: nodes[1].y + 120, width: 160}];+ const afterResize = routeManualMindmapRelation(resized[0], resized[1], resized, saved);+ validate(afterResize, resized);+ validateDirection(afterResize, resized[0], resized[1]);+ assert.deepEqual(routeMindmapRelation(nodes[0], nodes[1], nodes), automatic,+ "removing the manual route restores the automatic route");+ }+});++test("manual paths avoid obstacles and retain their configuration when a control is blocked", () => {+ const nodes = [{x: 0, y: 0, width: 100, height: 40}, {x: 600, y: 0, width: 100, height: 40}];+ const automatic = routeMindmapRelation(nodes[0], nodes[1], nodes);+ const moved = moveMindmapRouteSegment(automatic, 0, -80);+ const saved = encodeMindmapRoute(moved, nodes[0], nodes[1]);+ const snapshot = JSON.stringify(saved);+ const obstacle = {x: 335, y: -100, width: 30, height: 40};+ validate(routeManualMindmapRelation(nodes[0], nodes[1], [...nodes, obstacle], saved), [...nodes, obstacle]);+ const blocked = {...obstacle, x: moved[1].x - 10, y: moved[1].y - 10};+ assert.deepEqual(routeManualMindmapRelation(nodes[0], nodes[1], [...nodes, blocked], saved), []);+ assert.equal(JSON.stringify(saved), snapshot, "fallback does not delete manual configuration");+ validate(routeManualMindmapRelation(nodes[0], nodes[1], nodes, saved), nodes);+});++test("an outward drag can return through the generated endpoint bends", () => {+ const nodes = [+ {x: 300, y: 40, width: 110, height: 40},+ {x: 300, y: 220, width: 110, height: 40},+ {x: 470, y: 0, width: 120, height: 40},+ {x: 470, y: 100, width: 220, height: 40},+ ];+ const automatic = routeMindmapRelation(nodes[0], nodes[1], nodes);+ assert.equal(automatic.length, 2);+ for (const savedBends of [false, true]) {+ let route = encodeMindmapRoute(moveMindmapRouteSegment(automatic, 0, 500), nodes[0], nodes[1]);+ let points = routeManualMindmapRelation(nodes[0], nodes[1], nodes, route);+ validate(points, nodes);+ if (savedBends) {+ route = encodeMindmapRoute(points, nodes[0], nodes[1]);+ }+ let column = automatic[0].x + 500;+ for (const x of [800, 440, 400, automatic[0].x]) {+ const segment = points.slice(1).map((point, index) => ({point, index, previous: points[index]}))+ .find(item => item.point.x === column && item.previous.x === column);+ assert.ok(segment);+ route = adjustMindmapRoute(points, segment.index, x - segment.point.x, nodes[0], nodes[1], route);+ points = routeManualMindmapRelation(nodes[0], nodes[1], nodes, route);+ column = x;+ assert.ok(points.length, JSON.stringify({savedBends, x, route}));+ validate(points, nodes);+ validateDirection(points, nodes[0], nodes[1]);+ }+ assert.deepEqual(points, automatic);+ }+});+test("mixed widths keep arrows facing nodes", () => {for (const width of [64, 130, 260]) {const nodes = [diff --git a/app/src/protyle/render/listMindmap/routing.ts b/app/src/protyle/render/listMindmap/routing.tsindex ea417479f7..ccd9274e66 100644--- a/app/src/protyle/render/listMindmap/routing.ts+++ b/app/src/protyle/render/listMindmap/routing.ts@@ -1,5 +1,9 @@export interface MindmapRoutePoint {x: number; y: number;}export interface MindmapRouteBox extends MindmapRoutePoint {width: number; height: number; controlY?: number;}+export interface MindmapManualRoute {+ version: 1;+ points: (MindmapRoutePoint & {t: number})[];+}const bendCost = 24;@@ -61,6 +65,9 @@ const findRelationRoute = (from: MindmapRouteBox, to: MindmapRouteBox,top: (node.controlY ?? node.y + node.height) - 15, bottom: (node.controlY ?? node.y + node.height) + 15},]);const ports = (node: MindmapRouteBox, other: MindmapRouteBox) => {+ if (!node.width && !node.height) {+ return [0, 1, 2, 3].map(direction => ({x: node.x, y: node.y, direction}));+ }const centerX = node.x + node.width / 2;const otherCenterX = other.x + other.width / 2;const xs = [...new Set([centerX, ...(otherCenterX >= node.x + 12 &&@@ -189,3 +196,140 @@ const findRelationRoute = (from: MindmapRouteBox, to: MindmapRouteBox,}return [];};++const routeAnchor = (from: MindmapRouteBox, to: MindmapRouteBox, t: number): MindmapRoutePoint => ({+ x: (from.x + from.width / 2) * (1 - t) + (to.x + to.width / 2) * t,+ y: (from.y + from.height / 2) * (1 - t) + (to.y + to.height / 2) * t,+});++// 控制点相对两个端点保存;整体平移不改变配置,单端移动按路径比例带动控制点。+export const encodeMindmapRoute = (points: MindmapRoutePoint[], from: MindmapRouteBox,+ to: MindmapRouteBox): MindmapManualRoute => {+ const lengths = [0];+ points.slice(1).forEach((point, index) => lengths.push(lengths[index] ++ Math.hypot(point.x - points[index].x, point.y - points[index].y)));+ const total = lengths[lengths.length - 1] || 1;+ return {version: 1, points: points.slice(1, -1).map((point, index) => {+ const t = lengths[index + 1] / total;+ const anchor = routeAnchor(from, to, t);+ return {t, x: point.x - anchor.x, y: point.y - anchor.y};+ })};+};++const decodeMindmapRoute = (route: MindmapManualRoute, from: MindmapRouteBox, to: MindmapRouteBox) =>+ route.points.map(point => {+ const anchor = routeAnchor(from, to, point.t);+ return {x: Math.round((anchor.x + point.x) * 1e6) / 1e6,+ y: Math.round((anchor.y + point.y) * 1e6) / 1e6, width: 0, height: 0};+ });++export const routeManualMindmapRelation = (from: MindmapRouteBox, to: MindmapRouteBox,+ nodes: MindmapRouteBox[], route: MindmapManualRoute): MindmapRoutePoint[] => {+ const controls = decodeMindmapRoute(route, from, to);+ const stops = [from, ...controls, to];+ const result: MindmapRoutePoint[] = [];+ for (let i = 1; i < stops.length; i++) {+ const a = stops[i - 1];+ const b = stops[i];+ if (!a.width && !b.width && a.x === b.x && a.y === b.y) {+ continue;+ }+ const segment = routeMindmapRelation(a, b, nodes);+ if (segment.length < 2) {+ return [];+ }+ result.push(...(result.length ? segment.slice(1) : segment));+ }+ // 合并共线点和避障后重叠的折返段,避免接缝产生无效圆角。+ const simplified: MindmapRoutePoint[] = [];+ for (const point of result) {+ let b = simplified[simplified.length - 1];+ if (b && point.x === b.x && point.y === b.y) {+ continue;+ }+ let a = simplified[simplified.length - 2];+ while (a && ((a.x === b.x && b.x === point.x) || (a.y === b.y && b.y === point.y))) {+ simplified.pop();+ b = a;+ a = simplified[simplified.length - 2];+ }+ if (!b || b.x !== point.x || b.y !== point.y) {+ simplified.push(point);+ }+ }+ return simplified;+};++export const moveMindmapRouteSegment = (points: MindmapRoutePoint[], index: number, offset: number): MindmapRoutePoint[] => {+ if (index < 0 || index >= points.length - 1) {+ return [];+ }+ const result = points.map(point => ({...point}));+ const a = result[index];+ const b = result[index + 1];+ const axis = a.y === b.y ? "y" : "x";+ const length = Math.hypot(b.x - a.x, b.y - a.y);+ if (length < 12) {+ return [];+ }+ // 首尾线段只保存移动部分,连接端重新选择垂直于节点边缘的引出段。+ const start = index === 0 ? {x: a.x + (b.x - a.x) / 3, y: a.y + (b.y - a.y) / 3} : a;+ const end = index === points.length - 2 ? {x: b.x - (b.x - a.x) / 3, y: b.y - (b.y - a.y) / 3} : b;+ const movedStart = {...start, [axis]: start[axis] + offset};+ const movedEnd = {...end, [axis]: end[axis] + offset};+ return [...result.slice(0, index), ...(index === 0 ? [a] : []), movedStart, movedEnd,+ ...(index === points.length - 2 ? [b] : []), ...result.slice(index + 2)];+};++export const adjustMindmapRoute = (points: MindmapRoutePoint[], index: number, offset: number,+ from: MindmapRouteBox, to: MindmapRouteBox, route?: MindmapManualRoute): MindmapManualRoute | undefined => {+ const candidate = moveMindmapRouteSegment(points, index, offset);+ if (candidate.length < 3) {+ return;+ }+ const a = points[index];+ const b = points[index + 1];+ const axis = a.y === b.y ? "y" : "x";+ const along = axis === "x" ? "y" : "x";+ const controls = route ? decodeMindmapRoute(route, from, to) : [];+ const selected = controls.map((point, i) => Math.abs(point[axis] - a[axis]) < .001 ? i : -1).filter(i => i >= 0);+ if (!selected.length) {+ return candidate.length <= 66 ? encodeMindmapRoute(candidate, from, to) : undefined;+ }+ // 再次拖动沿用已保存的控制点,自动避障产生的拐点不转成固定约束。+ const removed = new Set<number>();+ const crosses = (point: MindmapRoutePoint) => point[axis] > Math.min(a[axis], a[axis] + offset) &&+ point[axis] < Math.max(a[axis], a[axis] + offset);+ // 越过相邻折线时收起被跨过的控制点,允许已保存的绕行逐段缩回。+ for (let i = selected[0] - 1; i >= 0 && crosses(controls[i]); i--) {+ removed.add(i);+ }+ for (let i = selected[selected.length - 1] + 1; i < controls.length && crosses(controls[i]); i++) {+ removed.add(i);+ }+ const size = along === "y" ? "height" : "width";+ const first = from[along] < to[along] ? from : to;+ const last = first === from ? to : from;+ return {...route, points: route.points.flatMap((point, i) => {+ if (removed.has(i)) {+ return [];+ }+ if (!selected.includes(i)) {+ return [point];+ }+ const moved = {...controls[i], [axis]: controls[i][axis] + offset};+ // 回到端点之间时,连接处的控制点退到节点外侧,由路由重新选择连接端口。+ const overlapsEndpoint = [from, to].some(node =>+ (moved.x > node.x - 6 && moved.x < node.x + node.width + 6 &&+ moved.y > node.y - 6 && moved.y < node.y + node.height + 6) ||+ (moved.x > node.x + node.width - 19 && moved.x < node.x + node.width + 61 &&+ moved.y > (node.controlY ?? node.y + node.height) - 15 &&+ moved.y < (node.controlY ?? node.y + node.height) + 15));+ const inset = along === "y" && moved.x > first.x + first.width - 19 &&+ moved.x < first.x + first.width + 61 ? 16 : 8;+ if (overlapsEndpoint && first[along] + first[size] + inset <= last[along] - 8) {+ moved[along] = Math.max(first[along] + first[size] + inset, Math.min(last[along] - 8, moved[along]));+ }+ return [{...point, x: point.x + moved.x - controls[i].x, y: point.y + moved.y - controls[i].y}];+ })};+};diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.tsindex c5b6abe7db..40fefb471e 100644--- a/app/src/protyle/render/listMindmap/view.ts+++ b/app/src/protyle/render/listMindmap/view.ts@@ -6,7 +6,8 @@ import {ListMindmapPosition,ListMindmapRelation,} from "./model";-import {routeMindmapRelation, MindmapRoutePoint} from "./routing";+import {routeMindmapRelation, routeManualMindmapRelation, adjustMindmapRoute,+ MindmapRoutePoint, MindmapManualRoute} from "./routing";import {mathRender} from "../mathRender";import {getAVRichTextSafeURL} from "../av/richTextValue";import {Constants} from "../../../constants";@@ -42,7 +43,7 @@ export interface ListMindmapViewOptions {onRedo?: () => void;onNodeStyle?: (id: string, patch: Partial<ListMindmapNodeStyle>) => void;onRelationAdd?: (from: string, to: string) => void;- onRelationChange?: (id: string, patch: Partial<ListMindmapRelation>) => void;+ onRelationChange?: (id: string, patch: Partial<ListMindmapRelation>, expected?: string) => void;onRelationDelete?: (id: string) => void;onExit: () => void;}@@ -57,6 +58,18 @@ interface PointerState {moved: boolean;targetId?: string;placement?: "before" | "child" | "after";+ relation?: {+ id: string;+ segment: number;+ points: MindmapRoutePoint[];+ original: string;+ offset: number;+ valid: boolean;+ handle: MindmapRoutePoint;+ endpoint?: "from" | "to";+ targetId?: string;+ route?: MindmapManualRoute;+ };}const createElement = <T extends keyof HTMLElementTagNameMap>(tag: T, className: string) => {@@ -92,6 +105,10 @@ export class ListMindmapView {private finishRelationEdit?: (save: boolean) => void;private linePaths: {id: string, relation: boolean, path: Path2D, end?: MindmapRoutePoint}[] = [];private relationRoutes = new Map<string, MindmapRoutePoint[]>();+ private readonly routeHandles = new Map<string, HTMLButtonElement>();+ private readonly routeStatus = createElement("div", "list-mindmap__route-status");+ private readonly fallbackRoutes = new Set<string>();+ private routeDragFrame = 0;private relationFrom?: string;private relationPreview?: {x: number, y: number, targetId?: string};private editingId?: string;@@ -135,7 +152,9 @@ export class ListMindmapView {this.tooltip.hidden = true;this.tooltip.setAttribute("role", "tooltip");this.colorProbe.setAttribute("aria-hidden", "true");- options.host.append(this.toolbar, this.viewport, this.inspector, this.tooltip, this.colorProbe);+ this.routeStatus.hidden = true;+ this.routeStatus.setAttribute("role", "status");+ options.host.append(this.toolbar, this.viewport, this.inspector, this.tooltip, this.colorProbe, this.routeStatus);this.createToolbar();this.listen(document, "pointerdown", this.dismissControls, {capture: true});this.listen(options.host, "pointerover", this.showButtonTooltip);@@ -180,6 +199,9 @@ export class ListMindmapView {event.stopPropagation();}));this.listen(window, "beforeprint", () => {+ if (this.pointer?.relation) {+ this.cancelPointer();+ }this.printTransform ||= {scale: this.scale, offsetX: this.offsetX, offsetY: this.offsetY};this.fitPrint();});@@ -268,7 +290,7 @@ export class ListMindmapView {private dismissControls = (event: PointerEvent) => {const target = event.target as Node;this.tooltip.hidden = true;- if (target instanceof Element && target.closest(".list-mindmap__relation-editor")) {+ if (target instanceof Element && target.closest(".list-mindmap__relation-editor, .list-mindmap__route-handle")) {return;}if (this.inspector.contains(target) || this.buttons.get("style")?.contains(target) ||@@ -357,6 +379,9 @@ export class ListMindmapView {}public update(model: ListMindmapModel) {+ if (this.pointer?.relation) {+ this.cancelPointer();+ }if (this.destroyed) {return;}@@ -489,11 +514,14 @@ export class ListMindmapView {}public refreshLayout() {- if (this.destroyed || this.frame) {+ if (this.destroyed || this.frame || this.pointer?.relation) {return;}this.frame = requestAnimationFrame(() => {this.frame = 0;+ if (this.pointer?.relation) {+ return;+ }if (!this.viewport.clientWidth || !this.viewport.clientHeight) {return;}@@ -510,7 +538,8 @@ export class ListMindmapView {children: node.children.map(child => makeLayoutNode(child.id)),};};- const anchorId = this.editingId || this.foldAnchor?.id;+ const anchorId = this.editingId || this.foldAnchor?.id ||+ this.model.metadata.relations.find(relation => relation.id === this.selectedRelation)?.from;const previous = anchorId ? this.positions.get(anchorId) : undefined;const layoutRoot = makeLayoutNode(this.model.root.id);let result = layoutListMindmap(layoutRoot);@@ -558,6 +587,7 @@ export class ListMindmapView {}this.positions = result.nodes;this.relationRoutes.clear();+ this.fallbackRoutes.clear();this.edges = result.edges;this.bounds = result;let top = 0;@@ -567,7 +597,7 @@ export class ListMindmapView {const from = this.positions.get(relation.from);const to = this.positions.get(relation.to);if (from && to) {- const points = routeMindmapRelation(from, to, this.routingObstacles());+ const points = this.calculateRelationRoute(relation, from, to);this.relationRoutes.set(relation.id, points);points.forEach(point => {top = Math.min(top, point.y - 24);@@ -597,7 +627,7 @@ export class ListMindmapView {element.style.top = `${position.y - 1}px`;}});- // 编辑或折叠改变布局时固定操作节点,避免光标和折叠按钮随整棵树跳动。+ // 编辑、折叠或调整路径时固定操作节点,避免整棵树随布局边界跳动。const current = anchorId ? this.positions.get(anchorId) : undefined;if (previous && current) {this.offsetX += (previous.x - current.x) * this.scale;@@ -663,7 +693,7 @@ export class ListMindmapView {private relationPath(id: string | undefined, from: ListMindmapPosition, to: ListMindmapPosition, label?: HTMLElement) {let points = id ? this.relationRoutes.get(id) : undefined;if (!points) {- points = routeMindmapRelation(from, to, this.routingObstacles());+ points = this.calculateRelationRoute(this.model.metadata.relations.find(relation => relation.id === id), from, to);if (id) {this.relationRoutes.set(id, points);}@@ -673,6 +703,9 @@ export class ListMindmapView {}const end = points[points.length - 1];const previous = points[points.length - 2];+ // 按整条路径限制箭头大小,短尾段不会把长关系线的箭头压小。+ const arrowSizeLimit = points.slice(1).reduce((length, point, i) =>+ length + Math.hypot(point.x - points[i].x, point.y - points[i].y), 0) / 3;// 重合路径从同一端绘制,避免反向虚线填满正向虚线的间隙。const drawingPoints = (points[0].x - end.x || points[0].y - end.y) > 0 ? [...points].reverse() : points;const path = new Path2D();@@ -690,7 +723,7 @@ export class ListMindmapView {const drawingEnd = drawingPoints[drawingPoints.length - 1];path.lineTo(drawingEnd.x, drawingEnd.y);if (!label) {- return {path, end, previous, labelPoint: undefined as MindmapRoutePoint | undefined};+ return {path, end, previous, arrowSizeLimit, labelPoint: undefined as MindmapRoutePoint | undefined};}const width = label.offsetWidth;const height = label.offsetHeight;@@ -711,8 +744,203 @@ export class ListMindmapView {break;}}- label.style.visibility = labelPoint ? "" : "hidden";- return {path, end, previous, labelPoint};+ // 调整关系线时隐藏文字,保留测量尺寸,避免遮挡手柄或改变节点布局。+ label.style.visibility = !labelPoint || (id === this.selectedRelation && !this.options.readOnly &&+ !this.printTransform && !this.options.printLayout) ? "hidden" : "";+ return {path, end, previous, arrowSizeLimit, labelPoint};+ }++ private calculateRelationRoute(relation: ListMindmapRelation | undefined, from: ListMindmapPosition, to: ListMindmapPosition) {+ if (relation) {+ this.fallbackRoutes.delete(relation.id);+ if (relation.route) {+ const points = routeManualMindmapRelation(from, to, this.routingObstacles(), relation.route);+ if (points.length >= 2) {+ return points;+ }+ this.fallbackRoutes.add(relation.id);+ }+ }+ return routeMindmapRelation(from, to, this.routingObstacles());+ }++ private renderRouteControls() {+ const id = this.selectedRelation;+ const drag = this.pointer?.relation;+ const editable = !this.options.readOnly && !this.printTransform && !this.options.printLayout && !this.finishRelationEdit;+ const points = editable && !drag?.endpoint ? drag?.points || this.relationRoutes.get(id) || [] : [];+ const visible = new Set<string>();+ for (let i = 0; i < points.length - 1; i++) {+ const a = points[i];+ const b = points[i + 1];+ if (Math.hypot(b.x - a.x, b.y - a.y) < 12 || (drag && drag.segment !== i)) {+ continue;+ }+ const horizontal = a.y === b.y;+ let x = this.offsetX + (a.x + b.x) / 2 * this.scale;+ let y = this.offsetY + (a.y + b.y) / 2 * this.scale;+ if (drag) {+ x = this.offsetX + (drag.handle.x + (horizontal ? 0 : drag.offset)) * this.scale;+ y = this.offsetY + (drag.handle.y + (horizontal ? drag.offset : 0)) * this.scale;+ }+ const key = `${id}:${i}`;+ visible.add(key);+ const handle = this.getRouteHandle(id, i);+ handle.style.left = `${x}px`;+ handle.style.top = `${y}px`;+ handle.style.cursor = horizontal ? "ns-resize" : "ew-resize";+ }+ const route = editable ? this.relationRoutes.get(id) : undefined;+ if (route?.length >= 2) {+ (["from", "to"] as const).forEach(endpoint => {+ visible.add(`${id}:${endpoint}`);+ const handle = this.getRouteHandle(id, endpoint);+ const point = drag?.endpoint === endpoint && this.pointer.moved ? drag.handle :+ route[endpoint === "from" ? 0 : route.length - 1];+ handle.style.left = `${this.offsetX + point.x * this.scale}px`;+ handle.style.top = `${this.offsetY + point.y * this.scale}px`;+ });+ }+ this.routeHandles.forEach((handle, key) => {+ if (!visible.has(key)) {+ handle.remove();+ this.routeHandles.delete(key);+ }+ });+ const invalid = this.pointer?.relation && !this.pointer.relation.valid;+ this.viewport.classList.toggle("list-mindmap__viewport--route-invalid", !!invalid);+ this.routeStatus.hidden = this.options.readOnly || !!this.options.printLayout || !!this.printTransform ||+ (!invalid && !this.fallbackRoutes.has(id));+ this.routeStatus.textContent = this.label(invalid ? "invalid" : "listMindmapRouteFallback");+ }++ private getRouteHandle(id: string, part: number | "from" | "to") {+ const key = `${id}:${part}`;+ let handle = this.routeHandles.get(key);+ if (handle) {+ return handle;+ }+ handle = createElement("button", "list-mindmap__route-handle");+ handle.type = "button";+ const endpoint = typeof part === "string" ? part : undefined;+ if (endpoint) {+ handle.classList.add("list-mindmap__route-endpoint");+ handle.dataset.endpoint = endpoint;+ }+ handle.setAttribute("aria-label", this.label(endpoint ?+ endpoint === "from" ? "listMindmapRouteStart" : "listMindmapRouteEnd" : "listMindmapRouteHandle"));+ handle.addEventListener("pointerdown", event => {+ event.stopPropagation();+ if (event.button === 0 && !this.options.readOnly && !this.pointer) {+ event.preventDefault();+ this.pendingPointerId = event.pointerId;+ this.finishThen(() => {+ if (this.pendingPointerId === event.pointerId) {+ this.beginRouteDrag(event, id, typeof part === "number" ? part : 0, endpoint);+ }+ });+ }+ });+ handle.addEventListener("dblclick", event => {+ event.stopPropagation();+ this.resetRelationRoute(id);+ });+ this.routeHandles.set(key, handle);+ this.viewport.append(handle);+ return handle;+ }++ private beginRouteDrag(event: PointerEvent, id: string, segment: number, endpoint?: "from" | "to") {+ const relation = this.model.metadata.relations.find(item => item.id === id);+ const points = this.relationRoutes.get(id);+ if (this.options.readOnly || !relation || !points?.[segment + 1]) {+ return;+ }+ this.selectedId = undefined;+ this.selectedEdge = undefined;+ this.selectedRelation = id;+ this.relationFrom = undefined;+ this.finishRelationEdit?.(true);+ this.options.host.focus({preventScroll: true});+ const handle = this.routeHandles.get(`${id}:${endpoint || segment}`);+ this.pointer = {pointerId: event.pointerId, startX: event.clientX, startY: event.clientY,+ x: this.offsetX, y: this.offsetY, moved: false,+ relation: {id, segment, endpoint, targetId: endpoint ? relation[endpoint] : undefined,+ points: points.map(point => ({...point})), original: JSON.stringify(relation), offset: 0, valid: true,+ handle: handle ? {x: (parseFloat(handle.style.left) - this.offsetX) / this.scale,+ y: (parseFloat(handle.style.top) - this.offsetY) / this.scale} :+ {x: (points[segment].x + points[segment + 1].x) / 2, y: (points[segment].y + points[segment + 1].y) / 2}}};+ try {+ this.pointerCapture = (event.target as Element).closest<HTMLElement>(".list-mindmap__route-handle") || this.viewport;+ this.pointerCapture.setPointerCapture(event.pointerId);+ } catch {+ this.cancelPointer();+ return;+ }+ this.inspector.hidden = false;+ this.updateSelection();+ this.renderInspector();+ }++ private previewRouteDrag() {+ cancelAnimationFrame(this.routeDragFrame);+ this.routeDragFrame = 0;+ const drag = this.pointer?.relation;+ const relation = this.model.metadata.relations.find(item => item.id === drag?.id);+ if (!drag || !relation) {+ return;+ }+ const from = this.positions.get(relation.from);+ const to = this.positions.get(relation.to);+ drag.valid = false;+ if (drag.endpoint) {+ const target = this.positions.get(drag.targetId);+ const point = target || {id: "", ...drag.handle, width: 0, height: 0};+ const nextFrom = drag.endpoint === "from" ? point : from;+ const nextTo = drag.endpoint === "to" ? point : to;+ const points = target?.id === relation[drag.endpoint] ? drag.points :+ routeMindmapRelation(nextFrom, nextTo, this.routingObstacles());+ drag.valid = !!target && this.canReconnectRelation(relation, drag.endpoint, target.id) && points.length >= 2;+ if (points.length >= 2) {+ this.relationRoutes.set(drag.id, points);+ }+ this.nodeElements.forEach((element, id) => element.classList.toggle("list-mindmap__node--relation",+ drag.valid && id === drag.targetId));+ this.draw();+ return;+ }+ const route = from && to && adjustMindmapRoute(drag.points, drag.segment, drag.offset, from, to,+ this.fallbackRoutes.has(drag.id) ? undefined : relation.route);+ if (route) {+ const points = routeManualMindmapRelation(from, to, this.routingObstacles(), route);+ if (points.length >= 2) {+ drag.route = route;+ drag.valid = true;+ this.relationRoutes.set(drag.id, points);+ }+ }+ this.draw();+ }++ private canReconnectRelation(relation: ListMindmapRelation, endpoint: "from" | "to", targetId: string) {+ const target = this.model.nodes.get(targetId);+ const from = endpoint === "from" ? targetId : relation.from;+ const to = endpoint === "to" ? targetId : relation.to;+ return target && !target.virtual && from !== to && !this.model.metadata.relations.some(item =>+ item.id !== relation.id && item.from === from && item.to === to);+ }++ private resetRelationRoute(id: string) {+ if (this.options.readOnly) {+ return;+ }+ this.cancelPointer();+ this.finishThen(() => {+ const relation = this.model.metadata.relations.find(item => item.id === id);+ if (!this.options.readOnly && relation?.route) {+ this.options.onRelationChange?.(id, {route: undefined}, JSON.stringify(relation));+ }+ });}private draw() {@@ -790,7 +1018,7 @@ export class ListMindmapView {element.hidden = true;return;}- const {path, end, previous, labelPoint} = route;+ const {path, end, previous, arrowSizeLimit, labelPoint} = route;this.linePaths.push({id: relation.id, relation: true, path, end});context.beginPath();context.strokeStyle = resolveColor(relation.color, primary);@@ -804,8 +1032,7 @@ export class ListMindmapView {context.beginPath();const direction = Math.atan2(end.y - previous.y, end.x - previous.x);// 短线上的双向箭头预留间隙,避免合并成菱形。- const arrowSize = Math.min(Math.max(7 / this.scale, (relation.width || 1.5) * 2),- Math.hypot(end.x - previous.x, end.y - previous.y) / 3);+ const arrowSize = Math.min(Math.max(7 / this.scale, (relation.width || 1.5) * 2), arrowSizeLimit);// 箭头随线条状态加宽,保持长度不变以保留双向箭头之间的间隙。const halfWidth = arrowSize / 2 + emphasis / 2;const baseX = end.x - arrowSize * Math.cos(Math.PI / 6) * Math.cos(direction);@@ -822,6 +1049,7 @@ export class ListMindmapView {}});this.drawRelationPreview(context, primary);+ this.renderRouteControls();}private drawRelationPreview(context: CanvasRenderingContext2D, color: string) {@@ -836,7 +1064,7 @@ export class ListMindmapView {if (!route) {return;}- const {path, end, previous} = route;+ const {path, end, previous, arrowSizeLimit} = route;context.beginPath();context.strokeStyle = color;context.lineWidth = 1.5;@@ -844,7 +1072,7 @@ export class ListMindmapView {context.stroke(path);context.setLineDash([]);context.beginPath();- const size = Math.min(Math.max(7 / this.scale, 3), Math.hypot(end.x - previous.x, end.y - previous.y) / 3);+ const size = Math.min(Math.max(7 / this.scale, 3), arrowSizeLimit);const direction = Math.atan2(end.y - previous.y, end.x - previous.x);context.fillStyle = color;context.moveTo(end.x - size * Math.cos(direction - Math.PI / 6), end.y - size * Math.sin(direction - Math.PI / 6));@@ -978,6 +1206,26 @@ export class ListMindmapView {};private beginPointer(event: PointerEvent, id?: string) {+ if (!id && !this.options.readOnly && !this.relationFrom) {+ const line = this.findLine(event);+ const points = line?.relation && this.relationRoutes.get(line.id);+ if (points) {+ const bounds = this.viewport.getBoundingClientRect();+ const x = (event.clientX - bounds.left - this.offsetX) / this.scale;+ const y = (event.clientY - bounds.top - this.offsetY) / this.scale;+ const segment = points.slice(1).map((b, index) => {+ const a = points[index];+ return {index, length: Math.hypot(b.x - a.x, b.y - a.y), distance: Math.hypot(+ x - Math.max(Math.min(a.x, b.x), Math.min(x, Math.max(a.x, b.x))),+ y - Math.max(Math.min(a.y, b.y), Math.min(y, Math.max(a.y, b.y))))};+ }).filter(item => item.length >= 12 && item.distance <= 12 / this.scale)+ .sort((a, b) => a.distance - b.distance)[0];+ if (segment) {+ this.beginRouteDrag(event, line.id, segment.index);+ return;+ }+ }+ }if (this.relationFrom && id) {this.suppressLinkClick = true;event.preventDefault();@@ -1042,6 +1290,23 @@ export class ListMindmapView {}event.preventDefault();pointer.moved = true;+ if (pointer.relation) {+ const drag = pointer.relation;+ if (drag.endpoint) {+ const bounds = this.viewport.getBoundingClientRect();+ drag.handle = {x: (event.clientX - bounds.left - this.offsetX) / this.scale,+ y: (event.clientY - bounds.top - this.offsetY) / this.scale};+ drag.targetId = [...this.positions.values()].find(node => drag.handle.x >= node.x &&+ drag.handle.x <= node.x + node.width && drag.handle.y >= node.y &&+ drag.handle.y <= node.y + node.height)?.id;+ } else {+ drag.offset = (drag.points[drag.segment].y === drag.points[drag.segment + 1].y ? dy : dx) / this.scale;+ }+ if (!this.routeDragFrame) {+ this.routeDragFrame = requestAnimationFrame(() => this.previewRouteDrag());+ }+ return;+ }this.viewport.classList.add("list-mindmap__viewport--dragging");if (!pointer.id) {this.offsetX = pointer.x + dx;@@ -1119,6 +1384,21 @@ export class ListMindmapView {return;}const {id, targetId, placement, moved} = pointer;+ if (pointer.relation) {+ if (moved) {+ this.previewRouteDrag();+ }+ const drag = pointer.relation;+ this.cancelPointer();+ const relation = this.model.metadata.relations.find(item => item.id === drag.id);+ if (moved && drag.endpoint && drag.valid && relation && !this.options.readOnly &&+ relation[drag.endpoint] !== drag.targetId && this.canReconnectRelation(relation, drag.endpoint, drag.targetId)) {+ this.options.onRelationChange?.(drag.id, {[drag.endpoint]: drag.targetId, route: undefined}, drag.original);+ } else if (moved && !drag.endpoint && Math.abs(drag.offset) > .01 && drag.valid && drag.route && !this.options.readOnly) {+ this.options.onRelationChange?.(drag.id, {route: drag.route}, drag.original);+ }+ return;+ }this.suppressLinkClick = moved;this.cancelPointer();if (moved && id && targetId && placement) {@@ -1199,6 +1479,8 @@ export class ListMindmapView {}private cancelPointer = () => {+ cancelAnimationFrame(this.routeDragFrame);+ this.routeDragFrame = 0;this.pendingPointerId = undefined;this.clearDrop();const pointer = this.pointer;@@ -1211,6 +1493,14 @@ export class ListMindmapView {this.ghost = undefined;this.viewport.classList.remove("list-mindmap__viewport--dragging");this.nodeElements.forEach(element => element.classList.remove("list-mindmap__node--dragging"));+ if (pointer?.relation) {+ if (pointer.relation.endpoint) {+ this.nodeElements.forEach(element => element.classList.remove("list-mindmap__node--relation"));+ }+ this.relationRoutes.set(pointer.relation.id, pointer.relation.points);+ this.draw();+ this.refreshLayout();+ }};private contentClick = (event: MouseEvent) => {@@ -1314,6 +1604,7 @@ export class ListMindmapView {this.update(this.model);};this.finishRelationEdit = finish;+ this.renderRouteControls();input.addEventListener("blur", () => finish(true));input.addEventListener("keydown", event => {event.stopPropagation();@@ -1357,12 +1648,13 @@ export class ListMindmapView {this.finishRelationEdit = undefined;const value = input.value;input.remove();- element.style.visibility = "";if (save && value !== (relation.label || "")) {this.options.onRelationChange?.(relation.id, {label: value});}+ this.draw();};this.finishRelationEdit = finish;+ this.renderRouteControls();input.addEventListener("blur", () => finish(true));input.addEventListener("keydown", event => {if (event.isComposing || (event.key !== "Enter" && event.key !== "Escape")) {@@ -1384,6 +1676,9 @@ export class ListMindmapView {}event.preventDefault();event.stopPropagation();+ if (this.pointer?.relation) {+ return;+ }const mode = event.deltaMode;const unitX = mode === WheelEvent.DOM_DELTA_LINE ? 16 :mode === WheelEvent.DOM_DELTA_PAGE ? this.viewport.clientWidth : 1;@@ -1480,6 +1775,9 @@ export class ListMindmapView {if (event.isComposing || target.closest("input, textarea, select, .list-mindmap__node--editing")) {return;}+ if (this.pointer?.relation && event.key !== "Escape") {+ return;+ }if (!this.options.readOnly && this.options.isTaskCycle?.(event)) {const id = target.closest<HTMLElement>(".list-mindmap__node")?.dataset.mindmapId || this.selectedId;if (this.model.nodes.get(id)?.taskMarker !== undefined) {@@ -1560,7 +1858,13 @@ export class ListMindmapView {}});} else if (event.key === "Escape") {+ const draggingRoute = !!this.pointer?.relation;this.cancelPointer();+ if (draggingRoute) {+ event.preventDefault();+ event.stopPropagation();+ return;+ }this.relationFrom = undefined;this.inspector.hidden = true;if (this.fullscreenMarker) {diff --git a/docs/LIST-MINDMAP.md b/docs/LIST-MINDMAP.mdindex 6f9ea2b5fb..fe2848ee23 100644--- a/docs/LIST-MINDMAP.md+++ b/docs/LIST-MINDMAP.md@@ -16,6 +16,8 @@- 使用节点旁的按钮添加子节点或折叠,选中节点后按 Delete 或 Backspace 删除(兼容 macOS 的 Delete 键);最后一个根节点保留,避免产生不能保存的空列表;撤销和重做保留编辑器快捷键,工具栏不再显示对应按钮- 点击画布空白处或脑图外部取消选中,收起节点样式及关系线设置;点击节点继续选择关系线终点,点击其他区域取消连线- 连接按钮使用带箭头的弯曲连线图标,位于缩小按钮前;先选择起点,再选择终点,可编辑文字、颜色或删除关系线;路径通过正交可视网格上的 A* 搜索避开节点和折叠、添加按钮区域,减少转弯并绘制圆角,布局变化时重新计算,平移和缩放时复用路径+- 关系线支持直接拖动,选中后在线段上显示手柄;水平线段上下拖动,垂直线段左右拖动,首尾线段保留连接节点的引出段;拖动时固定节点布局和画布,实时预览避障路径,松手保存一次事务,Esc 或指针取消恢复原路径;双击拖拽手柄恢复自动计算,双击线条或文字编辑关系文字;只读及导出显示保存的路径,不显示调整手柄+- 选中关系线后,空心圆标出起点,实心圆标出箭头端;拖动圆形手柄更换对应节点,可连接的节点会高亮;松手后重新计算路径并保存到同一事务,保留关系文字和样式,支持撤销;落在空白处、原节点、自身或已有的同向连接上不修改关系线- 节点默认无背景、不显示边框,正文格式通过节点内的 Protyle 编辑;选中节点后,脑图面板底部显示单排配色工具栏,仅展示节点配色及颜色管理入口,复用外观面板中的文字色与背景色组合,包含内置及自定义颜色并遵循其顺序和可见性,可恢复默认色;点击树连线或关系线,在脑图面板底部显示对应的设置菜单,线条颜色复用外观背景色,菜单不显示标题栏、虚线及宽度控件;双击关系线文字,在原位置显示输入框进行编辑- 滚轮或触控板滚动用于移动画布,Ctrl + 滚轮或触控板双指捏合以鼠标位置为中心缩放;工具栏提供缩放、适应画布和全屏;全屏沿用编辑器的窗口内全屏及窗口控件避让,点击全屏按钮或按 Esc 退出并回到原列表位置- 本次不包含概要和自由摆放节点@@ -26,6 +28,8 @@列表块使用 `custom-sy-list-mindmap="1"` 启用脑图视图。`custom-sy-list-mindmap-data` 保存版本为 `1` 的节点样式和关系线配置。关闭脑图视图保留该配置;折叠使用列表项的已有 `fold` 属性。未知版本或损坏的配置不会被自动覆盖,原列表仍可查看。+关系线可选的 `route` 字段使用独立的 `version: 1`,`points` 保存不超过 64 个控制点。每个控制点的 `x`、`y` 是相对两个节点中心插值位置的偏移,`t` 是沿路径长度计算的插值比例(0 到 1),坐标偏移的绝对值不超过 1000000。缺少 `route` 表示自动路径;双击恢复时只删除该字段,保留文字、样式和端点。旧配置无需迁移,未知路径版本及损坏配置保留原值。节点位置变化时重新避障,暂时无法使用的手动路径仍保留配置并显示自动路径,恢复可用布局后重新使用手动路径。拖动期间的外部刷新取消预览,提交前核对关系线快照,避免覆盖较新的配置。+修改前补齐折叠隐藏的列表内容。结构、正文和配置修改通过已有文档事务保存,并进入文档撤销记录。复制列表时,样式所关联的节点 ID 和关系线的端点随复制后的块 ID 一起更新。内核在文档事务完成结构修改后,按列表当前的完整节点树清理失效的样式及关系线,并将配置修改附加到同一事务的同步、撤销和重做记录中。普通列表编辑、其他窗口和通过文档事务执行的 API 删除共用此逻辑;同一事务内先删除再插入的节点及折叠后代不会被误清理。刷新脑图只读取配置,不执行清理;复制列表会过滤不属于副本的样式和关系线。未知版本及损坏配置保持原样。@@ -36,6 +40,8 @@关系线路由使用带进出方向约束的正交网格搜索,按节点边界及目标位置选择连接点,禁止立即折返。路线代价综合长度及转弯,各条关系线独立计算,不避让已有线条;新增连接的吸附预览与落点使用相同规则。节点宽度变化时可选择与目标对齐的连接点,节点和折叠、添加按钮仍作为避让区域。+再次拖动手动路径时移动保存的控制点,自动避障拐点不转成固定约束;往回拖过相邻折线时收起被跨过的控制点,进入端点区域时将控制点退到两节点之间,避免绕行路径无法缩回。+## 导出与验证思源格式的 HTML 和 PDF 预览沿用 `Protyle.mindmapRender` 加载列表脑图,资源均来自本地。Markdown、Markdown 格式的 HTML 和 Word 保留列表形式。diff --git a/kernel/model/transaction_list_mindmap.go b/kernel/model/transaction_list_mindmap.goindex 2709bc3cb0..733be74600 100644--- a/kernel/model/transaction_list_mindmap.go+++ b/kernel/model/transaction_list_mindmap.go@@ -77,11 +77,39 @@ func validListMindmapMetadata(data map[string]any) bool {if _, ok := relation["label"].(string); !ok || seen[relation["id"].(string)] {return false}+ if route, exists := relation["route"]; exists && !validListMindmapRoute(route) {+ return false+ }seen[relation["id"].(string)] = true}return true}+func validListMindmapRoute(value any) bool {+ route, ok := value.(map[string]any)+ if !ok || route["version"] != float64(1) {+ return false+ }+ points, ok := route["points"].([]any)+ if !ok || len(points) == 0 || len(points) > 64 {+ return false+ }+ for _, value := range points {+ point, ok := value.(map[string]any)+ if !ok {+ return false+ }+ for _, key := range []string{"x", "y", "t"} {+ number, ok := point[key].(float64)+ if !ok || math.IsNaN(number) || math.IsInf(number, 0) || math.Abs(number) > 1e6 ||+ (key == "t" && (number < 0 || number > 1)) {+ return false+ }+ }+ }+ return true+}+func pruneListMindmapMetadata(list *ast.Node) (string, bool) {original := list.IALAttr(listMindmapMetadataAttr)var data map[string]anydiff --git a/kernel/model/transaction_list_mindmap_test.go b/kernel/model/transaction_list_mindmap_test.goindex 30afce3162..f91fc95345 100644--- a/kernel/model/transaction_list_mindmap_test.go+++ b/kernel/model/transaction_list_mindmap_test.go@@ -23,11 +23,13 @@ func TestPruneListMindmapMetadata(t *testing.T) {_, list, child := mindmapTestTree()original := `{"version":1,"rootTitle":"A & B","extension":9007199254740993,"nodes":{"` + list.ID +`":{"backgroundColor":"red"},"child":{"bold":true,"extension":9007199254740993},"deleted":{}},` +- `"relations":[{"id":"keep","from":"` + list.ID + `","to":"child","label":"A & B"},` ++ `"relations":[{"id":"keep","from":"` + list.ID + `","to":"child","label":"A & B",` ++ `"route":{"version":1,"points":[{"x":-35,"y":20.5,"t":0.5}],"extension":9007199254740993}},` +`{"id":"remove","from":"child","to":"deleted","label":""}]}`list.SetIALAttr(listMindmapMetadataAttr, original)next, changed := pruneListMindmapMetadata(list)- if !changed || strings.Contains(next, "deleted") || strings.Count(next, "9007199254740993") != 2 {+ if !changed || strings.Contains(next, "deleted") || strings.Count(next, "9007199254740993") != 3 ||+ !strings.Contains(next, `"points":[{"x":-35,"y":20.5,"t":0.5}]`) {t.Fatalf("unexpected metadata: %s", next)}var result map[string]json.RawMessage@@ -47,6 +49,24 @@ func TestPruneListMindmapMetadata(t *testing.T) {}}+func TestPruneListMindmapPreservesInvalidRoutes(t *testing.T) {+ for _, route := range []string{+ `null`, `{}`, `{"version":2,"points":[{"x":0,"y":0,"t":0.5}]}`,+ `{"version":1,"points":[]}`, `{"version":1,"points":[{"x":"0","y":0,"t":0.5}]}`,+ `{"version":1,"points":[{"x":0,"y":0,"t":-0.1}]}`, `{"version":1,"points":[{"x":0,"y":0,"t":1.1}]}`,+ `{"version":1,"points":[{"x":1000001,"y":0,"t":0.5}]}`, `{"version":1,"points":[{"x":0,"y":null,"t":0.5}]}`,+ `{"version":1,"points":[{"x":0,"y":0}]}`,+ `{"version":1,"points":[` + strings.Repeat(`{"x":0,"y":0,"t":0.5},`, 64) + `{"x":0,"y":0,"t":0.5}]}`,+ } {+ _, list, _ := mindmapTestTree()+ original := `{"version":1,"nodes":{"deleted":{}},"relations":[{"id":"r","from":"a","to":"b","label":"","route":` + route + `}]}`+ list.SetIALAttr(listMindmapMetadataAttr, original)+ if next, changed := pruneListMindmapMetadata(list); changed || next != original {+ t.Fatalf("unsupported or corrupt route was changed: %s", next)+ }+ }+}+func TestPruneListMindmapExcludesListsInsideContentBlocks(t *testing.T) {_, list, child := mindmapTestTree()quote := &ast.Node{Type: ast.NodeBlockquote, ID: "quote"}@@ -79,7 +99,8 @@ func TestPruneListMindmapPreservesInvalidMetadata(t *testing.T) {func TestNormalizeListMindmapTransactions(t *testing.T) {for _, withUndo := range []bool{false, true} {tree, list, child := mindmapTestTree()- original := `{"version":1,"nodes":{"child":{"bold":true}},"relations":[{"id":"r","from":"` + list.ID + `","to":"child","label":""}]}`+ original := `{"version":1,"nodes":{"child":{"bold":true}},"relations":[{"id":"r","from":"` + list.ID + `","to":"child","label":"",` ++ `"route":{"version":1,"points":[{"x":-35,"y":20.5,"t":0.5}]}}]}`list.SetIALAttr(listMindmapMetadataAttr, original)parent := child.Parentchild.Unlink()