An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support an editable mind map view for list blocks https://github.com/siyuan-note/siyuan/issues/18831
Vanessaa96cc7c27621
diff --git a/app/appearance/icons/index.html b/app/appearance/icons/index.htmlindex a290e1b3d6..967f5e318f 100644--- a/app/appearance/icons/index.html+++ b/app/appearance/icons/index.html@@ -28,6 +28,12 @@<body><h2>SiYuan</h2><div class="fn__clear">+ <div>+ <svg>+ <use xlink:href="#iconRoute"></use>+ </svg>+ iconRoute+ </div><div><svg><use xlink:href="#iconAlignTop"></use>diff --git a/app/appearance/icons/litheness/icon.js b/app/appearance/icons/litheness/icon.jsindex e4c8f6fc3f..1d5fb4fd16 100644--- a/app/appearance/icons/litheness/icon.js+++ b/app/appearance/icons/litheness/icon.js@@ -1,5 +1,9 @@document.body.insertAdjacentHTML('afterbegin', `<svg id="iconsLitheness" style="position: absolute; width: 0; height: 0; overflow: hidden;"><defs>+ <symbol id="iconRoute" viewBox="0 0 24 24" fill="currentColor">+ <path d="M6 15C7.65685 15 9 16.3431 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.3431 4.34315 15 6 15ZM6 16.5C5.17157 16.5 4.5 17.1716 4.5 18C4.5 18.8284 5.17157 19.5 6 19.5C6.82843 19.5 7.5 18.8284 7.5 18C7.5 17.1716 6.82843 16.5 6 16.5Z" />+ <path d="M18.501 6.39551C18.501 6.18457 18.4277 6.00586 18.2812 5.85938C18.1289 5.71289 17.9531 5.63965 17.7539 5.63965L8.63086 5.64844C7.79297 5.64844 7.06641 5.80664 6.45117 6.12305C5.83008 6.44531 5.34961 6.88477 5.00977 7.44141C4.66992 8.00391 4.5 8.64844 4.5 9.375C4.5 10.1016 4.66992 10.7461 5.00977 11.3086C5.34375 11.877 5.82129 12.3223 6.44238 12.6445C7.05762 12.9668 7.78711 13.1279 8.63086 13.1279H16.1807C16.9541 13.1279 17.5664 13.3418 18.0176 13.7695C18.4629 14.2031 18.6855 14.7422 18.6855 15.3867C18.6855 16.0313 18.46 16.5615 18.0088 16.9775C17.5518 17.3994 16.9424 17.6104 16.1807 17.6104L8.38184 17.6104C8.17676 17.6104 8.00098 17.6836 7.85449 17.8301C7.70801 17.9766 7.63477 18.1523 7.63477 18.3574C7.63477 18.5625 7.70801 18.7383 7.85449 18.8848C8.00098 19.0371 8.17676 19.1133 8.38184 19.1133L16.0488 19.1133C16.8926 19.1133 17.625 18.9521 18.2461 18.6299C18.8672 18.3135 19.3447 17.874 19.6787 17.3115C20.0186 16.7549 20.1885 16.1133 20.1885 15.3867C20.1885 14.6602 20.0186 14.0127 19.6787 13.4443C19.3447 12.8818 18.8672 12.4395 18.2461 12.1172C17.625 11.7949 16.8926 11.6338 16.0488 11.6338H8.50781C7.73437 11.6338 7.125 11.417 6.67969 10.9834C6.22852 10.5557 6.00293 10.0195 6.00293 9.375C6.00293 8.73047 6.23145 8.19727 6.68848 7.77539C7.13965 7.35938 7.74609 7.15137 8.50781 7.15137L17.7539 7.14258C17.9531 7.14258 18.1289 7.06934 18.2812 6.92285C18.4277 6.77637 18.501 6.60059 18.501 6.39551ZM16.9277 4.37402V8.4082C16.9277 8.71875 17.0215 8.91211 17.209 8.98828C17.3906 9.07031 17.6016 9.02637 17.8418 8.85645L20.6455 6.8877C20.8447 6.74707 20.9443 6.58301 20.9443 6.39551C20.9502 6.20801 20.8506 6.04102 20.6455 5.89453L17.8506 3.92578C17.6045 3.75586 17.3906 3.70898 17.209 3.78516C17.0215 3.86133 16.9277 4.05762 16.9277 4.37402Z" />+ </symbol><symbol id="iconAlignTop" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><g transform="rotate(90 12 12)"><path d="M21 5H3"/><path d="M15 12H3"/><path d="M17 19H3"/></g></symbol>diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 9c0ea069ac..accf4f760d 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "أدخل نصًا",+ "listMindmapToMindmap": "التبديل إلى عرض الخريطة الذهنية",+ "listMindmapToList": "التبديل إلى عرض القائمة",+ "listMindmapRoot": "القائمة الحالية",+ "listMindmapChild": "إضافة عقدة فرعية",+ "listMindmapFit": "ملاءمة لوحة الرسم",+ "listMindmapInvalid": "تعذرت قراءة إعدادات الخريطة الذهنية؛ تم الاحتفاظ بالبيانات الأصلية",+ "listMindmapUnsupported": "بدّل إلى عرض القائمة لتحرير هذا المحتوى",+ "listMindmapStale": "تم تغيير المحتوى؛ يرجى تحريره مجددًا","agentWorkspaceSkills": "مهارات مساحة العمل","agentWorkspaceSkillsTip": "إدارة المهارات وملفات Markdown في مساحة العمل الحالية","agentSkillManager": "إدارة المهارات",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 18a8c127c6..0100829850 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Text eingeben",+ "listMindmapToMindmap": "Zur Mindmap-Ansicht wechseln",+ "listMindmapToList": "Zur Listenansicht wechseln",+ "listMindmapRoot": "Aktuelle Liste",+ "listMindmapChild": "Untergeordneten Knoten hinzufügen",+ "listMindmapFit": "An Zeichenfläche anpassen",+ "listMindmapInvalid": "Mindmap-Einstellungen können nicht gelesen werden; die Originaldaten wurden beibehalten",+ "listMindmapUnsupported": "Zum Bearbeiten dieses Inhalts zur Listenansicht wechseln",+ "listMindmapStale": "Der Inhalt wurde geändert; bitte erneut bearbeiten","agentWorkspaceSkills": "Arbeitsbereich-Fähigkeiten","agentWorkspaceSkillsTip": "Fähigkeiten und Markdown-Dateien im aktuellen Arbeitsbereich verwalten","agentSkillManager": "Fähigkeitenverwaltung",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 209a68defb..7a5860e57a 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Enter text",+ "listMindmapToMindmap": "Switch to mind map view",+ "listMindmapToList": "Switch to list view",+ "listMindmapRoot": "Current list",+ "listMindmapChild": "Add child node",+ "listMindmapFit": "Fit to canvas",+ "listMindmapInvalid": "Cannot read mind map settings; the original data has been preserved",+ "listMindmapUnsupported": "Switch to list view to edit this content",+ "listMindmapStale": "The content has changed; please edit it again","agentWorkspaceSkills": "Workspace skills","agentWorkspaceSkillsTip": "Manage skills and Markdown files in the current workspace","agentSkillManager": "Skill manager",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 860c0e1289..cca0f34647 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Introducir texto",+ "listMindmapToMindmap": "Cambiar a vista de mapa mental",+ "listMindmapToList": "Cambiar a vista de lista",+ "listMindmapRoot": "Lista actual",+ "listMindmapChild": "Añadir nodo hijo",+ "listMindmapFit": "Ajustar al lienzo",+ "listMindmapInvalid": "No se pueden leer los ajustes del mapa mental; se han conservado los datos originales",+ "listMindmapUnsupported": "Cambia a la vista de lista para editar este contenido",+ "listMindmapStale": "El contenido ha cambiado; vuelve a editarlo","agentWorkspaceSkills": "Habilidades del espacio de trabajo","agentWorkspaceSkillsTip": "Gestionar habilidades y archivos Markdown del espacio de trabajo actual","agentSkillManager": "Gestor de habilidades",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex f14422ec77..822defb02c 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Saisir du texte",+ "listMindmapToMindmap": "Passer à la vue carte mentale",+ "listMindmapToList": "Passer à la vue liste",+ "listMindmapRoot": "Liste actuelle",+ "listMindmapChild": "Ajouter un nœud enfant",+ "listMindmapFit": "Ajuster au canevas",+ "listMindmapInvalid": "Impossible de lire les paramètres de la carte mentale ; les données d’origine ont été conservées",+ "listMindmapUnsupported": "Passez à la vue liste pour modifier ce contenu",+ "listMindmapStale": "Le contenu a changé ; veuillez le modifier à nouveau","agentWorkspaceSkills": "Compétences de l’espace de travail","agentWorkspaceSkillsTip": "Gérer les compétences et les fichiers Markdown de l’espace de travail actuel","agentSkillManager": "Gestion des compétences",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex df15045e4d..e8748c478d 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "הזן טקסט",+ "listMindmapToMindmap": "מעבר לתצוגת מפת חשיבה",+ "listMindmapToList": "מעבר לתצוגת רשימה",+ "listMindmapRoot": "הרשימה הנוכחית",+ "listMindmapChild": "הוספת צומת בן",+ "listMindmapFit": "התאמה למשטח הציור",+ "listMindmapInvalid": "לא ניתן לקרוא את הגדרות מפת החשיבה; הנתונים המקוריים נשמרו",+ "listMindmapUnsupported": "יש לעבור לתצוגת רשימה כדי לערוך תוכן זה",+ "listMindmapStale": "התוכן השתנה; יש לערוך אותו מחדש","agentWorkspaceSkills": "מיומנויות סביבת העבודה","agentWorkspaceSkillsTip": "ניהול מיומנויות וקובצי Markdown בסביבת העבודה הנוכחית","agentSkillManager": "מנהל המיומנויות",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 565230af1e..b70f5a4bc0 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "पाठ दर्ज करें",+ "listMindmapToMindmap": "माइंड मैप दृश्य पर जाएँ",+ "listMindmapToList": "सूची दृश्य पर जाएँ",+ "listMindmapRoot": "वर्तमान सूची",+ "listMindmapChild": "उप-नोड जोड़ें",+ "listMindmapFit": "कैनवास में समायोजित करें",+ "listMindmapInvalid": "माइंड मैप सेटिंग पढ़ी नहीं जा सकीं; मूल डेटा सुरक्षित रखा गया है",+ "listMindmapUnsupported": "इस सामग्री को संपादित करने के लिए सूची दृश्य पर जाएँ",+ "listMindmapStale": "सामग्री बदल गई है; कृपया इसे फिर से संपादित करें","agentWorkspaceSkills": "कार्यक्षेत्र कौशल","agentWorkspaceSkillsTip": "वर्तमान कार्यक्षेत्र में कौशल और Markdown फ़ाइलें प्रबंधित करें","agentSkillManager": "कौशल प्रबंधक",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex a03fa883c6..fb94671714 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Masukkan teks",+ "listMindmapToMindmap": "Beralih ke tampilan peta pikiran",+ "listMindmapToList": "Beralih ke tampilan daftar",+ "listMindmapRoot": "Daftar saat ini",+ "listMindmapChild": "Tambah simpul anak",+ "listMindmapFit": "Sesuaikan dengan kanvas",+ "listMindmapInvalid": "Pengaturan peta pikiran tidak dapat dibaca; data asli telah dipertahankan",+ "listMindmapUnsupported": "Beralih ke tampilan daftar untuk mengedit konten ini",+ "listMindmapStale": "Konten telah berubah; silakan edit kembali","agentWorkspaceSkills": "Keterampilan ruang kerja","agentWorkspaceSkillsTip": "Kelola keterampilan dan berkas Markdown di ruang kerja saat ini","agentSkillManager": "Pengelola keterampilan",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex ee8c97a7cd..f8836047f4 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Inserisci testo",+ "listMindmapToMindmap": "Passa alla vista mappa mentale",+ "listMindmapToList": "Passa alla vista elenco",+ "listMindmapRoot": "Elenco attuale",+ "listMindmapChild": "Aggiungi nodo figlio",+ "listMindmapFit": "Adatta all’area di disegno",+ "listMindmapInvalid": "Impossibile leggere le impostazioni della mappa mentale; i dati originali sono stati conservati",+ "listMindmapUnsupported": "Passa alla vista elenco per modificare questo contenuto",+ "listMindmapStale": "Il contenuto è cambiato; modificalo di nuovo","agentWorkspaceSkills": "Competenze dell'area di lavoro","agentWorkspaceSkillsTip": "Gestisci competenze e file Markdown nell'area di lavoro corrente","agentSkillManager": "Gestione competenze",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex ce264fa534..7f04ba8083 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "テキストを入力",+ "listMindmapToMindmap": "マインドマップ表示に切り替え",+ "listMindmapToList": "リスト表示に切り替え",+ "listMindmapRoot": "現在のリスト",+ "listMindmapChild": "子ノードを追加",+ "listMindmapFit": "キャンバスに合わせる",+ "listMindmapInvalid": "マインドマップの設定を読み込めません。元のデータは保持されています",+ "listMindmapUnsupported": "この内容を編集するにはリスト表示に切り替えてください",+ "listMindmapStale": "内容が更新されました。もう一度編集してください","agentWorkspaceSkills": "ワークスペースのスキル","agentWorkspaceSkillsTip": "現在のワークスペースのスキルと Markdown ファイルを管理","agentSkillManager": "スキル管理",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex d955bc2a88..d8cb22ba9f 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "텍스트 입력",+ "listMindmapToMindmap": "마인드맵 보기로 전환",+ "listMindmapToList": "목록 보기로 전환",+ "listMindmapRoot": "현재 목록",+ "listMindmapChild": "하위 노드 추가",+ "listMindmapFit": "캔버스에 맞추기",+ "listMindmapInvalid": "마인드맵 설정을 읽을 수 없습니다. 원본 데이터는 보존되었습니다",+ "listMindmapUnsupported": "이 내용을 편집하려면 목록 보기로 전환하세요",+ "listMindmapStale": "내용이 변경되었습니다. 다시 편집하세요","agentWorkspaceSkills": "작업 공간 스킬","agentWorkspaceSkillsTip": "현재 작업 공간의 스킬과 Markdown 파일 관리","agentSkillManager": "스킬 관리",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 159a7bcb0f..70f0d4b970 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Voer tekst in",+ "listMindmapToMindmap": "Naar mindmapweergave schakelen",+ "listMindmapToList": "Naar lijstweergave schakelen",+ "listMindmapRoot": "Huidige lijst",+ "listMindmapChild": "Onderliggende knoop toevoegen",+ "listMindmapFit": "Aan canvas aanpassen",+ "listMindmapInvalid": "Mindmapinstellingen kunnen niet worden gelezen; de oorspronkelijke gegevens zijn behouden",+ "listMindmapUnsupported": "Schakel naar de lijstweergave om deze inhoud te bewerken",+ "listMindmapStale": "De inhoud is gewijzigd; bewerk deze opnieuw","agentWorkspaceSkills": "Werkruimtevaardigheden","agentWorkspaceSkillsTip": "Vaardigheden en Markdown-bestanden in de huidige werkruimte beheren","agentSkillManager": "Vaardighedenbeheer",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 2865dae0f5..b8b283c854 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Wpisz tekst",+ "listMindmapToMindmap": "Przełącz na widok mapy myśli",+ "listMindmapToList": "Przełącz na widok listy",+ "listMindmapRoot": "Bieżąca lista",+ "listMindmapChild": "Dodaj węzeł podrzędny",+ "listMindmapFit": "Dopasuj do płótna",+ "listMindmapInvalid": "Nie można odczytać ustawień mapy myśli; oryginalne dane zostały zachowane",+ "listMindmapUnsupported": "Przełącz na widok listy, aby edytować tę zawartość",+ "listMindmapStale": "Zawartość uległa zmianie; edytuj ją ponownie","agentWorkspaceSkills": "Umiejętności przestrzeni roboczej","agentWorkspaceSkillsTip": "Zarządzaj umiejętnościami i plikami Markdown w bieżącej przestrzeni roboczej","agentSkillManager": "Menedżer umiejętności",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 3d651ca7a9..55a7eb185e 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Digite o texto",+ "listMindmapToMindmap": "Alternar para a visualização de mapa mental",+ "listMindmapToList": "Alternar para a visualização de lista",+ "listMindmapRoot": "Lista atual",+ "listMindmapChild": "Adicionar nó filho",+ "listMindmapFit": "Ajustar à área de desenho",+ "listMindmapInvalid": "Não foi possível ler as configurações do mapa mental; os dados originais foram preservados",+ "listMindmapUnsupported": "Alterne para a visualização de lista para editar este conteúdo",+ "listMindmapStale": "O conteúdo foi alterado; edite-o novamente","agentWorkspaceSkills": "Habilidades do espaço de trabalho","agentWorkspaceSkillsTip": "Gerenciar habilidades e arquivos Markdown no espaço de trabalho atual","agentSkillManager": "Gerenciador de habilidades",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex df0caa9c60..9f95c55980 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Введите текст",+ "listMindmapToMindmap": "Переключить на интеллект-карту",+ "listMindmapToList": "Переключить на список",+ "listMindmapRoot": "Текущий список",+ "listMindmapChild": "Добавить дочерний узел",+ "listMindmapFit": "Вписать в холст",+ "listMindmapInvalid": "Не удалось прочитать настройки интеллект-карты; исходные данные сохранены",+ "listMindmapUnsupported": "Переключитесь на список, чтобы изменить это содержимое",+ "listMindmapStale": "Содержимое изменилось; отредактируйте его повторно","agentWorkspaceSkills": "Навыки рабочего пространства","agentWorkspaceSkillsTip": "Управление навыками и файлами Markdown в текущем рабочем пространстве","agentSkillManager": "Управление навыками",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 23391a4858..d8104c3449 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Zadajte text",+ "listMindmapToMindmap": "Prepnúť na zobrazenie myšlienkovej mapy",+ "listMindmapToList": "Prepnúť na zobrazenie zoznamu",+ "listMindmapRoot": "Aktuálny zoznam",+ "listMindmapChild": "Pridať podradený uzol",+ "listMindmapFit": "Prispôsobiť plátnu",+ "listMindmapInvalid": "Nastavenia myšlienkovej mapy sa nedajú načítať; pôvodné údaje boli zachované",+ "listMindmapUnsupported": "Ak chcete upraviť tento obsah, prepnite na zobrazenie zoznamu",+ "listMindmapStale": "Obsah sa zmenil; upravte ho znova","agentWorkspaceSkills": "Zručnosti pracovného priestoru","agentWorkspaceSkillsTip": "Správa zručností a súborov Markdown v aktuálnom pracovnom priestore","agentSkillManager": "Správca zručností",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 8bffd54f35..d18c3af4b2 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Унесите текст",+ "listMindmapToMindmap": "Пређи на приказ мапе ума",+ "listMindmapToList": "Пређи на приказ листе",+ "listMindmapRoot": "Тренутна листа",+ "listMindmapChild": "Додај подређени чвор",+ "listMindmapFit": "Уклопи у платно",+ "listMindmapInvalid": "Није могуће прочитати подешавања мапе ума; изворни подаци су сачувани",+ "listMindmapUnsupported": "Пређите на приказ листе да бисте уредили овај садржај",+ "listMindmapStale": "Садржај је промењен; уредите га поново","agentWorkspaceSkills": "Вештине радног простора","agentWorkspaceSkillsTip": "Управљајте вештинама и Markdown датотекама у тренутном радном простору","agentSkillManager": "Управљање вештинама",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex ed148a1566..0c460a8e77 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "ป้อนข้อความ",+ "listMindmapToMindmap": "เปลี่ยนเป็นมุมมองแผนผังความคิด",+ "listMindmapToList": "เปลี่ยนเป็นมุมมองรายการ",+ "listMindmapRoot": "รายการปัจจุบัน",+ "listMindmapChild": "เพิ่มโหนดลูก",+ "listMindmapFit": "ปรับให้พอดีกับพื้นที่วาด",+ "listMindmapInvalid": "ไม่สามารถอ่านการตั้งค่าแผนผังความคิดได้ โดยยังคงเก็บข้อมูลต้นฉบับไว้",+ "listMindmapUnsupported": "เปลี่ยนเป็นมุมมองรายการเพื่อแก้ไขเนื้อหานี้",+ "listMindmapStale": "เนื้อหามีการเปลี่ยนแปลง โปรดแก้ไขอีกครั้ง","agentWorkspaceSkills": "ทักษะของพื้นที่ทำงาน","agentWorkspaceSkillsTip": "จัดการทักษะและไฟล์ Markdown ในพื้นที่ทำงานปัจจุบัน","agentSkillManager": "ตัวจัดการทักษะ",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 0ca096ce9a..a4b354cc5f 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Metin girin",+ "listMindmapToMindmap": "Zihin haritası görünümüne geç",+ "listMindmapToList": "Liste görünümüne geç",+ "listMindmapRoot": "Geçerli liste",+ "listMindmapChild": "Alt düğüm ekle",+ "listMindmapFit": "Tuvale sığdır",+ "listMindmapInvalid": "Zihin haritası ayarları okunamadı; özgün veriler korundu",+ "listMindmapUnsupported": "Bu içeriği düzenlemek için liste görünümüne geçin",+ "listMindmapStale": "İçerik değişti; lütfen yeniden düzenleyin","agentWorkspaceSkills": "Çalışma alanı becerileri","agentWorkspaceSkillsTip": "Geçerli çalışma alanındaki becerileri ve Markdown dosyalarını yönetin","agentSkillManager": "Beceri yöneticisi",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 1ca3d028c5..efb0d21d6e 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "Введіть текст",+ "listMindmapToMindmap": "Перемкнути на мапу думок",+ "listMindmapToList": "Перемкнути на список",+ "listMindmapRoot": "Поточний список",+ "listMindmapChild": "Додати дочірній вузол",+ "listMindmapFit": "Вписати в полотно",+ "listMindmapInvalid": "Не вдалося прочитати налаштування мапи думок; початкові дані збережено",+ "listMindmapUnsupported": "Перемкніться на список, щоб редагувати цей вміст",+ "listMindmapStale": "Вміст змінився; відредагуйте його знову","agentWorkspaceSkills": "Навички робочого простору","agentWorkspaceSkillsTip": "Керування навичками та файлами Markdown у поточному робочому просторі","agentSkillManager": "Керування навичками",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex a87fb0cfb5..86d5797483 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "输入文字",+ "listMindmapToMindmap": "切换为脑图视图",+ "listMindmapToList": "切换为列表视图",+ "listMindmapRoot": "当前列表",+ "listMindmapChild": "添加子节点",+ "listMindmapFit": "适应画布",+ "listMindmapInvalid": "脑图配置无法读取,原数据已保留",+ "listMindmapUnsupported": "此内容请切回列表编辑",+ "listMindmapStale": "内容已更新,请重新编辑","agentWorkspaceSkills": "工作空间技能","agentWorkspaceSkillsTip": "管理当前工作空间中的技能及 Markdown 文件","agentSkillManager": "技能管理",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex df78a2cc84..33a5af7549 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,13 @@{+ "listMindmapPlaceholder": "輸入文字",+ "listMindmapToMindmap": "切換為心智圖檢視",+ "listMindmapToList": "切換為清單檢視",+ "listMindmapRoot": "目前清單",+ "listMindmapChild": "新增子節點",+ "listMindmapFit": "符合畫布大小",+ "listMindmapInvalid": "無法讀取心智圖設定,原始資料已保留",+ "listMindmapUnsupported": "請切回清單檢視以編輯此內容",+ "listMindmapStale": "內容已更新,請重新編輯","agentWorkspaceSkills": "工作空間技能","agentWorkspaceSkillsTip": "管理目前工作空間中的技能及 Markdown 檔案","agentSkillManager": "技能管理",diff --git a/app/src/assets/scss/export.scss b/app/src/assets/scss/export.scssindex 41b2099d10..7ed71a26e1 100644--- a/app/src/assets/scss/export.scss+++ b/app/src/assets/scss/export.scss@@ -3,8 +3,10 @@@use "protyle/wysiwyg" as *;@use "component/typography" as *;@use "protyle/attr" as *;+@use "protyle/list-mindmap" as *;@use "util/function" as *;@use "business/history" as *;+@use "business/block" as *;@use "component/button" as *;@use "component/select" as *;@use "component/switch" as *;diff --git a/app/src/assets/scss/protyle/_list-mindmap.scss b/app/src/assets/scss/protyle/_list-mindmap.scssnew file mode 100644index 0000000000..89f013b3a3--- /dev/null+++ b/app/src/assets/scss/protyle/_list-mindmap.scss@@ -0,0 +1,490 @@+@use "../util/mixin" as *;++.protyle-wysiwyg,+.b3-typography {+ [data-type="NodeList"][data-list-mindmap-rendered="true"] > [data-type="NodeListItem"] {+ display: none;+ }+}++.list-mindmap {+ position: relative;+ display: flex;+ flex-direction: column;+ width: 100%;+ height: 420px;+ min-height: 260px;+ box-sizing: border-box;+ overflow: hidden;+ border: 1px solid var(--b3-border-color);+ border-radius: var(--b3-border-radius);+ background: var(--b3-theme-background);+ color: var(--b3-theme-on-background);+ text-align: left;+ font-size: 14px;+ line-height: 1.5;+ outline: none;++ [hidden] {+ display: none !important;+ }++ &.fullscreen {+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100vh;+ max-height: none;+ border: 0;+ border-radius: 0;+ z-index: 8;+ }++ &__toolbar {+ gap: 4px;+ overflow-x: auto;+ scrollbar-width: none;++ &::-webkit-scrollbar {+ display: none;+ }+ }++ &__spacer {+ flex: 1;+ }++ &__zoom {+ flex-shrink: 0;+ min-width: 34px;+ color: var(--b3-theme-on-surface);+ text-align: center;+ font-size: 11px;+ font-variant-numeric: tabular-nums;+ user-select: none;+ }++ &__viewport {+ position: relative;+ flex: 1;+ min-height: 0;+ overflow: hidden;+ cursor: grab;+ touch-action: none;+ user-select: none;++ &--dragging {+ cursor: grabbing;+ }++ &--line-hover {+ cursor: pointer;+ }+ }++ &__canvas {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ pointer-events: none;+ }++ &__world {+ position: absolute;+ left: 0;+ top: 0;+ width: 0;+ height: 0;+ transform-origin: 0 0;+ }++ &__node {+ position: absolute;+ min-width: 64px;+ max-width: 300px;+ width: max-content;+ min-height: 36px;+ padding: 7px 12px;+ box-sizing: border-box;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--b3-theme-on-background);+ font-size: 16px;+ line-height: 1.5;+ cursor: grab;++ &:hover:not(.list-mindmap__node--dragging):not(.list-mindmap__node--editing):not(.list-mindmap__node--selected) {+ box-shadow: inset 0 0 0 2px var(--b3-list-hover);+ }++ &--virtual {+ font-weight: 600;+ }++ &--selected {+ box-shadow: inset 0 0 0 2px var(--b3-theme-primary);+ }++ &--relation {+ box-shadow: inset 0 0 0 2px var(--b3-theme-primary);+ }++ &--dragging {+ opacity: .35;+ }++ &--editing {+ z-index: 3;+ cursor: text;+ user-select: text;+ }++ &[data-mindmap-drop="child"] {+ box-shadow: inset 0 0 0 3px var(--b3-theme-primary);+ background: var(--b3-theme-primary-lightest) !important;+ }++ &[data-mindmap-drop="before"]::before,+ &[data-mindmap-drop="after"]::after {+ content: "";+ position: absolute;+ right: -5px;+ left: -5px;+ height: 3px;+ border-radius: 2px;+ background: var(--b3-theme-primary);+ }++ &[data-mindmap-drop="before"]::before {+ top: -8px;+ }++ &[data-mindmap-drop="after"]::after {+ bottom: -8px;+ }+ }++ &__content {+ min-width: 36px;+ min-height: 24px;+ overflow-wrap: anywhere;++ &--empty:not(.list-mindmap__editor) {+ > * {+ display: none;+ }++ &::before {+ content: attr(data-placeholder);+ color: var(--b3-theme-on-surface-light);+ }+ }++ > div,+ > .p {+ margin: 0;+ padding: 0;+ font-size: inherit;+ line-height: inherit;+ }++ img,+ video,+ iframe {+ max-width: 100%;+ }++ &.protyle,+ .protyle {+ overflow: visible;+ min-height: 24px;+ max-height: none;+ background: transparent;+ border: 0;+ border-radius: 0;+ box-shadow: none;+ font-size: inherit;+ }++ .protyle-content,+ .protyle-wysiwyg[spellcheck] {+ overflow: visible;+ min-height: 24px;+ padding: 0 !important;+ background: transparent;+ font-size: inherit !important;+ line-height: inherit;+ }++ .protyle-wysiwyg > [data-node-id] {+ margin: 0;+ padding: 0;+ line-height: inherit;++ [spellcheck] {+ min-height: 1.5em;+ }+ }++ .protyle-attr,+ .protyle-gutters {+ display: none;+ }+ }++ &__fold {+ position: absolute;+ z-index: 1;+ right: -11px;+ top: calc(50% - 11px);+ min-width: 22px;+ width: 22px;+ height: 22px;+ padding: 4px;+ border: 1px solid var(--b3-border-color);+ border-radius: 50%;+ background: var(--b3-theme-background);+ visibility: hidden;+ font-size: 10px;+ box-sizing: border-box;+ justify-content: center;++ svg {+ width: 14px;+ height: 14px;+ }++ &--closed {+ visibility: visible;++ svg {+ display: none;+ }+ }++ &:not(.list-mindmap__fold--closed) .list-mindmap__fold-count {+ display: none;+ }+ }++ &__add-child {+ position: absolute;+ right: -26px;+ top: calc(50% - 11px);+ min-width: 22px;+ width: 22px;+ height: 22px;+ padding: 4px;+ border: 1px solid var(--b3-border-color);+ border-radius: 50%;+ background: var(--b3-theme-surface);+ visibility: hidden;+ opacity: 0;+ cursor: pointer;+ box-sizing: border-box;+ justify-content: center;++ svg {+ width: 14px;+ height: 14px;+ }+ }++ // 按节点完整高度连接悬停区域,经过按钮边缘时也保持加号可见。+ &__add-bridge {+ position: absolute;+ left: 100%;+ top: 0;+ bottom: 0;+ width: 26px;+ visibility: hidden;+ }++ &__node--branch > &__add-child {+ right: -38px;+ }++ &__node--branch > &__add-bridge {+ width: 38px;+ }++ &__node:not(.list-mindmap__node--root) {+ > .list-mindmap__fold {+ top: calc(100% - 10px);+ }++ > .list-mindmap__add-child {+ top: calc(100% - 10px);+ }++ > .list-mindmap__add-bridge {+ bottom: -11px;+ }+ }++ &__node:hover > &__add-child,+ &__node:hover > &__fold,+ &__node:focus-within > &__fold,+ &__node:focus-within > &__add-child,+ &__node:hover > &__add-bridge,+ &__node:focus-within > &__add-bridge {+ visibility: visible;+ opacity: 1;+ }++ @media (hover: none) {+ &__node--selected > &__fold,+ &__node--selected > &__add-child,+ &__node--selected > &__add-bridge {+ visibility: visible;+ opacity: 1;+ }+ }++ &__viewport--dragging &__add-child,+ &__viewport--dragging &__add-bridge {+ visibility: hidden;+ opacity: 0;+ }++ &__ghost {+ z-index: 5;+ opacity: .8;+ outline: 2px solid var(--b3-theme-primary);+ pointer-events: none;+ }++ &__relation {+ position: absolute;+ max-width: 180px;+ padding: 2px 6px;+ overflow: hidden;+ transform: translate(-50%, -50%);+ border: 0;+ border-radius: 10px;+ background: var(--b3-theme-background);+ color: var(--b3-theme-primary);+ font: inherit;+ font-size: 11px;+ text-overflow: ellipsis;+ white-space: nowrap;+ cursor: pointer;++ &--hover {+ background: var(--b3-list-hover);+ }++ &--selected {+ outline: 2px solid var(--b3-theme-primary);+ }+ }++ &__inspector {+ @include protyle-toolbar-surface;+ position: absolute;+ left: 50%;+ right: auto;+ transform: translateX(-50%);+ bottom: 8px;+ z-index: 6;+ width: max-content;+ min-width: 0;+ max-width: calc(100% - 16px);+ padding: 4px;+ box-sizing: border-box;+ overflow-x: auto;+ overflow-y: hidden;+ }++ &__relation-editor {+ width: 160px;+ cursor: text;+ z-index: 6;+ outline: 1px solid var(--b3-theme-primary);+ border-radius: var(--b3-border-radius);+ }++ &__inspector--node {+ .color__square {+ flex-shrink: 0;+ }+ }++ &__inspector--line {+ align-items: center;+ flex-wrap: nowrap;+ gap: 8px 16px;++ .list-mindmap__palette {+ margin: 0;+ flex-shrink: 0;+ }++ > button {+ flex-shrink: 0;+ }+ }++ &__tooltip {+ position: absolute;+ z-index: 7;+ max-width: calc(100% - 16px);+ padding: 4px 8px;+ border-radius: var(--b3-border-radius);+ background: var(--b3-tooltips-background);+ color: var(--b3-tooltips-color);+ box-sizing: border-box;+ font-size: 12px;+ line-height: 1.5;+ overflow-wrap: anywhere;+ pointer-events: none;+ }++ &__color-probe {+ position: absolute;+ width: 0;+ height: 0;+ visibility: hidden;+ pointer-events: none;+ }++ &__palette {+ display: flex;+ flex-wrap: nowrap;+ }++ &__color {+ svg {+ visibility: hidden;+ }++ &[aria-pressed="true"] svg {+ visibility: visible;+ }+ }++}++@media print {+ .list-mindmap {+ break-inside: avoid;+ height: 420px;++ &__toolbar,+ &__inspector,+ &__tooltip,+ &__add-bridge,+ &__fold,+ &__add-child {+ display: none !important;+ }++ &__node--selected,+ &__relation--selected {+ outline: none;+ }+ }+}diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scssindex 398f7c993a..6a50ca77e6 100644--- a/app/src/assets/scss/protyle/_protyle.scss+++ b/app/src/assets/scss/protyle/_protyle.scss@@ -2,6 +2,7 @@@use "toolbar" as *;@use "wysiwyg" as *;@use "attr" as *;+@use "list-mindmap" as *;.protyle-lite-fragment .protyle-action__menu {display: none;diff --git a/app/src/assets/scss/protyle/_toolbar.scss b/app/src/assets/scss/protyle/_toolbar.scssindex 62d799a49d..e2eb2a3c20 100644--- a/app/src/assets/scss/protyle/_toolbar.scss+++ b/app/src/assets/scss/protyle/_toolbar.scss@@ -1,12 +1,11 @@+@use "../util/mixin" as *;+.protyle {&-toolbar {- background-color: var(--b3-theme-background);+ @include protyle-toolbar-surface;// 需高于 .layout__resizez-index: 7;position: fixed;- box-shadow: var(--b3-dialog-shadow);- border-radius: var(--b3-border-radius);- display: flex;&__item {display: inline-flex;diff --git a/app/src/assets/scss/util/_mixin.scss b/app/src/assets/scss/util/_mixin.scssindex 8a5bf4995b..5cc1ee04e2 100644--- a/app/src/assets/scss/util/_mixin.scss+++ b/app/src/assets/scss/util/_mixin.scss@@ -1,3 +1,10 @@+@mixin protyle-toolbar-surface {+ background-color: var(--b3-theme-background);+ box-shadow: var(--b3-dialog-shadow);+ border-radius: var(--b3-border-radius);+ display: flex;+}+@mixin text-clamp($line: 2) {word-break: break-all;-webkit-line-clamp: $line;diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.tsindex 4de4c70b8c..6ee7eb72e3 100644--- a/app/src/config/entryVisibility/catalog.test.ts+++ b/app/src/config/entryVisibility/catalog.test.ts@@ -744,13 +744,19 @@ test("list block submenu follows the base block entries", () => {"separator_numbering","prependListItem","appendListItem",+ "listMindmap",]);+ assert.equal(getEntryCatalogNode("gutter.single.listBlock.listMindmap")?.simple, true);+ assert.equal(getEntryCatalogNode("gutter.single.listBlock.listMindmap")?.type, "entry");+ assert.equal(getEntryParentPath("gutter.single.listBlock.listMindmap"), "gutter.single.listBlock");+ assert.equal(getEntryCatalogNode("gutter.multi.listBlock.listMindmap"), undefined);assert.equal(getEntryCatalogNode("gutter.single.listBlock.customTaskStatus")?.simple, true);assert.equal(getEntryCatalogNode("gutter.single.listBlock.customTaskStatus")?.type, "entry");assert.equal(getEntryCatalogNode("gutter.single.listBlock.taskStatus"), undefined);assert.equal(getEntryCatalogNode("gutter.single.listBlock.separator_taskStatus")?.type, "separator");const source = readFileSync(resolve(process.cwd(), "src/protyle/gutter/index.ts"), "utf8");const submenu = source.slice(source.indexOf("const genListBlockSubmenu"), source.indexOf("return submenu;", source.indexOf("const genListBlockSubmenu")));+ assert.match(submenu, /if \(type === "NodeList"\) \{\s+submenu\.push\(\{\s+id: "listMindmap"/);const taskSource = readFileSync(resolve(process.cwd(), "src/protyle/wysiwyg/taskStatusDialog.ts"), "utf8");assert.deepEqual([...Array.from(taskSource.matchAll(/id: "([^"]+)"/g), match => match[1]),...Array.from(submenu.matchAll(/id: "([^"]+)"/g), match => match[1])],diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 2efa06f490..c78a867a89 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -380,6 +380,7 @@ const gutterSingle = () => [separator("separator_numbering"),node("prependListItem", lang("prependListItem")),node("appendListItem", lang("appendListItem")),+ node("listMindmap", lang("listMindmapToMindmap")),]),separator("separator_tabs"),node("tabs", lang("tabs"), true, [diff --git a/app/src/config/entryVisibility/order.test.ts b/app/src/config/entryVisibility/order.test.tsindex 327d7417f6..7ab23057ce 100644--- a/app/src/config/entryVisibility/order.test.ts+++ b/app/src/config/entryVisibility/order.test.ts@@ -17,7 +17,7 @@ test("entry order keeps custom order and inserts new entries by their default netest("custom task status merges into saved list menus without moving existing entries", () => {const entries = getEntryCatalogChildren("gutter.single.listBlock");const defaults = entries.map(item => item.key);- const saved = ["appendListItem", "plugin:example:item", "orderedListStart", "continueListNumbering",+ const saved = ["appendListItem", "listMindmap", "plugin:example:item", "orderedListStart", "continueListNumbering","separator_numbering", "prependListItem"];const merged = mergeEntryOrderPreservingUnknown(defaults, saved);const added = ["taskStatusTodo", "taskStatusInProgress", "taskStatusDone", "taskStatusCanceled", "customTaskStatus", "separator_taskStatus"];@@ -27,6 +27,21 @@ test("custom task status merges into saved list menus without moving existing enmerged, new Set(["separator_numbering"])), ["appendListItem", "plugin:example:item", "customTaskStatus", "prependListItem"]);});+test("list mind map view merges into saved list menus and preserves plugin slots", () => {+ const entries = getEntryCatalogChildren("gutter.single.listBlock");+ const defaults = entries.map(item => item.key);+ const saved = defaults.filter(key => key !== "listMindmap");+ saved.splice(1, 0, "plugin:example:item");+ const merged = mergeEntryOrderPreservingUnknown(defaults, saved);+ const separators = new Set(entries.filter(item => item.type === "separator").map(item => item.key));+ assert.deepEqual(merged.filter(key => key !== "listMindmap"), saved);+ assert.equal(merged[1], "plugin:example:item");+ assert.equal(merged[merged.indexOf("appendListItem") + 1], "listMindmap");+ assert.deepEqual(resolveEntryOrder([...defaults, "plugin:example:item"], merged, separators), merged);+ assert.deepEqual(resolveEntryOrder(["prependListItem", "appendListItem", "listMindmap"], merged, separators),+ ["prependListItem", "appendListItem", "listMindmap"]);+});+test("definition conversion submenus preserve custom order and plugin slots", () => {for (const id of ["defBlock", "defBlockChildren"]) {const entries = getEntryCatalogChildren(`inline.ref.turnInto.${id}`);diff --git a/app/src/protyle/export/index.ts b/app/src/protyle/export/index.tsindex 1d1f4870c6..35fc99d403 100644--- a/app/src/protyle/export/index.ts+++ b/app/src/protyle/export/index.ts@@ -18,6 +18,18 @@ import {getHostCapabilities} from "../../util/hostCapabilities";import {getLastExportPath, setLastExportPath} from "./path";import type {APICallbackResponse, APIPOSTRoutes} from "../../types/api";+const getExportLanguages = () => {+ const keys = new Set([+ "copy", "mindmap", "fontSize", "bold", "italic", "colorFont", "color", "undo", "redo", "fold", "collapse", "expand",+ "fullscreen", "exitFullscreen", "zoomIn", "zoomOut", "delete", "close", "connect", "text",+ ]);+ const languages = Object.fromEntries(Object.entries(window.siyuan.languages)+ .filter(([key]) => keys.has(key) || key.startsWith("listMindmap")));+ // 转义脚本边界和行分隔符,保留各语言文案中的引号与换行。+ return JSON.stringify(languages).replace(/</g, "\\u003c")+ .replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");+};+const getPluginStyle = async () => {const response = await fetchSyncPost("/api/petal/loadPetals", {frontend: getFrontend()});let css = "";@@ -683,7 +695,7 @@ ${getIconScript(servePath)}katexMacros: decodeURI(\`${encodeURI(window.siyuan.config.editor.katexMacros)}\`),}},- languages: {copy:"${window.siyuan.languages.copy}"}+ languages: ${getExportLanguages()}};previewElement.addEventListener("click", (event) => {let target = event.target;@@ -1107,7 +1119,7 @@ ${getIconScript(servePath)}katexMacros: decodeURI(\`${encodeURI(window.siyuan.config.editor.katexMacros)}\`),}},- languages: {copy:"${window.siyuan.languages.copy}"}+ languages: ${getExportLanguages()}};const previewElement = document.getElementById('preview');Protyle.highlightRender(previewElement, "stage/protyle");diff --git a/app/src/protyle/export/listMindmapExport.test.ts b/app/src/protyle/export/listMindmapExport.test.tsnew file mode 100644index 0000000000..d7130f9499--- /dev/null+++ b/app/src/protyle/export/listMindmapExport.test.ts@@ -0,0 +1,61 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {resolve} from "node:path";+import test from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";++const exportSource = readFileSync(resolve(process.cwd(), "src/protyle/export/index.ts"), "utf8");++test("mind map export labels preserve localized text without closing the generated script", () => {+ const source = createSourceFile("export.ts", exportSource, ScriptTarget.Latest, true);+ const declaration = source.statements.filter(isVariableStatement)+ .flatMap(statement => Array.from(statement.declarationList.declarations))+ .find(item => item.name.getText(source) === "getExportLanguages");+ assert.ok(declaration?.initializer);+ const languages = {+ copy: "Copy \"text\"\n</script><script>alert(1)</script>",+ listMindmapRoot: "Current\u2028list\u2029root",+ connect: "Connect",+ text: "Text",+ listMindmapToList: "List view",+ fullscreen: "Fullscreen",+ exitFullscreen: "Exit fullscreen",+ unrelated: "Not exported",+ };+ const compiled = transpileModule(`(${declaration.initializer.getText(source)})()`, {+ compilerOptions: {target: ScriptTarget.ES2020},+ }).outputText;+ const serialized = runInNewContext(compiled, {window: {siyuan: {languages}}});+ assert.ok(!serialized.includes("</script>"));+ assert.ok(!serialized.includes("\u2028"));+ assert.ok(!serialized.includes("\u2029"));+ const expected: Record<string, string> = {...languages};+ delete expected.unrelated;+ assert.deepEqual(JSON.parse(serialized), expected);+ assert.equal(exportSource.match(/languages: \$\{getExportLanguages\(\)\}/g)?.length, 2);+});++test("the public mind map renderer also renders documents containing only list mind maps", () => {+ const source = readFileSync(resolve(process.cwd(), "src/protyle/render/mindmapRender.ts"), "utf8");+ const calls: string[] = [];+ const exported: {mindmapRender?: (element: unknown) => void} = {};+ const compiled = transpileModule(source, {+ compilerOptions: {target: ScriptTarget.ES2020, module: ModuleKind.CommonJS},+ }).outputText;+ const dependencies: Record<string, unknown> = {+ "../../constants": {Constants: {PROTYLE_CDN: "stage/protyle"}},+ "./listMindmap/render": {listMindmapRender: () => calls.push("list")},+ "../util/addScript": {addScript: () => calls.push("echarts")},+ };+ runInNewContext(compiled, {+ exports: exported,+ require: (name: string) => dependencies[name] || {},+ });+ assert.ok(exported.mindmapRender);+ exported.mindmapRender({+ getAttribute: (): string | null => null,+ querySelectorAll: (): Element[] => [],+ });+ assert.deepEqual(calls, ["list"]);+});diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex 8edd5822c0..4a9066ab05 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -42,6 +42,7 @@ import {hideElements} from "../ui/hideElements";import {markGutterForFoldRestore} from "../ui/gutterVisibility";import {highlightRender} from "../render/highlightRender";import {blockRender} from "../render/blockRender";+import {toggleListMindmap} from "../render/listMindmap";import {getContenteditableElement,getEmbedGutterOperationContext,@@ -2189,6 +2190,18 @@ export class Gutter {void appendListItem(protyle, nodeElement as HTMLElement, range);}});+ if (type === "NodeList") {+ submenu.push({+ id: "listMindmap",+ icon: "iconGraph",+ label: nodeElement.getAttribute("custom-list-mindmap") === "1" ?+ window.siyuan.languages.listMindmapToList : window.siyuan.languages.listMindmapToMindmap,+ click() {+ hideElements(["select"], protyle);+ void toggleListMindmap(protyle, nodeElement as HTMLElement);+ },+ });+ }return submenu;};window.siyuan.menus.menu.append(new MenuItem({id: "separator_listBlock", type: "separator"}).element);diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.tsindex a0a3cbda30..011057969a 100644--- a/app/src/protyle/index.ts+++ b/app/src/protyle/index.ts@@ -72,6 +72,7 @@ import {queueDatabaseRowRefreshForOperations} from "./render/av/databaseRowRefresh";import {initEditorTabs} from "./wysiwyg/tabs";+import {initListMindmaps} from "./render/listMindmap";import {registerCustomBlockRoot} from "../plugin/customBlockRender";import {getTransactionOperations} from "../util/transactionOperations";import {@@ -209,6 +210,7 @@ export class Protyle {this.protyle.undo = this.protyle.lite ? new LocalUndo() : new Undo();this.protyle.wysiwyg = new WYSIWYG(this.protyle);initEditorTabs(this.protyle);+ initListMindmaps(this.protyle);if (isProtyleCustomBlockRenderEnabled(this.protyle)) {registerCustomBlockRoot(this.protyle.wysiwyg.element, {disabled: () => this.protyle.disabled,diff --git a/app/src/protyle/render/listMindmap/editor.test.ts b/app/src/protyle/render/listMindmap/editor.test.tsnew file mode 100644index 0000000000..5284efde9e--- /dev/null+++ b/app/src/protyle/render/listMindmap/editor.test.ts@@ -0,0 +1,315 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import test from "node:test";+import {promisify} from "node:util";+import {ScriptTarget, transpileModule} from "typescript";++const browserCases = async (sourceCode: string, css: string) => {+ const check = require("node:assert/strict");+ const noop = (): void => undefined;+ const settle = async () => {+ await new Promise<void>(resolve => setTimeout(resolve, 0));+ };+ const until = async (condition: () => boolean) => {+ for (let attempt = 0; attempt < 100; attempt++) {+ if (condition()) {+ return;+ }+ await settle();+ }+ check.fail("Editor lifecycle did not settle");+ };+ const gate = () => {+ let release: () => void;+ const promise = new Promise<void>(resolve => {+ release = resolve;+ });+ return {promise, release};+ };+ const textHTML = (text: string) => {+ const block = document.createElement("div");+ block.dataset.type = "NodeParagraph";+ block.dataset.nodeId = "paragraph";+ block.textContent = text;+ return block.outerHTML;+ };+ const create = () => {+ const container = document.createElement("section");+ const element = document.createElement("div");+ element.dataset.type = "NodeListItem";+ element.dataset.nodeId = "item";+ element.innerHTML = textHTML("Initial");+ const host = document.createElement("div");+ host.style.display = "inline-block";+ host.style.width = "120px";+ host.style.minWidth = "36px";+ const wysiwyg = document.createElement("div");+ const hintElement = document.createElement("div");+ const toolbarElement = document.createElement("div");+ const subElement = document.createElement("div");+ [hintElement, toolbarElement, subElement].forEach(item => item.classList.add("fn__none"));+ container.append(element, host, hintElement, toolbarElement, subElement);+ document.body.append(container);+ const state = {+ flushed: 0,+ destroyed: 0,+ finished: 0,+ saves: [] as string[],+ messages: [] as string[],+ accept: true,+ flush: async (): Promise<void> => undefined,+ saveBarrier: undefined as Promise<void> | undefined,+ };+ const protyle = {+ block: {rootID: ""},+ undo: {clear: noop},+ wysiwyg: {flushPendingInput: async () => {+ state.flushed++;+ await state.flush();+ }},+ toolbar: {element: toolbarElement, subElement},+ };+ const dependencies = {+ showMessage: (message: string) => state.messages.push(message),+ escapeHtml: (value: string) => {+ const node = document.createElement("span");+ node.textContent = value;+ return node.innerHTML;+ },+ isMobile: () => false,+ hintRef: (): unknown[] => [],+ hintSlash: (): unknown[] => [],+ registerBuiltinSlashHint: (callback: unknown) => callback,+ mountProtyleLiteFragment: (target: HTMLElement, options: {+ initialBlockHTML: string;+ onChange: () => void;+ afterSetContent: (owner: unknown, element: HTMLElement) => void;+ }) => {+ target.style.width = "";+ wysiwyg.innerHTML = options.initialBlockHTML;+ target.append(wysiwyg);+ options.afterSetContent(protyle, wysiwyg);+ const observer = new MutationObserver(options.onChange);+ observer.observe(wysiwyg, {subtree: true, childList: true, characterData: true});+ return {+ protyle, wysiwyg, hintElement,+ focus: noop,+ getBlockHTML: () => wysiwyg.innerHTML,+ getMarkdown: () => wysiwyg.textContent,+ destroy: () => {+ observer.disconnect();+ state.destroyed++;+ },+ };+ },+ setMobileToolbarUndo: noop,+ getDefaultToolbar: (): unknown[] => [],+ hideElements: noop,+ matchHotKey: () => false,+ TABLE_CELL_SLASH_IDS: new Set<string>(),+ configureAVRichTextLute: noop,+ getAVRichTextLute: () => ({}),+ getAVRichTextUnsupportedPasteBlocks: (): string[] => [],+ sanitizeAVRichTextBlockDOM: (html: string) => html,+ highlightRender: noop,+ mathRender: noop,+ cleanListMindmapHTML: (html: string) => html,+ };+ const open = new Function(...Object.keys(dependencies), sourceCode + "; return openListMindmapEditor;")(+ ...Object.values(dependencies));+ const editor = open({+ owner: {app: {}, notebookId: "notebook", block: {rootID: "document"}},+ node: {element}, host,+ canEdit: () => element.isConnected,+ onResize: noop,+ onFinish: () => state.finished++,+ onUndo: noop,+ onSave: async (html: string) => {+ state.saves.push(html);+ await state.saveBarrier;+ if (!state.accept) {+ return false;+ }+ element.innerHTML = html;+ return true;+ },+ });+ check.ok(editor);+ check.equal(protyle.block.rootID, "document");+ const type = async (value: string) => {+ wysiwyg.innerHTML = textHTML(value);+ await settle();+ };+ const remove = async () => {+ editor.destroy();+ await until(() => state.destroyed === 1);+ container.remove();+ };+ return {container, element, host, wysiwyg, state, editor, type, remove};+ };+ window.siyuan = {+ languages: {listMindmapStale: "Content changed", listMindmapUnsupported: "Unsupported"},+ config: {keymap: {editor: {general: {undo: "undo", redo: "redo"}}}},+ } as unknown as typeof window.siyuan;++ // 关闭前等待输入转换完成,保存转换后的最终内容后再销毁编辑器。+ let current = create();+ check.equal(current.host.offsetWidth, 120, "mounting the editor preserves the preview width");+ await current.type("Pending");+ const flushGate = gate();+ current.state.flush = async () => {+ await flushGate.promise;+ current.wysiwyg.innerHTML = textHTML("Final after flush");+ };+ const finishing = current.editor.finish();+ check.equal(current.editor.finish(), finishing);+ await settle();+ check.equal(current.state.saves.length, 0);+ check.equal(current.state.destroyed, 0);+ flushGate.release();+ check.equal(await finishing, true);+ check.equal(current.element.textContent, "Final after flush");+ check.equal(current.state.destroyed, 1);+ check.equal(current.state.finished, 1);+ check.equal(current.host.style.minWidth, "36px", "closing restores the original minimum width");+ check.equal(current.state.saves.length, 1);+ await current.remove();++ // 保存失败时保留正文和编辑器,允许下一次关闭重新提交。+ current = create();+ await current.type("Retry me");+ current.state.accept = false;+ check.equal(await current.editor.finish(), false);+ check.equal(current.state.destroyed, 0);+ check.equal(current.state.finished, 0);+ check.equal(current.wysiwyg.textContent, "Retry me");+ check.equal(current.element.textContent, "Initial");+ current.state.accept = true;+ check.equal(await current.editor.finish(), true);+ check.equal(current.element.textContent, "Retry me");+ await current.remove();++ // 输入法组合期间拒绝关闭,组合结束后完成保存和延迟关闭。+ current = create();+ current.host.dispatchEvent(new CompositionEvent("compositionstart", {bubbles: true}));+ await current.type("Composing");+ check.equal(await current.editor.finish(), false);+ check.equal(current.state.saves.length, 0);+ check.equal(current.state.destroyed, 0);+ await current.type("Composition complete");+ current.host.dispatchEvent(new CompositionEvent("compositionend", {bubbles: true}));+ await until(() => current.state.destroyed === 1);+ check.equal(current.element.textContent, "Composition complete");+ check.equal(current.state.finished, 1);+ await current.remove();++ // 外部改动不能被旧会话覆盖,未保存正文保留在可恢复提示中。+ current = create();+ await current.type("Unsaved local content");+ current.element.innerHTML = textHTML("External content");+ check.equal(await current.editor.finish(), false);+ check.equal(current.element.textContent, "External content");+ check.equal(current.state.saves.length, 0);+ check.equal(current.state.destroyed, 0);+ check.ok(current.state.messages.some(message => message.includes("Unsaved local content")));+ await current.remove();++ // 强制卸载也要排空输入任务,并保留尚未写回的最终正文供恢复。+ current = create();+ await current.type("Before destroy");+ const destroyGate = gate();+ current.state.flush = async () => {+ await destroyGate.promise;+ current.wysiwyg.innerHTML = textHTML("Final before destroy");+ };+ current.editor.destroy();+ await settle();+ check.equal(current.state.destroyed, 0);+ destroyGate.release();+ await until(() => current.state.destroyed === 1);+ check.equal(current.element.textContent, "Initial");+ check.ok(current.state.messages.some(message => message.includes("Final before destroy")));+ await current.remove();++ // 保存等待期间继续输入,随后关闭必须保存后续文字,不能被旧请求清除变更标记。+ current = create();+ await current.type("First save");+ const saveGate = gate();+ current.state.saveBarrier = saveGate.promise;+ window.dispatchEvent(new Event("blur"));+ await until(() => current.state.saves.length === 1);+ await current.type("Typed during save");+ saveGate.release();+ await settle();+ check.equal(await current.editor.finish(), true);+ check.equal(current.element.textContent, "Typed during save");+ check.equal(current.state.destroyed, 1);+ await current.remove();++ // 使用完整样式和外层文档结构,覆盖嵌套编辑器的最小高度及行高继承。+ const style = document.createElement("style");+ style.textContent = css;+ document.head.append(style);+ const fixture = document.createElement("div");+ fixture.className = "protyle-wysiwyg";+ document.body.append(fixture);+ for (const text of ["Test text", '<span data-type="strong">11pppppp</span>', "First<br>Second"]) {+ fixture.innerHTML = `<div data-node-id="list" data-type="NodeList"><div class="list-mindmap"><div class="list-mindmap__node"><div class="list-mindmap__content"><div class="p"><div>${text}</div></div></div></div></div></div>`;+ const node = fixture.querySelector<HTMLElement>(".list-mindmap__node");+ const content = fixture.querySelector<HTMLElement>(".list-mindmap__content");+ const before = node.offsetHeight;+ content.style.minWidth = `${content.offsetWidth}px`;+ content.classList.add("list-mindmap__editor", "protyle");+ content.innerHTML = `<div class="protyle-content"><div class="protyle-wysiwyg" spellcheck="false" contenteditable="true"><div class="p" data-node-id="text" data-type="NodeParagraph"><div contenteditable="true" spellcheck="false">${text}</div></div></div></div>`;+ check.equal(node.offsetHeight, before, "entering edit mode preserves node height inside the document");+ }+ fixture.remove();+ style.remove();+ return "List mindmap editor lifecycle cases passed";+};++test("list mindmap editor flushes pending input and preserves text across finish, composition and destroy", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+}, async () => {+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-list-mindmap-editor-test-"));+ const script = path.join(temporary, "run.cjs");+ const source = transpileModule(readFileSync(path.join(__dirname, "editor.ts"), "utf8")+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""), {+ compilerOptions: {target: ScriptTarget.ES2021},+ }).outputText;+ const css = require("sass").compile(path.resolve(__dirname, "../../../assets/scss/base.scss"), {+ logger: require("sass").Logger.silent,+ }).css;+ const code = `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ const result = await win.webContents.executeJavaScript(${JSON.stringify(+ `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(source)}, ${JSON.stringify(css)})`)});+ console.log(result);+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`;+ writeFileSync(script, code, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const executable = require("electron") as unknown as string;+ const result = await promisify(execFile)(executable, [script], {env, timeout: 40000, windowsHide: true});+ assert.match(result.stdout, /List mindmap editor lifecycle cases passed/);+ } finally {+ rmSync(temporary, {recursive: true, force: true});+ }+});diff --git a/app/src/protyle/render/listMindmap/editor.ts b/app/src/protyle/render/listMindmap/editor.tsnew file mode 100644index 0000000000..24a1b40c0a--- /dev/null+++ b/app/src/protyle/render/listMindmap/editor.ts@@ -0,0 +1,281 @@+import {showMessage} from "../../../dialog/message";+import {escapeHtml} from "../../../util/escape";+import {isMobile} from "../../../util/functions";+import {hintRef, hintSlash} from "../../hint/extend";+import {registerBuiltinSlashHint} from "../../hint/builtinSlash";+import {mountProtyleLiteFragment} from "../../lite/fragmentEditor";+import {setMobileToolbarUndo} from "../../lite/mobileToolbar";+import {getDefaultToolbar} from "../../toolbar/defaults";+import {hideElements} from "../../ui/hideElements";+import {matchHotKey} from "../../util/hotKey";+import {TABLE_CELL_SLASH_IDS} from "../../util/tableCellRichMenu";+import {+ configureAVRichTextLute, getAVRichTextLute, getAVRichTextUnsupportedPasteBlocks, sanitizeAVRichTextBlockDOM,+} from "../av/richText";+import {highlightRender} from "../highlightRender";+import {mathRender} from "../mathRender";+import {cleanListMindmapHTML} from "./model";+import type {ListMindmapNode} from "./model";++interface ListMindmapEditorOptions {+ owner: IProtyle;+ node: ListMindmapNode;+ host: HTMLElement;+ canEdit: () => boolean;+ onSave: (html: string) => Promise<boolean>;+ onResize: () => void;+ onFinish: () => void;+ onUndo: (redo: boolean) => void;+}++const nodeContent = (node: ListMindmapNode) => Array.from(node.element?.children || []).filter(child =>+ child.hasAttribute("data-node-id") && child.getAttribute("data-type") !== "NodeList")+ .map(child => cleanListMindmapHTML(child.outerHTML)).join("");++// 编辑器只在双击时挂载到节点内容区,预览与编辑沿用同一尺寸和排版。+export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {+ const {owner, node, host} = options;+ const initialBlockHTML = nodeContent(node);+ if (!options.canEdit() || !node.element?.isConnected) {+ return;+ }+ if (getAVRichTextUnsupportedPasteBlocks(initialBlockHTML, true).length) {+ showMessage(window.siyuan.languages.listMindmapUnsupported);+ return;+ }+ hideElements(["gutter", "toolbar", "hint"], owner);+ let finished = false;+ let closing = false;+ let composing = false;+ let finishAfterComposition = false;+ let changed = false;+ let saving = false;+ let pendingSave: Promise<boolean> | undefined;+ let pendingFinish: Promise<boolean> | undefined;+ let saveTimer: number;+ let source = initialBlockHTML;+ let recoveryShown = false;+ const events = new AbortController();+ const toolbar = getDefaultToolbar(isMobile()).filter(item =>+ typeof item === "string" ? item !== "ai" : item.name !== "ai");+ const slash = registerBuiltinSlashHint((key: string, protyle: IProtyle, hintSource: THintSource) =>+ hintSlash(key, protyle, hintSource).filter(item => TABLE_CELL_SLASH_IDS.has(item.id)));+ const hint: IProtyleOptions["hint"] = {+ extend: [{key: "((", hint: hintRef}, {key: "【【", hint: hintRef}, {key: "((", hint: hintRef},+ {key: "[[", hint: hintRef}, {key: "/", hint: slash}, {key: "、", hint: slash}],+ };+ const originalMinWidth = host.style.minWidth;+ // 挂载前保留未缩放的内容宽度,避免轻量编辑器改变内在尺寸后挤压文字。+ host.style.minWidth = `${host.offsetWidth}px`;+ host.replaceChildren();+ host.classList.add("list-mindmap__editor");+ host.dataset.protyleLiteRender = "safe";+ host.contentEditable = "false";+ const fragment = mountProtyleLiteFragment(host, {+ app: owner.app,+ initialBlockHTML,+ placeholder: window.siyuan.languages.listMindmapPlaceholder,+ protyleOptions: {notebookId: owner.notebookId, toolbar, hint},+ runtimeCapabilities: {+ upload: false, websocket: false, pluginExtensions: false, customBlockRender: false,+ lute: getAVRichTextLute(), lockedOptions: {toolbar, hint},+ sanitizeBlockDOM: html => sanitizeAVRichTextBlockDOM(html, true),+ getUnsupportedPasteBlocks: html => getAVRichTextUnsupportedPasteBlocks(html, true),+ restoreLuteMarkdownSyntax: configureAVRichTextLute,+ },+ afterSetContent: (protyle, element) => {+ highlightRender(element);+ mathRender(element);+ protyle.undo.clear();+ },+ onChange: () => {+ if (finished || closing) {+ return;+ }+ changed = true;+ options.onResize();+ if (saving) {+ return;+ }+ clearTimeout(saveTimer);+ saveTimer = window.setTimeout((): void => { void commit(); }, 350);+ },+ });+ fragment.protyle.block.rootID = owner.block.rootID;+ const overlays = [fragment.hintElement, fragment.protyle.toolbar.element, fragment.protyle.toolbar.subElement];+ const overlayRoot = host.closest(".list-mindmap") || document.body;+ // 菜单使用未缩放的容器定位,同时保持在原生全屏元素内可见。+ overlays.forEach(element => overlayRoot.appendChild(element));+ let lastHTML = cleanListMindmapHTML(fragment.getBlockHTML());+ const recover = () => {+ if (recoveryShown) {+ return;+ }+ recoveryShown = true;+ // 原节点被外部事务替换时保留尚未提交的正文,避免覆盖新内容或静默丢弃输入。+ showMessage(`${escapeHtml(window.siyuan.languages.listMindmapStale)}<pre>${escapeHtml(fragment.getMarkdown())}</pre>`,+ 0, "error");+ };+ const commit = (finishSession = false): Promise<boolean> => {+ if (pendingSave) {+ return pendingSave;+ }+ pendingSave = save(finishSession).catch(error => {+ console.error(error);+ showMessage(window.siyuan.languages.listMindmapInvalid);+ return false;+ }).finally(() => {+ pendingSave = undefined;+ });+ return pendingSave;+ };+ const save = async (finishSession: boolean) => {+ clearTimeout(saveTimer);+ if (finished || closing || composing || saving) {+ return false;+ }+ await fragment.protyle.wysiwyg.flushPendingInput();+ if (finished || composing) {+ return false;+ }+ // 输入的新列表在结束本次编辑时转换为子节点,避免在连续输入中移走正在编辑的正文。+ if (!finishSession && Array.from(fragment.wysiwyg.children).some(element =>+ element.getAttribute("data-type") === "NodeList")) {+ return false;+ }+ const html = cleanListMindmapHTML(fragment.getBlockHTML());+ if (html === lastHTML) {+ changed = false;+ return true;+ }+ if (!options.canEdit() || !node.element.isConnected || nodeContent(node) !== source) {+ recover();+ return false;+ }+ saving = true;+ try {+ if (!await options.onSave(html)) {+ return false;+ }+ source = nodeContent(node);+ lastHTML = html;+ changed = cleanListMindmapHTML(fragment.getBlockHTML()) !== html;+ if (changed && !finishSession) {+ saveTimer = window.setTimeout((): void => { void commit(); }, 350);+ }+ return true;+ } finally {+ saving = false;+ }+ };+ const cleanup = () => {+ if (finished) {+ return;+ }+ const html = cleanListMindmapHTML(fragment.getBlockHTML());+ if (html !== lastHTML) {+ recover();+ }+ finished = true;+ clearTimeout(saveTimer);+ events.abort();+ observer.disconnect();+ fragment.destroy();+ overlays.forEach(element => element.remove());+ host.classList.remove("list-mindmap__editor");+ host.style.minWidth = originalMinWidth;+ delete host.dataset.protyleLiteRender;+ options.onFinish();+ };+ const destroy = () => {+ if (finished || closing) {+ return;+ }+ closing = true;+ events.abort();+ clearTimeout(saveTimer);+ // 卸载前排空输入任务,延迟转换不会再访问已销毁的编辑器。+ void fragment.protyle.wysiwyg.flushPendingInput().catch(error => console.error(error)).finally(cleanup);+ };+ const finish = (): Promise<boolean> => {+ if (!pendingFinish) {+ pendingFinish = endSession().finally(() => {+ pendingFinish = undefined;+ });+ }+ return pendingFinish;+ };+ const endSession = async () => {+ if (finished) {+ return true;+ }+ if (composing) {+ finishAfterComposition = true;+ return false;+ }+ if (pendingSave) {+ await pendingSave;+ }+ do {+ if (!await commit(true)) {+ return false;+ }+ } while (cleanListMindmapHTML(fragment.getBlockHTML()) !== lastHTML);+ cleanup();+ return true;+ };+ const undo = async (redo: boolean) => {+ if (await finish()) {+ options.onUndo(redo);+ }+ };+ setMobileToolbarUndo(fragment.protyle, owner, undo);+ const signal = events.signal;+ ["beforeinput", "input", "compositionstart", "compositionupdate", "compositionend", "copy", "cut", "paste",+ "pointerdown", "pointerup", "pointermove", "mousedown", "mouseup", "mousemove", "click", "dblclick",+ "contextmenu", "dragstart", "dragover", "drop", "focusin", "focusout", "keyup"]+ .forEach(type => host.addEventListener(type, event => event.stopPropagation(), {signal}));+ host.addEventListener("keydown", event => event.stopPropagation(), {signal});+ host.addEventListener("keydown", event => {+ if (event.isComposing || composing) {+ return;+ }+ const keymap = window.siyuan.config.keymap.editor.general;+ if (matchHotKey(keymap.undo, event) || matchHotKey(keymap.redo, event)) {+ event.preventDefault();+ event.stopImmediatePropagation();+ undo(matchHotKey(keymap.redo, event));+ } else if (event.key === "Escape" && fragment.hintElement.classList.contains("fn__none") &&+ fragment.protyle.toolbar.element.classList.contains("fn__none") &&+ fragment.protyle.toolbar.subElement.classList.contains("fn__none")) {+ event.preventDefault();+ event.stopImmediatePropagation();+ finish();+ }+ }, {capture: true, signal});+ host.addEventListener("compositionstart", () => {+ composing = true;+ clearTimeout(saveTimer);+ }, {capture: true, signal});+ host.addEventListener("compositionend", () => queueMicrotask(() => {+ composing = false;+ void commit();+ if (finishAfterComposition) {+ finish();+ }+ }), {capture: true, signal});+ const belongs = (target: Node) => host.contains(target) || fragment.hintElement.contains(target) ||+ fragment.protyle.toolbar.element.contains(target) || fragment.protyle.toolbar.subElement.contains(target) ||+ !!(target instanceof Element && target.closest("#keyboardToolbar, #commonMenu, .b3-dialog"));+ document.addEventListener("pointerdown", event => {+ if (!belongs(event.target as Node)) {+ finish();+ }+ }, {capture: true, signal});+ window.addEventListener("blur", () => void commit(), {signal});+ window.addEventListener("pagehide", () => void finish(), {signal});+ const observer = new ResizeObserver(() => options.onResize());+ observer.observe(host);+ fragment.focus(true);+ return {finish, destroy};+};diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.tsnew file mode 100644index 0000000000..f670dbaeb6--- /dev/null+++ b/app/src/protyle/render/listMindmap/index.ts@@ -0,0 +1,427 @@+import {Constants} from "../../../constants";+import {showMessage} from "../../../dialog/message";+import {fetchSyncPost} from "../../../util/fetch";+import {normalizeHTMLAssetIFrameBlockDOM} from "../../../asset/html";+import {updateTransaction, transaction} from "../../wysiwyg/transaction";+import {genListItemElement} from "../../wysiwyg/list";+import {completeTabsListSource} from "../../wysiwyg/tabsList";+import {waitForPendingTransactions} from "../../util/transactionQueue";+import {hideAllElements, hideElements} from "../../ui/hideElements";+import {globalClickHideMenu} from "../../../boot/globalEvent/click";+import {openLink} from "../../../editor/openLink";+import {matchHotKey} from "../../util/hotKey";+import {setFullscreen} from "../../breadcrumb/action";+import {+ getBuiltinColorPropertyValue, getBuiltinInlineStylePreview, getInlineStyleByID, getInlineStylePreview, getInlineStylePropertyValue,+ getInlineStylesCache, getVisibleOrderedStyleKeys, isBuiltinOrderKey,+ TBuiltinInlineStyleID,+} from "../../toolbar/inlineStyle";+import {openInlineStyleDialog} from "../../toolbar/inlineStyleDialog";+import {+ addListMindmapNode, cleanListMindmapHTML, deleteListMindmapNode,+ LIST_MINDMAP_VIEW_ATTRIBUTE, moveListMindmapNode, readListMindmap, replaceListMindmapContent,+ writeListMindmapMetadata,+} from "./model";+import type {ListMindmapMetadata, ListMindmapModel} from "./model";+import {getListMindmapElements, registerListMindmapRoot} from "./render";+import {ListMindmapView} from "./view";+import {openListMindmapEditor} from "./editor";++const roots = new WeakMap<IProtyle, {refresh: () => void, destroy: () => void}>();++const canEdit = (owner: IProtyle, list: HTMLElement) => !owner.disabled && !owner.lite &&+ !owner.options.action.includes(Constants.CB_GET_HISTORY) &&+ !list.closest(".protyle-wysiwyg__embed") && list.closest(".protyle-wysiwyg") === owner.wysiwyg.element;++export const toggleListMindmap = (owner: IProtyle, list: HTMLElement) => {+ if (list.dataset.type !== "NodeList" || !canEdit(owner, list)) {+ return;+ }+ const previous = list.getAttribute(LIST_MINDMAP_VIEW_ATTRIBUTE) || "";+ const next = previous === "1" ? "" : "1";+ if (next) {+ try {+ readListMindmap(list);+ } catch (error) {+ console.error(error);+ showMessage(window.siyuan.languages.listMindmapInvalid);+ return;+ }+ }+ hideElements(["gutter", "toolbar", "hint"], owner);+ list.setAttribute(LIST_MINDMAP_VIEW_ATTRIBUTE, next);+ transaction(owner, [{action: "setAttrs", id: list.dataset.nodeId,+ data: JSON.stringify({[LIST_MINDMAP_VIEW_ATTRIBUTE]: next})}], [{action: "setAttrs", id: list.dataset.nodeId,+ data: JSON.stringify({[LIST_MINDMAP_VIEW_ATTRIBUTE]: previous})}]);+ roots.get(owner)?.refresh();+};++class ListMindmapController {+ public readonly list: HTMLElement;+ private readonly owner: IProtyle;+ private readonly host: HTMLElement;+ private readonly view: ListMindmapView;+ private model: ListMindmapModel;+ private snapshot = "";+ private activeEditor?: {finish: () => Promise<boolean>, destroy: () => void};+ private editRequest = 0;+ private disposed = false;++ constructor(owner: IProtyle, list: HTMLElement) {+ this.owner = owner;+ this.list = list;+ this.model = readListMindmap(list);+ list.querySelector(":scope > .list-mindmap")?.remove();+ this.host = document.createElement("div");+ this.host.className = "list-mindmap";+ this.host.contentEditable = "false";+ this.host.addEventListener("pointerdown", event => {+ const target = event.target as HTMLElement;+ // 脑图阻止事件冒泡,主动复用公共收起逻辑,并保留内嵌编辑器浮层的交互。+ globalClickHideMenu(target);+ if (!target.closest(".protyle-toolbar, .protyle-util, [data-sub-element-source]")) {+ hideAllElements(["toolbar", "util", "gutter"]);+ hideElements(["hint"], this.owner);+ }+ }, {capture: true});+ this.host.addEventListener("keydown", event => {+ if (event.isComposing || (event.target instanceof Element &&+ event.target.closest("input, textarea, select, .list-mindmap__editor"))) {+ return;+ }+ const keys = owner.options?.action && window.siyuan.config.keymap.editor.general;+ if (keys && (matchHotKey(keys.undo, event) || matchHotKey(keys.redo, event))) {+ event.preventDefault();+ event.stopImmediatePropagation();+ void this.undo(matchHotKey(keys.redo, event));+ }+ }, {capture: true});+ list.appendChild(this.host);+ let restoreFullscreenChrome: () => void;+ this.view = new ListMindmapView({+ host: this.host, model: this.model, labels: window.siyuan.languages,+ onOpenLink: (href, event) => openLink(owner.app, href, event, event.ctrlKey || event.metaKey),+ readOnly: !canEdit(owner, list),+ onFullscreen: (enter, button) => {+ if (enter) {+ const drag = document.getElementById("drag");+ const controls = document.getElementById("windowControls");+ const dragHidden = drag?.classList.contains("fn__hidden");+ const controlsZIndex = controls?.style.zIndex;+ // 脑图可以从全屏编辑器中打开,退出后恢复原窗口控件状态。+ restoreFullscreenChrome = () => {+ drag?.classList.toggle("fn__hidden", !!dragHidden);+ if (controls) {+ controls.style.zIndex = controlsZIndex;+ }+ };+ }+ setFullscreen(this.host, enter, button);+ if (!enter) {+ restoreFullscreenChrome?.();+ restoreFullscreenChrome = undefined;+ }+ },+ colors: () => {+ const type = "backgroundColor";+ const data = getInlineStylesCache();+ return getVisibleOrderedStyleKeys(type, data).map(key => {+ if (isBuiltinOrderKey(type, key)) {+ return {label: `${window.siyuan.languages.color} ${key}`,+ value: getBuiltinColorPropertyValue(Number(key), type)};+ }+ const style = getInlineStyleByID(key, data);+ return {label: style.name, value: getInlineStylePropertyValue(style, type)};+ });+ },+ nodeColors: () => {+ const data = getInlineStylesCache();+ return getVisibleOrderedStyleKeys("style1", data).map(key => {+ if (isBuiltinOrderKey("style1", key)) {+ return {label: window.siyuan.languages[`${key}Style`],+ ...getBuiltinInlineStylePreview(key as TBuiltinInlineStyleID)};+ }+ const style = getInlineStyleByID(key, data);+ return {label: style.name, ...getInlineStylePreview(style)};+ });+ },+ onManageNodeColors: () => openInlineStyleDialog("style1"),+ finishEdit: () => this.activeEditor?.finish(),+ onExit: async () => {+ if (this.activeEditor && !await this.activeEditor.finish()) {+ return;+ }+ if (canEdit(owner, list)) {+ toggleListMindmap(owner, list);+ } else {+ this.destroy();+ }+ },+ onEdit: (id, contentHost) => this.edit(id, contentHost),+ onMove: (id, target, placement) => this.change(() => moveListMindmapNode(list, id, target, placement)),+ onAdd: async (id, kind) => {+ const target = this.model.nodes.get(id);+ if (!target) {+ return;+ }+ const item = genListItemElement(target.element || list);+ if (!await this.change(() => addListMindmapNode(list, id, kind === "child" ? "child" : "after", item))) {+ return;+ }+ const content = this.view.getContentHost(item.dataset.nodeId);+ if (content) {+ this.edit(item.dataset.nodeId, content);+ }+ },+ onDelete: id => this.change(() => deleteListMindmapNode(list, id)),+ onFold: id => this.change(() => {+ const node = this.model.nodes.get(id);+ if (node?.element && !node.virtual) {+ node.element.setAttribute("fold", node.collapsed ? "0" : "1");+ }+ }),+ onUndo: () => this.undo(false),+ onRedo: () => this.undo(true),+ onNodeStyle: (id, patch) => this.metadata(metadata => {+ metadata.nodes[id] = {...metadata.nodes[id], ...patch};+ }),+ onRelationAdd: (from, to) => this.metadata(metadata => {+ if (from !== to && !metadata.relations.some(relation => relation.from === from && relation.to === to)) {+ metadata.relations.push({id: Lute.NewNodeID(), from, to, label: ""});+ }+ }),+ onRelationChange: (id, patch) => this.metadata(metadata => {+ const relation = metadata.relations.find(item => item.id === id);+ if (relation) {+ Object.assign(relation, patch);+ }+ }),+ onRelationDelete: id => this.metadata(metadata => {+ metadata.relations = metadata.relations.filter(item => item.id !== id);+ }),+ });+ list.dataset.listMindmapRendered = "true";+ this.snapshot = cleanListMindmapHTML(list.outerHTML);+ }++ private metadata(change: (metadata: ListMindmapMetadata) => void) {+ this.change(() => {+ const metadata = readListMindmap(this.list).metadata;+ change(metadata);+ writeListMindmapMetadata(this.list, metadata);+ });+ }++ private async change(change: () => unknown, editing = false) {+ if (this.disposed || !this.list.isConnected || !canEdit(this.owner, this.list)) {+ return false;+ }+ if (!editing && this.activeEditor && !await this.activeEditor.finish()) {+ return false;+ }+ if (this.disposed || !this.list.isConnected || !canEdit(this.owner, this.list)) {+ return false;+ }+ const before = cleanListMindmapHTML(this.list.outerHTML);+ try {+ if (change() === false) {+ return false;+ }+ updateTransaction(this.owner, this.list, before);+ this.refresh();+ return true;+ } catch (error) {+ console.error(error);+ showMessage(window.siyuan.languages.listMindmapInvalid);+ return false;+ }+ }++ private async edit(id: string, host: HTMLElement) {+ const request = ++this.editRequest;+ if (!canEdit(this.owner, this.list) || (this.activeEditor && !await this.activeEditor.finish()) ||+ request !== this.editRequest || this.disposed || !host.isConnected) {+ return;+ }+ const node = this.model.nodes.get(id);+ if (!node || node.virtual) {+ return;+ }+ this.view.setEditing(id);+ this.activeEditor = openListMindmapEditor({+ owner: this.owner, node, host,+ canEdit: () => !this.disposed && this.list.isConnected && canEdit(this.owner, this.list),+ onSave: html => this.change(() => replaceListMindmapContent(this.list, id, html), true),+ onResize: () => this.view.refreshLayout(),+ onFinish: () => {+ this.activeEditor = undefined;+ this.view.setEditing(undefined);+ if (!this.disposed) {+ this.view.update(this.model);+ }+ },+ onUndo: redo => this.undo(redo),+ });+ if (!this.activeEditor) {+ this.view.setEditing(undefined);+ this.view.update(this.model);+ }+ }++ private async undo(redo: boolean) {+ if (!canEdit(this.owner, this.list) || (this.activeEditor && !await this.activeEditor.finish())) {+ return;+ }+ if (redo) {+ this.owner.undo.redo(this.owner);+ } else {+ this.owner.undo.undo(this.owner);+ }+ }++ public refresh() {+ this.view.setReadOnly(!canEdit(this.owner, this.list));+ const snapshot = cleanListMindmapHTML(this.list.outerHTML);+ if (snapshot === this.snapshot) {+ return;+ }+ this.model = readListMindmap(this.list);+ this.snapshot = snapshot;+ this.view.update(this.model);+ }++ public destroy() {+ if (this.disposed) {+ return;+ }+ this.disposed = true;+ this.activeEditor?.destroy();+ this.view.destroy();+ this.host.remove();+ this.list.removeAttribute("data-list-mindmap-rendered");+ }+}++// 补齐折叠隐藏的正文后才允许改动列表,避免以局部视图覆盖完整块树。+const completeList = async (owner: IProtyle, list: HTMLElement) => {+ await waitForPendingTransactions(owner);+ if (!list.isConnected) {+ return "failed";+ }+ const before = cleanListMindmapHTML(list.outerHTML);+ const response = await fetchSyncPost("/api/block/getBlockDOM", {id: list.dataset.nodeId, notebook: owner.notebookId});+ if (response.code !== 0 || !list.isConnected) {+ return "failed";+ }+ if (cleanListMindmapHTML(list.outerHTML) !== before) {+ return "changed";+ }+ const template = document.createElement("template");+ template.innerHTML = normalizeHTMLAssetIFrameBlockDOM(response.data?.dom || "");+ const full = template.content.firstElementChild;+ if (full?.getAttribute("data-type") !== "NodeList" || full.getAttribute("data-node-id") !== list.dataset.nodeId) {+ return "failed";+ }+ const completed = completeTabsListSource(list, full);+ list.replaceChildren(...Array.from(completed.childNodes));+ return "complete";+};++export const initListMindmaps = (owner: IProtyle) => {+ if (owner.lite || roots.has(owner)) {+ return;+ }+ const root = owner.wysiwyg.element;+ const instances = new Map<HTMLElement, ListMindmapController>();+ const loading = new WeakSet<HTMLElement>();+ let frame = 0;+ let disposed = false;+ const refresh = () => {+ if (disposed) {+ return;+ }+ const lists = new Set(getListMindmapElements(root));+ instances.forEach((instance, list) => {+ if (!lists.has(list)) {+ instance.destroy();+ instances.delete(list);+ } else {+ try {+ instance.refresh();+ } catch (error) {+ console.error(error);+ instance.destroy();+ instances.delete(list);+ }+ }+ });+ lists.forEach(list => {+ if (instances.has(list) || loading.has(list)) {+ return;+ }+ const mount = () => {+ if (disposed || !root.contains(list) || list.getAttribute(LIST_MINDMAP_VIEW_ATTRIBUTE) !== "1") {+ return;+ }+ try {+ instances.set(list, new ListMindmapController(owner, list));+ } catch (error) {+ console.error(error);+ list.querySelector(":scope > .list-mindmap")?.remove();+ list.removeAttribute("data-list-mindmap-rendered");+ }+ };+ if (canEdit(owner, list)) {+ loading.add(list);+ let retry = false;+ void completeList(owner, list).then(complete => {+ if (complete === "complete") {+ mount();+ } else if (complete === "changed") {+ retry = true;+ }+ }).catch(error => console.error(error)).finally(() => {+ loading.delete(list);+ if (retry) {+ schedule();+ }+ });+ } else {+ mount();+ }+ });+ };+ const schedule = () => {+ if (!frame && !disposed) {+ frame = requestAnimationFrame(() => {+ frame = 0;+ refresh();+ });+ }+ };+ const unregister = registerListMindmapRoot(root, schedule);+ const observer = new MutationObserver(records => {+ if (records.some(record => {+ const element = record.target instanceof Element ? record.target : record.target.parentElement;+ return !element?.closest(".list-mindmap") && !(record.type === "attributes" &&+ ["data-list-mindmap-rendered", Constants.ATTRIBUTE_EDITING].includes(record.attributeName));+ })) {+ schedule();+ }+ });+ observer.observe(root, {childList: true, subtree: true, attributes: true, characterData: true});+ roots.set(owner, {refresh: schedule, destroy: () => {+ disposed = true;+ unregister();+ observer.disconnect();+ cancelAnimationFrame(frame);+ instances.forEach(instance => instance.destroy());+ instances.clear();+ }});+ schedule();+};++export const destroyListMindmaps = (owner: IProtyle) => {+ roots.get(owner)?.destroy();+ roots.delete(owner);+};diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.tsnew file mode 100644index 0000000000..96d948c32b--- /dev/null+++ b/app/src/protyle/render/listMindmap/model.test.ts@@ -0,0 +1,899 @@+import * as assert from "node:assert/strict";+import test from "node:test";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {execFile} from "node:child_process";+import {promisify} from "node:util";+import {layoutListMindmap, parseListMindmapMetadata} from "./model";+import type {ListMindmapLayoutNode} from "./model";++const measured = (id: string, width = 100, height = 40,+ children: ListMindmapLayoutNode[] = []): ListMindmapLayoutNode => ({id, width, height, children});++test("mindmap metadata rejects unknown formats and invalid values without replacing original data", () => {+ const value = '{"version":1,"nodes":{"a":{"bold":true,"fontSize":18,"extension":"retained"}},' ++ '"relations":[{"id":"r","from":"a","to":"b","label":"label","dash":true}],"extension":42}';+ assert.equal(JSON.stringify(parseListMindmapMetadata(value)), value);+ assert.deepEqual(parseListMindmapMetadata(null).relations, []);+ for (const invalid of ["", "null", "[]", "{", '{"version":2,"nodes":{},"relations":[]}',+ '{"version":1,"nodes":{"a":{"fontSize":"18"}},"relations":[]}',+ '{"version":1,"nodes":{"a":{"lineWidth":-1}},"relations":[]}',+ '{"version":1,"nodes":{},"relations":[{"id":"r","from":"a","to":"b"}]}',+ '{"version":1,"nodes":{},"relations":[{"id":"r","from":"a","to":"b","label":"","dash":0}]}']) {+ assert.throws(() => parseListMindmapMetadata(invalid), /Invalid list mindmap metadata/);+ }+});++test("variable-size mindmap branches keep their order and never overlap", () => {+ const root = measured("root", 90, 55, [+ measured("a", 220, 200, [measured("a1", 150, 36), measured("a2", 90, 92)]),+ measured("b", 70, 34, [measured("b1", 200, 160), measured("b2", 60, 30)]),+ measured("c", 80, 55),+ ]);+ const snapshot = JSON.stringify(root);+ const layout = layoutListMindmap(root, {horizontalGap: 48, verticalGap: 20, padding: 30});+ const positions = [...layout.nodes.values()];+ assert.equal(positions.length, 8);+ assert.equal(layout.edges.length, 7);+ assert.equal(JSON.stringify(root), snapshot);+ for (const position of positions) {+ assert.ok(position.x >= 30 && position.y >= 30);+ assert.ok(position.x + position.width <= layout.width - 30);+ assert.ok(position.y + position.height <= layout.height - 30);+ if (position.parentId) {+ const parent = layout.nodes.get(position.parentId);+ assert.equal(position.x - parent.x - parent.width, 48);+ }+ for (const other of positions) {+ if (other.id !== position.id) {+ assert.ok(position.x + position.width <= other.x || other.x + other.width <= position.x ||+ position.y + position.height <= other.y || other.y + other.height <= position.y);+ }+ }+ }+ assert.ok(layout.nodes.get("a").y < layout.nodes.get("b").y);+ assert.ok(layout.nodes.get("b").y < layout.nodes.get("c").y);+ assert.equal(layout.nodes.get("a1").x - layout.nodes.get("b2").x, 150);+});++test("folded branches disappear from layout and restore deterministically", () => {+ const root = measured("root", 100, 40, [measured("branch", 100, 40, [measured("leaf", 100, 80)])]);+ const before = layoutListMindmap(root);+ root.children[0].collapsed = true;+ const folded = layoutListMindmap(root);+ assert.equal(folded.nodes.has("leaf"), false);+ assert.ok(folded.width < before.width);+ assert.ok(folded.height < before.height);+ root.children[0].collapsed = false;+ assert.deepEqual(layoutListMindmap(root), before);+});++test("layout rejects cyclic or invalid trees and supports deep nesting without recursive overflow", () => {+ const cyclic = measured("root");+ cyclic.children.push(cyclic);+ assert.throws(() => layoutListMindmap(cyclic), /Invalid list mindmap layout node/);+ assert.throws(() => layoutListMindmap(measured("a", 0)), /Invalid list mindmap layout node/);+ assert.throws(() => layoutListMindmap(measured("a"), {padding: Number.NaN}), /Invalid list mindmap layout spacing/);+ let root = measured("leaf");+ for (let index = 0; index < 5000; index++) {+ root = measured(`node-${index}`, 100, 40, [root]);+ }+ assert.equal(layoutListMindmap(root).nodes.size, 5001);+});++const browserCases = async (sourceCode: string, css: string) => {+ const check = require("node:assert/strict");+ const api = new Function("mathRender", "Constants", sourceCode + "; return {readListMindmap, moveListMindmapNode, addListMindmapNode, " ++ "deleteListMindmapNode, replaceListMindmapContent, cleanListMindmapHTML, remapListMindmapIDs, ListMindmapView};")(+ async (element: Element) => {+ const formulas = element.querySelectorAll('[data-subtype="math"]:not([data-render="true"])');+ await Promise.resolve();+ formulas.forEach(formula => {+ formula.innerHTML = '<span class="katex">rendered formula</span>';+ formula.setAttribute("data-render", "true");+ });+ }, {TIMEOUT_DBLCLICK: 190});+ const lute = Lute.New();+ lute.SetKramdownIAL(true);+ lute.SetProtyleWYSIWYG(true);+ const holder = document.createElement("div");+ const reset = (markdown: string) => {+ holder.innerHTML = lute.Md2BlockDOM(markdown);+ return holder.firstElementChild as HTMLElement;+ };+ const ids = (list: HTMLElement) => Array.from(list.querySelectorAll("[data-node-id]")).map(element =>+ element.getAttribute("data-node-id"));++ // 直属子列表形成分支,其他正文中的嵌套列表属于正文,读取不会重建或移动任何原始块。+ let list = reset("* Parent\n\n Second paragraph\n\n * Child\n * Grandchild\n\n* Sibling\n");+ let model = api.readListMindmap(list);+ check.equal(model.root.virtual, true);+ check.equal(model.root.id, list.dataset.nodeId);+ check.equal(model.root.children.length, 2);+ const parent = model.root.children[0];+ check.equal(parent.contentBlocks.length, 2);+ check.equal(parent.children.length, 1);+ check.equal(parent.children[0].children.length, 1);+ const beforeRead = list.outerHTML;+ check.equal(api.readListMindmap(list).nodes.get(parent.id).element, parent.element);+ check.equal(list.outerHTML, beforeRead);+ check.throws(() => api.readListMindmap(parent.element), /requires a list block/);++ // 移动子树保持正文对象、块 ID、引用和自定义属性,并拒绝循环及跨树目标。+ parent.contentBlocks[0].setAttribute("custom-preserve", "value");+ const source = parent.children[0];+ const sibling = model.root.children[1];+ const sourceHTML = source.element.outerHTML;+ const previousChildListId = source.element.parentElement.dataset.nodeId;+ const allIds = ids(list);+ check.equal(api.moveListMindmapNode(list, parent.id, source.id, "child"), false);+ check.equal(api.moveListMindmapNode(list, source.id, "not-in-this-tree", "child"), false);+ check.equal(api.moveListMindmapNode(list, source.id, sibling.id, "child", () => Lute.NewNodeID()), true);+ model = api.readListMindmap(list);+ check.equal(model.nodes.get(sibling.id).children[0].element, source.element);+ check.equal(source.element.outerHTML, sourceHTML);+ check.equal(parent.contentBlocks[0].getAttribute("custom-preserve"), "value");+ check.equal(parent.element.querySelector(':scope > [data-type="NodeList"]'), null);+ check.deepEqual(ids(list).filter(id => id !== source.element.parentElement.dataset.nodeId).sort(),+ allIds.filter(id => id !== previousChildListId).sort());++ // 有序列表移动首项时保留原起始编号,目标列表同时重新编号。+ list = reset("0. First\n1. Second\n2. Third\n");+ model = api.readListMindmap(list);+ const [first, second, third] = model.root.children;+ check.equal(api.moveListMindmapNode(list, first.id, third.id, "after"), true);+ check.deepEqual(Array.from(list.querySelectorAll(':scope > [data-type="NodeListItem"]')).map((item: Element) =>+ item.getAttribute("data-marker")), ["0.", "1.", "2."]);+ check.equal(api.readListMindmap(list).root.children[2].id, first.id);+ check.equal(api.moveListMindmapNode(list, third.id, second.id, "child", () => Lute.NewNodeID()), true);+ check.equal(third.element.getAttribute("data-marker"), "1.");+ check.equal(third.element.parentElement.getAttribute("data-subtype"), "o");+ check.deepEqual(Array.from(list.querySelectorAll(':scope > [data-type="NodeListItem"]')).map((item: Element) =>+ item.getAttribute("data-marker")), ["0.", "1."]);++ // 删除节点同步清理已删除子树的关系线和样式,其他关系及最后一个实际节点保留。+ list.setAttribute("custom-list-mindmap-data", JSON.stringify({version: 1,+ nodes: {[second.id]: {bold: true}, [third.id]: {textColor: "red"}, [first.id]: {italic: true}},+ relations: [{id: "r1", from: second.id, to: first.id, label: "remove"},+ {id: "r2", from: third.id, to: first.id, label: "remove child"},+ {id: "r3", from: first.id, to: list.dataset.nodeId, label: "retain"}]}));+ check.equal(api.deleteListMindmapNode(list, second.id), true);+ model = api.readListMindmap(list);+ check.equal(model.root.id, first.id);+ check.equal(model.root.virtual, false);+ check.equal(model.metadata.nodes[third.id], undefined);+ check.deepEqual(model.metadata.nodes[first.id], {italic: true});+ check.deepEqual(model.metadata.relations.map((relation: {id: string}) => relation.id), ["r3"]);+ check.equal(api.deleteListMindmapNode(list, first.id), false);+ const inserted = reset("* New\n").firstElementChild as HTMLElement;+ check.equal(api.addListMindmapNode(list, first.id, "child", inserted, () => Lute.NewNodeID()), true);+ check.equal(inserted.dataset.subtype, "o");+ check.equal(inserted.dataset.marker, "1.");++ // 未知版本或损坏配置在任何编辑之前报错,原内容保持不变。+ list.setAttribute("custom-list-mindmap-data", '{"version":2,"nodes":{},"relations":[]}');+ const corrupt = list.outerHTML;+ check.throws(() => api.moveListMindmapNode(list, inserted.dataset.nodeId, first.id, "after"), /metadata/);+ check.throws(() => api.deleteListMindmapNode(list, inserted.dataset.nodeId), /metadata/);+ check.equal(list.outerHTML, corrupt);++ // 正文编辑保留所有原块身份、属性和复杂内联内容,并保留穿插子列表的对象及位置。+ list = reset("* Parent\n\n Second paragraph\n\n * Child\n\n* Sibling\n");+ model = api.readListMindmap(list);+ const editable = model.root.children[0];+ const originalBlocks: HTMLElement[] = editable.contentBlocks;+ const childList = editable.element.querySelector(':scope > [data-type="NodeList"]');+ const childHTML = childList.outerHTML;+ originalBlocks[0].setAttribute("custom-preserve", "custom");+ originalBlocks[0].setAttribute("name", "named");+ originalBlocks[0].setAttribute("style", "color: red;");+ const rich = originalBlocks[0].querySelector('[contenteditable="true"]');+ rich.innerHTML = '<span data-type="block-ref" data-id="20260916000000-abcdefg" data-subtype="s">Reference</span>' ++ '<span class="img"><img src="assets/image.png" alt="image"></span><span data-type="code">literal</span>';+ const replacement = originalBlocks.map(block => block.cloneNode(true) as HTMLElement);+ replacement[0].removeAttribute("custom-preserve");+ replacement[0].removeAttribute("name");+ replacement[0].removeAttribute("style");+ replacement[1].querySelector('[contenteditable="true"]').textContent = "Updated";+ const extra = document.createElement("div");+ extra.innerHTML = lute.Md2BlockDOM("New paragraph\n");+ const added = extra.firstElementChild as HTMLElement;+ const editHTML = replacement.map(block => block.outerHTML).join("") + added.outerHTML + "<wbr>";+ const activeEditor = document.createElement("div");+ activeEditor.className = "list-mindmap";+ activeEditor.innerHTML = editHTML;+ list.appendChild(activeEditor);+ check.equal(api.replaceListMindmapContent(list, editable.id, editHTML), true);+ activeEditor.remove();+ const edited = api.readListMindmap(list).nodes.get(editable.id);+ check.equal(edited.contentBlocks.length, 3);+ check.equal(edited.contentBlocks[0].dataset.nodeId, originalBlocks[0].dataset.nodeId);+ check.equal(edited.contentBlocks[0].getAttribute("custom-preserve"), "custom");+ check.equal(edited.contentBlocks[0].getAttribute("name"), "named");+ check.equal(edited.contentBlocks[0].getAttribute("style"), "color: red;");+ check.equal(edited.contentBlocks[0].querySelector('[data-type="block-ref"]').getAttribute("data-id"), "20260916000000-abcdefg");+ check.equal(edited.contentBlocks[0].querySelector("img").getAttribute("src"), "assets/image.png");+ check.equal(edited.contentBlocks[0].querySelector('[data-type="code"]').textContent, "literal");+ check.equal(edited.contentBlocks[1].dataset.nodeId, originalBlocks[1].dataset.nodeId);+ check.equal(edited.contentBlocks[2].dataset.nodeId, added.dataset.nodeId);+ check.equal(editable.element.querySelector(':scope > [data-type="NodeList"]'), childList);+ check.equal(childList.outerHTML, childHTML);+ check.equal(list.querySelector("wbr"), null);+ const beforeRejectedEdit = list.outerHTML;+ check.equal(api.replaceListMindmapContent(list, editable.id, childHTML), false);+ check.equal(api.replaceListMindmapContent(list, editable.id, edited.contentBlocks[0].outerHTML.repeat(2)), false);+ check.equal(api.replaceListMindmapContent(list, editable.id, ""), false);+ check.equal(list.outerHTML, beforeRejectedEdit);+ extra.innerHTML = lute.Md2BlockDOM("* New child\n");+ check.equal(api.replaceListMindmapContent(list, editable.id,+ edited.contentBlocks.map((block: HTMLElement) => block.outerHTML).join("") + extra.innerHTML), true);+ check.equal(api.readListMindmap(list).nodes.get(editable.id).children.length, 2);+ check.equal(childList.outerHTML, childHTML);++ // 渲染和编辑标记不会进入持久化 DOM,列表视图属性及关系线配置仍然保留。+ list.setAttribute("custom-list-mindmap", "1");+ list.setAttribute("data-list-mindmap-rendered", "true");+ list.setAttribute("data-list-mindmap-editing", "true");+ const derived = document.createElement("div");+ derived.className = "list-mindmap";+ derived.innerHTML = '<div class="list-mindmap__editor">Derived editor</div>';+ list.appendChild(derived);+ list.appendChild(document.createComment("list-mindmap"));+ list.appendChild(document.createComment("unrelated list-mindmap comment"));+ const cleaned = api.cleanListMindmapHTML(list.outerHTML);+ check.equal(cleaned.includes("Derived editor"), false);+ check.equal(cleaned.includes("data-list-mindmap-rendered"), false);+ check.equal(cleaned.includes("data-list-mindmap-editing"), false);+ check.equal(cleaned.includes("<!--list-mindmap-->"), false);+ check.equal(cleaned.includes("<!--unrelated list-mindmap comment-->"), true);+ check.equal(cleaned.includes('custom-list-mindmap="1"'), true);+ check.ok(list.contains(derived));+ check.equal(api.cleanListMindmapHTML("<div>unrelated</div>"), "<div>unrelated</div>");+ check.ok(lute.BlockDOM2Md(cleaned).includes("New child"));++ // 复制后关系线与节点样式引用新块 ID,遇到任一损坏配置时不进行部分迁移。+ list.setAttribute("custom-list-mindmap-data", JSON.stringify({version: 1, extension: "keep",+ nodes: {a: {bold: true}, b: {italic: true}},+ relations: [{id: "relation", from: "a", to: "b", label: "keep"}]}));+ const child = list.querySelector('[data-type="NodeList"]');+ child.setAttribute("custom-list-mindmap-data", '{"version":2,"nodes":{},"relations":[]}');+ const beforeRemap = list.outerHTML;+ check.throws(() => api.remapListMindmapIDs(list, new Map([["a", "new-a"], ["b", "new-b"]])), /metadata/);+ check.equal(list.outerHTML, beforeRemap);+ child.removeAttribute("custom-list-mindmap-data");+ api.remapListMindmapIDs(list, new Map([["a", "new-a"], ["b", "new-b"]]));+ const remapped = JSON.parse(list.getAttribute("custom-list-mindmap-data"));+ check.deepEqual(remapped.nodes, {"new-a": {bold: true}, "new-b": {italic: true}});+ check.deepEqual(remapped.relations, [{id: "relation", from: "new-a", to: "new-b", label: "keep"}]);+ check.equal(remapped.extension, "keep");+ check.equal(list.querySelector(".list-mindmap"), null);+ check.equal(list.hasAttribute("data-list-mindmap-rendered"), false);+ check.equal(list.hasAttribute("data-list-mindmap-editing"), false);+ check.equal(list.outerHTML.includes("<!--list-mindmap-->"), false);++ // 使用真实布局和事件验证单击拖拽、双击挂载、撤销入口、只读折叠及全屏还原。+ const style = document.createElement("style");+ style.textContent = css;+ document.head.append(style);+ const hostParent = document.createElement("div");+ hostParent.style.width = "760px";+ const host = document.createElement("div");+ hostParent.append(host);+ document.body.append(hostParent);+ list = reset("* Alpha\n * Child\n* Beta\n");+ model = api.readListMindmap(list);+ const alpha = model.root.children[0].id;+ const beta = model.root.children[1].id;+ const edits: string[] = [];+ const moves: unknown[] = [];+ const additions: unknown[] = [];+ const folds: string[] = [];+ const deletions: string[] = [];+ const relationDeletions: string[] = [];+ const relationAdditions: unknown[] = [];+ const relationChanges: unknown[] = [];+ const nodeStyles: unknown[] = [];+ const fullscreenChanges: boolean[] = [];+ let undo = 0;+ let redo = 0;+ let finishAllowed: boolean | Promise<boolean> = true;+ const options = {+ host, model,+ labels: new Proxy({}, {get: (_target, key) => String(key)}),+ colors: () => [{label: "Appearance background", value: "var(--b3-font-background1)"}],+ nodeColors: () => [{label: "Appearance combined", color: "var(--b3-font-color1)", backgroundColor: "var(--b3-font-background1)"}],+ onFullscreen: (enter: boolean) => fullscreenChanges.push(enter),+ onEdit: (id: string) => edits.push(id),+ finishEdit: () => finishAllowed,+ onMove: (...args: unknown[]) => moves.push(args),+ onAdd: (...args: unknown[]) => additions.push(args),+ onDelete: (id: string) => deletions.push(id),+ onFold: (id: string) => folds.push(id),+ onUndo: () => undo++,+ onRedo: () => redo++,+ onNodeStyle: (...args: unknown[]) => nodeStyles.push(args),+ onRelationAdd: (...args: unknown[]) => relationAdditions.push(args),+ onRelationChange: (...args: unknown[]) => relationChanges.push(args),+ onRelationDelete: (id: string) => relationDeletions.push(id),+ onExit: (): void => undefined,+ };+ const frame = () => new Promise<void>(resolve => requestAnimationFrame(() => resolve()));+ const settle = async () => { await frame(); await frame(); };+ const view = new api.ListMindmapView(options);+ await settle();+ const viewport = host.querySelector<HTMLElement>(".list-mindmap__viewport");+ const originalCapture = HTMLElement.prototype.setPointerCapture;+ const originalHasCapture = HTMLElement.prototype.hasPointerCapture;+ const originalReleaseCapture = HTMLElement.prototype.releasePointerCapture;+ HTMLElement.prototype.setPointerCapture = () => undefined;+ HTMLElement.prototype.hasPointerCapture = () => false;+ HTMLElement.prototype.releasePointerCapture = () => undefined;+ const nodeElement = (id: string) => host.querySelector<HTMLElement>(`[data-mindmap-id="${id}"]`);+ const sendPointer = (element: Element, type: string, x: number, y: number) => element.dispatchEvent(new PointerEvent(type, {+ bubbles: true, cancelable: true, pointerId: 1, pointerType: "mouse", button: 0, clientX: x, clientY: y,+ }));+ const sourceRect = nodeElement(alpha).getBoundingClientRect();+ const targetRect = nodeElement(beta).getBoundingClientRect();+ const sourcePoint = {x: sourceRect.left + sourceRect.width / 2, y: sourceRect.top + sourceRect.height / 2};+ const targetPoint = {x: targetRect.left + targetRect.width / 2, y: targetRect.top + targetRect.height / 2};+ check.ok(sourceRect.width >= 64 && sourceRect.height >= 36);+ check.equal(host.querySelector("[data-node-id]"), null);+ sendPointer(nodeElement(alpha), "pointerdown", sourcePoint.x, sourcePoint.y);+ sendPointer(viewport, "pointerup", sourcePoint.x, sourcePoint.y);+ check.equal(edits.length, 0);+ check.equal(moves.length, 0);+ sendPointer(nodeElement(alpha), "pointerdown", sourcePoint.x, sourcePoint.y);+ sendPointer(viewport, "pointermove", targetPoint.x, targetPoint.y);+ check.ok(host.querySelector(".list-mindmap__ghost"));+ check.equal(nodeElement(beta).dataset.mindmapDrop, "child");+ sendPointer(viewport, "pointerup", targetPoint.x, targetPoint.y);+ check.deepEqual(moves, [[alpha, beta, "child"]]);+ check.equal(host.querySelector(".list-mindmap__ghost"), null);+ sendPointer(nodeElement(alpha), "pointerdown", sourcePoint.x, sourcePoint.y);+ sendPointer(viewport, "pointermove", targetPoint.x, targetPoint.y);+ host.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ sendPointer(viewport, "pointerup", targetPoint.x, targetPoint.y);+ check.equal(moves.length, 1);+ nodeElement(alpha).dispatchEvent(new MouseEvent("dblclick", {bubbles: true, cancelable: true}));+ check.deepEqual(edits, [alpha]);+ const editorHost = view.getContentHost(alpha);+ const editorMarker = document.createElement("div");+ editorMarker.className = "protyle";+ editorHost.replaceChildren(editorMarker);+ view.update(api.readListMindmap(list));+ check.equal(view.getContentHost(alpha).firstElementChild, editorMarker);+ view.setEditing();+ view.update(api.readListMindmap(list));+ check.equal(host.querySelector('[aria-label="undo"]'), null);+ check.equal(host.querySelector('[aria-label="redo"]'), null);+ check.equal(undo, 0);+ check.equal(redo, 0);+ finishAllowed = false;+ nodeElement(alpha).querySelector<HTMLButtonElement>(".list-mindmap__add-child").click();+ check.equal(additions.length, 0);+ finishAllowed = true;+ nodeElement(alpha).querySelector<HTMLButtonElement>(".list-mindmap__add-child").click();+ check.equal(additions.length, 1, "add callback after finishing editing");++ // 悬浮添加按钮不改变拖拽和双击语义,未选中节点也必须使用自身 ID 添加子节点。+ const nativeInput = (events: Record<string, unknown>[]) =>+ require("electron").ipcRenderer.invoke("list-mindmap-native-input", events);+ const centerPoint = (element: Element) => {+ const rect = element.getBoundingClientRect();+ return {x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2)};+ };+ const moveMouse = async (element?: Element) => {+ await nativeInput([{type: "mouseMove", ...(element ? centerPoint(element) : {x: 2, y: 2})}]);+ await settle();+ };+ const clickMouse = async (element: Element) => {+ const point = centerPoint(element);+ await nativeInput([+ {type: "mouseMove", ...point},+ {type: "mouseDown", ...point, button: "left", clickCount: 1},+ {type: "mouseUp", ...point, button: "left", clickCount: 1},+ ]);+ await settle();+ };+ const addChildButton = (id: string) => nodeElement(id).querySelector<HTMLButtonElement>(".list-mindmap__add-child");+ const visiblyRendered = (element: HTMLElement) => {+ const computed = getComputedStyle(element);+ return !element.hidden && computed.display !== "none" && computed.visibility !== "hidden" &&+ Number(computed.opacity) > 0;+ };+ const betaAdd = addChildButton(beta);+ check.ok(betaAdd, "each editable node has its own add-child control");+ await moveMouse();+ check.equal(visiblyRendered(betaAdd), false, "add-child control is hidden before hovering");+ check.equal(nodeElement(beta).getAttribute("aria-selected"), "false");+ await moveMouse(nodeElement(beta));+ check.equal(visiblyRendered(betaAdd), true, "hovering the node exposes its add-child control");+ const betaRect = nodeElement(beta).getBoundingClientRect();+ const betaButtonRect = betaAdd.getBoundingClientRect();+ const nodeScale = betaRect.width / nodeElement(beta).offsetWidth;+ check.ok((betaButtonRect.left - betaRect.right) / nodeScale <= 5,+ "leaf add controls stay close to the node edge");+ await nativeInput([{type: "mouseMove", x: Math.round((betaRect.right + betaButtonRect.left) / 2),+ y: Math.round(betaButtonRect.top + betaButtonRect.height / 2)}]);+ await settle();+ check.equal(visiblyRendered(betaAdd), true, "crossing the gap to the add control keeps it visible");+ await nativeInput([{type: "mouseMove", x: Math.round((betaRect.right + betaButtonRect.left) / 2),+ y: Math.round(betaRect.top + 2)}]);+ await settle();+ check.equal(visiblyRendered(betaAdd), true, "the hover corridor covers the full node height");+ check.equal(host.querySelector<HTMLElement>('[role="tooltip"]').hidden, true,+ "the gap is not part of the clickable add button");+ await moveMouse(betaAdd);+ check.equal(visiblyRendered(betaAdd), true, "moving onto the protruding control keeps it visible");+ const buttonPoint = centerPoint(betaAdd);+ check.equal(document.elementFromPoint(buttonPoint.x, buttonPoint.y)?.closest(".list-mindmap__add-child"), betaAdd,+ "the visible add-child control remains pointer-accessible outside the node edge");+ const hoverTooltip = host.querySelector<HTMLElement>('[role="tooltip"]');+ check.equal(hoverTooltip.hidden, false);+ betaAdd.dispatchEvent(new PointerEvent("pointerout", {bubbles: true, relatedTarget: betaAdd.querySelector("svg")}));+ check.equal(hoverTooltip.hidden, false, "moving from the button to its icon must not hide the tooltip");+ betaAdd.querySelector("svg").dispatchEvent(new PointerEvent("pointerover", {bubbles: true, relatedTarget: betaAdd}));+ check.equal(hoverTooltip.hidden, false);+ const beforeButtonEdits = edits.length;+ const beforeButtonMoves = moves.length;+ await clickMouse(betaAdd);+ check.deepEqual(additions[additions.length - 1], [beta, "child"]);+ check.equal(edits.length, beforeButtonEdits);+ check.equal(moves.length, beforeButtonMoves);+ check.equal(host.querySelector(".list-mindmap__ghost"), null);+ betaAdd.dispatchEvent(new MouseEvent("dblclick", {bubbles: true, cancelable: true}));+ check.equal(edits.length, beforeButtonEdits, "double clicking the add control does not open a node editor");+ finishAllowed = false;+ const beforeRejectedAddition = additions.length;+ await clickMouse(betaAdd);+ check.equal(additions.length, beforeRejectedAddition, "a pending edit prevents adding a child");+ finishAllowed = true;+ view.setReadOnly(true);+ await settle();+ host.querySelectorAll<HTMLButtonElement>(".list-mindmap__add-child").forEach(button => {+ check.equal(visiblyRendered(button), false, "read-only nodes hide their add-child controls");+ button.click();+ });+ check.equal(additions.length, beforeRejectedAddition, "read-only add controls cannot invoke mutations");+ view.setReadOnly(false);+ await settle();+ await moveMouse(nodeElement(beta));+ check.equal(visiblyRendered(addChildButton(beta)), true, "restoring editing restores the hover control");+ await clickMouse(addChildButton(beta));+ check.equal(additions.length, beforeRejectedAddition + 1);+ check.deepEqual(additions[additions.length - 1], [beta, "child"]);+ model.nodes.get(alpha).collapsed = true;+ view.update(model);+ await settle();+ await moveMouse(nodeElement(alpha));+ check.equal(visiblyRendered(addChildButton(alpha)), true, "folded nodes retain their add-child control");+ const foldButton = nodeElement(alpha).querySelector<HTMLButtonElement>(".list-mindmap__fold");+ const foldPoint = centerPoint(foldButton);+ check.equal(document.elementFromPoint(foldPoint.x, foldPoint.y)?.closest(".list-mindmap__fold"), foldButton,+ "the hover bridge does not cover the neighboring fold control");+ const beforeFoldAdditions = additions.length;+ await clickMouse(foldButton);+ check.deepEqual(folds, [alpha]);+ check.equal(additions.length, beforeFoldAdditions, "clicking fold must not add a child");+ await clickMouse(addChildButton(alpha));+ check.deepEqual(additions[additions.length - 1], [alpha, "child"]);+ check.equal(edits.length, beforeButtonEdits);+ check.equal(moves.length, beforeButtonMoves);++ // 删除只作用于选中的节点,编辑输入、只读状态及取消选中后均不得删除正文。+ const pressDelete = (target: Element = host, init: KeyboardEventInit = {}) =>+ target.dispatchEvent(new KeyboardEvent("keydown", {key: "Delete", bubbles: true, cancelable: true, ...init}));+ const select = (id: string) => {+ const point = centerPoint(nodeElement(id));+ sendPointer(nodeElement(id), "pointerdown", point.x, point.y);+ sendPointer(viewport, "pointerup", point.x, point.y);+ };+ const blank = () => {+ const rect = viewport.getBoundingClientRect();+ sendPointer(viewport, "pointerdown", rect.left + 5, rect.top + 5);+ sendPointer(viewport, "pointerup", rect.left + 5, rect.top + 5);+ };+ select(beta);+ pressDelete();+ check.deepEqual(deletions, [beta]);+ finishAllowed = false;+ pressDelete();+ finishAllowed = true;+ pressDelete(host, {isComposing: true});+ pressDelete(host, {ctrlKey: true});+ view.setEditing(beta);+ pressDelete(view.getContentHost(beta));+ view.setEditing();+ check.deepEqual(deletions, [beta]);+ let finishDelete: () => void;+ finishAllowed = new Promise<boolean>(resolve => finishDelete = () => resolve(true));+ pressDelete();+ blank();+ finishDelete();+ await settle();+ finishAllowed = true;+ check.deepEqual(deletions, [beta], "a pending deletion cannot follow a changed selection");+ view.update(model);+ check.equal(host.querySelector(".list-mindmap__node--selected"), null);+ pressDelete();+ check.deepEqual(deletions, [beta]);+ select(model.root.id);+ pressDelete();+ check.deepEqual(deletions, [beta], "virtual root cannot be deleted");++ // 面板外部点击关闭设置,外观颜色保存变量引用并解析为画布可用的实际颜色。+ const toolbar = host.querySelector(".list-mindmap__toolbar");+ ["listMindmapChild", "delete", "fold"].forEach(label =>+ check.equal(toolbar.querySelector(`[aria-label="${label}"]`), null));+ const relationButton = toolbar.querySelector<HTMLButtonElement>('[aria-label="connect"]');+ check.equal(relationButton.nextElementSibling.getAttribute("aria-label"), "zoomOut");+ check.equal(relationButton.querySelector("use").getAttribute("xlink:href"), "#iconRoute");+ const inspector = host.querySelector<HTMLElement>(".list-mindmap__inspector");+ const fitButton = toolbar.querySelector<HTMLButtonElement>('[aria-label="listMindmapFit"]');+ check.equal(fitButton.querySelector("use").getAttribute("xlink:href"), "#iconRefresh");+ fitButton.dispatchEvent(new PointerEvent("pointerover", {bubbles: true}));+ check.equal(host.querySelector<HTMLElement>('[role="tooltip"]').hidden, false);+ check.equal(host.querySelector('[role="tooltip"]').textContent, "listMindmapFit");+ select(beta);+ check.equal(inspector.hidden, false);+ check.equal(inspector.classList.contains("list-mindmap__inspector--node"), true);+ check.equal(getComputedStyle(inspector).bottom, "8px");+ check.equal(host.querySelector(".list-mindmap__status"), null);+ const nodeMenuBounds = inspector.getBoundingClientRect();+ const panelBounds = host.getBoundingClientRect();+ check.ok(Math.abs(nodeMenuBounds.left + nodeMenuBounds.width / 2 - panelBounds.left - panelBounds.width / 2) < 2);+ check.ok(nodeMenuBounds.width < panelBounds.width / 2);+ check.equal(inspector.querySelectorAll('input[type="number"]').length, 0);+ check.equal(inspector.querySelectorAll('input[type="checkbox"]').length, 0);+ check.equal(inspector.querySelector('input[type="color"]'), null);+ check.equal(inspector.querySelectorAll('[role="group"]').length, 1);+ const nodePalette = inspector.querySelector<HTMLElement>('[role="group"][aria-label="color"]');+ const nodeColorButton = nodePalette.querySelector<HTMLButtonElement>('[aria-label="Appearance combined"]');+ check.equal(nodeColorButton.textContent, "A");+ check.equal(nodeColorButton.classList.contains("color__square"), true);+ nodeColorButton.click();+ check.deepEqual(nodeStyles[nodeStyles.length - 1], [beta, {textColor: "var(--b3-font-color1)", backgroundColor: "var(--b3-font-background1)"}]);+ host.style.setProperty("--b3-font-color1", "#123456");+ host.style.setProperty("--b3-font-background1", "#abcdef");+ model.metadata.nodes[beta] = {textColor: "var(--b3-font-color1)", backgroundColor: "var(--b3-font-background1)"};+ view.update(model);+ check.equal(getComputedStyle(nodeElement(beta)).backgroundColor, "rgb(171, 205, 239)");+ check.equal(getComputedStyle(nodeElement(beta)).color, "rgb(18, 52, 86)");+ check.equal(inspector.querySelector('[aria-label="Appearance combined"]').getAttribute("aria-pressed"), "true");+ host.style.setProperty("--b3-font-background1", "#334455");+ check.equal(getComputedStyle(nodeElement(beta)).backgroundColor, "rgb(51, 68, 85)",+ "node colors follow changes to the appearance palette");+ inspector.querySelector<HTMLButtonElement>('[aria-label="color"] [aria-label="default"]').click();+ check.deepEqual(nodeStyles[nodeStyles.length - 1], [beta, {textColor: "", backgroundColor: ""}]);+ model.metadata.nodes[beta].backgroundColor = "";+ model.metadata.nodes[beta].textColor = "";+ view.update(model);+ check.equal(nodeElement(beta).style.backgroundColor, "", "default removes the node color override");+ check.equal(nodeElement(beta).style.color, "", "default removes the node text color override");+ host.style.setProperty("--b3-font-background1", "#123456");+ model.metadata.nodes[model.root.id] = {lineColor: "var(--b3-font-background1)"};+ view.update(model);+ check.equal(host.querySelector("canvas").getContext("2d").strokeStyle, "#123456");+ check.equal(getComputedStyle(nodeElement(beta)).borderWidth, "0px");+ await settle();+ const parentBounds = nodeElement(model.nodes.get(beta).parentId).getBoundingClientRect();+ const childBounds = nodeElement(beta).getBoundingClientRect();+ const lineX = (parentBounds.right + childBounds.left) / 2;+ const parentY = model.nodes.get(beta).parentId === model.root.id ? parentBounds.top + parentBounds.height / 2 : parentBounds.bottom;+ const lineY = (parentY + childBounds.bottom) / 2;+ sendPointer(viewport, "pointermove", lineX, lineY);+ check.equal(viewport.classList.contains("list-mindmap__viewport--line-hover"), true);+ viewport.dispatchEvent(new PointerEvent("pointerleave"));+ check.equal(viewport.classList.contains("list-mindmap__viewport--line-hover"), false);+ sendPointer(viewport, "pointerdown", lineX, lineY);+ sendPointer(viewport, "pointerup", lineX, lineY);+ check.equal(inspector.hidden, false, "clicking the tree curve opens its settings");+ check.equal(inspector.classList.contains("list-mindmap__inspector--line"), true);+ inspector.querySelector<HTMLButtonElement>('[aria-label="Appearance background"]').click();+ check.deepEqual(nodeStyles[nodeStyles.length - 1], [beta, {lineColor: "var(--b3-font-background1)"}]);+ blank();+ check.equal(inspector.hidden, true);+ select(beta);+ document.body.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}));+ check.equal(inspector.hidden, true);+ check.equal(nodeElement(beta).getAttribute("aria-selected"), "false");+ select(alpha);+ relationButton.click();+ blank();+ select(beta);+ check.equal(relationAdditions.length, 0, "outside click cancels pending relation creation");+ relationButton.click();+ select(alpha);+ check.deepEqual(relationAdditions, [[beta, alpha]]);+ model.metadata.relations.push({id: "relation-test", from: alpha, to: beta, label: "Relation"});+ view.update(model);+ host.querySelector<HTMLButtonElement>(".list-mindmap__relation").click();+ const relationElement = host.querySelector<HTMLElement>(".list-mindmap__relation");+ relationElement.dispatchEvent(new PointerEvent("pointerover", {bubbles: true}));+ check.equal(host.querySelector<HTMLElement>('[role="tooltip"]').hidden, true);+ const relationPoint = centerPoint(relationElement);+ sendPointer(relationElement, "pointermove", relationPoint.x, relationPoint.y);+ check.equal(relationElement.classList.contains("list-mindmap__relation--hover"), true);+ viewport.dispatchEvent(new PointerEvent("pointerleave"));+ check.equal(relationElement.classList.contains("list-mindmap__relation--hover"), false);+ check.equal(inspector.hidden, false);+ check.equal(inspector.classList.contains("list-mindmap__inspector--line"), true);+ check.equal(getComputedStyle(inspector).bottom, "8px");+ const lineMenuBounds = inspector.getBoundingClientRect();+ check.ok(Math.abs(lineMenuBounds.left + lineMenuBounds.width / 2 - panelBounds.left - panelBounds.width / 2) < 2);+ check.ok(lineMenuBounds.width < panelBounds.width / 2);+ check.equal(inspector.querySelector(".list-mindmap__section"), null);+ host.querySelector(".list-mindmap__relation").dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));+ const relationLabel = host.querySelector<HTMLInputElement>(".list-mindmap__relation-editor");+ check.equal(document.activeElement, relationLabel);+ check.equal(relationLabel.selectionEnd, relationLabel.value.length);+ relationLabel.value = "Renamed";+ relationLabel.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));+ check.deepEqual(relationChanges.pop(), ["relation-test", {label: "Renamed"}]);+ check.equal(host.querySelector(".list-mindmap__relation-editor"), null);+ host.querySelector<HTMLButtonElement>(".list-mindmap__relation").click();+ host.querySelector(".list-mindmap__relation").dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));+ const cancelledLabel = host.querySelector<HTMLInputElement>(".list-mindmap__relation-editor");+ cancelledLabel.value = "Cancelled";+ cancelledLabel.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ check.equal(relationChanges.length, 0);+ host.querySelector<HTMLButtonElement>(".list-mindmap__relation").click();+ check.equal(inspector.querySelector("input"), null);+ inspector.querySelector<HTMLButtonElement>('[aria-label="Appearance background"]').click();+ check.deepEqual(relationChanges, [["relation-test", {color: "var(--b3-font-background1)"}]]);+ model.metadata.relations[0].color = "var(--b3-font-background1)";+ view.update(model);+ check.equal(host.querySelector("canvas").getContext("2d").strokeStyle, "#123456");+ pressDelete();+ check.deepEqual(relationDeletions, ["relation-test"]);+ blank();+ check.equal(inspector.hidden, true);+ check.equal(host.querySelector(".list-mindmap__relation--selected"), null);++ // 全屏使用编辑器同款窗口内布局,不调用浏览器全屏,并在退出和销毁时恢复原位置。+ Object.defineProperty(host, "requestFullscreen", {configurable: true, value: () => check.fail("Native fullscreen must not be requested")});+ hostParent.style.transform = "translateX(5px)";+ hostParent.style.overflow = "hidden";+ host.querySelector<HTMLButtonElement>('[aria-label="fullscreen"]').click();+ await settle();+ check.equal(host.parentElement, document.body);+ check.equal(host.classList.contains("fullscreen"), true);+ check.equal(host.querySelector(".list-mindmap__toolbar").classList.contains("block__icons"), true);+ check.equal(host.getBoundingClientRect().left, 0);+ check.equal(host.getBoundingClientRect().width, window.innerWidth);+ check.equal(getComputedStyle(host).zIndex, "8");+ check.deepEqual(fullscreenChanges, [true]);+ view.setReadOnly(true);+ check.ok(host.querySelector('[aria-label="exitFullscreen"]'));+ view.setReadOnly(false);+ host.querySelector<HTMLButtonElement>('[aria-label="exitFullscreen"]').click();+ check.equal(host.parentElement, hostParent);+ check.equal(host.classList.contains("fullscreen"), false);+ check.deepEqual(fullscreenChanges, [true, false]);+ host.querySelector<HTMLButtonElement>('[aria-label="fullscreen"]').click();+ host.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ check.equal(host.parentElement, hostParent);+ check.equal(host.classList.contains("fullscreen"), false);+ check.equal(host.querySelector(".list-mindmap__toolbar").classList.contains("block__icons"), true);+ host.querySelector<HTMLButtonElement>('[aria-label="fullscreen"]').click();+ view.destroy();+ check.equal(host.parentElement, hostParent);+ check.equal(host.classList.contains("fullscreen"), false);+ check.deepEqual(fullscreenChanges, [true, false, true, false, true, false]);+ check.equal(Array.from(hostParent.childNodes).some(node => node.nodeType === Node.COMMENT_NODE), false);+ hostParent.style.transform = "";+ hostParent.style.overflow = "";++ const readonly = new api.ListMindmapView({...options, readOnly: true});+ await settle();+ check.equal(host.querySelector('.list-mindmap__toolbar [aria-label="listMindmapChild"]'), null);+ check.equal(host.querySelector('[aria-label="undo"]'), null);+ nodeElement(beta).dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));+ host.dispatchEvent(new KeyboardEvent("keydown", {key: "z", ctrlKey: true, bubbles: true}));+ check.equal(edits.length, 1);+ check.equal(undo, 0);+ const persistedBeforeFold = list.outerHTML;+ pressDelete();+ check.deepEqual(deletions, [beta]);+ nodeElement(model.root.id).querySelector<HTMLButtonElement>(".list-mindmap__fold").click();+ await settle();+ check.equal(nodeElement(alpha).hidden, true);+ const foldedButton = nodeElement(model.root.id).querySelector<HTMLButtonElement>(".list-mindmap__fold");+ check.equal(foldedButton.querySelector("span").textContent, String(model.nodes.size - 1));+ check.equal(getComputedStyle(foldedButton).visibility, "visible");+ foldedButton.click();+ await settle();+ check.equal(nodeElement(alpha).hidden, false);+ check.equal(list.outerHTML, persistedBeforeFold);+ readonly.destroy();++ const singleList = reset("* Single\n");+ const single = new api.ListMindmapView({...options, model: api.readListMindmap(singleList)});+ const emptyModel = api.readListMindmap(singleList);+ const emptyBlock = document.createElement("div");+ emptyBlock.innerHTML = "<div><br></div>";+ emptyModel.root.contentBlocks = [emptyBlock];+ single.update(emptyModel);+ const emptyContent = host.querySelector<HTMLElement>(".list-mindmap__content");+ check.equal(emptyContent.classList.contains("list-mindmap__content--empty"), true);+ check.equal(emptyContent.dataset.placeholder, "listMindmapPlaceholder");+ check.equal(emptyContent.textContent, "", "placeholder is not node content");+ emptyBlock.innerHTML = '<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">';+ single.update(emptyModel);+ check.equal(emptyContent.classList.contains("list-mindmap__content--empty"), false);+ single.update(api.readListMindmap(singleList));+ pressDelete();+ check.deepEqual(deletions, [beta], "the last root node cannot be deleted");+ await settle();+ HTMLElement.prototype.setPointerCapture = originalCapture;+ HTMLElement.prototype.hasPointerCapture = originalHasCapture;+ HTMLElement.prototype.releasePointerCapture = originalReleaseCapture;+ const nativeRect = host.querySelector<HTMLElement>("[data-mindmap-id]").getBoundingClientRect();+ const nativePoint = {x: Math.round(nativeRect.left + nativeRect.width / 2), y: Math.round(nativeRect.top + nativeRect.height / 2)};+ const beforeNativeEdits = edits.length;+ await require("electron").ipcRenderer.invoke("list-mindmap-native-input", [+ {type: "mouseMove", ...nativePoint},+ {type: "mouseDown", ...nativePoint, button: "left", clickCount: 1},+ {type: "mouseUp", ...nativePoint, button: "left", clickCount: 1},+ {type: "mouseDown", ...nativePoint, button: "left", clickCount: 2},+ {type: "mouseUp", ...nativePoint, button: "left", clickCount: 2},+ ]);+ await settle();+ check.equal(edits.length, beforeNativeEdits + 1, "native double click must edit despite pointer capture");+ single.destroy();++ // 使用真实鼠标及两种删除按键修改源列表,覆盖 macOS Delete 键发送 Backspace 的情况。+ const deleteList = reset("* Root\n * First\n * Second\n");+ const deleteModel = api.readListMindmap(deleteList);+ const deleteFirst = deleteModel.root.children[0].id;+ const deleteSecond = deleteModel.root.children[1].id;+ const deleting = new api.ListMindmapView({...options, model: deleteModel, onDelete: (id: string) => {+ check.equal(api.deleteListMindmapNode(deleteList, id), true);+ deleting.update(api.readListMindmap(deleteList));+ }});+ const nativeKey = async (keyCode: string) => {+ await nativeInput([{type: "keyDown", keyCode}, {type: "keyUp", keyCode}]);+ await settle();+ };+ await settle();+ await clickMouse(nodeElement(deleteFirst));+ check.equal(document.activeElement, host);+ await nativeKey("Backspace");+ check.equal(deleteList.querySelector(`[data-node-id="${deleteFirst}"]`), null);+ check.equal(nodeElement(deleteFirst), null);+ check.ok(deleteList.querySelector(`[data-node-id="${deleteSecond}"]`));+ await clickMouse(nodeElement(deleteSecond));+ const beforeProtectedDelete = deleteList.outerHTML;+ deleting.setEditing(deleteSecond);+ for (const key of ["Backspace", "Delete"]) {+ pressDelete(deleting.getContentHost(deleteSecond), {key});+ }+ deleting.setEditing();+ deleting.setReadOnly(true);+ await nativeKey("Backspace");+ await nativeKey("Delete");+ check.equal(deleteList.outerHTML, beforeProtectedDelete);+ deleting.setReadOnly(false);+ await clickMouse(nodeElement(deleteSecond));+ await nativeKey("Delete");+ check.equal(deleteList.querySelector(`[data-node-id="${deleteSecond}"]`), null);+ check.equal(nodeElement(deleteSecond), null);+ check.ok(nodeElement(deleteModel.root.id));+ await clickMouse(nodeElement(deleteModel.root.id));+ await nativeKey("Backspace");+ check.ok(nodeElement(deleteModel.root.id), "the last root is preserved for the macOS Delete key");+ deleting.destroy();+ // 公式在副本上异步渲染;链接单击跳转,双击和拖拽不跳转。+ const richList = reset("* $x^2$ [example](https://example.com)\n * child\n");+ const richHost = document.createElement("div");+ hostParent.append(richHost);+ const opened: string[] = [];+ let richEdits = 0;+ const richView = new api.ListMindmapView({host: richHost, model: api.readListMindmap(richList),+ onExit: () => {}, onOpenLink: (href: string) => opened.push(href), onEdit: () => richEdits++});+ await settle();+ check.ok(richHost.querySelector('[data-subtype="math"] .katex'));+ check.equal(richList.querySelector(".katex"), null, "preview rendering does not mutate the source");+ const link = richHost.querySelector<HTMLElement>('[data-type="a"]');+ const clickLink = (detail = 1) => link.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true, detail}));+ clickLink();+ await new Promise(resolve => setTimeout(resolve, 220));+ check.deepEqual(opened, ["https://example.com"]);+ clickLink();+ clickLink(2);+ link.dispatchEvent(new MouseEvent("dblclick", {bubbles: true, cancelable: true, detail: 2}));+ await new Promise(resolve => setTimeout(resolve, 220));+ check.equal(richEdits, 1);+ check.equal(opened.length, 1);+ richView.setEditing();+ const point = centerPoint(link);+ sendPointer(link, "pointerdown", point.x, point.y);+ sendPointer(richHost.querySelector(".list-mindmap__viewport"), "pointermove", point.x + 30, point.y);+ sendPointer(richHost.querySelector(".list-mindmap__viewport"), "pointerup", point.x + 30, point.y);+ clickLink();+ await new Promise(resolve => setTimeout(resolve, 220));+ check.equal(opened.length, 1);+ const ref = document.createElement("span");+ ref.dataset.type = "block-ref";+ ref.dataset.id = "20260917000000-abcdefg";+ link.after(ref);+ sendPointer(ref, "pointerdown", point.x, point.y);+ sendPointer(richHost.querySelector(".list-mindmap__viewport"), "pointerup", point.x, point.y);+ ref.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true, detail: 1}));+ await new Promise(resolve => setTimeout(resolve, 220));+ check.equal(opened[1], "siyuan://blocks/20260917000000-abcdefg");+ richView.destroy();+ const exportView = new api.ListMindmapView({host: richHost, model: api.readListMindmap(richList),+ readOnly: true, onExit: () => {}});+ const anchor = document.createElement("a");+ anchor.href = "#export-target";+ richHost.querySelector(".list-mindmap__content").append(anchor);+ let exportClick = false;+ richHost.parentElement.addEventListener("click", event => {+ if (event.target === anchor) {+ exportClick = true;+ event.preventDefault();+ }+ });+ anchor.click();+ check.equal(exportClick, true, "export anchor clicks reach the existing navigation handler");+ exportView.destroy();+ hostParent.remove();+ style.remove();+ return "List mindmap DOM cases passed";+};++test("list mindmap mutations preserve block data in the real DOM and Lute", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+}, async () => {+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-list-mindmap-test-"));+ const script = path.join(temporary, "run.cjs");+ const typescript = require("typescript") as typeof import("typescript");+ const compile = (file: string) => typescript.transpileModule(+ readFileSync(file, "utf8").replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""), {+ compilerOptions: {target: typescript.ScriptTarget.ES2021},+ }).outputText;+ const source = compile(path.join(__dirname, "../av/richTextValue.ts")) + compile(path.join(__dirname, "../../wysiwyg/listContext.ts")) ++ compile(path.join(__dirname, "model.ts")) + compile(path.join(__dirname, "routing.ts")) + compile(path.join(__dirname, "view.ts"));+ const css = require("sass").compile(path.resolve(__dirname, "../../../assets/scss/business/_block.scss")).css ++ require("sass").compile(path.resolve(__dirname, "../../../assets/scss/business/_color.scss")).css ++ require("sass").compile(path.resolve(__dirname, "../../../assets/scss/protyle/_list-mindmap.scss")).css;+ const lutePath = path.resolve(__dirname, "../../../../stage/protyle/js/lute/lute.min.js");+ const code = `const {app, BrowserWindow, ipcMain} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ ipcMain.handle("list-mindmap-native-input", async (_event, events) => {+ for (const event of events) {+ win.webContents.sendInputEvent(event);+ await new Promise(resolve => setTimeout(resolve, 20));+ }+ });+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));+ const result = await win.webContents.executeJavaScript(${JSON.stringify(+ `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(source)}, ${JSON.stringify(css)})`)});+ console.log(result);+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`;+ writeFileSync(script, code, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const executable = require("electron") as unknown as string;+ const result = await promisify(execFile)(executable, [script], {env, timeout: 40000, windowsHide: true});+ assert.match(result.stdout, /List mindmap DOM cases passed/);+ } finally {+ rmSync(temporary, {recursive: true, force: true});+ }+});diff --git a/app/src/protyle/render/listMindmap/model.ts b/app/src/protyle/render/listMindmap/model.tsnew file mode 100644index 0000000000..9897b144c3--- /dev/null+++ b/app/src/protyle/render/listMindmap/model.ts@@ -0,0 +1,561 @@+import {getOrderedListMarkerUpdates} from "../../wysiwyg/listContext";++export const LIST_MINDMAP_VIEW_ATTRIBUTE = "custom-list-mindmap";+export const LIST_MINDMAP_META_ATTRIBUTE = "custom-list-mindmap-data";++export interface ListMindmapNodeStyle {+ textColor?: string;+ backgroundColor?: string;+ borderColor?: string;+ fontSize?: number;+ borderWidth?: number;+ borderRadius?: number;+ bold?: boolean;+ italic?: boolean;+ lineColor?: string;+ lineWidth?: number;+ lineDash?: boolean;+}++export interface ListMindmapRelation {+ id: string;+ from: string;+ to: string;+ label: string;+ color?: string;+ width?: number;+ dash?: boolean;+}++export interface ListMindmapMetadata {+ version: 1;+ nodes: Record<string, ListMindmapNodeStyle>;+ relations: ListMindmapRelation[];+}++export interface ListMindmapNode {+ id: string;+ parentId?: string;+ element?: HTMLElement;+ contentBlocks: HTMLElement[];+ children: ListMindmapNode[];+ collapsed: boolean;+ virtual: boolean;+}++export interface ListMindmapModel {+ list: HTMLElement;+ root: ListMindmapNode;+ nodes: Map<string, ListMindmapNode>;+ metadata: ListMindmapMetadata;+}++export interface ListMindmapLayoutNode {+ id: string;+ width: number;+ height: number;+ children: ListMindmapLayoutNode[];+ collapsed?: boolean;+}++export interface ListMindmapPosition {+ id: string;+ parentId?: string;+ x: number;+ y: number;+ width: number;+ height: number;+}++export type ListMindmapPlacement = "child" | "before" | "after";++const isRecord = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === "object" && !Array.isArray(value);++const invalidMetadata = () => new Error("Invalid list mindmap metadata");++// 校验已知字段并保留扩展字段,防止损坏或较新版本的配置被编辑操作覆盖。+export const parseListMindmapMetadata = (value: string | null): ListMindmapMetadata => {+ if (value === null) {+ return {version: 1, nodes: Object.create(null), relations: []};+ }+ let data: unknown;+ try {+ data = JSON.parse(value);+ } catch {+ throw invalidMetadata();+ }+ if (!isRecord(data) || data.version !== 1 || !isRecord(data.nodes) || !Array.isArray(data.relations)) {+ throw invalidMetadata();+ }+ const stringKeys = ["textColor", "backgroundColor", "borderColor", "lineColor"];+ const numberKeys = ["fontSize", "borderWidth", "borderRadius", "lineWidth"];+ const booleanKeys = ["bold", "italic", "lineDash"];+ for (const [id, style] of Object.entries(data.nodes)) {+ if (!id || !isRecord(style) ||+ stringKeys.some(key => key in style && typeof style[key] !== "string") ||+ numberKeys.some(key => key in style && (typeof style[key] !== "number" ||+ !Number.isFinite(style[key]) || Number(style[key]) < 0)) ||+ booleanKeys.some(key => key in style && typeof style[key] !== "boolean")) {+ throw invalidMetadata();+ }+ }+ const relationIds = new Set<string>();+ for (const relation of data.relations) {+ if (!isRecord(relation) || typeof relation.id !== "string" || !relation.id ||+ relationIds.has(relation.id) || typeof relation.from !== "string" || !relation.from ||+ typeof relation.to !== "string" || !relation.to || typeof relation.label !== "string" ||+ ("color" in relation && typeof relation.color !== "string") ||+ ("width" in relation && (typeof relation.width !== "number" ||+ !Number.isFinite(relation.width) || relation.width < 0)) ||+ ("dash" in relation && typeof relation.dash !== "boolean")) {+ throw invalidMetadata();+ }+ relationIds.add(relation.id);+ }+ return data as unknown as ListMindmapMetadata;+};++export const writeListMindmapMetadata = (list: HTMLElement, metadata: ListMindmapMetadata) => {+ parseListMindmapMetadata(list.getAttribute(LIST_MINDMAP_META_ATTRIBUTE));+ const value = JSON.stringify(metadata);+ parseListMindmapMetadata(value);+ list.setAttribute(LIST_MINDMAP_META_ATTRIBUTE, value);+};++// 复制块树时同步替换节点样式和关系线端点,先校验全部配置再写入,避免出现部分改写。+export const remapListMindmapIDs = (root: Element, ids: Map<string, string>) => {+ const lists = Array.from(root.querySelectorAll<HTMLElement>(`[${LIST_MINDMAP_META_ATTRIBUTE}]`)).filter(list =>+ !list.closest(".list-mindmap"));+ if (root.hasAttribute(LIST_MINDMAP_META_ATTRIBUTE)) {+ lists.unshift(root as HTMLElement);+ }+ const updates = lists.map(list => {+ const metadata = parseListMindmapMetadata(list.getAttribute(LIST_MINDMAP_META_ATTRIBUTE));+ const nodes: Record<string, ListMindmapNodeStyle> = Object.create(null);+ Object.entries(metadata.nodes).forEach(([id, style]) => {+ const mappedId = ids.get(id) || id;+ if (Object.prototype.hasOwnProperty.call(nodes, mappedId)) {+ throw new Error("Duplicate copied list mindmap identity");+ }+ nodes[mappedId] = style;+ });+ return {list, metadata: {...metadata, nodes, relations: metadata.relations.map(relation => ({+ ...relation,+ from: ids.get(relation.from) || relation.from,+ to: ids.get(relation.to) || relation.to,+ }))}};+ });+ updates.forEach(({list, metadata}) => list.setAttribute(LIST_MINDMAP_META_ATTRIBUTE, JSON.stringify(metadata)));+ cleanListMindmapDOM(root);+};++const directBlocks = (element: HTMLElement) => Array.from(element.children).filter(child =>+ child.hasAttribute("data-node-id")) as HTMLElement[];++const sourceBlocks = (element: HTMLElement) => Array.from(element.querySelectorAll<HTMLElement>("[data-node-id]")).filter(child =>+ !child.closest(".list-mindmap"));++const directItems = (list: HTMLElement) => directBlocks(list).filter(child =>+ child.getAttribute("data-type") === "NodeListItem");++export const readListMindmap = (list: HTMLElement): ListMindmapModel => {+ if (list.getAttribute("data-type") !== "NodeList" || !list.getAttribute("data-node-id")) {+ throw new Error("A list mindmap requires a list block");+ }+ const metadata = parseListMindmapMetadata(list.getAttribute(LIST_MINDMAP_META_ATTRIBUTE));+ const nodes = new Map<string, ListMindmapNode>();+ const virtualRoot: ListMindmapNode = {+ id: list.getAttribute("data-node-id"),+ contentBlocks: [],+ children: [],+ collapsed: false,+ virtual: true,+ };+ const pending = [{list, parent: virtualRoot}];+ while (pending.length > 0) {+ const current = pending.pop();+ for (const item of directItems(current.list)) {+ const id = item.getAttribute("data-node-id");+ if (!id || nodes.has(id) || id === virtualRoot.id) {+ throw new Error("Invalid list mindmap node identity");+ }+ const blocks = directBlocks(item);+ const node: ListMindmapNode = {+ id,+ parentId: current.parent.id,+ element: item,+ contentBlocks: blocks.filter(block => block.getAttribute("data-type") !== "NodeList"),+ children: [],+ collapsed: item.getAttribute("fold") === "1",+ virtual: false,+ };+ current.parent.children.push(node);+ nodes.set(id, node);+ // 子列表可以与其他正文块交错出现,只将直属子列表映射为下一级节点。+ blocks.filter(block => block.getAttribute("data-type") === "NodeList").reverse().forEach(child => {+ pending.push({list: child, parent: node});+ });+ }+ }+ const root = virtualRoot.children.length === 1 ? virtualRoot.children[0] : virtualRoot;+ if (root.virtual) {+ nodes.set(root.id, root);+ } else {+ delete root.parentId;+ }+ return {list, root, nodes, metadata};+};++const cleanListMindmapDOM = (root: Element | DocumentFragment) => {+ root.querySelectorAll(".list-mindmap").forEach(element => element.remove());+ const elements = Array.from(root.querySelectorAll("[data-list-mindmap-rendered], [data-list-mindmap-editing]"));+ if (root.nodeType === 1) {+ elements.push(root as Element);+ }+ elements.forEach(element => {+ element.removeAttribute("data-list-mindmap-rendered");+ element.removeAttribute("data-list-mindmap-editing");+ });+ const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_COMMENT);+ const markers: Comment[] = [];+ while (walker.nextNode()) {+ if (walker.currentNode.nodeValue === "list-mindmap") {+ markers.push(walker.currentNode as Comment);+ }+ }+ markers.forEach(marker => marker.remove());+};++export const cleanListMindmapHTML = (html: string): string => {+ if (!html.includes("list-mindmap")) {+ return html;+ }+ const template = document.createElement("template");+ template.innerHTML = html;+ cleanListMindmapDOM(template.content);+ return template.innerHTML;+};++// 按每层最大宽度对齐节点,并为每个分支保留完整的垂直空间,避免富文本节点相互遮挡。+export const layoutListMindmap = (root: ListMindmapLayoutNode, options: {+ horizontalGap?: number;+ verticalGap?: number;+ padding?: number;+} = {}) => {+ const horizontalGap = options.horizontalGap ?? 40;+ const verticalGap = options.verticalGap ?? 24;+ const padding = options.padding ?? 32;+ if ([horizontalGap, verticalGap, padding].some(value => !Number.isFinite(value) || value < 0)) {+ throw new Error("Invalid list mindmap layout spacing");+ }+ const ordered: {node: ListMindmapLayoutNode, depth: number, parentId?: string}[] = [];+ const pending = [{node: root, depth: 0, parentId: undefined as string | undefined}];+ const seen = new Set<string>();+ while (pending.length > 0) {+ const current = pending.pop();+ if (!current.node.id || seen.has(current.node.id) ||+ !Number.isFinite(current.node.width) || current.node.width <= 0 ||+ !Number.isFinite(current.node.height) || current.node.height <= 0) {+ throw new Error("Invalid list mindmap layout node");+ }+ seen.add(current.node.id);+ ordered.push(current);+ if (!current.node.collapsed) {+ [...current.node.children].reverse().forEach(node => {+ pending.push({node, depth: current.depth + 1, parentId: current.node.id});+ });+ }+ }+ const heights = new Map<string, number>();+ [...ordered].reverse().forEach(({node}) => {+ const children = node.collapsed ? [] : node.children;+ const childHeight = children.reduce((sum, child) => sum + heights.get(child.id), 0) ++ Math.max(0, children.length - 1) * verticalGap;+ heights.set(node.id, Math.max(node.height, childHeight));+ });+ const tops = new Map([[root.id, padding]]);+ const nodes = new Map<string, ListMindmapPosition>();+ const edges: {from: string, to: string}[] = [];+ let width = padding;+ ordered.forEach(({node, parentId}) => {+ const top = tops.get(node.id);+ const height = heights.get(node.id);+ const parent = nodes.get(parentId);+ const position = {+ id: node.id,+ parentId,+ x: parent ? parent.x + parent.width + horizontalGap : padding,+ y: top + (height - node.height) / 2,+ width: node.width,+ height: node.height,+ };+ nodes.set(node.id, position);+ width = Math.max(width, position.x + position.width);+ if (parentId) {+ edges.push({from: parentId, to: node.id});+ }+ const children = node.collapsed ? [] : node.children;+ const childHeight = children.reduce((sum, child) => sum + heights.get(child.id), 0) ++ Math.max(0, children.length - 1) * verticalGap;+ let childTop = top + (height - childHeight) / 2;+ children.forEach(child => {+ tops.set(child.id, childTop);+ childTop += heights.get(child.id) + verticalGap;+ });+ });+ return {nodes, edges, width: width + padding, height: heights.get(root.id) + padding * 2};+};++const getListStart = (list: HTMLElement) => {+ const start = Number.parseInt(directItems(list)[0]?.getAttribute("data-marker"), 10);+ return Number.isFinite(start) ? start : 1;+};++const normalizeList = (list: HTMLElement, start: number) => {+ const subtype = list.getAttribute("data-subtype") || "u";+ const items = directItems(list);+ const markers = getOrderedListMarkerUpdates(items.map(item => item.getAttribute("data-marker")), start);+ items.forEach((item, index) => {+ const previousSubtype = item.getAttribute("data-subtype");+ item.setAttribute("data-subtype", subtype);+ let action = Array.from(item.children).find(child => child.classList.contains("protyle-action")) as HTMLElement;+ if (previousSubtype !== subtype || !action) {+ const replacement = list.ownerDocument.createElement("div");+ replacement.setAttribute("draggable", "true");+ replacement.setAttribute("contenteditable", "false");+ replacement.className = "protyle-action";+ if (subtype === "o") {+ replacement.classList.add("protyle-action--order");+ } else {+ if (subtype === "t") {+ replacement.classList.add("protyle-action--task");+ if (!item.hasAttribute("data-task")) {+ item.setAttribute("data-task", " ");+ }+ }+ const icon = subtype === "t" ? (item.getAttribute("data-task") === " " ? "iconUncheck" : "iconCheck") : "iconDot";+ replacement.innerHTML = `<svg><use xlink:href="#${icon}"></use></svg>`;+ }+ if (action) {+ action.replaceWith(replacement);+ } else {+ item.insertBefore(replacement, item.firstElementChild);+ }+ action = replacement;+ }+ if (subtype === "o") {+ const marker = markers[index] || item.getAttribute("data-marker");+ item.setAttribute("data-marker", marker);+ action.textContent = marker;+ } else {+ item.setAttribute("data-marker", "*");+ }+ if (subtype !== "t") {+ item.removeAttribute("data-task");+ item.classList.remove("protyle-task--done");+ } else {+ item.classList.toggle("protyle-task--done", item.getAttribute("data-task") !== " ");+ }+ });+};++const getDestinationList = (model: ListMindmapModel, targetId: string, placement: ListMindmapPlacement,+ createListId: () => string): HTMLElement | undefined => {+ if (targetId === model.list.getAttribute("data-node-id")) {+ return placement === "child" ? model.list : undefined;+ }+ const target = model.nodes.get(targetId)?.element;+ if (!target) {+ return;+ }+ if (placement !== "child") {+ return target.parentElement;+ }+ let childList = directBlocks(target).find(child => child.getAttribute("data-type") === "NodeList");+ if (!childList) {+ const id = createListId();+ if (!id || model.nodes.has(id) || id === model.list.getAttribute("data-node-id") ||+ sourceBlocks(model.list).some(element => element.getAttribute("data-node-id") === id)) {+ throw new Error("Invalid new list identity");+ }+ childList = model.list.ownerDocument.createElement("div");+ childList.className = "list";+ childList.setAttribute("data-type", "NodeList");+ childList.setAttribute("data-node-id", id);+ childList.setAttribute("data-subtype", target.getAttribute("data-subtype") || "u");+ const attr = model.list.ownerDocument.createElement("div");+ attr.className = "protyle-attr";+ attr.setAttribute("contenteditable", "false");+ childList.appendChild(attr);+ target.insertBefore(childList, Array.from(target.children).find(child =>+ child.classList.contains("protyle-attr")) || null);+ }+ target.removeAttribute("fold");+ return childList;+};++const insertItem = (list: HTMLElement, item: HTMLElement, target: HTMLElement | undefined,+ placement: ListMindmapPlacement) => {+ const reference = placement === "before" ? target : placement === "after" ? target.nextElementSibling :+ Array.from(list.children).find(child => child.classList.contains("protyle-attr")) || null;+ list.insertBefore(item, reference);+};++export const moveListMindmapNode = (list: HTMLElement, sourceId: string, targetId: string,+ placement: ListMindmapPlacement, createListId = () => Lute.NewNodeID()): boolean => {+ const model = readListMindmap(list);+ const source = model.nodes.get(sourceId)?.element;+ const target = model.nodes.get(targetId)?.element;+ if (!source || sourceId === targetId || (target && source.contains(target)) ||+ (!target && targetId !== list.getAttribute("data-node-id"))) {+ return false;+ }+ const oldList = source.parentElement;+ const oldStart = getListStart(oldList);+ const destination = getDestinationList(model, targetId, placement, createListId);+ if (!destination) {+ return false;+ }+ const destinationStart = getListStart(destination);+ insertItem(destination, source, target, placement);+ normalizeList(destination, destinationStart);+ if (oldList !== destination) {+ if (directItems(oldList).length === 0 && oldList !== list) {+ oldList.remove();+ } else {+ normalizeList(oldList, oldStart);+ }+ }+ return true;+};++export const addListMindmapNode = (list: HTMLElement, targetId: string, placement: ListMindmapPlacement,+ item: HTMLElement, createListId = () => Lute.NewNodeID()): boolean => {+ const model = readListMindmap(list);+ const id = item.getAttribute("data-node-id");+ if (item.getAttribute("data-type") !== "NodeListItem" || !id || model.nodes.has(id) ||+ id === list.getAttribute("data-node-id") || list.contains(item) || item.contains(list)) {+ return false;+ }+ const existingIds = new Set([list.getAttribute("data-node-id")]);+ sourceBlocks(list).forEach(block => existingIds.add(block.getAttribute("data-node-id")));+ const incomingIds = new Set<string>();+ for (const block of [item, ...Array.from(item.querySelectorAll("[data-node-id]"))]) {+ const blockId = block.getAttribute("data-node-id");+ if (!blockId || existingIds.has(blockId) || incomingIds.has(blockId)) {+ return false;+ }+ incomingIds.add(blockId);+ }+ const destination = getDestinationList(model, targetId, placement, createListId);+ if (!destination) {+ return false;+ }+ const start = getListStart(destination);+ insertItem(destination, item, model.nodes.get(targetId)?.element, placement);+ normalizeList(destination, start);+ return true;+};++export const deleteListMindmapNode = (list: HTMLElement, id: string): boolean => {+ const model = readListMindmap(list);+ const node = model.nodes.get(id);+ if (!node?.element || (node === model.root && !model.root.virtual)) {+ return false;+ }+ const removedIds = new Set<string>([id]);+ node.element.querySelectorAll("[data-node-id]").forEach(element => {+ removedIds.add(element.getAttribute("data-node-id"));+ });+ const parent = node.element.parentElement;+ const start = getListStart(parent);+ node.element.remove();+ if (directItems(parent).length === 0 && parent !== list) {+ parent.remove();+ } else {+ normalizeList(parent, start);+ }+ removedIds.forEach(removedId => delete model.metadata.nodes[removedId]);+ model.metadata.relations = model.metadata.relations.filter(relation =>+ !removedIds.has(relation.from) && !removedIds.has(relation.to));+ if (list.hasAttribute(LIST_MINDMAP_META_ATTRIBUTE)) {+ writeListMindmapMetadata(list, model.metadata);+ }+ return true;+};++// 只替换指定的直属正文块,并沿用块身份和属性,其余正文及嵌套列表保持原样。+export const replaceListMindmapBlock = (list: HTMLElement, nodeId: string, blockId: string,+ replacement: HTMLElement): boolean => {+ const node = readListMindmap(list).nodes.get(nodeId);+ const block = node?.contentBlocks.find(item => item.getAttribute("data-node-id") === blockId);+ if (!block || replacement.getAttribute("data-type") !== block.getAttribute("data-type")) {+ return false;+ }+ const updated = replacement.cloneNode(true) as HTMLElement;+ Array.from(block.attributes).forEach(attribute => updated.setAttribute(attribute.name, attribute.value));+ block.replaceWith(updated);+ return true;+};++// 按原正文槽位写入编辑结果,保留穿插在正文之间的子列表及未改写的持久属性。+export const replaceListMindmapContent = (list: HTMLElement, nodeId: string, blockHTML: string): boolean => {+ const node = readListMindmap(list).nodes.get(nodeId);+ if (!node?.element) {+ return false;+ }+ const template = list.ownerDocument.createElement("template");+ template.innerHTML = cleanListMindmapHTML(blockHTML);+ template.content.querySelectorAll("wbr").forEach(element => element.remove());+ const incoming = Array.from(template.content.children) as HTMLElement[];+ if (incoming.length === 0 || incoming.some(block => !block.hasAttribute("data-node-id") ||+ !block.getAttribute("data-type") || block.getAttribute("data-type") === "NodeListItem")) {+ return false;+ }+ const originals = new Map<string, HTMLElement>();+ node.contentBlocks.forEach(block => {+ originals.set(block.getAttribute("data-node-id"), block);+ block.querySelectorAll<HTMLElement>("[data-node-id]").forEach(child => {+ originals.set(child.getAttribute("data-node-id"), child);+ });+ });+ const existingIds = new Set([list.getAttribute("data-node-id")]);+ sourceBlocks(list).forEach(block => existingIds.add(block.getAttribute("data-node-id")));+ const incomingIds = new Set<string>();+ for (const block of Array.from(template.content.querySelectorAll<HTMLElement>("[data-node-id]"))) {+ const id = block.getAttribute("data-node-id");+ if (!id || incomingIds.has(id) || (existingIds.has(id) && !originals.has(id))) {+ return false;+ }+ incomingIds.add(id);+ const original = originals.get(id);+ if (original) {+ Array.from(original.attributes).forEach(attribute => {+ if (!["data-type", "data-subtype", "class", "updated", "contenteditable"].includes(attribute.name) &&+ !attribute.name.startsWith("data-list-mindmap-")) {+ block.setAttribute(attribute.name, attribute.value);+ }+ });+ }+ }+ let lastInserted: HTMLElement;+ node.contentBlocks.forEach((block, index) => {+ if (incoming[index]) {+ block.replaceWith(incoming[index]);+ lastInserted = incoming[index];+ } else {+ block.remove();+ }+ });+ incoming.slice(node.contentBlocks.length).forEach(block => {+ if (lastInserted) {+ lastInserted.after(block);+ } else {+ node.element.insertBefore(block, Array.from(node.element.children).find(child =>+ child.classList.contains("protyle-attr")) || null);+ }+ lastInserted = block;+ });+ return true;+};diff --git a/app/src/protyle/render/listMindmap/render.ts b/app/src/protyle/render/listMindmap/render.tsnew file mode 100644index 0000000000..51f914b0b8--- /dev/null+++ b/app/src/protyle/render/listMindmap/render.ts@@ -0,0 +1,61 @@+import {LIST_MINDMAP_VIEW_ATTRIBUTE, readListMindmap} from "./model";+import {ListMindmapView} from "./view";++const editorRoots = new WeakMap<Element, () => void>();+const previews = new WeakMap<HTMLElement, ListMindmapView>();++export const registerListMindmapRoot = (root: Element, refresh: () => void) => {+ editorRoots.set(root, refresh);+ return () => editorRoots.delete(root);+};++export const getListMindmapElements = (root: Element) => {+ const selector = `[data-type="NodeList"][${LIST_MINDMAP_VIEW_ATTRIBUTE}="1"]`;+ const lists = Array.from(root.querySelectorAll<HTMLElement>(selector));+ if (root.matches(selector)) {+ lists.unshift(root as HTMLElement);+ }+ return lists.filter(list => !list.closest(".list-mindmap") &&+ !list.parentElement?.closest(selector));+};++// 导出页面和只读预览共用节点布局,源列表始终保留在文档中。+export const listMindmapRender = (root: Element, cdn?: string) => {+ const editor = root.closest(".protyle-wysiwyg");+ const refresh = editor && editorRoots.get(editor);+ if (refresh) {+ refresh();+ return;+ }+ getListMindmapElements(root).forEach(list => {+ const previous = previews.get(list);+ if (previous) {+ previous.refreshLayout();+ return;+ }+ try {+ const model = readListMindmap(list);+ list.querySelector(":scope > .list-mindmap")?.remove();+ const host = document.createElement("div");+ host.className = "list-mindmap";+ host.contentEditable = "false";+ list.appendChild(host);+ const view = new ListMindmapView({+ host, model, readOnly: true, labels: window.siyuan?.languages || {}, cdn,+ onExit: () => {+ view.destroy();+ host.remove();+ list.removeAttribute("data-list-mindmap-rendered");+ previews.delete(list);+ },+ });+ previews.set(list, view);+ list.dataset.listMindmapRendered = "true";+ } catch (error) {+ // 无法识别配置时继续显示原列表,避免隐藏源内容。+ console.error(error);+ list.querySelector(":scope > .list-mindmap")?.remove();+ list.removeAttribute("data-list-mindmap-rendered");+ }+ });+};diff --git a/app/src/protyle/render/listMindmap/routing.test.ts b/app/src/protyle/render/listMindmap/routing.test.tsnew file mode 100644index 0000000000..32be1fa764--- /dev/null+++ b/app/src/protyle/render/listMindmap/routing.test.ts@@ -0,0 +1,56 @@+import * as assert from "node:assert/strict";+import test from "node:test";+import {routeMindmapRelation, MindmapRouteBox, MindmapRoutePoint} from "./routing";++const validate = (route: MindmapRoutePoint[], nodes: MindmapRouteBox[]) => {+ assert.ok(route.length >= 2, "a route must exist");+ for (let i = 1; i < route.length; i++) {+ const a = route[i - 1];+ const b = route[i];+ assert.ok(a.x === b.x || a.y === b.y, "segments are orthogonal");+ for (const node of nodes) {+ for (const box of [node, {x: node.x + node.width - 11, y: (node.controlY ?? node.y + node.height) - 11, width: 49, height: 22}]) {+ const intersects = a.x === b.x ? a.x > box.x && a.x < box.x + box.width &&+ Math.max(a.y, b.y) > box.y && Math.min(a.y, b.y) < box.y + box.height :+ a.y > box.y && a.y < box.y + box.height && Math.max(a.x, b.x) > box.x && Math.min(a.x, b.x) < box.x + box.width;+ assert.equal(intersects, false, "route avoids nodes and their controls");+ }+ }+ }+};++test("relations route around intervening nodes in both directions", () => {+ const nodes = [+ {x: 300, y: 100, width: 165, height: 76},+ {x: 300, y: 250, width: 220, height: 48},+ {x: 300, y: 380, width: 180, height: 60},+ ];+ validate(routeMindmapRelation(nodes[2], nodes[0], nodes), nodes);+ validate(routeMindmapRelation(nodes[0], nodes[2], nodes), nodes);+});++test("right-side endpoints remain close to node text while avoiding bottom controls", () => {+ const from = {x: 0, y: 0, width: 120, height: 40};+ const to = {x: 240, y: 0, width: 120, height: 40};+ const route = routeMindmapRelation(from, to, [from, to]);+ validate(route, [from, to]);+ assert.equal(route[0].x - from.x - from.width, 12);+});++test("relations find side ports when vertical gaps are too narrow", () => {+ const nodes = Array.from({length: 8}, (_, i) => ({x: 200, y: i * 60, width: 120 + i * 8, height: 40}));+ validate(routeMindmapRelation(nodes[1], nodes[6], nodes), nodes);+});++test("cross-column routes remain deterministic with mixed node sizes", () => {+ const nodes = [+ {x: 0, y: 140, width: 100, height: 50},+ {x: 180, y: 0, width: 160, height: 60},+ {x: 180, y: 120, width: 180, height: 180},+ {x: 430, y: 50, width: 160, height: 100},+ {x: 430, y: 240, width: 160, height: 60},+ ];+ const route = routeMindmapRelation(nodes[0], nodes[4], nodes);+ validate(route, nodes);+ assert.deepEqual(routeMindmapRelation(nodes[0], nodes[4], nodes), route);+});diff --git a/app/src/protyle/render/listMindmap/routing.ts b/app/src/protyle/render/listMindmap/routing.tsnew file mode 100644index 0000000000..f7d48916d0--- /dev/null+++ b/app/src/protyle/render/listMindmap/routing.ts@@ -0,0 +1,128 @@+export interface MindmapRoutePoint {x: number; y: number;}+export interface MindmapRouteBox extends MindmapRoutePoint {width: number; height: number; controlY?: number;}++// 在障碍边界构成的正交可视网格上搜索,方向纳入状态以惩罚多余转弯。+export const routeMindmapRelation = (from: MindmapRouteBox, to: MindmapRouteBox,+ nodes: MindmapRouteBox[], clearance = 12): MindmapRoutePoint[] => {+ const boxes = nodes.flatMap(node => [+ {left: node.x - clearance, right: node.x + node.width + clearance,+ top: node.y - clearance, bottom: node.y + node.height + clearance},+ {left: node.x + node.width - 19, right: node.x + node.width + 46,+ top: (node.controlY ?? node.y + node.height) - 19, bottom: (node.controlY ?? node.y + node.height) + 19},+ ]);+ const ports = (node: MindmapRouteBox) => [+ {x: node.x + node.width / 2, y: node.y - clearance, direction: 1},+ {x: node.x + node.width / 2, y: node.y + node.height + clearance, direction: 1},+ {x: node.x - clearance, y: node.y + node.height / 2, direction: 0},+ {x: node.x + node.width + clearance, y: node.y + Math.max(0, Math.min(node.height / 2, node.height - 22)), direction: 0},+ ];+ const starts = ports(from);+ const goals = ports(to);+ const xs = [...new Set([...boxes.flatMap(box => [box.left, box.right]), ...starts.map(p => p.x), ...goals.map(p => p.x)])].sort((a, b) => a - b);+ const ys = [...new Set([...boxes.flatMap(box => [box.top, box.bottom]), ...starts.map(p => p.y), ...goals.map(p => p.y)])].sort((a, b) => a - b);+ const point = (index: number) => ({x: xs[index % xs.length], y: ys[Math.floor(index / xs.length)]});+ const indexOf = (p: MindmapRoutePoint) => ys.indexOf(p.y) * xs.length + xs.indexOf(p.x);+ const columns = new Map<number, typeof boxes>();+ const rows = new Map<number, typeof boxes>();+ const blocked = (a: MindmapRoutePoint, b: MindmapRoutePoint) => {+ if (a.x === b.x) {+ if (!columns.has(a.x)) {+ columns.set(a.x, boxes.filter(box => a.x > box.left && a.x < box.right));+ }+ return columns.get(a.x).some(box => Math.max(a.y, b.y) > box.top && Math.min(a.y, b.y) < box.bottom);+ }+ if (!rows.has(a.y)) {+ rows.set(a.y, boxes.filter(box => a.y > box.top && a.y < box.bottom));+ }+ return rows.get(a.y).some(box => Math.max(a.x, b.x) > box.left && Math.min(a.x, b.x) < box.right);+ };+ const heuristic = (p: MindmapRoutePoint) => Math.min(...goals.map(goal => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)));+ const targets = new Set(goals.map(goal => indexOf(goal) * 2 + goal.direction));+ const distance = new Map<number, number>();+ const previous = new Map<number, number>();+ const heap: {key: number, cost: number, score: number}[] = [];+ const push = (item: typeof heap[number]) => {+ let i = heap.length;+ heap.push(item);+ while (i > 0) {+ const parent = (i - 1) >> 1;+ if (heap[parent].score <= item.score) {+ break;+ }+ heap[i] = heap[parent];+ i = parent;+ }+ heap[i] = item;+ };+ const pop = () => {+ const first = heap[0];+ const last = heap.pop();+ if (heap.length) {+ let i = 0;+ while (i * 2 + 1 < heap.length) {+ let child = i * 2 + 1;+ if (child + 1 < heap.length && heap[child + 1].score < heap[child].score) {+ child++;+ }+ if (last.score <= heap[child].score) {+ break;+ }+ heap[i] = heap[child];+ i = child;+ }+ heap[i] = last;+ }+ return first;+ };+ starts.forEach(start => {+ if (blocked(start, start)) {+ return;+ }+ const key = indexOf(start) * 2 + start.direction;+ distance.set(key, 0);+ push({key, cost: 0, score: heuristic(start)});+ });+ while (heap.length) {+ const current = pop();+ if (distance.get(current.key) !== current.cost) {+ continue;+ }+ const index = Math.floor(current.key / 2);+ const a = point(index);+ if (targets.has(current.key)) {+ const route: MindmapRoutePoint[] = [];+ let key: number | undefined = current.key;+ while (key !== undefined) {+ route.push(point(Math.floor(key / 2)));+ key = previous.get(key);+ }+ route.reverse();+ return route.filter((p, i) => i === 0 || i === route.length - 1 ||+ !((route[i - 1].x === p.x && route[i + 1].x === p.x) || (route[i - 1].y === p.y && route[i + 1].y === p.y)));+ }+ const x = index % xs.length;+ const y = Math.floor(index / xs.length);+ const neighbors = [x > 0 ? index - 1 : -1, x + 1 < xs.length ? index + 1 : -1,+ y > 0 ? index - xs.length : -1, y + 1 < ys.length ? index + xs.length : -1];+ neighbors.forEach((next, side) => {+ if (next < 0) {+ return;+ }+ const b = point(next);+ const direction = side < 2 ? 0 : 1;+ // 起终点保留垂直于节点边缘的引出段,箭头始终朝向目标节点。+ if ((!previous.has(current.key) && direction !== current.key % 2) || blocked(a, b)) {+ return;+ }+ const key = next * 2 + direction;+ const cost = current.cost + Math.abs(a.x - b.x) + Math.abs(a.y - b.y) + (direction === current.key % 2 ? 0 : 24);+ if (cost >= (distance.get(key) ?? Infinity)) {+ return;+ }+ distance.set(key, cost);+ previous.set(key, current.key);+ push({key, cost, score: cost + heuristic(b)});+ });+ }+ return [];+};diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.tsnew file mode 100644index 0000000000..1398f396e7--- /dev/null+++ b/app/src/protyle/render/listMindmap/view.ts@@ -0,0 +1,1286 @@+import {+ layoutListMindmap,+ ListMindmapLayoutNode,+ ListMindmapModel,+ ListMindmapNodeStyle,+ ListMindmapPosition,+ ListMindmapRelation,+} from "./model";+import {routeMindmapRelation, MindmapRoutePoint} from "./routing";+import {mathRender} from "../mathRender";+import {getAVRichTextSafeURL} from "../av/richTextValue";+import {Constants} from "../../../constants";++export interface ListMindmapViewOptions {+ host: HTMLElement;+ model: ListMindmapModel;+ readOnly?: boolean;+ labels?: Record<string, string>;+ cdn?: string;+ onOpenLink?: (href: string, event: MouseEvent) => void;+ colors?: () => {label: string, value: string}[];+ nodeColors?: () => {label: string, color: string, backgroundColor: string}[];+ onManageNodeColors?: () => void;+ onFullscreen?: (enter: boolean, button: HTMLButtonElement) => void;+ onEdit?: (id: string, contentHost: HTMLElement) => void;+ finishEdit?: () => boolean | void | Promise<boolean | void>;+ onMove?: (id: string, targetId: string, placement: "before" | "child" | "after") => void;+ onAdd?: (id: string, kind: "child" | "sibling") => void;+ onDelete?: (id: string) => void;+ onFold?: (id: string) => void;+ onUndo?: () => void;+ onRedo?: () => void;+ onNodeStyle?: (id: string, patch: Partial<ListMindmapNodeStyle>) => void;+ onRelationAdd?: (from: string, to: string) => void;+ onRelationChange?: (id: string, patch: Partial<ListMindmapRelation>) => void;+ onRelationDelete?: (id: string) => void;+ onExit: () => void;+}++interface PointerState {+ pointerId: number;+ id?: string;+ startX: number;+ startY: number;+ x: number;+ y: number;+ moved: boolean;+ targetId?: string;+ placement?: "before" | "child" | "after";+}++const createElement = <T extends keyof HTMLElementTagNameMap>(tag: T, className: string) => {+ const element = document.createElement(tag);+ element.className = className;+ return element;+};++export class ListMindmapView {+ private readonly options: ListMindmapViewOptions;+ private model: ListMindmapModel;+ private readonly viewport: HTMLDivElement;+ private readonly world: HTMLDivElement;+ private readonly canvas: HTMLCanvasElement;+ private readonly toolbar: HTMLDivElement;+ private readonly inspector: HTMLDivElement;+ private readonly zoomLabel: HTMLSpanElement;+ private readonly nodeElements = new Map<string, HTMLDivElement>();+ private readonly relationElements = new Map<string, HTMLButtonElement>();+ private readonly buttons = new Map<string, HTMLButtonElement>();+ private readonly folded = new Map<string, boolean>();+ private readonly tooltip = createElement("div", "list-mindmap__tooltip");+ private tooltipButton?: HTMLButtonElement;+ private readonly colorProbe = createElement("span", "list-mindmap__color-probe");+ private positions = new Map<string, ListMindmapPosition>();+ private edges: {from: string, to: string}[] = [];+ private bounds = {width: 1, height: 1};+ private selectedId?: string;+ private selectedRelation?: string;+ private selectedEdge?: string;+ private hoveredLine?: string;+ private finishRelationEdit?: (save: boolean) => void;+ private linePaths: {id: string, relation: boolean, path: Path2D}[] = [];+ private relationRoutes = new Map<string, MindmapRoutePoint[]>();+ private relationFrom?: string;+ private editingId?: string;+ private pointer?: PointerState;+ private pointerCapture?: HTMLElement;+ private pendingPointerId?: number;+ private linkTimer = 0;+ private suppressLinkClick = false;+ private ghost?: HTMLDivElement;+ private scale = 1;+ private offsetX = 0;+ private offsetY = 0;+ private frame = 0;+ private initialFit = true;+ private destroyed = false;+ private readonly resizeObserver: ResizeObserver;+ private fullscreenMarker?: Comment;+ private readonly disposers: (() => void)[] = [];+ private printTransform?: {scale: number, offsetX: number, offsetY: number};++ constructor(options: ListMindmapViewOptions) {+ this.options = options;+ this.model = options.model;+ this.selectedId = options.model.root.id;+ options.host.classList.add("list-mindmap");+ options.host.contentEditable = "false";+ options.host.setAttribute("role", "group");+ options.host.setAttribute("aria-label", this.label("mindmap"));+ options.host.tabIndex = 0;+ this.toolbar = createElement("div", "list-mindmap__toolbar block__icons");+ this.toolbar.setAttribute("role", "toolbar");+ this.viewport = createElement("div", "list-mindmap__viewport");+ this.canvas = createElement("canvas", "list-mindmap__canvas");+ this.canvas.setAttribute("aria-hidden", "true");+ this.world = createElement("div", "list-mindmap__world");+ this.inspector = createElement("div", "list-mindmap__inspector");+ this.inspector.hidden = true;+ this.zoomLabel = createElement("span", "list-mindmap__zoom");+ this.viewport.append(this.canvas, this.world);+ this.tooltip.hidden = true;+ this.tooltip.setAttribute("role", "tooltip");+ this.colorProbe.setAttribute("aria-hidden", "true");+ options.host.append(this.toolbar, this.viewport, this.inspector, this.tooltip, this.colorProbe);+ this.createToolbar();+ this.listen(document, "pointerdown", this.dismissControls, {capture: true});+ this.listen(options.host, "pointerover", this.showButtonTooltip);+ this.listen(options.host, "focusin", this.showButtonTooltip);+ ["pointerout", "focusout"].forEach(type => this.listen(options.host, type, this.hideButtonTooltip));+ this.listen(options.host, "wheel", () => this.tooltip.hidden = true);+ const themeObserver = new MutationObserver(() => this.refreshLayout());+ themeObserver.observe(document.documentElement, {attributes: true, attributeFilter: ["data-theme-mode", "style"]});+ themeObserver.observe(document.head, {childList: true, subtree: true, characterData: true, attributes: true});+ this.disposers.push(() => themeObserver.disconnect());+ this.listen(document.head, "load", () => this.refreshLayout(), {capture: true});+ this.listen(this.viewport, "pointerdown", this.pointerDown);+ this.listen(this.viewport, "pointermove", this.pointerMove);+ this.listen(this.viewport, "pointerleave", () => this.setHoveredLine());+ this.listen(this.viewport, "pointerup", this.pointerUp);+ this.listen(this.viewport, "pointercancel", this.cancelPointer);+ this.listen(this.viewport, "lostpointercapture", this.cancelPointer);+ this.listen(window, "pointerup", (event: PointerEvent) => {+ if (this.pendingPointerId === event.pointerId) {+ this.pendingPointerId = undefined;+ }+ });+ this.listen(window, "pointercancel", (event: PointerEvent) => {+ if (this.pendingPointerId === event.pointerId) {+ this.pendingPointerId = undefined;+ }+ });+ this.listen(this.viewport, "dblclick", this.doubleClick);+ this.listen(this.viewport, "click", this.contentClick);+ this.listen(this.viewport, "wheel", this.wheel, {passive: false});+ this.listen(this.viewport, "dragstart", (event: Event) => event.preventDefault());+ this.listen(options.host, "keydown", this.keyDown);+ // 脑图内部先处理交互,再阻止外层文档将节点操作识别为列表块编辑。+ ["pointerdown", "pointerup", "pointermove", "pointercancel", "mousedown", "mouseup", "mousemove", "click",+ "dblclick", "contextmenu", "dragstart", "dragover", "drop", "beforeinput", "input", "compositionstart",+ "compositionupdate", "compositionend", "copy", "cut", "paste", "focusin", "focusout", "keydown", "keyup",+ "wheel"].forEach(type => this.listen(options.host, type, event => {+ if (type === "click" && !event.defaultPrevented && !this.options.onOpenLink &&+ (event.target as Element).closest(".list-mindmap__content a[href]")) {+ return;+ }+ event.stopPropagation();+ }));+ this.listen(window, "beforeprint", () => {+ this.printTransform = {scale: this.scale, offsetX: this.offsetX, offsetY: this.offsetY};+ this.fit();+ });+ this.listen(window, "afterprint", () => {+ if (this.printTransform) {+ Object.assign(this, this.printTransform);+ this.printTransform = undefined;+ this.draw();+ }+ });+ this.resizeObserver = new ResizeObserver(() => this.refreshLayout());+ this.resizeObserver.observe(this.viewport);+ this.update(this.model);+ }++ private label(key: string) {+ return this.options.labels?.[key] || window.siyuan?.languages?.[key] || key;+ }++ private listen(target: EventTarget, event: string, handler: EventListener, options?: AddEventListenerOptions) {+ target.addEventListener(event, handler, options);+ this.disposers.push(() => target.removeEventListener(event, handler, options));+ }++ private makeButton(key: string, icon: string, action: () => void, className = "") {+ const button = createElement("button", "block__icon block__icon--show " + className);+ button.type = "button";+ button.setAttribute("aria-label", this.label(key));+ // 图标引用现有图标集,避免复制或生成路径数据。+ button.innerHTML = `<svg aria-hidden="true"><use xlink:href="#${icon}"></use></svg>`;+ button.addEventListener("click", (event) => {+ event.stopPropagation();+ this.finishThen(action);+ });+ return button;+ }++ 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("list-mindmap__relation")) {+ this.tooltip.hidden = true;+ return;+ }+ if (this.tooltipButton === button && !this.tooltip.hidden) {+ return;+ }+ this.tooltipButton = button;+ this.tooltip.textContent = button.getAttribute("aria-label");+ this.tooltip.hidden = false;+ const host = this.options.host.getBoundingClientRect();+ const rect = button.getBoundingClientRect();+ const left = rect.left - host.left + (rect.width - this.tooltip.offsetWidth) / 2;+ const below = rect.bottom - host.top + 6;+ this.tooltip.style.left = `${Math.max(4, Math.min(left, host.width - this.tooltip.offsetWidth - 4))}px`;+ this.tooltip.style.top = `${Math.max(4, below + this.tooltip.offsetHeight < host.height ?+ below : rect.top - host.top - this.tooltip.offsetHeight - 6)}px`;+ };++ private hideButtonTooltip = (event: MouseEvent | FocusEvent) => {+ if (event.relatedTarget instanceof Node && this.tooltipButton?.contains(event.relatedTarget)) {+ return;+ }+ this.tooltip.hidden = true;+ this.tooltipButton = undefined;+ };++ private clearSelection() {+ this.inspector.hidden = true;+ if (!this.selectedId && !this.selectedRelation && !this.selectedEdge && !this.relationFrom) {+ return;+ }+ this.selectedId = undefined;+ this.selectedRelation = undefined;+ this.selectedEdge = undefined;+ this.relationFrom = undefined;+ this.updateSelection();+ }++ private dismissControls = (event: PointerEvent) => {+ const target = event.target as Node;+ this.tooltip.hidden = true;+ if (target instanceof Element && target.closest(".list-mindmap__relation-editor")) {+ return;+ }+ if (this.inspector.contains(target) || this.buttons.get("style")?.contains(target) ||+ this.buttons.get("relation")?.contains(target)) {+ return;+ }+ this.inspector.hidden = true;+ const node = target instanceof Element && target.closest(".list-mindmap__node, .list-mindmap__relation");+ if (!node || !this.options.host.contains(node)) {+ this.clearSelection();+ }+ };++ private finishThen(action: () => void) {+ const finished = this.options.finishEdit?.();+ if (finished instanceof Promise) {+ void finished.then(result => {+ if (result !== false && !this.destroyed) {+ action();+ }+ }).catch(error => console.error(error));+ } else if (finished !== false && !this.destroyed) {+ action();+ }+ }++ public setReadOnly(value: boolean) {+ if (!!this.options.readOnly === value) {+ return;+ }+ this.options.readOnly = value;+ this.cancelPointer();+ this.relationFrom = undefined;+ this.inspector.hidden = true;+ this.toolbar.replaceChildren();+ this.buttons.clear();+ this.createToolbar();+ if (this.fullscreenMarker) {+ this.fullscreenChange();+ }+ this.nodeElements.forEach(element => {+ const addChild = element.querySelector<HTMLButtonElement>(".list-mindmap__add-child");+ addChild.hidden = value;+ addChild.disabled = value;+ element.querySelector<HTMLElement>(".list-mindmap__add-bridge").hidden = value;+ });+ this.updateSelection();+ }++ private createToolbar() {+ const add = (id: string, key: string, icon: string, action: () => void) => {+ const button = this.makeButton(key, icon, action);+ this.buttons.set(id, button);+ this.toolbar.append(button);+ };+ add("exit", "listMindmapToList", "iconList", () => this.options.onExit());+ this.toolbar.append(createElement("span", "list-mindmap__spacer fn__flex-1"));+ if (!this.options.readOnly) {+ add("relation", "connect", "iconRoute", () => {+ this.inspector.hidden = true;+ this.relationFrom = this.relationFrom ? undefined : this.selectedId;+ this.updateSelection();+ });+ }+ add("zoomOut", "zoomOut", "iconZoomOut", () => this.zoomAt(this.scale / 1.2));+ this.toolbar.append(this.zoomLabel);+ add("zoomIn", "zoomIn", "iconZoomIn", () => this.zoomAt(this.scale * 1.2));+ add("fit", "listMindmapFit", "iconRefresh", () => this.fit());+ add("fullscreen", "fullscreen", "iconFullscreen", () => this.toggleFullscreen());+ }++ public update(model: ListMindmapModel) {+ if (this.destroyed) {+ return;+ }+ this.model = model;+ const descendants = new Map<string, number>();+ const ordered = [model.root];+ for (let i = 0; i < ordered.length; i++) {+ ordered.push(...ordered[i].children);+ }+ for (let i = ordered.length - 1; i >= 0; i--) {+ descendants.set(ordered[i].id, ordered[i].children.reduce((count, child) => count + 1 + descendants.get(child.id), 0));+ }+ this.nodeElements.forEach((element, id) => {+ if (!model.nodes.has(id)) {+ this.resizeObserver.unobserve(element);+ element.remove();+ this.nodeElements.delete(id);+ }+ });+ model.nodes.forEach((node, id) => {+ let element = this.nodeElements.get(id);+ if (!element) {+ element = createElement("div", "list-mindmap__node");+ element.dataset.mindmapId = id;+ element.setAttribute("role", "treeitem");+ element.append(createElement("div", "list-mindmap__content"));+ const addBridge = createElement("span", "list-mindmap__add-bridge");+ addBridge.hidden = !!this.options.readOnly;+ addBridge.setAttribute("aria-hidden", "true");+ element.append(addBridge);+ const fold = this.makeButton("collapse", "iconDown", () => this.toggleFold(id), "list-mindmap__fold");+ fold.append(createElement("span", "list-mindmap__fold-count"));+ element.append(fold);+ const addChild = this.makeButton("listMindmapChild", "iconAdd", () => {+ if (!this.options.readOnly && this.model.nodes.has(id)) {+ this.options.onAdd?.(id, "child");+ }+ }, "list-mindmap__add-child");+ addChild.hidden = !!this.options.readOnly;+ addChild.disabled = !!this.options.readOnly;+ element.append(addChild);+ this.nodeElements.set(id, element);+ this.world.append(element);+ this.resizeObserver.observe(element);+ }+ element.classList.toggle("list-mindmap__node--virtual", node.virtual);+ element.classList.toggle("list-mindmap__node--root", id === model.root.id);+ element.classList.toggle("list-mindmap__node--branch", node.children.length > 0);+ element.style.backgroundColor = model.metadata.nodes[id]?.backgroundColor || "";+ element.style.color = model.metadata.nodes[id]?.textColor || "";+ const collapsed = this.folded.get(id) ?? node.collapsed;+ element.setAttribute("aria-expanded", String(!collapsed));+ const fold = element.querySelector<HTMLButtonElement>(".list-mindmap__fold");+ fold.hidden = !node.children.length;+ fold.classList.toggle("list-mindmap__fold--closed", collapsed);+ fold.setAttribute("aria-label", this.label(collapsed ? "expand" : "collapse"));+ fold.querySelector("span").textContent = String(descendants.get(id));+ if (id !== this.editingId) {+ const content = this.getContentHost(id);+ content.replaceChildren();+ if (node.virtual) {+ content.textContent = this.label("listMindmapRoot");+ } else {+ node.contentBlocks.forEach((block) => {+ const clone = block.cloneNode(true) as HTMLElement;+ clone.querySelectorAll(".protyle-attr, .protyle-action, .protyle-icons, .list-mindmap").forEach(item => item.remove());+ [clone, ...Array.from(clone.querySelectorAll<HTMLElement>("*"))].forEach((item) => {+ item.removeAttribute("contenteditable");+ item.removeAttribute("data-node-id");+ item.removeAttribute("spellcheck");+ item.removeAttribute("draggable");+ if (item.getAttribute("data-type")?.startsWith("Node")) {+ item.removeAttribute("data-type");+ }+ });+ content.append(clone);+ });+ }+ const empty = !content.textContent.replace(/[\u200b\ufeff]/g, "").trim() &&+ !content.querySelector("img, svg, video, audio, iframe, canvas, hr, [data-content]");+ content.classList.toggle("list-mindmap__content--empty", empty);+ content.dataset.placeholder = this.label("listMindmapPlaceholder");+ // 副本独立渲染公式,避免源节点的异步渲染完成后脑图仍保留未渲染内容。+ void mathRender(content, this.options.cdn)?.then(() => this.refreshLayout()).catch(error => console.error(error));+ }+ });+ if (this.selectedId && !model.nodes.has(this.selectedId)) {+ this.selectedId = undefined;+ this.inspector.hidden = true;+ }+ if (this.selectedRelation && !model.metadata.relations.some(relation => relation.id === this.selectedRelation)) {+ this.selectedRelation = undefined;+ this.inspector.hidden = true;+ }+ if (this.selectedEdge && !model.nodes.has(this.selectedEdge)) {+ this.selectedEdge = undefined;+ this.inspector.hidden = true;+ }+ this.updateRelations();+ this.updateSelection();+ this.renderInspector();+ this.refreshLayout();+ }++ public getContentHost(id: string): HTMLElement | undefined {+ return this.nodeElements.get(id)?.querySelector<HTMLElement>(".list-mindmap__content");+ }++ public setEditing(id?: string) {+ if (this.editingId) {+ this.nodeElements.get(this.editingId)?.classList.remove("list-mindmap__node--editing");+ }+ this.editingId = id;+ if (id) {+ this.selectNode(id);+ this.nodeElements.get(id)?.classList.add("list-mindmap__node--editing");+ }+ this.refreshLayout();+ }++ public refreshLayout() {+ if (this.destroyed || this.frame) {+ return;+ }+ this.frame = requestAnimationFrame(() => {+ this.frame = 0;+ if (!this.viewport.clientWidth || !this.viewport.clientHeight) {+ return;+ }+ const makeLayoutNode = (id: string): ListMindmapLayoutNode => {+ const node = this.model.nodes.get(id);+ const element = this.nodeElements.get(id);+ return {+ id,+ width: Math.max(64, element.offsetWidth),+ height: Math.max(36, element.offsetHeight),+ collapsed: this.folded.get(id) ?? node.collapsed,+ children: node.children.map(child => makeLayoutNode(child.id)),+ };+ };+ const previous = this.editingId ? this.positions.get(this.editingId) : undefined;+ const result = layoutListMindmap(makeLayoutNode(this.model.root.id));+ this.positions = result.nodes;+ this.relationRoutes.clear();+ this.edges = result.edges;+ this.bounds = result;+ let top = 0;+ let left = 0;+ this.model.metadata.relations.forEach((relation) => {+ const from = this.positions.get(relation.from);+ const to = this.positions.get(relation.to);+ if (from && to) {+ const points = routeMindmapRelation(from, to, this.routingObstacles());+ this.relationRoutes.set(relation.id, points);+ points.forEach(point => {+ top = Math.min(top, point.y - 24);+ left = Math.min(left, point.x - 100);+ this.bounds.width = Math.max(this.bounds.width, point.x + 100);+ this.bounds.height = Math.max(this.bounds.height, point.y + 24);+ });+ }+ });+ if (top < 0 || left < 0) {+ this.positions.forEach(position => {+ position.y -= top;+ position.x -= left;+ });+ this.relationRoutes.forEach(points => points.forEach(point => {+ point.x -= left;+ point.y -= top;+ }));+ this.bounds.height -= top;+ this.bounds.width -= left;+ }+ this.nodeElements.forEach((element, id) => {+ const position = this.positions.get(id);+ element.hidden = !position;+ if (position) {+ element.style.left = `${position.x}px`;+ element.style.top = `${position.y - 1}px`;+ }+ });+ // 编辑导致尺寸变化时固定当前节点,避免输入光标随整棵树跳动。+ const current = this.editingId ? this.positions.get(this.editingId) : undefined;+ if (previous && current) {+ this.offsetX += (previous.x - current.x) * this.scale;+ this.offsetY += (previous.y - current.y) * this.scale;+ }+ if (this.initialFit) {+ this.initialFit = false;+ this.fit();+ } else {+ this.draw();+ }+ });+ }++ private updateRelations() {+ this.relationElements.forEach((element, id) => {+ if (!this.model.metadata.relations.some(relation => relation.id === id)) {+ element.remove();+ this.relationElements.delete(id);+ }+ });+ this.model.metadata.relations.forEach((relation) => {+ let element = this.relationElements.get(relation.id);+ if (!element) {+ element = createElement("button", "list-mindmap__relation");+ element.type = "button";+ element.dataset.relationId = relation.id;+ element.addEventListener("click", (event) => {+ event.stopPropagation();+ this.finishThen(() => {+ this.selectedRelation = relation.id;+ this.selectedEdge = undefined;+ this.relationFrom = undefined;+ this.selectedId = undefined;+ this.updateSelection();+ if (!this.options.readOnly) {+ this.inspector.hidden = false;+ this.renderInspector();+ }+ });+ });+ this.relationElements.set(relation.id, element);+ this.world.append(element);+ }+ element.textContent = relation.label || "";+ element.setAttribute("aria-label", relation.label || this.label("connect"));+ element.style.color = relation.color || "";+ });+ }++ private routingObstacles() {+ return [...this.positions.values()].map(node => ({...node,+ controlY: node.y + (node.id === this.model.root.id ? node.height / 2 : node.height),+ }));+ }++ private relationPath(id: string, from: ListMindmapPosition, to: ListMindmapPosition, label: HTMLElement) {+ let points = this.relationRoutes.get(id);+ if (!points) {+ points = routeMindmapRelation(from, to, this.routingObstacles());+ this.relationRoutes.set(id, points);+ }+ if (points.length < 2) {+ return;+ }+ const path = new Path2D();+ path.moveTo(points[0].x, points[0].y);+ for (let i = 1; i < points.length - 1; i++) {+ const a = points[i - 1];+ const b = points[i];+ const c = points[i + 1];+ const before = Math.hypot(b.x - a.x, b.y - a.y);+ const after = Math.hypot(c.x - b.x, c.y - b.y);+ const radius = Math.min(8, before / 2, after / 2);+ path.lineTo(b.x + (a.x - b.x) * radius / before, b.y + (a.y - b.y) * radius / before);+ path.quadraticCurveTo(b.x, b.y, b.x + (c.x - b.x) * radius / after, b.y + (c.y - b.y) * radius / after);+ }+ const end = points[points.length - 1];+ const previous = points[points.length - 2];+ path.lineTo(end.x, end.y);+ const width = label.offsetWidth;+ 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);+ let labelPoint: MindmapRoutePoint;+ for (const segment of segments) {+ const center = {x: (segment.a.x + segment.b.x) / 2, y: (segment.a.y + segment.b.y) / 2};+ const candidates = [center, {x: center.x + width / 2 + 6, y: center.y},+ {x: center.x - width / 2 - 6, y: center.y},+ {x: center.x, y: center.y - height / 2 - 6}, {x: center.x, y: center.y + height / 2 + 6}];+ labelPoint = candidates.find(p => ![...this.positions.values()].some(node =>+ p.x + width / 2 > node.x - 4 && p.x - width / 2 < node.x + node.width + 40 &&+ p.y + height / 2 > node.y - 4 && p.y - height / 2 < node.y + node.height + 4));+ if (labelPoint) {+ break;+ }+ }+ label.style.visibility = labelPoint ? "" : "hidden";+ return {path, end, previous, labelPoint};+ }++ private draw() {+ if (this.destroyed) {+ return;+ }+ this.world.style.transform = `translate(${this.offsetX}px, ${this.offsetY}px) scale(${this.scale})`;+ this.zoomLabel.textContent = `${Math.round(this.scale * 100)}%`;+ const width = this.viewport.clientWidth;+ const height = this.viewport.clientHeight;+ const ratio = window.devicePixelRatio || 1;+ if (this.canvas.width !== Math.round(width * ratio) || this.canvas.height !== Math.round(height * ratio)) {+ this.canvas.width = Math.round(width * ratio);+ this.canvas.height = Math.round(height * ratio);+ }+ const context = this.canvas.getContext("2d");+ this.linePaths = [];+ if (!context) {+ return;+ }+ context.setTransform(ratio, 0, 0, ratio, 0, 0);+ context.clearRect(0, 0, width, height);+ context.translate(this.offsetX, this.offsetY);+ context.scale(this.scale, this.scale);+ const theme = getComputedStyle(this.options.host);+ const defaultLine = theme.getPropertyValue("--b3-border-color").trim() || "#a8adb5";+ const primary = theme.getPropertyValue("--b3-theme-primary").trim() || "#3574f0";+ const colors = new Map<string, string>();+ const resolveColor = (value: string, fallback: string) => {+ const key = value || fallback;+ if (!colors.has(key)) {+ this.colorProbe.style.color = fallback;+ if (value) {+ this.colorProbe.style.color = value;+ }+ colors.set(key, getComputedStyle(this.colorProbe).color);+ }+ return colors.get(key);+ };+ this.edges.forEach((edge) => {+ const from = this.positions.get(edge.from);+ const to = this.positions.get(edge.to);+ if (!from || !to) {+ return;+ }+ const style = {...this.model.metadata.nodes[this.model.root.id], ...this.model.metadata.nodes[edge.to]};+ const startX = from.x + from.width;+ const startY = from.y + (edge.from === this.model.root.id ? from.height / 2 : from.height);+ const endX = to.x;+ const endY = to.y + to.height;+ const center = (startX + endX) / 2;+ const path = new Path2D();+ path.moveTo(startX, startY);+ path.bezierCurveTo(center, startY, center, endY, endX, endY);+ path.lineTo(to.x + to.width, endY);+ this.linePaths.push({id: edge.to, relation: false, path});+ context.beginPath();+ context.strokeStyle = resolveColor(style.lineColor, defaultLine);+ context.lineWidth = (style.lineWidth || 1.5) + (this.selectedEdge === edge.to ? 1 : 0) ++ (this.hoveredLine === `edge:${edge.to}` ? 1.5 / this.scale : 0);+ context.setLineDash(style.lineDash ? [6, 4] : []);+ context.stroke(path);+ });+ this.model.metadata.relations.forEach((relation) => {+ const from = this.positions.get(relation.from);+ const to = this.positions.get(relation.to);+ const element = this.relationElements.get(relation.id);+ element.hidden = !from || !to || !relation.label?.trim();+ if (!from || !to) {+ return;+ }+ const route = this.relationPath(relation.id, from, to, element);+ if (!route) {+ element.hidden = true;+ return;+ }+ const {path, end, previous, labelPoint} = route;+ this.linePaths.push({id: relation.id, relation: true, path});+ context.beginPath();+ context.strokeStyle = resolveColor(relation.color, primary);+ context.lineWidth = (relation.width || 1.5) + (relation.id === this.selectedRelation ? 1 : 0) ++ (this.hoveredLine === `relation:${relation.id}` ? 1.5 / this.scale : 0);+ element.classList.toggle("list-mindmap__relation--hover", this.hoveredLine === `relation:${relation.id}`);+ context.setLineDash(relation.dash === false ? [] : [5, 4]);+ context.stroke(path);+ context.setLineDash([]);+ context.beginPath();+ const direction = Math.atan2(end.y - previous.y, end.x - previous.x);+ // 箭头保持最小屏幕尺寸,并沿避障路径朝向目标节点。+ const arrowSize = Math.max(10 / this.scale, (relation.width || 1.5) * 3);+ context.fillStyle = context.strokeStyle;+ context.moveTo(end.x - arrowSize * Math.cos(direction - Math.PI / 6), end.y - arrowSize * Math.sin(direction - Math.PI / 6));+ context.lineTo(end.x, end.y);+ context.lineTo(end.x - arrowSize * Math.cos(direction + Math.PI / 6), end.y - arrowSize * Math.sin(direction + Math.PI / 6));+ context.closePath();+ context.fill();+ if (labelPoint) {+ element.style.left = `${labelPoint.x}px`;+ element.style.top = `${labelPoint.y}px`;+ }+ });+ }++ private selectNode(id: string) {+ const changed = this.selectedId !== id || !!this.selectedRelation;+ this.selectedId = id;+ this.selectedRelation = undefined;+ this.selectedEdge = undefined;+ this.updateSelection();+ if (!this.options.readOnly && !this.relationFrom) {+ this.inspector.hidden = false;+ }+ if (changed || !this.inspector.hidden) {+ this.renderInspector();+ }+ }++ private updateSelection() {+ this.nodeElements.forEach((element, id) => {+ element.classList.toggle("list-mindmap__node--selected", this.selectedId === id);+ element.classList.toggle("list-mindmap__node--relation", this.relationFrom === id);+ element.setAttribute("aria-selected", String(this.selectedId === id));+ });+ this.relationElements.forEach((element, id) => element.classList.toggle("list-mindmap__relation--selected", this.selectedRelation === id));+ const node = this.model.nodes.get(this.selectedId);+ const disabled: Record<string, boolean> = {+ relation: !node || node.virtual,+ style: !node && !this.selectedRelation && !this.selectedEdge,+ };+ Object.keys(disabled).forEach((key) => {+ const button = this.buttons.get(key);+ if (button) {+ button.disabled = disabled[key];+ }+ });+ this.buttons.get("relation")?.classList.toggle("block__icon--active", !!this.relationFrom);+ this.draw();+ }++ private toggleFold(id: string) {+ const node = this.model.nodes.get(id);+ if (!node?.children.length) {+ return;+ }+ if (this.options.readOnly || node.virtual) {+ this.folded.set(id, !(this.folded.get(id) ?? node.collapsed));+ this.update(this.model);+ } else {+ this.options.onFold?.(id);+ }+ }++ private deleteSelection() {+ if (this.options.readOnly) {+ return;+ }+ if (this.selectedRelation) {+ this.options.onRelationDelete?.(this.selectedRelation);+ } else {+ const node = this.model.nodes.get(this.selectedId);+ if (node && !node.virtual && node !== this.model.root) {+ this.options.onDelete?.(node.id);+ }+ }+ }++ private pointerDown = (event: PointerEvent) => {+ clearTimeout(this.linkTimer);+ this.suppressLinkClick = false;+ const target = event.target as HTMLElement;+ if (event.button !== 0 || target.closest("button, input, select, textarea, .list-mindmap__node--editing")) {+ return;+ }+ const element = target.closest<HTMLElement>(".list-mindmap__node");+ const id = element?.dataset.mindmapId;+ this.pendingPointerId = event.pointerId;+ this.finishThen(() => {+ if (this.pendingPointerId === event.pointerId) {+ this.beginPointer(event, id);+ }+ });+ };++ private beginPointer(event: PointerEvent, id?: string) {+ if (this.relationFrom && id) {+ this.suppressLinkClick = true;+ event.preventDefault();+ if (id !== this.relationFrom && !this.model.nodes.get(id)?.virtual) {+ this.options.onRelationAdd?.(this.relationFrom, id);+ this.relationFrom = undefined;+ this.selectNode(id);+ }+ return;+ }+ if (id) {+ this.selectNode(id);+ }+ this.options.host.focus({preventScroll: true});+ this.pointer = {+ pointerId: event.pointerId,+ id: !this.options.readOnly && id && !this.model.nodes.get(id)?.virtual ? id : undefined,+ startX: event.clientX,+ startY: event.clientY,+ x: this.offsetX,+ y: this.offsetY,+ moved: false,+ };+ try {+ // 在原点击元素捕获指针,保留链接目标,同时让连续点击可以识别为双击。+ this.pointerCapture = id ? event.target as HTMLElement : this.viewport;+ this.pointerCapture.setPointerCapture(event.pointerId);+ } catch {+ this.pointer = undefined;+ }+ }++ private pointerMove = (event: PointerEvent) => {+ const pointer = this.pointer;+ if (!pointer) {+ const target = event.target as Element;+ const relation = target.closest<HTMLElement>(".list-mindmap__relation[data-relation-id]");+ const line = target.closest(".list-mindmap__node, input, button") ? undefined : this.findLine(event);+ this.setHoveredLine(relation ? `relation:${relation.dataset.relationId}` :+ line ? `${line.relation ? "relation" : "edge"}:${line.id}` : undefined);+ return;+ }+ this.setHoveredLine();+ if (!pointer || event.pointerId !== pointer.pointerId) {+ return;+ }+ const dx = event.clientX - pointer.startX;+ const dy = event.clientY - pointer.startY;+ if (!pointer.moved && Math.hypot(dx, dy) < 5) {+ return;+ }+ event.preventDefault();+ pointer.moved = true;+ this.viewport.classList.add("list-mindmap__viewport--dragging");+ if (!pointer.id) {+ this.offsetX = pointer.x + dx;+ this.offsetY = pointer.y + dy;+ this.draw();+ return;+ }+ if (!this.ghost) {+ const source = this.nodeElements.get(pointer.id);+ this.ghost = source.cloneNode(true) as HTMLDivElement;+ this.ghost.className = "list-mindmap__node list-mindmap__ghost";+ this.ghost.removeAttribute("data-mindmap-id");+ this.ghost.querySelectorAll(".list-mindmap__fold, .list-mindmap__add-child, .list-mindmap__add-bridge")+ .forEach(button => button.remove());+ this.world.append(this.ghost);+ source.classList.add("list-mindmap__node--dragging");+ }+ const source = this.positions.get(pointer.id);+ this.ghost.style.left = `${source.x + dx / this.scale}px`;+ this.ghost.style.top = `${source.y + dy / this.scale}px`;+ this.clearDrop();+ const target = document.elementFromPoint(event.clientX, event.clientY)?.closest<HTMLElement>(".list-mindmap__node");+ const targetId = target?.dataset.mindmapId;+ if (!targetId || !this.world.contains(target) || !this.canDrop(pointer.id, targetId)) {+ return;+ }+ const rect = target.getBoundingClientRect();+ const part = (event.clientY - rect.top) / rect.height;+ const node = this.model.nodes.get(targetId);+ const placement = node.virtual ? "child" : part < .25 ? "before" : part > .75 ? "after" : "child";+ pointer.targetId = targetId;+ pointer.placement = placement;+ target.dataset.mindmapDrop = placement;+ };++ private canDrop(id: string, targetId: string) {+ let current = this.model.nodes.get(targetId);+ while (current) {+ if (current.id === id) {+ return false;+ }+ current = this.model.nodes.get(current.parentId);+ }+ return true;+ }++ private pointerUp = (event: PointerEvent) => {+ this.pendingPointerId = undefined;+ const pointer = this.pointer;+ if (!pointer || event.pointerId !== pointer.pointerId) {+ return;+ }+ const {id, targetId, placement, moved} = pointer;+ this.suppressLinkClick = moved;+ this.cancelPointer();+ if (moved && id && targetId && placement) {+ this.options.onMove?.(id, targetId, placement);+ } else if (!moved && !id && !this.options.readOnly) {+ this.selectLine(event);+ }+ };++ private setHoveredLine(key?: string) {+ if (key === this.hoveredLine) {+ return;+ }+ this.hoveredLine = key;+ this.viewport.classList.toggle("list-mindmap__viewport--line-hover", !!key);+ this.draw();+ }++ private findLine(event: MouseEvent) {+ const context = this.canvas.getContext("2d");+ if (!context) {+ return;+ }+ const bounds = this.viewport.getBoundingClientRect();+ const x = (event.clientX - bounds.left - this.offsetX) / this.scale;+ const y = (event.clientY - bounds.top - this.offsetY) / this.scale;+ context.save();+ context.resetTransform();+ context.setLineDash([]);+ context.lineWidth = 12 / this.scale;+ const line = this.linePaths.slice().reverse().find(item => context.isPointInStroke(item.path, x, y));+ context.restore();+ return line;+ }++ private selectLine(event: MouseEvent) {+ const line = this.findLine(event);+ if (!line) {+ return;+ }+ this.selectedId = undefined;+ this.relationFrom = undefined;+ this.selectedRelation = line.relation ? line.id : undefined;+ this.selectedEdge = line.relation ? undefined : line.id;+ this.inspector.hidden = false;+ this.updateSelection();+ this.renderInspector();+ }++ private clearDrop() {+ if (this.pointer) {+ this.pointer.targetId = undefined;+ this.pointer.placement = undefined;+ }+ this.world.querySelectorAll<HTMLElement>("[data-mindmap-drop]").forEach(element => element.removeAttribute("data-mindmap-drop"));+ }++ private cancelPointer = () => {+ this.pendingPointerId = undefined;+ this.clearDrop();+ const pointer = this.pointer;+ this.pointer = undefined;+ if (pointer && this.pointerCapture?.hasPointerCapture(pointer.pointerId)) {+ this.pointerCapture.releasePointerCapture(pointer.pointerId);+ }+ this.pointerCapture = undefined;+ this.ghost?.remove();+ this.ghost = undefined;+ this.viewport.classList.remove("list-mindmap__viewport--dragging");+ this.nodeElements.forEach(element => element.classList.remove("list-mindmap__node--dragging"));+ };++ private contentClick = (event: MouseEvent) => {+ const target = event.target as Element;+ if (target.closest(".list-mindmap__node--editing")) {+ return;+ }+ const link = target.closest<HTMLElement>('a[href], [data-type~="a"][data-href], [data-type~="block-ref"][data-id]');+ if (!link?.closest(".list-mindmap__content")) {+ return;+ }+ clearTimeout(this.linkTimer);+ if (this.suppressLinkClick || this.relationFrom || event.detail > 1) {+ event.preventDefault();+ return;+ }+ const href = getAVRichTextSafeURL(link.getAttribute("data-type")?.split(" ").includes("block-ref") ?+ `siyuan://blocks/${link.dataset.id}` : link.dataset.href || link.getAttribute("href"));+ if (!href) {+ event.preventDefault();+ return;+ }+ if (this.options.onOpenLink) {+ event.preventDefault();+ // 等待双击判定,拖拽和进入节点编辑均不触发跳转。+ this.linkTimer = window.setTimeout(() => {+ if (!this.destroyed && link.isConnected) {+ this.finishThen(() => this.options.onOpenLink(href, event));+ }+ }, Constants.TIMEOUT_DBLCLICK);+ }+ };++ private doubleClick = (event: MouseEvent) => {+ clearTimeout(this.linkTimer);+ if (this.options.readOnly || this.relationFrom) {+ return;+ }+ const target = event.target as HTMLElement;+ if (target.closest(".list-mindmap__relation")) {+ this.editRelationLabel(event);+ return;+ }+ if (target.closest("button, input, select, .list-mindmap__node--editing")) {+ return;+ }+ const id = target.closest<HTMLElement>(".list-mindmap__node")?.dataset.mindmapId;+ if (!id) {+ this.selectLine(event);+ if (this.selectedRelation) {+ this.editRelationLabel(event);+ }+ return;+ }+ if (!id || this.model.nodes.get(id)?.virtual) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ this.cancelPointer();+ this.finishThen(() => {+ this.setEditing(id);+ this.options.onEdit?.(id, this.getContentHost(id));+ });+ };++ private editRelationLabel(event: MouseEvent) {+ const relation = this.model.metadata.relations.find(item => item.id === this.selectedRelation);+ const element = this.relationElements.get(this.selectedRelation);+ if (!relation || !element) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ this.finishRelationEdit?.(true);+ this.inspector.hidden = true;+ const input = createElement("input", "b3-text-field list-mindmap__relation list-mindmap__relation-editor");+ input.type = "text";+ input.value = relation.label || "";+ input.setAttribute("aria-label", this.label("text"));+ input.style.left = element.style.left;+ input.style.top = element.style.top;+ element.style.visibility = "hidden";+ let finished = false;+ const finish = (save: boolean) => {+ if (finished) {+ return;+ }+ finished = true;+ this.finishRelationEdit = undefined;+ const value = input.value;+ input.remove();+ element.style.visibility = "";+ if (save && value !== (relation.label || "")) {+ this.options.onRelationChange?.(relation.id, {label: value});+ }+ };+ this.finishRelationEdit = finish;+ input.addEventListener("blur", () => finish(true));+ input.addEventListener("keydown", event => {+ if (event.isComposing || (event.key !== "Enter" && event.key !== "Escape")) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ finish(event.key === "Enter");+ this.options.host.focus({preventScroll: true});+ });+ this.world.append(input);+ input.focus();+ input.select();+ }++ private wheel = (event: WheelEvent) => {+ if ((event.target as HTMLElement).closest(".list-mindmap__node--editing")) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ const mode = event.deltaMode;+ const unitX = mode === WheelEvent.DOM_DELTA_LINE ? 16 :+ mode === WheelEvent.DOM_DELTA_PAGE ? this.viewport.clientWidth : 1;+ const unitY = mode === WheelEvent.DOM_DELTA_LINE ? 16 :+ mode === WheelEvent.DOM_DELTA_PAGE ? this.viewport.clientHeight : 1;+ this.offsetX -= event.deltaX * unitX;+ this.offsetY -= event.deltaY * unitY;+ this.draw();+ };++ private zoomAt(scale: number, x = this.viewport.clientWidth / 2, y = this.viewport.clientHeight / 2) {+ const next = Math.min(2.5, Math.max(.15, scale));+ this.offsetX = x - (x - this.offsetX) * next / this.scale;+ this.offsetY = y - (y - this.offsetY) * next / this.scale;+ this.scale = next;+ this.draw();+ }++ public fit() {+ const width = this.viewport.clientWidth;+ const height = this.viewport.clientHeight;+ this.scale = Math.min(1, Math.max(.15, Math.min((width - 64) / this.bounds.width, (height - 64) / this.bounds.height)));+ this.offsetX = (width - this.bounds.width * this.scale) / 2;+ this.offsetY = (height - this.bounds.height * this.scale) / 2;+ this.draw();+ }++ private keyDown = (event: KeyboardEvent) => {+ const target = event.target as HTMLElement;+ if (event.isComposing || target.closest("input, textarea, select, .list-mindmap__node--editing")) {+ return;+ }+ if ((event.key === "Delete" || event.key === "Backspace") &&+ !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {+ const selectedId = this.selectedId;+ const selectedRelation = this.selectedRelation;+ this.finishThen(() => {+ if (selectedId === this.selectedId && selectedRelation === this.selectedRelation) {+ this.deleteSelection();+ }+ });+ } else if (event.key === "Escape") {+ this.cancelPointer();+ this.relationFrom = undefined;+ this.inspector.hidden = true;+ if (this.fullscreenMarker) {+ this.exitFullscreen();+ }+ this.updateSelection();+ } else {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ };++ private renderInspector() {+ if (this.inspector.hidden || this.options.readOnly) {+ return;+ }+ this.inspector.replaceChildren();+ const lineSelected = !!this.selectedRelation || !!this.selectedEdge;+ this.inspector.classList.toggle("list-mindmap__inspector--node", !lineSelected);+ this.inspector.classList.toggle("list-mindmap__inspector--line", lineSelected);+ this.inspector.style.left = "";+ this.inspector.style.top = "";+ const color = (value: string, action: (value: string) => void, key = "color") => {+ const palette = createElement("div", "list-mindmap__palette");+ palette.setAttribute("role", "group");+ palette.setAttribute("aria-label", this.label(key));+ const colors = [{label: this.label("default"), value: ""}, ...(this.options.colors?.() || [])];+ colors.forEach(item => {+ const button = this.makeButton("color", "iconCheck", () => action(item.value));+ const selected = (value || "") === item.value;+ button.className = "color__square list-mindmap__color" + (selected ? " color__square--current" : "");+ button.querySelector("svg").classList.add("svg--mid");+ button.setAttribute("aria-label", item.label);+ button.setAttribute("aria-pressed", String(selected));+ button.style.backgroundColor = item.value || "var(--b3-theme-background)";+ palette.append(button);+ });+ this.inspector.append(palette);+ };+ if (this.selectedRelation) {+ const relation = this.model.metadata.relations.find(item => item.id === this.selectedRelation);+ if (!relation) {+ return;+ }+ const change = (patch: Partial<ListMindmapRelation>) => this.options.onRelationChange?.(relation.id, patch);+ color(relation.color, value => change({color: value}));+ const remove = this.makeButton("delete", "iconTrashcan", () => this.options.onRelationDelete?.(relation.id));+ this.inspector.append(remove);+ return;+ }+ if (this.selectedEdge) {+ const id = this.selectedEdge;+ const style = {...this.model.metadata.nodes[this.model.root.id], ...this.model.metadata.nodes[id]};+ const change = (patch: Partial<ListMindmapNodeStyle>) => this.options.onNodeStyle?.(id, patch);+ color(style.lineColor, value => change({lineColor: value}));+ return;+ }+ if (!this.selectedId) {+ return;+ }+ const id = this.selectedId;+ const style = this.model.metadata.nodes[id] || {};+ const change = (patch: Partial<ListMindmapNodeStyle>) => this.options.onNodeStyle?.(id, patch);+ const nodePalette = createElement("div", "fn__flex");+ nodePalette.setAttribute("role", "group");+ nodePalette.setAttribute("aria-label", this.label("color"));+ [{label: this.label("default"), color: "", backgroundColor: ""}, ...(this.options.nodeColors?.() || [])].forEach(item => {+ const button = this.makeButton("color", "iconFont", () => change({+ textColor: item.color, backgroundColor: item.backgroundColor,+ }));+ const selected = (style.textColor || "") === item.color && (style.backgroundColor || "") === item.backgroundColor;+ button.className = "color__square" + (selected ? " color__square--current" : "");+ button.textContent = "A";+ button.setAttribute("aria-label", item.label);+ button.setAttribute("aria-pressed", String(selected));+ button.style.color = item.color;+ button.style.backgroundColor = item.backgroundColor;+ nodePalette.append(button);+ });+ if (this.options.onManageNodeColors) {+ const manage = this.makeButton("manageColors", "iconSettings", this.options.onManageNodeColors);+ manage.className = "color__square";+ manage.querySelector("svg").classList.add("svg--mid");+ nodePalette.append(manage);+ }+ this.inspector.append(nodePalette);+ const node = this.model.nodes.get(id);+ if (node && !node.virtual && node !== this.model.root) {+ this.inspector.append(this.makeButton("delete", "iconTrashcan", () => this.deleteSelection()));+ }+ }++ private toggleFullscreen() {+ if (this.fullscreenMarker) {+ this.exitFullscreen();+ } else {+ this.enterFullscreen();+ }+ }++ private enterFullscreen() {+ if (this.destroyed || this.fullscreenMarker) {+ return;+ }+ // 移到独立容器,避免编辑器祖先的变换和裁剪改变全屏覆盖范围。+ this.fullscreenMarker = document.createComment("list-mindmap");+ this.options.host.before(this.fullscreenMarker);+ document.body.append(this.options.host);+ this.options.onFullscreen?.(true, this.buttons.get("fullscreen"));+ this.options.host.classList.add("fullscreen");+ this.toolbar.classList.add("block__icons");+ this.fullscreenChange();+ this.options.host.focus({preventScroll: true});+ }++ private exitFullscreen() {+ if (!this.fullscreenMarker) {+ return;+ }+ this.options.onFullscreen?.(false, this.buttons.get("fullscreen"));+ this.options.host.classList.remove("fullscreen");+ this.fullscreenMarker.replaceWith(this.options.host);+ this.fullscreenMarker = undefined;+ this.fullscreenChange();+ if (!this.destroyed) {+ this.options.host.focus({preventScroll: true});+ }+ }++ private fullscreenChange = () => {+ const active = !!this.fullscreenMarker;+ this.tooltip.hidden = true;+ const button = this.buttons.get("fullscreen");+ button.setAttribute("aria-label", this.label(active ? "exitFullscreen" : "fullscreen"));+ button.querySelector("use").setAttribute("xlink:href", active ? "#iconFullscreenExit" : "#iconFullscreen");+ this.initialFit = true;+ this.refreshLayout();+ };++ public destroy() {+ this.finishRelationEdit?.(false);+ if (this.destroyed) {+ return;+ }+ this.destroyed = true;+ clearTimeout(this.linkTimer);+ this.cancelPointer();+ if (this.frame) {+ cancelAnimationFrame(this.frame);+ }+ this.resizeObserver.disconnect();+ this.disposers.forEach(dispose => dispose());+ this.exitFullscreen();+ this.nodeElements.clear();+ this.relationElements.clear();+ this.options.host.replaceChildren();+ }+}diff --git a/app/src/protyle/render/mindmapRender.ts b/app/src/protyle/render/mindmapRender.tsindex 8d519bfa54..cb5ad8006a 100644--- a/app/src/protyle/render/mindmapRender.ts+++ b/app/src/protyle/render/mindmapRender.ts@@ -4,8 +4,10 @@ import {hasClosestByClassName} from "../util/hasClosest";import {genIconHTML} from "./util";import {escapeHtml} from "../../util/escape";import {getHostCapabilities} from "../../util/hostCapabilities";+import {listMindmapRender} from "./listMindmap/render";export const mindmapRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {+ listMindmapRender(element, cdn);let mindmapElements: Element[] | NodeListOf<Element> = [];if (element.getAttribute("data-subtype") === "mindmap" && element.getAttribute("data-render") !== "true") {mindmapElements = [element];diff --git a/app/src/protyle/util/blockDOMClipboard.ts b/app/src/protyle/util/blockDOMClipboard.tsindex f73aad314e..e87faad958 100644--- a/app/src/protyle/util/blockDOMClipboard.ts+++ b/app/src/protyle/util/blockDOMClipboard.ts@@ -1,4 +1,5 @@import {removeZWJ} from "./normalizeText";+import {cleanListMindmapHTML} from "../render/listMindmap/model";interface IBlockDOMClipboardHTMLLute {BlockDOM2HTML(blockDOM: string): string;@@ -8,12 +9,15 @@ interface IBlockDOMClipboardLute extends IBlockDOMClipboardHTMLLute {BlockDOM2StdMd(blockDOM: string): string;}-export const buildBlockDOMClipboardRichData = (lute: IBlockDOMClipboardHTMLLute, blockDOM: string) => ({- textHTML: removeZWJ(lute.BlockDOM2HTML(blockDOM).trimEnd()),- textSiyuan: blockDOM + "\u200b",-});+export const buildBlockDOMClipboardRichData = (lute: IBlockDOMClipboardHTMLLute, blockDOM: string) => {+ const source = cleanListMindmapHTML(blockDOM);+ return {+ textHTML: removeZWJ(lute.BlockDOM2HTML(source).trimEnd()),+ textSiyuan: source + "\u200b",+ };+};export const buildBlockDOMClipboardData = (lute: IBlockDOMClipboardLute, blockDOM: string) => ({- textPlain: lute.BlockDOM2StdMd(blockDOM).trimEnd(),+ textPlain: lute.BlockDOM2StdMd(cleanListMindmapHTML(blockDOM)).trimEnd(),...buildBlockDOMClipboardRichData(lute, blockDOM),});diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.tsindex 4b0a1414ab..c39c02a26e 100644--- a/app/src/protyle/util/destroy.ts+++ b/app/src/protyle/util/destroy.ts@@ -1,4 +1,5 @@import {destroyTabsRender} from "../render/tabsRender";+import {destroyListMindmaps} from "../render/listMindmap";import {hideElements} from "../ui/hideElements";import {isSupportCSSHL} from "../render/searchMarkRender";import {destroyAIEditor} from "../../ai/editor";@@ -14,6 +15,7 @@ export const destroy = (protyle: IProtyle) => {if (!protyle) {return;}+ destroyListMindmaps(protyle);invalidateFocusFoldRequests(protyle);destroyTrackedRanges(protyle);cancelAssetUploads(protyle);diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.tsindex 3252596d0d..4030283b70 100644--- a/app/src/protyle/util/editorCommonEvent.ts+++ b/app/src/protyle/util/editorCommonEvent.ts@@ -86,6 +86,7 @@ import {getCaretRect} from "./caretRect";import {isBlockRefDropTargetDisabled} from "./blockRefDrop";import {appendCancelSuperBlockOperations} from "../../block/cancelSuperBlock";import {preserveTabTask, remapTabsDOMIDs} from "./tabsCopy";+import {remapListMindmapIDs} from "../render/listMindmap/model";import {getTabItems, getTabTask} from "../render/tabsRender";import {repairActiveTab} from "../wysiwyg/tabsRemoval";import {sortAVRows} from "../render/av/rowSort";@@ -408,6 +409,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemene.setAttribute("updated", newId.split("-")[0]);});remapTabsDOMIDs(copyElement, copiedIDs);+ remapListMindmapIDs(copyElement, copiedIDs);const targetSubtype = targetElement.getAttribute("data-subtype");if (copyElement.getAttribute("data-type") === "NodeListItem" &&targetElement.getAttribute("data-type") === "NodeListItem" && targetSubtype &&diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex 677152795c..b38cb49eff 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -28,6 +28,7 @@ import {captureAVAssetUploadHandler} from "../render/av/asset";import {fixAdjacentTags, getCalloutInfo, getContenteditableElement} from "../wysiwyg/getBlock";import {clearBlockElement} from "./clear";import {remapTabsDOMIDs, wrapPastedTabItems} from "./tabsCopy";+import {remapListMindmapIDs} from "../render/listMindmap/model";import {getTabItems, getTabTitle} from "../render/tabsRender";import {removeZWJ} from "./normalizeText";import {base64ToURL, showBase64ImageSizeLimit} from "../upload/base64";@@ -1114,6 +1115,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenclearBlockElement(e, isCutPaste); // 剪切粘贴保留引用角标});remapTabsDOMIDs(tempElement, pastedIDs);+ remapListMindmapIDs(tempElement, pastedIDs);const updated = dayjs().format("YYYYMMDDHHmmss");pastedBlockElements.forEach((e) => {e.setAttribute("updated", updated);diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex 6a98a9b30d..41ce78a2bc 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -17,6 +17,7 @@ import {hasClosestByTag, hasTopClosestByClassName} from "../util/hasClosest";import {removeEmbed} from "./removeEmbed";import {clearBlockElement} from "../util/clear";import {remapTabsDOMIDs} from "../util/tabsCopy";+import {remapListMindmapIDs} from "../render/listMindmap/model";import {isEncryptedBox} from "../../util/pathName";import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";import {captureCommandContext} from "../../command/context";@@ -339,6 +340,7 @@ export const duplicateBlock = async (nodeElements: Element[], protyle: IProtyle)clearBlockElement(childItem);});remapTabsDOMIDs(tempElement, copiedIDs);+ remapListMindmapIDs(tempElement, copiedIDs);if (typeof starIndex === "number") {const orderIndex = starIndex + index + 1;tempElement.setAttribute("data-marker", (orderIndex) + ".");@@ -381,6 +383,7 @@ export const duplicateBlock = async (nodeElements: Element[], protyle: IProtyle)childItem.setAttribute("data-node-id", newChildId);clearBlockElement(childItem);remapTabsDOMIDs(childItem, foldedIDs);+ remapListMindmapIDs(childItem, foldedIDs);doOperations.push({context: {ignoreProcess: "true"diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 1b842ad993..c3fd0512d9 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -183,6 +183,7 @@ import {isEncryptedBox, parseSiYuanUriInfo} from "../../util/pathName";import {processSiYuanUri} from "../../util/uri";import {enhanceRichClipboard, prepareExternalClipboardHTML, prepareRichClipboardHTML} from "../util/richClipboard";import {buildBlockDOMClipboardRichData} from "../util/blockDOMClipboard";+import {cleanListMindmapHTML} from "../render/listMindmap/model";import {getSemanticInlineVisibleText,getTextWithoutSemanticMarkers,@@ -1069,7 +1070,7 @@ export class WYSIWYG {html = visibleTabsSelectionHTML(html);textPlain = "";}- html = sanitizeViewFoldHTML(html);+ html = cleanListMindmapHTML(sanitizeViewFoldHTML(html));if (protyle.disabled) {html = getEnableHTML(html);}@@ -3478,7 +3479,7 @@ export class WYSIWYG {}if (!isInCodeBlock) {- html = sanitizeViewFoldHTML(html);+ html = cleanListMindmapHTML(sanitizeViewFoldHTML(html));enableLuteMarkdownSyntax(protyle);const clipboardBlockDOM = selectAVElement ? html :transformSemanticInlineHTML(normalizeSemanticInlineHTML(html), "legacy");diff --git a/app/src/protyle/wysiwyg/tabs.ts b/app/src/protyle/wysiwyg/tabs.tsindex 0d8eee81d5..c2298b8129 100644--- a/app/src/protyle/wysiwyg/tabs.ts+++ b/app/src/protyle/wysiwyg/tabs.ts@@ -11,6 +11,7 @@ import {avRender} from "../render/av/render";import {isHiddenTabContent} from "../render/tabsVisibility";import {queueTransaction} from "../util/transactionQueue";import {remapTabsDOMIDs} from "../util/tabsCopy";+import {remapListMindmapIDs} from "../render/listMindmap/model";import {copySubMenu} from "../../menus/commonMenuItem";import {isTaskListMarker, nextTaskListMarker} from "./taskListMarker";import {hideElements} from "../ui/hideElements";@@ -174,6 +175,7 @@ export const openTabsMenu = (protyle: IProtyle, tabs: HTMLElement, item: HTMLEleblock.setAttribute("updated", id.substring(0, 14));});remapTabsDOMIDs(copy, ids);+ remapListMindmapIDs(copy, ids);changeTabs(protyle, [tabs], () => {item.after(copy);tabs.setAttribute("tabs-active-id", copy.dataset.nodeId);diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 7df2185bb2..2172ad7c52 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -74,6 +74,7 @@ import {} from "./blockSelection";import {isEmptyParagraph} from "./emptyTextBlock";import {cleanTableCellRichHTML, retainTableCellRichMetadata} from "../util/tableCellRich";+import {cleanListMindmapHTML} from "../render/listMindmap/model";import {completeTabsListSource, convertTabsList, isTabsListConversion} from "./tabsList";import {waitForPendingTransactions} from "../util/transactionQueue";import {@@ -86,7 +87,7 @@ const cleanBlockSelectionModeOperations = (operations?: IOperation[]) => {operations?.forEach(operation => {if (["appendInsert", "insert", "prependInsert", "update"].includes(operation.action) &&typeof operation.data === "string") {- operation.data = cleanTableCellRichHTML(cleanBlockSelectionModeHTML(operation.data));+ operation.data = cleanListMindmapHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(operation.data)));}if (operation.action === "unfoldHeading" && typeof operation.retData === "string") {operation.retData = cleanBlockSelectionModeHTML(operation.retData);@@ -2481,8 +2482,8 @@ export const updateTransaction = (protyle: IProtyle, element: Element, oldHTML:refreshSbResize(element);}const id = element.getAttribute("data-node-id");- const newHTML = cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(element.outerHTML)));- const cleanOldHTML = cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(oldHTML)));+ const newHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(element.outerHTML))));+ const cleanOldHTML = cleanListMindmapHTML(cleanHeadingNumberHTML(cleanTableCellRichHTML(cleanBlockSelectionModeHTML(oldHTML))));if (newHTML === cleanOldHTML.replace("<wbr>", "") && !additionalOperations) {return;}diff --git a/app/src/protyle/wysiwyg/transactionAV.test.ts b/app/src/protyle/wysiwyg/transactionAV.test.tsindex 9aa6250a4c..fce2753c9f 100644--- a/app/src/protyle/wysiwyg/transactionAV.test.ts+++ b/app/src/protyle/wysiwyg/transactionAV.test.ts@@ -27,6 +27,7 @@ const fixture = () => {({doOperations, undoOperations}),cleanBlockSelectionModeHTML: (html: string) => html,cleanTableCellRichHTML: (html: string) => html,+ cleanListMindmapHTML: (html: string) => html,normalizeHTMLAssetIFrameBlockDOM: (html: string) => html,cleanHeadingNumberOperations: (): void => undefined,needSubscribe: () => true,diff --git a/docs/LIST-MINDMAP.md b/docs/LIST-MINDMAP.mdnew file mode 100644index 0000000000..ac5489bdce--- /dev/null+++ b/docs/LIST-MINDMAP.md@@ -0,0 +1,36 @@+# 列表脑图++列表脑图是列表块的另一种视图,入口位于列表块菜单 - 切换为脑图视图。列表项菜单不提供这个入口。已有的 `mindmap` 代码块继续使用原有渲染方式。++## 交互++- 按住节点拖动,调整同级顺序或父子层级;目标节点上部、中心、下部分别表示放在前面、作为子节点、放在后面,松手后自动布局+- 双击节点正文才创建轻量 Protyle,直接在原节点内编辑;文字选择和输入由编辑器接管+- 编辑能力复用数据库文本字段的轻量 Protyle,同时保留既有图片;不支持编辑的复杂正文保留原数据,可切回列表编辑+- 点击编辑器外部或按 Esc 结束编辑,保存前等待 Protyle 完成待处理输入;候选菜单和格式菜单优先处理 Esc+- 鼠标移入节点时,右侧显示添加子节点的加号;点击后自动展开父节点,并直接进入新节点编辑+- 节点文字位于分支线条上方,线条延伸到节点末端;展开状态下悬停节点显示折叠按钮,折叠后常驻显示隐藏节点数量;空节点以浅色显示“输入文字”,提示不写入正文+- 使用节点旁的按钮添加子节点或折叠,选中节点后按 Delete 或 Backspace 删除(兼容 macOS 的 Delete 键);最后一个根节点保留,避免产生不能保存的空列表;撤销和重做保留编辑器快捷键,工具栏不再显示对应按钮+- 点击画布空白处或脑图外部取消选中,收起节点样式及关系线设置;点击节点继续选择关系线终点,点击其他区域取消连线+- 连接按钮使用带箭头的弯曲连线图标,位于缩小按钮前;先选择起点,再选择终点,可编辑文字、颜色或删除关系线;路径通过正交可视网格上的 A* 搜索避开节点和折叠、添加按钮区域,减少转弯并绘制圆角,布局变化时重新计算,平移和缩放时复用路径+- 节点默认无背景、不显示边框,正文格式通过节点内的 Protyle 编辑;选中节点后,脑图面板底部显示单排配色工具栏,仅展示节点配色及颜色管理入口,复用外观面板中的文字色与背景色组合,包含内置及自定义颜色并遵循其顺序和可见性,可恢复默认色;点击树连线或关系线,在脑图面板底部显示对应的设置菜单,线条颜色复用外观背景色,菜单不显示标题栏、虚线及宽度控件;双击关系线文字,在原位置显示输入框进行编辑+- 滚轮或触控板滚动用于移动画布,工具栏提供缩放、适应画布和全屏;全屏沿用编辑器的窗口内全屏及窗口控件避让,点击全屏按钮或按 Esc 退出并回到原列表位置+- 本次不包含概要和自由摆放节点++## 数据与兼容性++正文仍存放在原列表和原列表项中,搜索、块引用和反链继续使用原块 ID。单个顶层列表项直接作为根节点;多个顶层项使用只读的虚拟中心节点,它不新增实际块。++列表块使用 `custom-list-mindmap="1"` 启用脑图视图。`custom-list-mindmap-data` 保存版本为 `1` 的节点样式和关系线配置。关闭脑图视图保留该配置;折叠使用列表项的已有 `fold` 属性。未知版本或损坏的配置不会被自动覆盖,原列表仍可查看。++修改前补齐折叠隐藏的列表内容。结构、正文和配置修改通过已有文档事务保存,并进入文档撤销记录。复制列表时,样式所关联的节点 ID 和关系线的端点随复制后的块 ID 一起更新。++节点内容编辑保留原正文块的身份和属性,以及穿插在正文之间的子列表。编辑器中新建的列表在结束该次编辑时转换为实际子节点。外部更新导致编辑目标失效时,不覆盖较新的正文,并显示尚未保存的内容供恢复。++脑图 DOM、画布、全屏占位和编辑器均为派生显示内容,不写入列表事务或剪贴板的思源块数据。此功能沿用现有块存储、加密、历史和备份格式。++## 导出与验证++思源格式的 HTML 和 PDF 预览沿用 `Protyle.mindmapRender` 加载列表脑图,资源均来自本地。Markdown、Markdown 格式的 HTML 和 Word 保留列表形式。++从 `app/` 运行 `pnpm run lint`。列表模型、真实 DOM 与 Lute、编辑生命周期、导出和菜单配置的回归测试位于 `src/protyle/render/listMindmap/`、`src/protyle/export/listMindmapExport.test.ts` 和 `src/config/entryVisibility/`。真实浏览器测试使用独立 Electron 实例,不启动或重启思源内核;没有图形显示环境的 Linux 会跳过浏览器部分。