Skip to content

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

:sparkles: Support bracket summaries in mind map blocks https://github.com/siyuan-note/siyuan/issues/19871

Daniel6d7dde40d2f8
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index a807b3e46a..c405bad86a 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "ملخص",
+ "listMindmapSummarySelect": "حدد آخر عقدة شقيقة في نطاق الملخص؛ لا يمكن أن تتداخل الملخصات",
"mcpOAuthServer": "OAuth لخادم MCP",
"mcpOAuthTip": "يتطلب كلمة مرور قفل الشاشة أو تسجيل دخول OIDC وأصل HTTPS عامًا؛ يؤدي التعطيل أو تغيير الأصل إلى إلغاء جميع التفويضات",
"mcpOAuthPublicURL": "أصل HTTPS العام",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 6c248a9114..4bd814f618 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Zusammenfassung",
+ "listMindmapSummarySelect": "Wähle den letzten gleichgeordneten Knoten des Bereichs; Zusammenfassungen dürfen sich nicht überschneiden",
"mcpOAuthServer": "OAuth für MCP-Server",
"mcpOAuthTip": "Erfordert ein Sperrbildschirmpasswort oder eine OIDC-Anmeldung und einen öffentlichen HTTPS-Ursprung; Deaktivieren oder Ändern des Ursprungs widerruft alle Autorisierungen",
"mcpOAuthPublicURL": "Öffentlicher HTTPS-Ursprung",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 6c1e6077a6..6984eccd26 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Summary",
+ "listMindmapSummarySelect": "Select the last sibling node in the summary range; summaries cannot overlap",
"mcpOAuthServer": "MCP server OAuth",
"mcpOAuthTip": "Requires a lock screen password or OIDC login and a public HTTPS origin; disabling or changing the origin revokes all authorizations",
"mcpOAuthPublicURL": "Public HTTPS origin",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index d84b50e88e..3ac6348945 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Resumen",
+ "listMindmapSummarySelect": "Selecciona el último nodo del mismo nivel del rango; los resúmenes no pueden superponerse",
"mcpOAuthServer": "OAuth del servidor MCP",
"mcpOAuthTip": "Requiere una contraseña de bloqueo o inicio de sesión OIDC y un origen HTTPS público; desactivarlo o cambiar el origen revoca todas las autorizaciones",
"mcpOAuthPublicURL": "Origen HTTPS público",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 5711adf88d..5e1542ac80 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Résumé",
+ "listMindmapSummarySelect": "Sélectionnez le dernier nœud de même parent dans la plage ; les résumés ne peuvent pas se chevaucher",
"mcpOAuthServer": "OAuth du serveur MCP",
"mcpOAuthTip": "Nécessite un mot de passe de verrouillage ou une connexion OIDC et une origine HTTPS publique ; désactiver ou modifier cette origine révoque toutes les autorisations",
"mcpOAuthPublicURL": "Origine HTTPS publique",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index bdecc12b93..53615311a8 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "סיכום",
+ "listMindmapSummarySelect": "יש לבחור את הצומת האח האחרון בטווח הסיכום; סיכומים אינם יכולים לחפוף",
"mcpOAuthServer": "OAuth של שרת MCP",
"mcpOAuthTip": "נדרשים סיסמת נעילת מסך או כניסת OIDC ומקור HTTPS ציבורי; השבתה או שינוי המקור מבטלים את כל ההרשאות",
"mcpOAuthPublicURL": "מקור HTTPS ציבורי",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index d37ce90944..0defa27058 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "सारांश",
+ "listMindmapSummarySelect": "सारांश के दायरे में समान मूल नोड वाला अंतिम नोड चुनें; सारांशों के दायरे आपस में नहीं मिलने चाहिए",
"mcpOAuthServer": "MCP सर्वर OAuth",
"mcpOAuthTip": "लॉक स्क्रीन पासवर्ड या OIDC लॉगिन और सार्वजनिक HTTPS ओरिजिन आवश्यक है; बंद करने या ओरिजिन बदलने से सभी प्राधिकरण रद्द हो जाते हैं",
"mcpOAuthPublicURL": "सार्वजनिक HTTPS ओरिजिन",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 9c86af516f..88ef828b3e 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Ringkasan",
+ "listMindmapSummarySelect": "Pilih simpul terakhir dengan induk yang sama dalam rentang ringkasan; ringkasan tidak boleh tumpang tindih",
"mcpOAuthServer": "OAuth server MCP",
"mcpOAuthTip": "Memerlukan kata sandi layar kunci atau login OIDC dan origin HTTPS publik; menonaktifkan atau mengubah origin mencabut semua otorisasi",
"mcpOAuthPublicURL": "Origin HTTPS publik",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index fc653fe785..64d6b3d6e7 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Riepilogo",
+ "listMindmapSummarySelect": "Seleziona l'ultimo nodo con lo stesso genitore nell'intervallo; i riepiloghi non possono sovrapporsi",
"mcpOAuthServer": "OAuth del server MCP",
"mcpOAuthTip": "Richiede una password di blocco o un accesso OIDC e un’origine HTTPS pubblica; disattivare o modificare l’origine revoca tutte le autorizzazioni",
"mcpOAuthPublicURL": "Origine HTTPS pubblica",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 6fc5d49a8b..81c6497a5e 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "要約",
+ "listMindmapSummarySelect": "要約範囲の末端にある同じ親のノードを選択してください。要約範囲は重複できません",
"mcpOAuthServer": "MCP サーバー OAuth",
"mcpOAuthTip": "画面ロックのパスワードまたは OIDC ログインと公開 HTTPS オリジンが必要です。無効化またはオリジンの変更で全認可が取り消されます",
"mcpOAuthPublicURL": "公開 HTTPS オリジン",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 3592e2bdba..6779b34970 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "요약",
+ "listMindmapSummarySelect": "요약 범위에서 부모가 같은 마지막 노드를 선택하세요. 요약 범위는 겹칠 수 없습니다",
"mcpOAuthServer": "MCP 서버 OAuth",
"mcpOAuthTip": "화면 잠금 암호 또는 OIDC 로그인과 공개 HTTPS 출처가 필요하며, 비활성화하거나 출처를 변경하면 모든 승인이 취소됩니다",
"mcpOAuthPublicURL": "공개 HTTPS 출처",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index df7a3380bd..b9392c33a3 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Samenvatting",
+ "listMindmapSummarySelect": "Selecteer de laatste knoop met dezelfde ouder in het bereik; samenvattingen mogen niet overlappen",
"mcpOAuthServer": "OAuth voor MCP-server",
"mcpOAuthTip": "Vereist een vergrendelwachtwoord of OIDC-aanmelding en een openbare HTTPS-oorsprong; uitschakelen of wijzigen van de oorsprong trekt alle machtigingen in",
"mcpOAuthPublicURL": "Openbare HTTPS-oorsprong",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index f14258449f..2a4f3c2578 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Podsumowanie",
+ "listMindmapSummarySelect": "Wybierz ostatni węzeł o tym samym rodzicu w zakresie; podsumowania nie mogą się nakładać",
"mcpOAuthServer": "OAuth serwera MCP",
"mcpOAuthTip": "Wymaga hasła blokady lub logowania OIDC oraz publicznego adresu HTTPS; wyłączenie lub zmiana adresu cofa wszystkie autoryzacje",
"mcpOAuthPublicURL": "Publiczny adres HTTPS",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index b8f8dcc5d5..875de75e87 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Resumo",
+ "listMindmapSummarySelect": "Selecione o último nó com o mesmo pai no intervalo; os resumos não podem se sobrepor",
"mcpOAuthServer": "OAuth do servidor MCP",
"mcpOAuthTip": "Exige uma senha de bloqueio ou login OIDC e uma origem HTTPS pública; desativar ou alterar a origem revoga todas as autorizações",
"mcpOAuthPublicURL": "Origem HTTPS pública",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index c9972000eb..90f9d31823 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Обобщение",
+ "listMindmapSummarySelect": "Выберите последний узел с тем же родителем в диапазоне; обобщения не могут пересекаться",
"mcpOAuthServer": "OAuth сервера MCP",
"mcpOAuthTip": "Требуется пароль блокировки или вход через OIDC и публичный адрес HTTPS; отключение или изменение адреса отзывает все разрешения",
"mcpOAuthPublicURL": "Публичный адрес HTTPS",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 445ebec2c5..005aadc214 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Súhrn",
+ "listMindmapSummarySelect": "Vyberte posledný uzol s rovnakým rodičom v rozsahu; súhrny sa nesmú prekrývať",
"mcpOAuthServer": "OAuth servera MCP",
"mcpOAuthTip": "Vyžaduje heslo uzamknutia alebo prihlásenie OIDC a verejný pôvod HTTPS; vypnutie alebo zmena pôvodu odvolá všetky autorizácie",
"mcpOAuthPublicURL": "Verejný pôvod HTTPS",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index f17f10b78d..954c9d356f 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Сажетак",
+ "listMindmapSummarySelect": "Изаберите последњи чвор са истим родитељем у опсегу; сажеци се не смеју преклапати",
"mcpOAuthServer": "OAuth MCP сервера",
"mcpOAuthTip": "Захтева лозинку за закључавање или OIDC пријаву и јавну HTTPS адресу; искључивање или промена адресе опозива сва овлашћења",
"mcpOAuthPublicURL": "Јавна HTTPS адреса",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 10ef9728ac..110cd1fb7f 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "สรุป",
+ "listMindmapSummarySelect": "เลือกโหนดสุดท้ายที่มีโหนดแม่เดียวกันในช่วงสรุป โดยช่วงสรุปต้องไม่ทับซ้อนกัน",
"mcpOAuthServer": "OAuth ของเซิร์ฟเวอร์ MCP",
"mcpOAuthTip": "ต้องมีรหัสผ่านล็อกหน้าจอหรือการเข้าสู่ระบบ OIDC และต้นทาง HTTPS สาธารณะ การปิดหรือเปลี่ยนต้นทางจะเพิกถอนการอนุญาตทั้งหมด",
"mcpOAuthPublicURL": "ต้นทาง HTTPS สาธารณะ",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index e30f80fa54..ff7be69031 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Özet",
+ "listMindmapSummarySelect": "Özet aralığında aynı üst düğüme bağlı son düğümü seçin; özetler çakışamaz",
"mcpOAuthServer": "MCP sunucusu OAuth",
"mcpOAuthTip": "Ekran kilidi parolası veya OIDC oturumu ve herkese açık bir HTTPS kaynağı gerektirir; kapatmak veya kaynağı değiştirmek tüm yetkileri iptal eder",
"mcpOAuthPublicURL": "Herkese açık HTTPS kaynağı",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 756c1c7321..ce01d143b3 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "Узагальнення",
+ "listMindmapSummarySelect": "Виберіть останній вузол зі спільним батьківським вузлом у діапазоні; узагальнення не можуть перетинатися",
"mcpOAuthServer": "OAuth сервера MCP",
"mcpOAuthTip": "Потрібен пароль блокування або вхід через OIDC та публічна адреса HTTPS; вимкнення або зміна адреси відкликає всі дозволи",
"mcpOAuthPublicURL": "Публічна адреса HTTPS",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 7f2e3cb0e2..d6bce80bc0 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "概要",
+ "listMindmapSummarySelect": "选择概要范围的末端同级节点,范围不能与已有概要重叠",
"mcpOAuthServer": "MCP 服务端 OAuth",
"mcpOAuthTip": "需要锁屏密码或 OIDC 登录,以及公开的 HTTPS 地址;关闭或修改地址会撤销全部授权",
"mcpOAuthPublicURL": "公开 HTTPS 地址",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 41df7905aa..c2764a82e7 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,6 @@
{
+ "listMindmapSummary": "概要",
+ "listMindmapSummarySelect": "選擇概要範圍的末端同層節點,範圍不能與既有概要重疊",
"mcpOAuthServer": "MCP 伺服器 OAuth",
"mcpOAuthTip": "需要鎖定畫面密碼或 OIDC 登入,以及公開的 HTTPS 網址;停用或修改網址會撤銷全部授權",
"mcpOAuthPublicURL": "公開 HTTPS 網址",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
index 422fddcb12..c3935f8be9 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
@@ -6,7 +6,7 @@
"id": "20200924101225-k254i8g",
"title": "Content Block Type",
"type": "doc",
- "updated": "20260923221935"
+ "updated": "20260926152549"
},
"Children": [
{
@@ -2533,7 +2533,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260921215916-r1kfene",
- "updated": "20260923221935"
+ "updated": "20260926151827"
},
"Children": [
{
@@ -2556,6 +2556,57 @@
}
]
},
+ {
+ "ID": "20260926151827-kkcg79g",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-kkcg79g",
+ "updated": "20260926152549"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Select the first node in a range, click "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Summary"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " in the mind map toolbar, then select the last sibling node to add a bracket and summary text. The range must be contiguous and cannot overlap or contain another summary. These steps also work on mobile. You can also use the up and down arrow keys to select the last node, Enter to confirm the range, and Esc to cancel."
+ }
+ ]
+ },
+ {
+ "ID": "20260926151827-2f033n1",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-2f033n1",
+ "updated": "20260926151827"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Double-click the summary text, or select the summary and use the edit button at the bottom, to edit it. Enter saves and Esc cancels. You can change its color or delete it using the bottom toolbar; Delete also removes the selected summary. These changes support undo and redo."
+ }
+ ]
+ },
+ {
+ "ID": "20260926151827-z49ph4y",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-z49ph4y",
+ "updated": "20260926151827"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Converting to a list hides the summary but preserves its data; converting back restores it. Nodes inserted inside the range are included automatically. Removing or moving members out shrinks the range; one remaining member keeps the summary, while removing all members removes it. Summary text is an annotation, not an independently searchable or referenceable block. SiYuan-format HTML and PDF previews display summaries."
+ }
+ ]
+ },
{
"ID": "20210104091538-wqiaxdu",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
index 5cdded2b17..cf10960b96 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
@@ -7,7 +7,7 @@
"id": "20200924100950-9op5xi1",
"title": "Shortcuts",
"type": "doc",
- "updated": "20260926131843"
+ "updated": "20260926152753"
},
"Children": [
{
@@ -12577,7 +12577,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260921105011-4zeuyl4",
- "updated": "20260925094732"
+ "updated": "20260926152753"
},
"HeadingLevel": 3,
"Children": [
@@ -13082,6 +13082,20 @@
}
]
},
+ {
+ "ID": "20260926152753-8trdt10",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926152753-8trdt10",
+ "updated": "20260926152753"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "While selecting a summary range, use the up and down arrow keys to select the last sibling node, Enter to confirm, and Esc to cancel. While editing summary text, Enter saves and Esc cancels. Delete or Backspace removes the selected summary."
+ }
+ ]
+ },
{
"ID": "20210106154319-jeh8w1g",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
index 90551ef6aa..c43640507b 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
@@ -6,7 +6,7 @@
"id": "20200905090211-2vixtlf",
"title": "内容块类型",
"type": "doc",
- "updated": "20260923221935"
+ "updated": "20260926152549"
},
"Children": [
{
@@ -2612,7 +2612,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260921215916-j34ty5i",
- "updated": "20260923221935"
+ "updated": "20260926151827"
},
"Children": [
{
@@ -2635,6 +2635,57 @@
}
]
},
+ {
+ "ID": "20260926151827-8wl1iml",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-8wl1iml",
+ "updated": "20260926152549"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "选中范围的第一个节点,点击脑图工具栏中的 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "概要"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",再选择末端同级节点,即可添加方括号和概要文字。范围必须连续,不能与已有概要重叠或嵌套。移动端也可按相同步骤操作。选择范围时也可使用上下方向键选择末端节点,Enter 确认范围,Esc 取消。"
+ }
+ ]
+ },
+ {
+ "ID": "20260926151827-csjz6es",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-csjz6es",
+ "updated": "20260926151827"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "双击概要文字,或选中概要后点击底部的编辑按钮,即可修改文字;Enter 保存,Esc 取消。可以通过底部工具栏修改颜色或删除概要,也可以按 Delete 删除选中的概要。这些操作均支持撤销和重做。"
+ }
+ ]
+ },
+ {
+ "ID": "20260926151827-bcv3d7b",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-bcv3d7b",
+ "updated": "20260926151827"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "转成列表后,概要隐藏但数据保留,转回脑图后恢复显示。范围内插入的节点自动纳入概要,删除成员或将成员移出范围会缩小范围;剩一个成员仍保留概要,全部删除时一并删除概要。概要文字属于附加说明,不作为可独立搜索或引用的正文块。思源格式的 HTML 和 PDF 预览会显示概要。"
+ }
+ ]
+ },
{
"ID": "20210104090624-n9anlgh",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
index e50ad910df..2ed57dff69 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
@@ -7,7 +7,7 @@
"id": "20200813004551-gm0pbn1",
"title": "快捷键",
"type": "doc",
- "updated": "20260926131843"
+ "updated": "20260926152753"
},
"Children": [
{
@@ -12567,7 +12567,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260921105011-hmrchvc",
- "updated": "20260925094732"
+ "updated": "20260926152753"
},
"HeadingLevel": 3,
"Children": [
@@ -13160,6 +13160,20 @@
}
]
},
+ {
+ "ID": "20260926152753-tamny2o",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926152753-tamny2o",
+ "updated": "20260926152753"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "选择概要范围时,使用上下方向键选择末端同级节点,Enter 确认,Esc 取消。编辑概要文字时,Enter 保存,Esc 取消。选中概要后,Delete 或 Backspace 删除概要。"
+ }
+ ]
+ },
{
"ID": "20201227133317-xpgtzbg",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
index 7e636c5748..7efd12a293 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
@@ -6,7 +6,7 @@
"id": "20211226120147-ib6yy3i",
"title": "內容區塊類型",
"type": "doc",
- "updated": "20260923221935"
+ "updated": "20260926152549"
},
"Children": [
{
@@ -2548,7 +2548,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260921215916-cfx2ewc",
- "updated": "20260923221935"
+ "updated": "20260926151827"
},
"Children": [
{
@@ -2571,6 +2571,57 @@
}
]
},
+ {
+ "ID": "20260926151827-6pycwgr",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-6pycwgr",
+ "updated": "20260926152549"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "選取範圍的第一個節點,點選心智圖工具列中的 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "概要"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",再選擇末端同層節點,即可新增方括號與概要文字。範圍必須連續,不能與既有概要重疊或巢狀包含。行動端也可依相同步驟操作。選擇範圍時也可使用上下方向鍵選擇末端節點,Enter 確認範圍,Esc 取消。"
+ }
+ ]
+ },
+ {
+ "ID": "20260926151827-nenflr8",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-nenflr8",
+ "updated": "20260926151827"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "按兩下概要文字,或選取概要後點選底部的編輯按鈕,即可修改文字;Enter 儲存,Esc 取消。可以透過底部工具列修改顏色或刪除概要,也可以按 Delete 刪除選取的概要。這些操作皆支援復原與重做。"
+ }
+ ]
+ },
+ {
+ "ID": "20260926151827-99amoq6",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-99amoq6",
+ "updated": "20260926151827"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "轉成列表後,概要隱藏但資料保留,轉回心智圖後恢復顯示。範圍內插入的節點自動納入概要,刪除成員或將成員移出範圍會縮小範圍;剩一個成員仍保留概要,全部刪除時一併刪除概要。概要文字屬於附加說明,不作為可獨立搜尋或引用的正文區塊。思源格式的 HTML 與 PDF 預覽會顯示概要。"
+ }
+ ]
+ },
{
"ID": "20211226120227-ot6klof",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
index 9cca948db3..4499f223ae 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
@@ -7,7 +7,7 @@
"id": "20211226122549-jktxego",
"title": "快捷鍵",
"type": "doc",
- "updated": "20260926131843"
+ "updated": "20260926152753"
},
"Children": [
{
@@ -12573,7 +12573,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260921105011-z0oyw36",
- "updated": "20260925094732"
+ "updated": "20260926152753"
},
"HeadingLevel": 3,
"Children": [
@@ -13078,6 +13078,20 @@
}
]
},
+ {
+ "ID": "20260926152753-0k1m0f6",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926152753-0k1m0f6",
+ "updated": "20260926152753"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "選擇概要範圍時,使用上下方向鍵選擇末端同層節點,Enter 確認,Esc 取消。編輯概要文字時,Enter 儲存,Esc 取消。選取概要後,Delete 或 Backspace 刪除概要。"
+ }
+ ]
+ },
{
"ID": "20211226122652-x2dmpab",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
index aa1adc6f80..7cdfbd360e 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
@@ -9,7 +9,7 @@
"id": "20240530101000-xsbxokr",
"title": "ショートカット",
"type": "doc",
- "updated": "20260926131843"
+ "updated": "20260926152753"
},
"Children": [
{
@@ -12527,7 +12527,7 @@
"Type": "NodeHeading",
"Properties": {
"id": "20260921105011-icqlkb6",
- "updated": "20260925094732"
+ "updated": "20260926152753"
},
"HeadingLevel": 3,
"Children": [
@@ -13032,6 +13032,20 @@
}
]
},
+ {
+ "ID": "20260926152753-5vwcnw1",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926152753-5vwcnw1",
+ "updated": "20260926152753"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "要約範囲の選択中は上下の矢印キーで同じ親を持つ末端のノードを選び、Enter で確定、Esc でキャンセルします。要約テキストの編集中は Enter で保存、Esc でキャンセルします。選択中の要約は Delete または Backspace で削除できます。"
+ }
+ ]
+ },
{
"ID": "20240530101000-9x0xqew",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
index 402417a4b7..8fecdf78fa 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-35bbvcx",
"title": "コンテンツブロックの種類",
"type": "doc",
- "updated": "20260923221935"
+ "updated": "20260926152549"
},
"Children": [
{
@@ -2699,7 +2699,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20260921215916-odykie5",
- "updated": "20260923221935"
+ "updated": "20260926151827"
},
"Children": [
{
@@ -2722,6 +2722,57 @@
}
]
},
+ {
+ "ID": "20260926151827-vknoaqd",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-vknoaqd",
+ "updated": "20260926152549"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "範囲の最初のノードを選択し、マインドマップのツールバーで "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "要約"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " をクリックしてから、同じ親を持つ末端のノードを選択すると、角括弧と要約テキストを追加できます。範囲は連続している必要があり、既存の要約と重複したり、入れ子にしたりすることはできません。モバイルでも同じ手順で操作できます。範囲の選択中は上下の矢印キーで末端のノードを選び、Enter で範囲を確定し、Esc でキャンセルすることもできます。"
+ }
+ ]
+ },
+ {
+ "ID": "20260926151827-l7l2w92",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-l7l2w92",
+ "updated": "20260926151827"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "要約テキストをダブルクリックするか、要約を選択して下部の編集ボタンを押すと、テキストを編集できます。Enter で保存し、Esc でキャンセルします。下部のツールバーで色の変更や削除ができ、Delete でも選択中の要約を削除できます。これらの操作は元に戻す・やり直しに対応しています。"
+ }
+ ]
+ },
+ {
+ "ID": "20260926151827-fuc3d23",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260926151827-fuc3d23",
+ "updated": "20260926151827"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "リストに変換すると要約は非表示になりますが、データは保持され、マインドマップに戻すと再表示されます。範囲内に挿入したノードは自動的に含まれます。ノードを削除したり範囲外に移動したりすると範囲が縮まり、1 つ残っていれば要約を保持し、すべて削除すると要約も削除します。要約テキストは注釈であり、個別に検索や参照ができる本文ブロックではありません。SiYuan 形式の HTML と PDF プレビューには要約が表示されます。"
+ }
+ ]
+ },
{
"ID": "20240530101000-y5kx7kx",
"Type": "NodeHeading",
diff --git a/app/src/assets/scss/protyle/_mindmap-view.scss b/app/src/assets/scss/protyle/_mindmap-view.scss
index 8c7f9e2a4e..8e51a13b15 100644
--- a/app/src/assets/scss/protyle/_mindmap-view.scss
+++ b/app/src/assets/scss/protyle/_mindmap-view.scss
@@ -649,6 +649,25 @@
}
}
+ &__summary {
+ position: absolute;
+ width: max-content;
+ max-width: 240px;
+ white-space: normal;
+ overflow-wrap: anywhere;
+
+ &--selected {
+ outline: 2px solid var(--b3-theme-primary);
+ outline-offset: 2px;
+ }
+ }
+
+ &__summary-editor {
+ position: absolute;
+ width: 240px;
+ z-index: 6;
+ }
+
&__route-handle {
position: absolute;
z-index: 4;
@@ -801,6 +820,7 @@
}
&__node--selected,
+ &__summary--selected,
&__relation--selected {
outline: none;
}
diff --git a/app/src/protyle/render/listMindmap/fold.test.ts b/app/src/protyle/render/listMindmap/fold.test.ts
index c6d56203b3..d072b6ae8a 100644
--- a/app/src/protyle/render/listMindmap/fold.test.ts
+++ b/app/src/protyle/render/listMindmap/fold.test.ts
@@ -114,6 +114,8 @@ test("batch folding saves a single undo snapshot and reads the source after fini
const context: any = {
canEdit: () => allowed,
readListMindmap: () => ({root, nodes}),
+ getListMindmapSiblingIDs: () => new Map(),
+ normalizeListMindmapSummaryMetadata: () => {},
getListMindmapFoldStates,
cleanListMindmapHTML: (html: string) => html,
updateTransaction: (_owner: unknown, _list: unknown, before: string) => {
diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.ts
index 69cfb0bda9..23bf357ef5 100644
--- a/app/src/protyle/render/listMindmap/index.ts
+++ b/app/src/protyle/render/listMindmap/index.ts
@@ -28,7 +28,7 @@ import {openInlineStyleDialog} from "../../toolbar/inlineStyleDialog";
import {
addListMindmapNode, cleanListMindmapHTML, deleteListMindmapNode,
moveListMindmapNode, readListMindmap, replaceListMindmapContent,
- writeListMindmapMetadata, getListMindmapTabItem, retagMindmapBranch,
+ writeListMindmapMetadata, getListMindmapTabItem, retagMindmapBranch, normalizeListMindmapSummaryMetadata,
} from "./model";
import type {ListMindmapMetadata, ListMindmapModel} from "./model";
import {getListMindmapElements, registerListMindmapRoot, registerListMindmapView} from "./render";
@@ -38,6 +38,7 @@ import {openListMindmapEditor} from "./editor";
import {focusListMindmap} from "./create";
import {getListMindmapFoldStates} from "./fold";
import {isMobile} from "../../../util/functions";
+import {getListMindmapSiblingIDs, getListMindmapSummaryRange} from "./summary";
const roots = new WeakMap<IProtyle, {refresh: () => void, mountNew: (list: HTMLElement) => void,
restoreFocus: (listID: string, candidateIDs: string[]) => void, destroy: () => void}>();
@@ -323,6 +324,32 @@ class ListMindmapController {
onRelationDelete: id => this.metadata(metadata => {
metadata.relations = metadata.relations.filter(item => item.id !== id);
}),
+ onSummaryAdd: async (from, to) => {
+ const id = Lute.NewNodeID();
+ const saved = await this.change(() => {
+ const model = readListMindmap(list);
+ const nodeIds = getListMindmapSummaryRange(model, from, to);
+ if (!nodeIds.length) {
+ return false;
+ }
+ model.metadata.summaries ||= [];
+ model.metadata.summaries.push({id, parentId: model.nodes.get(from).parentId,
+ nodeIds, label: window.siyuan.languages.listMindmapSummary});
+ writeListMindmapMetadata(list, model.metadata);
+ });
+ return saved ? id : undefined;
+ },
+ onSummaryChange: (id, patch, expected) => this.metadata(metadata => {
+ const summary = metadata.summaries?.find(item => item.id === id);
+ if (!summary || (expected !== undefined && JSON.stringify(summary) !== expected)) {
+ showMessage(window.siyuan.languages.listMindmapStale);
+ return false;
+ }
+ Object.assign(summary, patch);
+ }),
+ onSummaryDelete: id => this.metadata(metadata => {
+ metadata.summaries = metadata.summaries?.filter(item => item.id !== id) || [];
+ }),
});
list.dataset.mindmapViewRendered = "true";
this.unregisterVisible = registerListMindmapView(list, this.view, this.host);
@@ -419,9 +446,11 @@ class ListMindmapController {
}
const before = cleanListMindmapHTML(this.list.outerHTML);
try {
+ const previous = getListMindmapSiblingIDs(readListMindmap(this.list));
if (change() === false) {
return false;
}
+ normalizeListMindmapSummaryMetadata(this.list, previous);
updateTransaction(this.owner, this.list, before);
this.refresh();
return true;
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index 49335c1a4d..544f6db963 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -66,6 +66,27 @@ test("manual relation routes are optional, versioned and validated without dropp
}
});
+test("summary metadata is optional and rejects damaged groups while retaining extension fields", () => {
+ const old = '{"version":1,"rootTitle":"Root","nodes":{},"relations":[]}';
+ assert.equal(JSON.stringify(parseListMindmapMetadata(old)), old);
+ const summary = {id: "s", parentId: "root", nodeIds: ["a", "b"], label: "Summary", extension: "keep"};
+ const value = {...JSON.parse(old), summaries: [summary]};
+ assert.equal(JSON.stringify(parseListMindmapMetadata(JSON.stringify(value))), JSON.stringify(value));
+ for (const summaries of [null, {}, [{...summary, nodeIds: []}], [{...summary, nodeIds: ["a", "a"]}],
+ [{...summary, nodeIds: ["root"]}], [{...summary, label: 1}], [{...summary, color: 1}],
+ [summary, {...summary, id: "other"}], [summary, {...summary, nodeIds: ["c"]}]]) {
+ assert.throws(() => parseListMindmapMetadata(JSON.stringify({...value, summaries})), /Invalid list mindmap metadata/);
+ }
+});
+
+test("large summary labels reserve space on both sides of the group", () => {
+ const root = measured("root", 100, 40, [measured("before"), measured("a"), measured("b"), measured("after")]);
+ const {nodes} = layoutListMindmap(root, {summaries: [{nodeIds: ["a", "b"], height: 500}]});
+ const center = (nodes.get("a").y + nodes.get("b").y + 40) / 2;
+ assert.ok(center - 250 > nodes.get("before").y + 40);
+ assert.ok(center + 250 < nodes.get("after").y);
+});
+
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)]),
@@ -128,6 +149,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
const check = require("node:assert/strict");
const api = new Function("mathRender", "Constants", "highlightRender", sourceCode + "; return {readListMindmap, moveListMindmapNode, addListMindmapNode, " +
"deleteListMindmapNode, replaceListMindmapContent, cleanListMindmapHTML, convertListMindmapToList, listMindmapConversionSource, remapListMindmapIDs, writeListMindmapMetadata, retagMindmapBranch, " +
+ "getListMindmapSiblingIDs, normalizeListMindmapSummaryMetadata, getListMindmapSummaryRange, " +
"normalizeLegacyMindmapCodes, replaceLegacyMindmapHTML, spinListMindmapDOM, focusListMindmap, " +
"tabsRender, destroyTabsRender, getTabTask, getListMindmapTabItem, convertTabsList, ListMindmapView, registerListMindmapView, resolveVisibleListMindmapBlock};")(
async (element: Element) => {
@@ -2476,14 +2498,15 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
taskParent.append(taskHost);
const operations: {id: string, before: string, after: string}[] = [];
const taskAPI = new Function("readListMindmap", "canEdit", "Constants", "dayjs", "updateTransaction", "showMessage",
- "getListMindmapTabItem", "getTabTask", "cleanListMindmapHTML",
+ "getListMindmapTabItem", "getTabTask", "cleanListMindmapHTML", "getListMindmapSiblingIDs", "normalizeListMindmapSummaryMetadata",
taskSource + "; return {setTaskListItemMarker, nextTaskListMarker, nextTaskListStatus, TaskController};")(
api.readListMindmap, (owner: any) => !owner.disabled && !owner.history && !owner.embedded,
{CB_GET_HISTORY: "history", ATTRIBUTE_EDITING: "data-editing"},
() => ({format: () => "20260920000000"}),
(_owner: unknown, element: HTMLElement, before: string) => operations.push({id: element.dataset.nodeId,
before, after: api.cleanListMindmapHTML(element.outerHTML)}), () => check.fail("Task update failed"),
- api.getListMindmapTabItem, api.getTabTask, api.cleanListMindmapHTML);
+ api.getListMindmapTabItem, api.getTabTask, api.cleanListMindmapHTML,
+ api.getListMindmapSiblingIDs, api.normalizeListMindmapSummaryMetadata);
const owner = {disabled: false, history: false, embedded: false, options: {action: [] as string[]}};
let finishTask: boolean | Promise<boolean> = true;
let menus = 0;
@@ -2851,6 +2874,111 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
dragParent.remove();
taskStyle.remove();
hostParent.remove();
+
+ // 概要的触屏点选、编辑、复制及列表往返使用真实 DOM 和 Lute。
+ const summaryList = reset("- Root\n - First\n - Descendant\n - Second\n - Third\n");
+ const summaryModel = api.readListMindmap(summaryList);
+ const summaryIds = summaryModel.root.children.map((node: ListMindmapNode) => node.id);
+ const summaryHost = document.createElement("div");
+ summaryHost.style.width = "700px";
+ document.body.append(summaryHost);
+ let summaryView: any;
+ summaryView = new api.ListMindmapView({host: summaryHost, model: summaryModel, onExit: () => {},
+ labels: new Proxy({}, {get: (_target, key) => String(key)}),
+ onSummaryAdd: async (from: string, to: string) => {
+ const model = api.readListMindmap(summaryList);
+ const nodeIds = api.getListMindmapSummaryRange(model, from, to);
+ check.equal(nodeIds.length, 3);
+ model.metadata.summaries = [{id: "summary", parentId: model.root.id, nodeIds, label: "Summary"}];
+ api.writeListMindmapMetadata(summaryList, model.metadata);
+ summaryView.update(api.readListMindmap(summaryList));
+ return "summary";
+ },
+ onSummaryChange: (id: string, patch: object, expected: string) => {
+ const model = api.readListMindmap(summaryList);
+ const summary = model.metadata.summaries.find((item: {id: string}) => item.id === id);
+ check.equal(JSON.stringify(summary), expected);
+ Object.assign(summary, patch);
+ api.writeListMindmapMetadata(summaryList, model.metadata);
+ summaryView.update(api.readListMindmap(summaryList));
+ }});
+ await settle();
+ summaryView.focusNode(summaryIds[0]);
+ const summaryButton = summaryHost.querySelector<HTMLButtonElement>('[aria-label="listMindmapSummary"]');
+ check.equal(summaryButton.disabled, false);
+ summaryButton.click();
+ check.equal(summaryButton.getAttribute("aria-pressed"), "true");
+ summaryHost.querySelector(`[data-mindmap-id="${summaryIds[2]}"]`).dispatchEvent(new PointerEvent("pointerdown",
+ {bubbles: true, pointerId: 71, pointerType: "touch", isPrimary: true, button: 0}));
+ await settle();
+ await settle();
+ const summaryInput = summaryHost.querySelector<HTMLInputElement>(".mindmap-view__summary-editor");
+ check.ok(summaryInput, "new summaries enter text editing on touch selection");
+ summaryInput.value = "<script>plain text</script> " + "Long summary ".repeat(25);
+ summaryInput.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));
+ await settle();
+ const summaryLabel = summaryHost.querySelector<HTMLElement>(".mindmap-view__summary");
+ check.ok(summaryLabel.textContent.startsWith("<script>"));
+ check.equal(summaryLabel.querySelector("script"), null);
+ const savedSummary = api.readListMindmap(summaryList).metadata.summaries[0];
+ const originalIDs = ids(summaryList);
+ api.retagMindmapBranch(summaryList, true);
+ const plain = api.convertListMindmapToList(summaryList, "UL2OL", lute);
+ const converted = document.createElement("div");
+ converted.innerHTML = plain;
+ check.equal(converted.firstElementChild.getAttribute("data-type"), "NodeList");
+ check.deepEqual(api.readListMindmap(converted.firstElementChild).metadata.summaries, [savedSummary]);
+ api.retagMindmapBranch(converted.firstElementChild, true);
+ check.deepEqual(ids(converted.firstElementChild as HTMLElement), originalIDs);
+ check.deepEqual(api.readListMindmap(converted.firstElementChild).metadata.summaries, [savedSummary]);
+ const copied = summaryList.cloneNode(true) as HTMLElement;
+ const copiedIDs = new Map<string, string>();
+ [copied, ...Array.from(copied.querySelectorAll<HTMLElement>("[data-node-id]"))].forEach(element => {
+ const id = Lute.NewNodeID();
+ copiedIDs.set(element.dataset.nodeId, id);
+ element.dataset.nodeId = id;
+ });
+ api.remapListMindmapIDs(copied, copiedIDs);
+ const copiedSummary = api.readListMindmap(copied).metadata.summaries[0];
+ check.equal(copiedSummary.parentId, copiedIDs.get(savedSummary.parentId));
+ check.deepEqual(copiedSummary.nodeIds, savedSummary.nodeIds.map((id: string) => copiedIDs.get(id)));
+ const keyboardModel = api.readListMindmap(summaryList);
+ keyboardModel.metadata.summaries = [];
+ api.writeListMindmapMetadata(summaryList, keyboardModel.metadata);
+ summaryView.update(api.readListMindmap(summaryList));
+ summaryView.focusNode(summaryIds[0]);
+ summaryButton.click();
+ for (const key of ["ArrowDown", "ArrowDown", "Enter"]) {
+ summaryHost.dispatchEvent(new KeyboardEvent("keydown", {key, bubbles: true}));
+ }
+ await settle();
+ await settle();
+ const keyboardInput = summaryHost.querySelector<HTMLInputElement>(".mindmap-view__summary-editor");
+ check.ok(keyboardInput, "keyboard range selection creates an editable summary");
+ keyboardInput.value = savedSummary.label;
+ keyboardInput.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));
+ await settle();
+ summaryView.destroy();
+ summaryHost.style.width = "280px";
+ summaryView = new api.ListMindmapView({host: summaryHost, model: api.readListMindmap(summaryList),
+ readOnly: true, printLayout: true, onExit: () => {}});
+ await settle();
+ await settle();
+ const printedLabel = summaryHost.querySelector<HTMLElement>(".mindmap-view__summary");
+ const printedBounds = printedLabel.getBoundingClientRect();
+ const printViewport = summaryHost.querySelector(".mindmap-view__viewport").getBoundingClientRect();
+ check.ok(printedBounds.right <= printViewport.right + 1, "narrow PDF previews include the full summary width");
+ check.ok(printedBounds.bottom <= printViewport.bottom + 1, "PDF previews include tall summary labels");
+ printedLabel.dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));
+ check.equal(summaryHost.querySelector(".mindmap-view__summary-editor"), null);
+ check.equal(summaryHost.querySelector('[aria-label="listMindmapSummary"]'), null);
+ summaryView.destroy();
+ summaryHost.remove();
+ api.deleteListMindmapNode(summaryList, summaryIds[0]);
+ api.deleteListMindmapNode(summaryList, summaryIds[1]);
+ check.deepEqual(api.readListMindmap(summaryList).metadata.summaries[0].nodeIds, [summaryIds[2]]);
+ api.deleteListMindmapNode(summaryList, summaryIds[2]);
+ check.deepEqual(api.readListMindmap(summaryList).metadata.summaries, []);
style.remove();
return "List mindmap DOM cases passed";
};
@@ -2920,12 +3048,13 @@ test("list mindmap mutations preserve block data in the real DOM and Lute", {
"return {tabsRender, destroyTabsRender, getTabTask, revealTabsForTarget};})();\n";
const source = tabsSource + compile(path.join(__dirname, "../../wysiwyg/tabsList.ts")) +
compile(path.join(__dirname, "../av/richTextValue.ts")) + compile(path.join(__dirname, "../../wysiwyg/listContext.ts")) +
- compile(path.join(__dirname, "model.ts")) + compile(path.join(__dirname, "fold.ts")) +
+ compile(path.join(__dirname, "summary.ts")) + compile(path.join(__dirname, "model.ts")) + compile(path.join(__dirname, "fold.ts")) +
compile(path.join(__dirname, "routing.ts")) + compile(path.join(__dirname, "pan.ts")) +
compile(path.join(__dirname, "view.ts")) +
compile(path.join(__dirname, "legacy.ts")) + compile(path.join(__dirname, "migrate.ts")) +
compile(path.join(__dirname, "create.ts")) + compile(path.join(__dirname, "render.ts"));
const css = require("sass").compile(path.resolve(__dirname, "../../../assets/scss/business/_block.scss")).css +
+ require("sass").compile(path.resolve(__dirname, "../../../assets/scss/component/_button.scss")).css +
require("sass").compile(path.resolve(__dirname, "../../../assets/scss/business/_color.scss")).css +
require("sass").compile(path.resolve(__dirname, "../../../assets/scss/component/_tooltips.scss")).css +
require("sass").compile(path.resolve(__dirname, "../../../assets/scss/protyle/_mindmap-view.scss")).css;
diff --git a/app/src/protyle/render/listMindmap/model.ts b/app/src/protyle/render/listMindmap/model.ts
index c4352ca8b0..07f160abd9 100644
--- a/app/src/protyle/render/listMindmap/model.ts
+++ b/app/src/protyle/render/listMindmap/model.ts
@@ -1,6 +1,8 @@
import {Constants} from "../../../constants";
import {getOrderedListMarkerUpdates} from "../../wysiwyg/listContext";
import type {MindmapManualRoute} from "./routing";
+import {getListMindmapSiblingIDs, normalizeListMindmapSummaries} from "./summary";
+import type {ListMindmapSummary} from "./summary";
export interface ListMindmapNodeStyle {
textColor?: string;
@@ -32,6 +34,7 @@ export interface ListMindmapMetadata {
rootTitle?: string;
nodes: Record<string, ListMindmapNodeStyle>;
relations: ListMindmapRelation[];
+ summaries?: ListMindmapSummary[];
}
export interface ListMindmapNode {
@@ -128,6 +131,28 @@ export const parseListMindmapMetadata = (value: string | null): ListMindmapMetad
}
relationIds.add(relation.id);
}
+ if ("summaries" in data) {
+ if (!Array.isArray(data.summaries)) {
+ throw invalidMetadata();
+ }
+ const summaryIds = new Set<string>();
+ const members = new Set<string>();
+ for (const summary of data.summaries) {
+ if (!isRecord(summary) || typeof summary.id !== "string" || !summary.id || summaryIds.has(summary.id) ||
+ typeof summary.parentId !== "string" || !summary.parentId || typeof summary.label !== "string" ||
+ !Array.isArray(summary.nodeIds) || !summary.nodeIds.length ||
+ ("color" in summary && typeof summary.color !== "string")) {
+ throw invalidMetadata();
+ }
+ summaryIds.add(summary.id);
+ for (const id of summary.nodeIds) {
+ if (typeof id !== "string" || !id || id === summary.parentId || members.has(id)) {
+ throw invalidMetadata();
+ }
+ members.add(id);
+ }
+ }
+ }
return data as unknown as ListMindmapMetadata;
};
@@ -179,11 +204,18 @@ export const remapListMindmapIDs = (root: Element, ids: Map<string, string>) =>
}
nodes[mappedId] = style;
});
- return {list, metadata: {...metadata, nodes, relations: metadata.relations.map(relation => ({
+ const copied = {...metadata, nodes, relations: metadata.relations.map(relation => ({
...relation,
from: ids.get(relation.from) || relation.from,
to: ids.get(relation.to) || relation.to,
- })).filter(relation => validIds.has(relation.from) && validIds.has(relation.to))}};
+ })).filter(relation => validIds.has(relation.from) && validIds.has(relation.to))};
+ if (metadata.summaries) {
+ copied.summaries = metadata.summaries.map(summary => ({...summary,
+ parentId: ids.get(summary.parentId) || summary.parentId,
+ nodeIds: summary.nodeIds.map(id => ids.get(id) || id).filter(id => validIds.has(id)),
+ })).filter(summary => validIds.has(summary.parentId) && summary.nodeIds.length > 0);
+ }
+ return {list, metadata: copied};
});
updates.forEach(({list, metadata}) => list.setAttribute(Constants.CUSTOM_SY_LIST_MINDMAP_DATA, JSON.stringify(metadata)));
cleanListMindmapDOM(root);
@@ -318,6 +350,7 @@ export const layoutListMindmap = (root: ListMindmapLayoutNode, options: {
padding?: number;
horizontalGaps?: Map<string, number>;
verticalGaps?: Map<string, number>;
+ summaries?: {nodeIds: string[], height: number}[];
} = {}) => {
const horizontalGap = options.horizontalGap ?? 40;
const verticalGap = options.verticalGap ?? 24;
@@ -347,6 +380,20 @@ export const layoutListMindmap = (root: ListMindmapLayoutNode, options: {
const heights = new Map<string, number>();
[...ordered].reverse().forEach(({node}) => {
const children = node.collapsed ? [] : node.children;
+ (options.summaries || []).forEach(summary => {
+ const start = children.findIndex(child => child.id === summary.nodeIds[0]);
+ if (start < 0 || !summary.nodeIds.every((id, index) => children[start + index]?.id === id)) {
+ return;
+ }
+ const total = summary.nodeIds.reduce((sum, id, index) => sum + heights.get(id) + (index ? gapBefore(id) : 0), 0);
+ if (summary.height + 16 > total) {
+ const extra = (summary.height + 16 - total) / 2;
+ const first = summary.nodeIds[0];
+ const last = summary.nodeIds[summary.nodeIds.length - 1];
+ heights.set(first, heights.get(first) + extra);
+ heights.set(last, heights.get(last) + extra);
+ }
+ });
const childHeight = children.reduce((sum, child, index) => sum + heights.get(child.id) +
(index ? gapBefore(child.id) : 0), 0);
heights.set(node.id, Math.max(node.height, childHeight));
@@ -507,9 +554,23 @@ export const moveListMindmapNode = (list: HTMLElement, sourceId: string, targetI
normalizeList(oldList, oldStart);
}
}
+ normalizeListMindmapSummaryMetadata(list, getListMindmapSiblingIDs(model), new Set([sourceId]));
return true;
};
+export const normalizeListMindmapSummaryMetadata = (list: HTMLElement, previous: Map<string, string[]>,
+ moved?: Set<string>) => {
+ const model = readListMindmap(list);
+ if (!model.metadata.summaries) {
+ return;
+ }
+ const summaries = normalizeListMindmapSummaries(model.metadata.summaries, getListMindmapSiblingIDs(model), previous, moved);
+ if (JSON.stringify(summaries) !== JSON.stringify(model.metadata.summaries)) {
+ model.metadata.summaries = summaries;
+ writeListMindmapMetadata(list, model.metadata);
+ }
+};
+
export const addListMindmapNode = (list: HTMLElement, targetId: string, placement: ListMindmapPlacement,
item: HTMLElement, createListId = () => Lute.NewNodeID()): boolean => {
const model = readListMindmap(list);
@@ -535,6 +596,7 @@ export const addListMindmapNode = (list: HTMLElement, targetId: string, placemen
const start = getListStart(destination);
insertItem(destination, item, model.nodes.get(targetId)?.element, placement);
normalizeList(destination, start);
+ normalizeListMindmapSummaryMetadata(list, getListMindmapSiblingIDs(model));
return true;
};
@@ -561,6 +623,7 @@ export const deleteListMindmapNode = (list: HTMLElement, id: string): boolean =>
!removedIds.has(relation.from) && !removedIds.has(relation.to));
if (list.hasAttribute(Constants.CUSTOM_SY_LIST_MINDMAP_DATA)) {
writeListMindmapMetadata(list, model.metadata);
+ normalizeListMindmapSummaryMetadata(list, getListMindmapSiblingIDs(model));
}
return true;
};
diff --git a/app/src/protyle/render/listMindmap/relation.test.ts b/app/src/protyle/render/listMindmap/relation.test.ts
index 0f5c2b867c..f7203a8e02 100644
--- a/app/src/protyle/render/listMindmap/relation.test.ts
+++ b/app/src/protyle/render/listMindmap/relation.test.ts
@@ -33,6 +33,8 @@ test("manual route save and reset use one transaction and reject stale relation
const list = {isConnected: true, get outerHTML() { return JSON.stringify(data); }};
const context: any = {
canEdit: () => true,
+ getListMindmapSiblingIDs: () => new Map(),
+ normalizeListMindmapSummaryMetadata: () => {},
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,
diff --git a/app/src/protyle/render/listMindmap/summary.test.ts b/app/src/protyle/render/listMindmap/summary.test.ts
new file mode 100644
index 0000000000..70763be9c6
--- /dev/null
+++ b/app/src/protyle/render/listMindmap/summary.test.ts
@@ -0,0 +1,66 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {getListMindmapSummaryRange, layoutListMindmapSummaries, normalizeListMindmapSummaries} from "./summary";
+import type {ListMindmapSummary} from "./summary";
+import type {ListMindmapModel, ListMindmapNode} from "./model";
+
+const summary = (nodeIds = ["a", "b", "c"]): ListMindmapSummary => ({id: "s", parentId: "root", nodeIds, label: "Summary"});
+const siblings = (...ids: string[]) => new Map([["root", ids]]);
+
+test("summary membership follows insertions, removal and moves without absorbing existing outsiders", () => {
+ const original = summary();
+ const before = siblings("a", "b", "c", "d");
+ const normalize = (ids: string[], moved?: string[]) => normalizeListMindmapSummaries([original],
+ siblings(...ids), before, new Set(moved))[0]?.nodeIds;
+ assert.deepEqual(normalize(["a", "new", "b", "c", "d"]), ["a", "new", "b", "c"]);
+ assert.deepEqual(normalize(["new", "a", "b", "c", "d"]), ["a", "b", "c"]);
+ assert.deepEqual(normalize(["a", "c", "d"]), ["a", "c"]);
+ assert.deepEqual(normalize(["c", "d"]), ["c"]);
+ assert.equal(normalize(["d"]), undefined);
+ assert.deepEqual(normalize(["a", "b", "d", "c"], ["c"]), ["a", "b"]);
+ assert.deepEqual(normalize(["b", "a", "c", "d"], ["a"]), ["b", "a", "c"]);
+ assert.deepEqual(original, summary());
+ const pair = [summary(["a", "b"])];
+ assert.deepEqual(normalizeListMindmapSummaries(pair, siblings("b", "d", "a"), before, new Set(["a"]))[0].nodeIds, ["b"]);
+ assert.deepEqual(normalizeListMindmapSummaries(pair, new Map([["other", ["a", "b"]]]), before), []);
+});
+
+const makeModel = (): ListMindmapModel => {
+ const make = (id: string, parentId?: string): ListMindmapNode => ({id, parentId, children: [],
+ contentBlocks: [], virtual: false, collapsed: false});
+ const root = make("root");
+ root.children = [make("a", "root"), make("b", "root"), make("c", "root")];
+ root.children[0].children = [make("nested", "a")];
+ return {list: undefined, root, nodes: new Map([root, ...root.children, ...root.children[0].children].map(node => [node.id, node])),
+ metadata: {version: 1, nodes: {}, relations: []}};
+};
+
+test("summary creation accepts sibling ranges and rejects cross-level, overlapping and nested groups", () => {
+ const model = makeModel();
+ assert.deepEqual(getListMindmapSummaryRange(model, "c", "a"), ["a", "b", "c"]);
+ assert.deepEqual(getListMindmapSummaryRange(model, "a", "nested"), []);
+ assert.deepEqual(getListMindmapSummaryRange(model, "root", "root"), []);
+ model.metadata.summaries = [summary(["a", "b"])];
+ assert.deepEqual(getListMindmapSummaryRange(model, "b", "c"), []);
+ assert.deepEqual(getListMindmapSummaryRange(model, "nested", "nested"), []);
+ assert.deepEqual(getListMindmapSummaryRange(model, "c", "c"), ["c"]);
+});
+
+test("summary brackets cover visible descendants and disappear with their members", () => {
+ const model = makeModel();
+ model.metadata.summaries = [summary(["a", "b"])];
+ const positions = new Map([
+ ["a", {id: "a", x: 100, y: 40, width: 100, height: 40}],
+ ["b", {id: "b", x: 100, y: 160, width: 120, height: 50}],
+ ["nested", {id: "nested", x: 240, y: 20, width: 200, height: 90}],
+ ]);
+ const sizes = new Map([["s", {width: 150, height: 60}]]);
+ const expanded = layoutListMindmapSummaries(model, positions, sizes).get("s");
+ assert.equal(expanded.x, 476);
+ assert.equal(expanded.top, 12);
+ assert.equal(expanded.bottom, 218);
+ positions.delete("nested");
+ assert.equal(layoutListMindmapSummaries(model, positions, sizes).get("s").x, 256);
+ positions.delete("a");
+ assert.equal(layoutListMindmapSummaries(model, positions, sizes).size, 0);
+});
diff --git a/app/src/protyle/render/listMindmap/summary.ts b/app/src/protyle/render/listMindmap/summary.ts
new file mode 100644
index 0000000000..23a6276283
--- /dev/null
+++ b/app/src/protyle/render/listMindmap/summary.ts
@@ -0,0 +1,129 @@
+import type {ListMindmapModel, ListMindmapPosition} from "./model";
+
+export interface ListMindmapSummary {
+ id: string;
+ parentId: string;
+ nodeIds: string[];
+ label: string;
+ color?: string;
+}
+
+export interface ListMindmapSummaryPosition {
+ id: string;
+ x: number;
+ top: number;
+ bottom: number;
+ labelX: number;
+ labelY: number;
+ width: number;
+ height: number;
+}
+
+export const getListMindmapSiblingIDs = (model: ListMindmapModel) => {
+ const siblings = new Map<string, string[]>();
+ siblings.set(model.list.dataset.nodeId, model.root.virtual ? model.root.children.map(node => node.id) : [model.root.id]);
+ model.nodes.forEach(node => {
+ if (node.children.length) {
+ siblings.set(node.id, node.children.map(child => child.id));
+ }
+ });
+ return siblings;
+};
+
+// 新插入的节点只在已有成员之间加入范围;原有范围被拆开时保留未移动成员最多的连续部分。
+export const normalizeListMindmapSummaries = (summaries: ListMindmapSummary[], siblings: Map<string, string[]>,
+ previous = siblings, moved = new Set<string>()) => {
+ const claimed = new Set<string>();
+ return summaries.flatMap(summary => {
+ const members = new Set(summary.nodeIds);
+ const old = new Set(previous.get(summary.parentId) || []);
+ const groups: string[][] = [[]];
+ (siblings.get(summary.parentId) || []).forEach(id => {
+ if (!claimed.has(id) && (members.has(id) || !old.has(id))) {
+ groups[groups.length - 1].push(id);
+ } else if (groups[groups.length - 1].length) {
+ groups.push([]);
+ }
+ });
+ const candidates = groups.map(group => {
+ const start = group.findIndex(id => members.has(id));
+ const end = group.length - 1 - [...group].reverse().findIndex(id => members.has(id));
+ return start < 0 ? [] : group.slice(start, end + 1);
+ });
+ const score = (group: string[]) => group.reduce((count, id) =>
+ count + (members.has(id) ? moved.has(id) ? 1 : summary.nodeIds.length + 1 : 0), 0);
+ const nodeIds = candidates.reduce((best, group) => score(group) > score(best) ? group : best, []);
+ if (!nodeIds.length) {
+ return [];
+ }
+ nodeIds.forEach(id => claimed.add(id));
+ return [{...summary, nodeIds}];
+ });
+};
+
+export const getListMindmapSummaryRange = (model: ListMindmapModel, from: string, to: string) => {
+ const parentId = model.nodes.get(from)?.parentId;
+ if (!parentId || model.nodes.get(to)?.parentId !== parentId) {
+ return [];
+ }
+ const siblings = model.nodes.get(parentId)?.children || [];
+ const start = siblings.findIndex(node => node.id === from);
+ const end = siblings.findIndex(node => node.id === to);
+ if (start < 0 || end < 0) {
+ return [];
+ }
+ const nodeIds = siblings.slice(Math.min(start, end), Math.max(start, end) + 1).map(node => node.id);
+ const related = (a: string, b: string) => {
+ while (a) {
+ if (a === b) {
+ return true;
+ }
+ a = model.nodes.get(a)?.parentId;
+ }
+ return false;
+ };
+ if (model.metadata.summaries?.some(summary => summary.nodeIds.some(member =>
+ nodeIds.some(id => related(member, id) || related(id, member))))) {
+ return [];
+ }
+ return nodeIds;
+};
+
+// 括号包围成员的可见子树,文字尺寸参与边界计算,折叠隐藏的成员不产生独立概要。
+export const layoutListMindmapSummaries = (model: ListMindmapModel, positions: Map<string, ListMindmapPosition>,
+ sizes: Map<string, {width: number, height: number}>) => {
+ const result = new Map<string, ListMindmapSummaryPosition>();
+ (model.metadata.summaries || []).forEach(summary => {
+ const size = sizes.get(summary.id);
+ if (!size || !summary.nodeIds.length || summary.nodeIds.some(id => !positions.has(id))) {
+ return;
+ }
+ const siblings = model.nodes.get(summary.parentId)?.children.map(node => node.id) ||
+ (model.list?.dataset.nodeId === summary.parentId ? [model.root.id] : []);
+ const start = siblings.indexOf(summary.nodeIds[0]);
+ if (start < 0 || !summary.nodeIds.every((id, index) => siblings[start + index] === id)) {
+ return;
+ }
+ let right = 0;
+ let top = Infinity;
+ let bottom = -Infinity;
+ const pending = [...summary.nodeIds];
+ while (pending.length) {
+ const id = pending.pop();
+ const position = positions.get(id);
+ if (!position) {
+ continue;
+ }
+ right = Math.max(right, position.x + position.width);
+ top = Math.min(top, position.y);
+ bottom = Math.max(bottom, position.y + position.height);
+ pending.push(...(model.nodes.get(id)?.children.map(node => node.id) || []));
+ }
+ const center = (top + bottom) / 2;
+ result.set(summary.id, {id: summary.id, x: right + 36,
+ top: Math.min(top - 8, center - size.height / 2),
+ bottom: Math.max(bottom + 8, center + size.height / 2),
+ labelX: right + 60, labelY: center - size.height / 2, ...size});
+ });
+ return result;
+};
diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.ts
index fc6ca41032..6f1f5a1042 100644
--- a/app/src/protyle/render/listMindmap/view.ts
+++ b/app/src/protyle/render/listMindmap/view.ts
@@ -16,6 +16,8 @@ import {destroyTabsRender, tabsRender} from "../tabsRender";
import {getListMindmapFoldStates} from "./fold";
import type {ListMindmapFoldTarget} from "./fold";
import {clampMindmapPanOffset} from "./pan";
+import {getListMindmapSummaryRange, layoutListMindmapSummaries} from "./summary";
+import type {ListMindmapSummary, ListMindmapSummaryPosition} from "./summary";
export interface ListMindmapViewOptions {
host: HTMLElement;
@@ -57,6 +59,9 @@ export interface ListMindmapViewOptions {
onRelationAdd?: (from: string, to: string) => void;
onRelationChange?: (id: string, patch: Partial<ListMindmapRelation>, expected?: string) => void;
onRelationDelete?: (id: string) => void;
+ onSummaryAdd?: (from: string, to: string) => Promise<string | undefined>;
+ onSummaryChange?: (id: string, patch: Pick<Partial<ListMindmapSummary>, "label" | "color">, expected?: string) => void;
+ onSummaryDelete?: (id: string) => void;
onExit: () => void;
}
@@ -105,6 +110,13 @@ export class ListMindmapView {
private readonly nodeElements = new Map<string, HTMLDivElement>();
private readonly previewID = `mindmap-view-${Lute.NewNodeID()}-`;
private readonly relationElements = new Map<string, HTMLButtonElement>();
+ private readonly summaryElements = new Map<string, HTMLButtonElement>();
+ private summaryPositions = new Map<string, ListMindmapSummaryPosition>();
+ private readonly summaryStatus = createElement("div", "mindmap-view__route-status");
+ private selectedSummary?: string;
+ private summaryFrom?: string;
+ private finishSummaryEdit?: (save: boolean) => void;
+ private editingSummary?: string;
private readonly buttons = new Map<string, HTMLButtonElement>();
private readonly folded = new Map<string, boolean>();
private levelSelect?: HTMLSelectElement;
@@ -119,7 +131,7 @@ export class ListMindmapView {
private selectedEdge?: string;
private hoveredLine?: string;
private finishRelationEdit?: (save: boolean) => void;
- private linePaths: {id: string, relation: boolean, path: Path2D, end?: MindmapRoutePoint}[] = [];
+ private linePaths: {id: string, relation: boolean, summary?: boolean, path: Path2D, end?: MindmapRoutePoint}[] = [];
private relationRoutes = new Map<string, MindmapRoutePoint[]>();
private readonly routeHandles = new Map<string, HTMLButtonElement>();
private readonly routeStatus = createElement("div", "mindmap-view__route-status");
@@ -177,6 +189,10 @@ export class ListMindmapView {
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.summaryStatus.hidden = true;
+ this.summaryStatus.setAttribute("role", "status");
+ this.summaryStatus.textContent = this.label("listMindmapSummarySelect");
+ options.host.append(this.summaryStatus);
this.createToolbar();
this.listen(document, "pointerdown", this.dismissControls, {capture: true});
this.listen(options.host, "pointerover", this.showButtonTooltip);
@@ -284,7 +300,8 @@ export class ListMindmapView {
private showButtonTooltip = (event: Event) => {
const button = (event.target as Element).closest<HTMLButtonElement>("button[aria-label]");
- if (!button || !this.options.host.contains(button) || button.classList.contains("mindmap-view__relation")) {
+ if (!button || !this.options.host.contains(button) || button.classList.contains("mindmap-view__relation") ||
+ button.classList.contains("mindmap-view__summary")) {
this.tooltip.hidden = true;
return;
}
@@ -313,35 +330,40 @@ export class ListMindmapView {
private clearSelection() {
this.inspector.hidden = true;
- if (!this.selectedId && !this.selectedRelation && !this.selectedEdge && !this.relationFrom) {
+ if (!this.selectedId && !this.selectedRelation && !this.selectedEdge && !this.relationFrom &&
+ !this.selectedSummary && !this.summaryFrom) {
return;
}
this.selectedId = undefined;
this.selectedRelation = undefined;
this.selectedEdge = undefined;
this.relationFrom = undefined;
+ this.selectedSummary = undefined;
+ this.summaryFrom = undefined;
this.updateSelection();
}
private dismissControls = (event: PointerEvent) => {
const target = event.target as Node;
this.tooltip.hidden = true;
- if (target instanceof Element && target.closest(".mindmap-view__relation-editor, .mindmap-view__route-handle")) {
+ if (target instanceof Element && target.closest(".mindmap-view__relation-editor, .mindmap-view__route-handle, .mindmap-view__summary-editor")) {
return;
}
if (this.inspector.contains(target) || this.buttons.get("style")?.contains(target) ||
this.buttons.get("relation")?.contains(target) || this.buttons.get("expandLevel")?.contains(target) ||
+ this.buttons.get("summary")?.contains(target) ||
this.levelSelect?.contains(target)) {
return;
}
this.inspector.hidden = true;
- const node = target instanceof Element && target.closest(".mindmap-view__node, .mindmap-view__relation");
+ const node = target instanceof Element && target.closest(".mindmap-view__node, .mindmap-view__relation, .mindmap-view__summary");
if (!node || !this.options.host.contains(node)) {
this.clearSelection();
}
};
private finishThen(action: () => void) {
+ this.finishSummaryEdit?.(true);
const finished = this.options.finishEdit?.();
if (finished instanceof Promise) {
void finished.then(result => {
@@ -359,6 +381,8 @@ export class ListMindmapView {
return;
}
this.options.readOnly = value;
+ this.finishSummaryEdit?.(false);
+ this.summaryFrom = undefined;
this.cancelPointer();
this.relationFrom = undefined;
this.inspector.hidden = true;
@@ -389,7 +413,15 @@ export class ListMindmapView {
};
this.toolbar.append(createElement("span", "mindmap-view__spacer fn__flex-1"));
if (!this.options.readOnly) {
+ add("summary", "listMindmapSummary", "iconGroups", () => {
+ this.setPanning(false);
+ this.inspector.hidden = true;
+ this.relationFrom = undefined;
+ this.summaryFrom = this.summaryFrom ? undefined : this.selectedId;
+ this.updateSelection();
+ });
add("relation", "connect", "iconRoute", () => {
+ this.summaryFrom = undefined;
this.setPanning(false);
this.inspector.hidden = true;
this.relationFrom = this.relationFrom ? undefined : this.selectedId;
@@ -453,6 +485,9 @@ export class ListMindmapView {
}
private setPanning(value: boolean) {
+ if (value) {
+ this.summaryFrom = undefined;
+ }
this.panning = value;
this.viewport.classList.toggle("mindmap-view__viewport--pan", value);
const button = this.buttons.get("pan");
@@ -468,6 +503,7 @@ export class ListMindmapView {
return;
}
this.model = model;
+ this.summaryFrom = undefined;
if (this.levelSelect) {
const placeholder = new Option(this.label("expandLevel"), "");
placeholder.disabled = true;
@@ -638,7 +674,12 @@ export class ListMindmapView {
this.selectedEdge = undefined;
this.inspector.hidden = true;
}
+ if (this.selectedSummary && !model.metadata.summaries?.some(summary => summary.id === this.selectedSummary)) {
+ this.selectedSummary = undefined;
+ this.inspector.hidden = true;
+ }
this.updateRelations();
+ this.updateSummaries();
this.updateSelection();
this.renderInspector();
this.refreshLayout();
@@ -740,7 +781,15 @@ export class ListMindmapView {
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);
+ const summarySizes = new Map<string, {width: number, height: number}>();
+ this.summaryElements.forEach((element, id) => {
+ element.hidden = false;
+ summarySizes.set(id, {width: Math.max(1, element.offsetWidth), height: Math.max(1, element.offsetHeight)});
+ });
+ const summaries = (this.model.metadata.summaries || []).map(summary => ({
+ nodeIds: summary.nodeIds, height: summarySizes.get(summary.id)?.height || 0,
+ }));
+ let result = layoutListMindmap(layoutRoot, {summaries});
const horizontalGaps = new Map<string, number>();
const verticalGaps = new Map<string, number>();
const reserve = (gaps: Map<string, number>, id: string, size: number) => {
@@ -781,15 +830,21 @@ export class ListMindmapView {
}
});
if (horizontalGaps.size || verticalGaps.size) {
- result = layoutListMindmap(layoutRoot, {horizontalGaps, verticalGaps});
+ result = layoutListMindmap(layoutRoot, {horizontalGaps, verticalGaps, summaries});
}
this.positions = result.nodes;
+ this.summaryPositions = layoutListMindmapSummaries(this.model, this.positions, summarySizes);
this.relationRoutes.clear();
this.fallbackRoutes.clear();
this.edges = result.edges;
this.bounds = result;
let top = 0;
let left = 0;
+ this.summaryPositions.forEach(position => {
+ top = Math.min(top, position.top - 32);
+ this.bounds.width = Math.max(this.bounds.width, position.labelX + position.width + 32);
+ this.bounds.height = Math.max(this.bounds.height, position.bottom + 32);
+ });
// 每条连接独立避让节点和按钮,已有关系线不影响路径选择。
this.model.metadata.relations.forEach((relation) => {
const from = this.positions.get(relation.from);
@@ -814,6 +869,13 @@ export class ListMindmapView {
point.x -= left;
point.y -= top;
}));
+ this.summaryPositions.forEach(position => {
+ position.x -= left;
+ position.labelX -= left;
+ position.top -= top;
+ position.bottom -= top;
+ position.labelY -= top;
+ });
this.bounds.height -= top;
this.bounds.width -= left;
}
@@ -849,6 +911,145 @@ export class ListMindmapView {
});
}
+ private updateSummaries() {
+ this.summaryElements.forEach((element, id) => {
+ if (!this.model.metadata.summaries?.some(summary => summary.id === id)) {
+ this.resizeObserver.unobserve(element);
+ element.remove();
+ this.summaryElements.delete(id);
+ }
+ });
+ (this.model.metadata.summaries || []).forEach(summary => {
+ let element = this.summaryElements.get(summary.id);
+ if (!element) {
+ element = createElement("button", "b3-button b3-button--outline mindmap-view__summary");
+ element.type = "button";
+ element.dataset.summaryId = summary.id;
+ element.addEventListener("click", event => {
+ event.stopPropagation();
+ this.finishThen(() => this.selectSummary(summary.id));
+ });
+ this.summaryElements.set(summary.id, element);
+ this.world.append(element);
+ this.resizeObserver.observe(element);
+ }
+ element.textContent = summary.label || this.label("listMindmapSummary");
+ element.setAttribute("aria-label", element.textContent);
+ element.style.color = summary.color || "";
+ });
+ }
+
+ private selectSummary(id: string) {
+ this.selectedSummary = id;
+ this.selectedId = undefined;
+ this.selectedRelation = undefined;
+ this.selectedEdge = undefined;
+ this.relationFrom = undefined;
+ this.summaryFrom = undefined;
+ this.inspector.hidden = !!this.options.readOnly;
+ this.updateSelection();
+ this.renderInspector();
+ }
+
+ private finishSummaryRange(id: string) {
+ const from = this.summaryFrom;
+ if (!from || !getListMindmapSummaryRange(this.model, from, id).length) {
+ return;
+ }
+ this.summaryFrom = undefined;
+ this.updateSelection();
+ void this.options.onSummaryAdd?.(from, id).then(summaryId => {
+ if (summaryId && !this.destroyed) {
+ this.selectSummary(summaryId);
+ requestAnimationFrame(() => {
+ if (!this.destroyed && this.selectedSummary === summaryId) {
+ this.editSummaryLabel(summaryId);
+ }
+ });
+ }
+ }).catch(error => console.error(error));
+ }
+
+ private editSummaryLabel(id: string) {
+ const summary = this.model.metadata.summaries?.find(item => item.id === id);
+ const position = this.summaryPositions.get(id);
+ if (this.options.readOnly || !summary || !position) {
+ return;
+ }
+ this.finishSummaryEdit?.(true);
+ this.finishRelationEdit?.(true);
+ this.inspector.hidden = true;
+ const expected = JSON.stringify(summary);
+ const input = createElement("input", "b3-text-field mindmap-view__summary-editor");
+ input.type = "text";
+ input.value = summary.label;
+ input.setAttribute("aria-label", this.label("listMindmapSummary"));
+ input.style.left = `${position.labelX}px`;
+ input.style.top = `${position.labelY}px`;
+ this.editingSummary = id;
+ let finished = false;
+ const finish = (save: boolean) => {
+ if (finished) {
+ return;
+ }
+ finished = true;
+ this.finishSummaryEdit = undefined;
+ this.editingSummary = undefined;
+ input.remove();
+ if (save && input.value !== summary.label) {
+ this.options.onSummaryChange?.(id, {label: input.value}, expected);
+ }
+ this.draw();
+ };
+ this.finishSummaryEdit = finish;
+ input.addEventListener("blur", () => finish(true));
+ input.addEventListener("keydown", event => {
+ if (!event.isComposing && (event.key === "Enter" || event.key === "Escape")) {
+ event.preventDefault();
+ event.stopPropagation();
+ finish(event.key === "Enter");
+ this.options.host.focus({preventScroll: true});
+ }
+ });
+ this.world.append(input);
+ this.draw();
+ input.focus();
+ input.select();
+ }
+
+ private drawSummaries(context: CanvasRenderingContext2D, resolveColor: (color: string) => string, primary: string) {
+ (this.model.metadata.summaries || []).forEach(summary => {
+ const position = this.summaryPositions.get(summary.id);
+ const element = this.summaryElements.get(summary.id);
+ if (!element) {
+ return;
+ }
+ element.hidden = !position;
+ if (!position) {
+ return;
+ }
+ const {x, top, bottom, labelX, labelY} = position;
+ const path = new Path2D();
+ path.moveTo(x - 10, top);
+ path.lineTo(x, top);
+ path.lineTo(x, bottom);
+ path.lineTo(x - 10, bottom);
+ path.moveTo(x, (top + bottom) / 2);
+ path.lineTo(labelX - 6, (top + bottom) / 2);
+ const selected = this.selectedSummary === summary.id && !this.printTransform && !this.options.printLayout;
+ context.strokeStyle = selected ? primary : resolveColor(summary.color);
+ context.lineWidth = selected ? 2.5 : 1.5;
+ context.setLineDash([]);
+ context.stroke(path);
+ this.linePaths.push({id: summary.id, relation: false, summary: true, path});
+ element.style.left = `${labelX}px`;
+ element.style.top = `${labelY}px`;
+ element.style.visibility = this.editingSummary === summary.id ? "hidden" : "";
+ element.classList.toggle("mindmap-view__summary--selected", selected);
+ element.setAttribute("aria-pressed", String(selected));
+ });
+ }
+
private updateRelations() {
this.relationElements.forEach((element, id) => {
if (!this.model.metadata.relations.some(relation => relation.id === id)) {
@@ -866,6 +1067,8 @@ export class ListMindmapView {
event.stopPropagation();
this.finishThen(() => {
this.selectedRelation = relation.id;
+ this.selectedSummary = undefined;
+ this.summaryFrom = undefined;
this.selectedEdge = undefined;
this.relationFrom = undefined;
this.selectedId = undefined;
@@ -888,7 +1091,11 @@ export class ListMindmapView {
private routingObstacles() {
return [...this.positions.values()].map(node => ({...node,
controlY: node.y + (node.id === this.model.root.id ? node.height / 2 : node.height),
- }));
+ })).concat([...this.summaryPositions.values()].map(summary => ({
+ id: `summary:${summary.id}`, x: summary.x - 10, y: summary.top,
+ width: summary.labelX + summary.width - summary.x + 10, height: summary.bottom - summary.top,
+ controlY: summary.top,
+ })));
}
private relationPath(id: string | undefined, from: ListMindmapPosition, to: ListMindmapPosition, label?: HTMLElement) {
@@ -930,7 +1137,7 @@ export class ListMindmapView {
const height = label.offsetHeight;
const segments = points.slice(1).map((p, i) => ({a: points[i], b: p,
length: Math.hypot(p.x - points[i].x, p.y - points[i].y)})).sort((a, b) => b.length - a.length);
- const nodes = [...this.positions.values()];
+ const nodes = this.routingObstacles();
const available = (p: MindmapRoutePoint) => !nodes.some(node =>
p.x + width / 2 > node.x - 4 && p.x - width / 2 < node.x + node.width + 4 &&
p.y + height / 2 > node.y - 4 && p.y - height / 2 < node.y + node.height + 4);
@@ -1269,6 +1476,7 @@ export class ListMindmapView {
}
});
this.drawRelationPreview(context, resolveColor(relationStyles[0].color, primary), relationStyles[0].width || 1.5);
+ this.drawSummaries(context, color => resolveColor(color, defaultLine), primary);
this.renderRouteControls();
}
@@ -1343,10 +1551,11 @@ export class ListMindmapView {
private selectNode(id: string) {
const changed = this.selectedId !== id || !!this.selectedRelation;
this.selectedId = id;
+ this.selectedSummary = undefined;
this.selectedRelation = undefined;
this.selectedEdge = undefined;
this.updateSelection();
- if (!this.options.readOnly && !this.relationFrom) {
+ if (!this.options.readOnly && !this.relationFrom && !this.summaryFrom) {
this.inspector.hidden = false;
}
if (changed || !this.inspector.hidden) {
@@ -1361,13 +1570,15 @@ export class ListMindmapView {
this.nodeElements.forEach((element, id) => {
element.classList.toggle("mindmap-view__node--selected", this.selectedId === id);
element.classList.toggle("mindmap-view__node--relation", this.relationFrom === id ||
- this.relationPreview?.targetId === id);
+ this.relationPreview?.targetId === id || !!this.summaryFrom &&
+ getListMindmapSummaryRange(this.model, this.summaryFrom, id).length > 0);
element.setAttribute("aria-selected", String(this.selectedId === id));
});
this.relationElements.forEach((element, id) => element.classList.toggle("mindmap-view__relation--selected", this.selectedRelation === id));
const node = this.model.nodes.get(this.selectedId);
const disabled: Record<string, boolean> = {
relation: !node || node.virtual,
+ summary: !this.summaryFrom && (!node || !getListMindmapSummaryRange(this.model, node.id, node.id).length),
style: !node && !this.selectedRelation && !this.selectedEdge,
};
Object.keys(disabled).forEach((key) => {
@@ -1377,6 +1588,9 @@ export class ListMindmapView {
}
});
this.buttons.get("relation")?.classList.toggle("block__icon--active", !!this.relationFrom);
+ this.buttons.get("summary")?.classList.toggle("block__icon--active", !!this.summaryFrom);
+ this.buttons.get("summary")?.setAttribute("aria-pressed", String(!!this.summaryFrom));
+ this.summaryStatus.hidden = !this.summaryFrom;
this.draw();
}
@@ -1419,6 +1633,8 @@ export class ListMindmapView {
}
}
this.selectedId = selected.id;
+ this.selectedSummary = undefined;
+ this.summaryFrom = undefined;
this.selectedRelation = undefined;
this.selectedEdge = undefined;
this.relationFrom = undefined;
@@ -1432,7 +1648,9 @@ export class ListMindmapView {
if (this.options.readOnly) {
return;
}
- if (this.selectedRelation) {
+ if (this.selectedSummary) {
+ this.options.onSummaryDelete?.(this.selectedSummary);
+ } else if (this.selectedRelation) {
this.options.onRelationDelete?.(this.selectedRelation);
} else {
const node = this.model.nodes.get(this.selectedId);
@@ -1526,6 +1744,12 @@ export class ListMindmapView {
}
private beginPointer(event: PointerEvent, id?: string) {
+ if (this.summaryFrom && id && !this.options.readOnly && event.button === 0 && !this.panning) {
+ event.preventDefault();
+ this.suppressLinkClick = true;
+ this.finishSummaryRange(id);
+ return;
+ }
if (this.panning || event.button === 2) {
id = undefined;
event.preventDefault();
@@ -1608,7 +1832,7 @@ export class ListMindmapView {
const relation = target.closest<HTMLElement>(".mindmap-view__relation[data-relation-id]");
const line = target.closest(".mindmap-view__node, input, button") ? undefined : this.findLine(event);
this.setHoveredLine(relation ? `relation:${relation.dataset.relationId}` :
- line ? `${line.relation ? "relation" : "edge"}:${line.id}` : undefined);
+ line ? `${line.summary ? "summary" : line.relation ? "relation" : "edge"}:${line.id}` : undefined);
return;
}
this.setHoveredLine();
@@ -1805,6 +2029,12 @@ export class ListMindmapView {
if (!line) {
return;
}
+ if (line.summary) {
+ this.selectSummary(line.id);
+ return;
+ }
+ this.selectedSummary = undefined;
+ this.summaryFrom = undefined;
this.selectedId = undefined;
this.relationFrom = undefined;
this.selectedRelation = line.relation ? line.id : undefined;
@@ -1859,7 +2089,7 @@ export class ListMindmapView {
return;
}
clearTimeout(this.linkTimer);
- if (this.panning || this.suppressLinkClick || this.relationFrom || event.detail > 1) {
+ if (this.panning || this.suppressLinkClick || this.relationFrom || this.summaryFrom || event.detail > 1) {
event.preventDefault();
return;
}
@@ -1882,10 +2112,15 @@ export class ListMindmapView {
private doubleClick = (event: MouseEvent) => {
clearTimeout(this.linkTimer);
- if (this.options.readOnly || this.relationFrom || this.panning || this.pinching) {
+ if (this.options.readOnly || this.relationFrom || this.summaryFrom || this.panning || this.pinching) {
return;
}
const target = event.target as HTMLElement;
+ const summary = target.closest<HTMLElement>(".mindmap-view__summary");
+ if (summary) {
+ this.editSummaryLabel(summary.dataset.summaryId);
+ return;
+ }
if (target.closest(".mindmap-view__relation")) {
this.editRelationLabel(event);
return;
@@ -1898,6 +2133,8 @@ export class ListMindmapView {
this.selectLine(event);
if (this.selectedRelation) {
this.editRelationLabel(event);
+ } else if (this.selectedSummary) {
+ this.editSummaryLabel(this.selectedSummary);
}
return;
}
@@ -2085,6 +2322,9 @@ export class ListMindmapView {
};
this.positions.forEach(node => include(node.x, node.y - 1, node.width, node.height + 1));
this.relationRoutes.forEach(points => points.forEach(point => include(point.x, point.y)));
+ this.summaryPositions.forEach(summary => {
+ include(summary.x - 10, summary.top, summary.labelX + summary.width - summary.x + 10, summary.bottom - summary.top);
+ });
this.relationElements.forEach(element => {
if (!element.hidden && element.style.visibility !== "hidden") {
const x = parseFloat(element.style.left);
@@ -2142,6 +2382,27 @@ export class ListMindmapView {
if (this.pointer?.relation && event.key !== "Escape") {
return;
}
+ if (this.summaryFrom && event.key !== "Escape") {
+ if (startingComposition || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) {
+ return;
+ }
+ if (event.key === "Enter") {
+ this.finishSummaryRange(this.selectedId);
+ } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {
+ const parent = this.model.nodes.get(this.model.nodes.get(this.summaryFrom)?.parentId);
+ const index = parent?.children.findIndex(node => node.id === this.selectedId) ?? -1;
+ const next = parent?.children[index + (event.key === "ArrowUp" ? -1 : 1)];
+ if (next) {
+ this.selectNode(next.id);
+ this.revealNode(next.id);
+ }
+ } else {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
const noModifiers = !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey;
const siblingShortcut = !startingComposition &&
(event.key === "Enter" && noModifiers || this.options.isAddSiblingShortcut?.(event));
@@ -2254,8 +2515,9 @@ export class ListMindmapView {
!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
const selectedId = this.selectedId;
const selectedRelation = this.selectedRelation;
+ const selectedSummary = this.selectedSummary;
this.finishThen(() => {
- if (selectedId === this.selectedId && selectedRelation === this.selectedRelation) {
+ if (selectedId === this.selectedId && selectedRelation === this.selectedRelation && selectedSummary === this.selectedSummary) {
this.deleteSelection();
}
});
@@ -2268,6 +2530,7 @@ export class ListMindmapView {
return;
}
this.relationFrom = undefined;
+ this.summaryFrom = undefined;
this.inspector.hidden = true;
if (this.fullscreenMarker) {
this.exitFullscreen();
@@ -2285,7 +2548,7 @@ export class ListMindmapView {
return;
}
this.inspector.replaceChildren();
- const lineSelected = !!this.selectedRelation || !!this.selectedEdge;
+ const lineSelected = !!this.selectedRelation || !!this.selectedEdge || !!this.selectedSummary;
this.inspector.classList.toggle("mindmap-view__inspector--node", !lineSelected);
this.inspector.classList.toggle("mindmap-view__inspector--line", lineSelected);
this.inspector.style.left = "";
@@ -2315,6 +2578,15 @@ export class ListMindmapView {
}
this.inspector.append(palette);
};
+ if (this.selectedSummary) {
+ const summary = this.model.metadata.summaries?.find(item => item.id === this.selectedSummary);
+ if (summary) {
+ color(summary.color, value => this.options.onSummaryChange?.(summary.id, {color: value}));
+ this.inspector.append(squareButton("edit", "iconEdit", () => this.editSummaryLabel(summary.id)),
+ squareButton("delete", "iconTrashcan", () => this.options.onSummaryDelete?.(summary.id)));
+ }
+ return;
+ }
if (this.selectedRelation) {
const relation = this.model.metadata.relations.find(item => item.id === this.selectedRelation);
if (!relation) {
@@ -2421,6 +2693,7 @@ export class ListMindmapView {
};
public destroy() {
+ this.finishSummaryEdit?.(false);
this.finishRelationEdit?.(false);
if (this.destroyed) {
return;
@@ -2437,6 +2710,7 @@ export class ListMindmapView {
this.nodeElements.forEach((_element, id) => destroyTabsRender(this.getContentHost(id)));
this.nodeElements.clear();
this.relationElements.clear();
+ this.summaryElements.clear();
this.options.host.replaceChildren();
}
}
diff --git a/docs/LIST-MINDMAP.md b/docs/LIST-MINDMAP.md
index ef925666e7..0c9214ade2 100644
--- a/docs/LIST-MINDMAP.md
+++ b/docs/LIST-MINDMAP.md
@@ -24,7 +24,11 @@
- 选中关系线后,空心圆标出起点,实心圆标出箭头端;拖动圆形手柄更换对应节点,可连接的节点会高亮;松手后重新计算路径并保存到同一事务,保留关系文字和样式,支持撤销;落在空白处、原节点、自身或已有的同向连接上不修改关系线
- 节点默认无背景、不显示边框,正文格式通过节点内的 Protyle 编辑;选中节点后,脑图面板底部显示单排配色工具栏,仅展示节点配色及颜色管理入口,复用外观面板中的文字色与背景色组合,包含内置及自定义颜色并遵循其顺序和可见性,可恢复默认色;点击树连线或关系线,在脑图面板底部显示对应的设置菜单,线条颜色复用外观背景色,菜单不显示标题栏、虚线及宽度控件;双击关系线文字,在原位置显示输入框进行编辑
- 滚轮或触控板滚动用于移动画布,Ctrl + 滚轮或触控板双指捏合以鼠标位置为中心缩放;工具栏提供缩放、适应画布和全屏;全屏沿用编辑器的窗口内全屏及窗口控件避让,点击全屏按钮或按 Esc 退出并回到原列表位置
-- 本次不包含概要和自由摆放节点
+- 选中范围首节点后点击工具栏的概要按钮,再点击末端同级节点,创建连续范围的方括号概要;范围不能跨层、重叠或嵌套,移动端使用相同的点选方式
+- 选择概要范围时也可使用上下方向键选择末端节点,Enter 确认范围,Esc 取消
+- 双击概要文字或使用底部编辑按钮修改纯文本,Enter 保存、Esc 取消;底部面板支持配色与删除,Delete 和 Backspace 也可删除选中的概要,操作进入文档撤销记录
+- 概要包围成员的可见子树,折叠后重新布局;概要文字和括号参与关系线避让、适应画布以及 HTML/PDF 预览的边界计算
+- 本次不包含自由摆放节点
## 数据与兼容性
@@ -36,6 +40,10 @@
修改前补齐折叠隐藏的列表内容。结构、正文和配置修改通过已有文档事务保存,并进入文档撤销记录。复制列表时,样式所关联的节点 ID 和关系线的端点随复制后的块 ID 一起更新。
+版本 `1` 的元数据可选 `summaries` 数组保存概要,每项包含 `id`、所属父节点 `parentId`、按顺序排列的成员块 ID `nodeIds`、纯文本 `label` 和可选颜色 `color`。旧配置缺少该字段时表示没有概要,无需迁移;未知字段继续保留,损坏的概要配置不覆盖原值。括号坐标由布局派生,不持久化。转换为列表时保留该属性,转回脑图后恢复显示;概要文字不生成独立正文块,不参与正文全文搜索或块引用。
+
+复制时同步重映射概要的父节点和成员 ID。事务在修改前记录同级节点顺序,范围内部新增的节点自动纳入,范围外新增的节点不纳入。成员删除或移出后缩小范围,剩一个成员仍保留,全部移除后删除概要;范围被既有节点分隔时保留未移动成员最多的连续部分。普通列表编辑共用该规则,配置变化与原操作一起同步、撤销和重做,重放时使用记录的原始快照。
+
内核在文档事务完成结构修改后,按列表当前的完整节点树清理失效的样式及关系线,并将配置修改附加到同一事务的同步、撤销和重做记录中。普通列表编辑、其他窗口和通过文档事务执行的 API 删除共用此逻辑;同一事务内先删除再插入的节点及折叠后代不会被误清理。刷新脑图只读取配置,不执行清理;复制列表会过滤不属于副本的样式和关系线。未知版本及损坏配置保持原样。
节点内容编辑保留原正文块的身份和属性,以及穿插在正文之间的子列表。编辑器中新建的列表在结束该次编辑时转换为实际子节点。外部更新导致编辑目标失效时,不覆盖较新的正文,并显示尚未保存的内容供恢复。
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index 50a039a581..fad8e43c24 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -2621,6 +2621,7 @@ type Transaction struct {
attributeViewDeletionErr error
structureCheckNodes map[*ast.Node]struct{}
crossTreeMoveRefRefreshes []crossTreeMoveRefRefresh
+ mindmapSummarySiblings map[string]map[string][]string
luteEngine *lute.Lute
m *sync.Mutex
@@ -2673,6 +2674,7 @@ func (tx *Transaction) begin() (err error) {
tx.templateDocTreeRootSnapshot = nil
tx.trees = map[string]*parse.Tree{}
tx.nodes = map[string]*ast.Node{}
+ tx.mindmapSummarySiblings = nil
tx.mutatedRootIDs = nil
tx.changedRootIDs = nil
tx.boxIcons = map[string]string{}
@@ -2903,6 +2905,7 @@ func (tx *Transaction) commit() (err error) {
// releaseCommittedResources 释放执行期间的文档树;操作中的撤销快照及广播所需的文档 ID 继续保留。
func (tx *Transaction) releaseCommittedResources() {
tx.trees, tx.nodes, tx.boxIcons = nil, nil, nil
+ tx.mindmapSummarySiblings = nil
tx.relatedAvIDs = nil
tx.removedCreatedDocs, tx.removedTemplateCreatedDocs = nil, nil
tx.restoredCreatedDocs, tx.restoredTemplateCreatedDocs = nil, nil
@@ -2919,6 +2922,7 @@ func (tx *Transaction) releaseCommittedResources() {
}
func (tx *Transaction) rollback() {
+ tx.mindmapSummarySiblings = nil
tx.finishAttributeViewMutation(true)
for _, tree := range tx.blockSwapOriginalTrees {
treenode.RemoveBlockTreesByRootID(tree.Box, tree.ID)
@@ -3030,6 +3034,7 @@ func (tx *Transaction) loadTreeByBlockTree(bt *treenode.BlockTree) (ret *parse.T
return
}
tx.trees[bt.RootID] = ret
+ tx.captureListMindmapSummarySiblings(ret)
return
}
@@ -3062,6 +3067,7 @@ func (tx *Transaction) loadTree(id string) (ret *parse.Tree, err error) {
return
}
tx.trees[rootID] = ret
+ tx.captureListMindmapSummarySiblings(ret)
return
}
diff --git a/kernel/model/transaction_list_mindmap.go b/kernel/model/transaction_list_mindmap.go
index f4b0812ab4..40fb8bd0c8 100644
--- a/kernel/model/transaction_list_mindmap.go
+++ b/kernel/model/transaction_list_mindmap.go
@@ -30,6 +30,9 @@ func validListMindmapMetadata(data map[string]any) bool {
return false
}
}
+ if summaries, exists := data["summaries"]; exists && !validListMindmapSummaries(summaries) {
+ return false
+ }
validFields := func(value map[string]any, strings, numbers, booleans []string) bool {
for _, key := range strings {
if field, exists := value[key]; exists {
@@ -110,7 +113,7 @@ func validListMindmapRoute(value any) bool {
return true
}
-func pruneListMindmapMetadata(list *ast.Node) (string, bool) {
+func pruneListMindmapMetadata(list *ast.Node, contexts ...*listMindmapSummaryContext) (string, bool) {
original := list.IALAttr(listMindmapMetadataAttr)
var data map[string]any
if json.Unmarshal([]byte(original), &data) != nil || !validListMindmapMetadata(data) {
@@ -135,6 +138,15 @@ func pruneListMindmapMetadata(list *ast.Node) (string, bool) {
}
}
changed := false
+ var raw map[string]json.RawMessage
+ _ = json.Unmarshal([]byte(original), &raw)
+ if summaries, exists := raw["summaries"]; exists {
+ var context *listMindmapSummaryContext
+ if len(contexts) > 0 {
+ context = contexts[0]
+ }
+ raw["summaries"], changed = normalizeListMindmapSummaries(summaries, listMindmapSiblingIDs(list), context)
+ }
nodes := data["nodes"].(map[string]any)
for id := range nodes {
if !ids[id] {
@@ -155,8 +167,6 @@ func pruneListMindmapMetadata(list *ast.Node) (string, bool) {
return original, false
}
// 使用原始 JSON 字段重组,避免扩展字段中的大整数在浮点解码后丢失精度。
- var raw map[string]json.RawMessage
- _ = json.Unmarshal([]byte(original), &raw)
var rawNodes map[string]json.RawMessage
_ = json.Unmarshal(raw["nodes"], &rawNodes)
for id := range rawNodes {
@@ -185,6 +195,12 @@ func (tx *Transaction) normalizeListMindmapMetadata() (ret *TxErr) {
return nil
}
hasUndo := len(tx.UndoOperations) > 0
+ moved := map[string]bool{}
+ for _, operation := range tx.DoOperations {
+ if operation.Action == "move" {
+ moved[operation.ID] = true
+ }
+ }
var undo []*Operation
for _, tree := range tx.trees {
ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
@@ -192,7 +208,9 @@ func (tx *Transaction) normalizeListMindmapMetadata() (ret *TxErr) {
return ast.WalkContinue
}
previous := node.IALAttr(listMindmapMetadataAttr)
- next, changed := pruneListMindmapMetadata(node)
+ next, changed := pruneListMindmapMetadata(node, &listMindmapSummaryContext{
+ previous: tx.mindmapSummarySiblings[node.ID], moved: moved,
+ })
if !changed {
return ast.WalkContinue
}
diff --git a/kernel/model/transaction_mindmap_summary.go b/kernel/model/transaction_mindmap_summary.go
new file mode 100644
index 0000000000..502e2aa5f3
--- /dev/null
+++ b/kernel/model/transaction_mindmap_summary.go
@@ -0,0 +1,189 @@
+package model
+
+import (
+ "encoding/json"
+ "slices"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+)
+
+type listMindmapSummaryContext struct {
+ previous map[string][]string
+ moved map[string]bool
+}
+
+func validListMindmapSummaries(value any) bool {
+ summaries, ok := value.([]any)
+ if !ok {
+ return false
+ }
+ ids, members := map[string]bool{}, map[string]bool{}
+ for _, value := range summaries {
+ summary, ok := value.(map[string]any)
+ if !ok {
+ return false
+ }
+ id, ok := summary["id"].(string)
+ if !ok || id == "" || ids[id] {
+ return false
+ }
+ ids[id] = true
+ parent, ok := summary["parentId"].(string)
+ if !ok || parent == "" {
+ return false
+ }
+ if _, ok = summary["label"].(string); !ok {
+ return false
+ }
+ if color, exists := summary["color"]; exists {
+ if _, ok = color.(string); !ok {
+ return false
+ }
+ }
+ nodes, ok := summary["nodeIds"].([]any)
+ if !ok || len(nodes) == 0 {
+ return false
+ }
+ for _, value := range nodes {
+ id, ok = value.(string)
+ if !ok || id == "" || id == parent || members[id] {
+ return false
+ }
+ members[id] = true
+ }
+ }
+ return true
+}
+
+// 按所属列表项合并直属分支,正文中的列表不参与脑图成员计算。
+func listMindmapSiblingIDs(list *ast.Node) map[string][]string {
+ ret := map[string][]string{}
+ type branch struct {
+ list *ast.Node
+ parent string
+ }
+ pending := []branch{{list, list.ID}}
+ for len(pending) > 0 {
+ current := pending[0]
+ pending = pending[1:]
+ for item := current.list.FirstChild; item != nil; item = item.Next {
+ if item.Type != ast.NodeListItem && item.Type != ast.NodeMindmapItem {
+ continue
+ }
+ ret[current.parent] = append(ret[current.parent], item.ID)
+ for child := item.FirstChild; child != nil; child = child.Next {
+ if child.Type == ast.NodeList || child.Type == ast.NodeMindmap {
+ pending = append(pending, branch{child, item.ID})
+ }
+ }
+ }
+ }
+ return ret
+}
+
+// 在结构变更前记录成员顺序,用于区分新插入节点与范围外的既有节点。
+func (tx *Transaction) captureListMindmapSummarySiblings(tree *parse.Tree) {
+ if tx.isReplay || tree == nil {
+ return
+ }
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || (node.Type != ast.NodeList && node.Type != ast.NodeMindmap) {
+ return ast.WalkContinue
+ }
+ value := node.IALAttr(listMindmapMetadataAttr)
+ if value == "" {
+ return ast.WalkContinue
+ }
+ var data map[string]any
+ if json.Unmarshal([]byte(value), &data) == nil && data["summaries"] != nil && validListMindmapMetadata(data) {
+ if tx.mindmapSummarySiblings == nil {
+ tx.mindmapSummarySiblings = map[string]map[string][]string{}
+ }
+ if _, exists := tx.mindmapSummarySiblings[node.ID]; !exists {
+ tx.mindmapSummarySiblings[node.ID] = listMindmapSiblingIDs(node)
+ }
+ }
+ return ast.WalkContinue
+ })
+}
+
+// 仅改写概要成员,未知字段保留原始 JSON 精度,范围消失时随事务删除概要。
+func normalizeListMindmapSummaries(raw json.RawMessage, siblings map[string][]string,
+ context *listMindmapSummaryContext) (json.RawMessage, bool) {
+ var summaries []map[string]json.RawMessage
+ if json.Unmarshal(raw, &summaries) != nil {
+ return raw, false
+ }
+ previous, moved := siblings, map[string]bool{}
+ if context != nil {
+ if context.previous != nil {
+ previous = context.previous
+ }
+ moved = context.moved
+ }
+ kept := make([]map[string]json.RawMessage, 0, len(summaries))
+ claimed := map[string]bool{}
+ changed := false
+ for _, summary := range summaries {
+ var parent string
+ var members []string
+ _ = json.Unmarshal(summary["parentId"], &parent)
+ _ = json.Unmarshal(summary["nodeIds"], &members)
+ memberSet, old := map[string]bool{}, map[string]bool{}
+ for _, id := range members {
+ memberSet[id] = true
+ }
+ for _, id := range previous[parent] {
+ old[id] = true
+ }
+ var group, best []string
+ bestScore := 0
+ finish := func() {
+ start, end, score := -1, -1, 0
+ for i, id := range group {
+ if memberSet[id] {
+ if start < 0 {
+ start = i
+ }
+ end = i
+ if moved[id] {
+ score++
+ } else {
+ score += len(members) + 1
+ }
+ }
+ }
+ if score > bestScore {
+ bestScore = score
+ best = slices.Clone(group[start : end+1])
+ }
+ group = nil
+ }
+ for _, id := range siblings[parent] {
+ if !claimed[id] && (memberSet[id] || !old[id]) {
+ group = append(group, id)
+ } else {
+ finish()
+ }
+ }
+ finish()
+ if len(best) == 0 {
+ changed = true
+ continue
+ }
+ for _, id := range best {
+ claimed[id] = true
+ }
+ if !slices.Equal(best, members) {
+ summary["nodeIds"], _ = json.Marshal(best)
+ changed = true
+ }
+ kept = append(kept, summary)
+ }
+ if !changed {
+ return raw, false
+ }
+ ret, _ := json.Marshal(kept)
+ return ret, true
+}
diff --git a/kernel/model/transaction_mindmap_summary_test.go b/kernel/model/transaction_mindmap_summary_test.go
new file mode 100644
index 0000000000..307a40e873
--- /dev/null
+++ b/kernel/model/transaction_mindmap_summary_test.go
@@ -0,0 +1,112 @@
+package model
+
+import (
+ "encoding/json"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+)
+
+func TestMindmapSummaryMembership(t *testing.T) {
+ raw := json.RawMessage(`[{"id":"s","parentId":"root","nodeIds":["a","b","c"],"label":"Summary","extension":9007199254740993}]`)
+ for _, tc := range []struct {
+ name string
+ current []string
+ moved string
+ want []string
+ }{
+ {"insert within", []string{"a", "new", "b", "c", "d"}, "", []string{"a", "new", "b", "c"}},
+ {"insert outside", []string{"new", "a", "b", "c", "d"}, "", []string{"a", "b", "c"}},
+ {"delete middle", []string{"a", "c", "d"}, "", []string{"a", "c"}},
+ {"keep one", []string{"c", "d"}, "", []string{"c"}},
+ {"delete all", []string{"d"}, "", nil},
+ {"move out", []string{"a", "b", "d", "c"}, "c", []string{"a", "b"}},
+ {"reorder within", []string{"b", "a", "c", "d"}, "a", []string{"b", "a", "c"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ next, _ := normalizeListMindmapSummaries(raw, map[string][]string{"root": tc.current},
+ &listMindmapSummaryContext{previous: map[string][]string{"root": {"a", "b", "c", "d"}},
+ moved: map[string]bool{tc.moved: true}})
+ var summaries []struct {
+ NodeIDs []string `json:"nodeIds"`
+ }
+ if err := json.Unmarshal(next, &summaries); err != nil {
+ t.Fatal(err)
+ }
+ if tc.want == nil {
+ if len(summaries) != 0 {
+ t.Fatalf("empty range retained: %s", next)
+ }
+ } else if len(summaries) != 1 || !slices.Equal(summaries[0].NodeIDs, tc.want) ||
+ !strings.Contains(string(next), "9007199254740993") {
+ t.Fatalf("unexpected range or lost extension: %s", next)
+ }
+ })
+ }
+}
+
+func TestMindmapSummaryInvalidMetadataPreserved(t *testing.T) {
+ _, list, _ := mindmapTestTree()
+ for _, summaries := range []string{
+ `null`, `{}`, `[{"id":"s","parentId":"p","nodeIds":[],"label":"x"}]`,
+ `[{"id":"s","parentId":"p","nodeIds":["a","a"],"label":"x"}]`,
+ `[{"id":"s","parentId":"p","nodeIds":["p"],"label":"x"}]`,
+ `[{"id":"s","parentId":"p","nodeIds":["a"],"label":1}]`,
+ `[{"id":"s","parentId":"p","nodeIds":["a"],"label":"x","color":1}]`,
+ } {
+ original := `{"version":1,"nodes":{"deleted":{}},"relations":[],"summaries":` + summaries + `}`
+ list.SetIALAttr(listMindmapMetadataAttr, original)
+ if next, changed := pruneListMindmapMetadata(list); changed || next != original {
+ t.Fatalf("invalid source was changed: %s", next)
+ }
+ }
+}
+
+func TestMindmapSummaryTransactionsAndListRoundTrip(t *testing.T) {
+ tree, list, child := mindmapTestTree()
+ parent := child.Parent.Parent.ID
+ second := &ast.Node{Type: ast.NodeListItem, ID: "second"}
+ child.Parent.AppendChild(second)
+ original := `{"version":1,"nodes":{},"relations":[],"summaries":[{"id":"s","parentId":"` + parent +
+ `","nodeIds":["child","second"],"label":"Summary","extension":9007199254740993}]}`
+ list.SetIALAttr(listMindmapMetadataAttr, original)
+ tx := &Transaction{trees: map[string]*parse.Tree{tree.ID: tree},
+ DoOperations: []*Operation{{Action: "insert", ID: "new"}}, UndoOperations: []*Operation{{Action: "delete", ID: "new"}}}
+ tx.captureListMindmapSummarySiblings(tree)
+ child.InsertAfter(&ast.Node{Type: ast.NodeListItem, ID: "new"})
+ if ret := tx.normalizeListMindmapMetadata(); ret != nil {
+ t.Fatal(ret)
+ }
+ next := list.IALAttr(listMindmapMetadataAttr)
+ if !strings.Contains(next, `"nodeIds":["child","new","second"]`) || len(tx.DoOperations) != 2 || len(tx.UndoOperations) != 2 {
+ t.Fatalf("insert did not update and broadcast summary: %s", next)
+ }
+ var attrs map[string]string
+ _ = json.Unmarshal([]byte(tx.UndoOperations[0].Data.(string)), &attrs)
+ if attrs[listMindmapMetadataAttr] != original {
+ t.Fatal("undo did not retain the original summary")
+ }
+ // 转换块类型和折叠不改变成员或概要文字。
+ ast.Walk(list, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering {
+ if node.Type == ast.NodeList {
+ node.Type = ast.NodeMindmap
+ } else if node.Type == ast.NodeListItem {
+ node.Type = ast.NodeMindmapItem
+ node.SetIALAttr("fold", "1")
+ }
+ }
+ return ast.WalkContinue
+ })
+ if ret, changed := pruneListMindmapMetadata(list); changed || ret != next {
+ t.Fatalf("type conversion or folding changed metadata: %s", ret)
+ }
+ tx.isReplay = true
+ child.Unlink()
+ if ret := tx.normalizeListMindmapMetadata(); ret != nil || list.IALAttr(listMindmapMetadataAttr) != next {
+ t.Fatal("replay rewrote the recorded summary snapshot")
+ }
+}