An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lipstick: Align mind map node and line color palettes https://github.com/siyuan-note/siyuan/issues/20856
Daniel5740e3114238
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 69cf2e928f..e03c98b6b8 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "إدارة ألوان العقد",+ "listMindmapManageLineColors": "إدارة ألوان الخطوط","listMindmapDocumentLayout": "تخطيط المستند","fullCheckSnapshot": "فحص المحتوى بالكامل","fullCheckSnapshotTip": "قراءة جميع الملفات المحلية لاكتشاف تغييرات المحتوى حتى مع ثبات الحجم ووقت التعديل، وإنشاء لقطة عند الحاجة؛ لن تُنزّل الموارد لهذا الفحص، وقد تستغرق مساحات العمل الكبيرة وقتًا أطول",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex e3d1d7ff00..4c5e7312a4 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Knotenfarben verwalten",+ "listMindmapManageLineColors": "Linienfarben verwalten","listMindmapDocumentLayout": "Dokumentlayout","fullCheckSnapshot": "Vollständige Inhaltsprüfung","fullCheckSnapshotTip": "Alle lokalen Dateien lesen, um Inhaltsänderungen auch bei unveränderter Größe und Änderungszeit zu erkennen und bei Bedarf einen Schnappschuss zu erstellen; Ressourcen werden dafür nicht heruntergeladen, große Arbeitsbereiche können mehr Zeit benötigen",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 4066980482..858249b0bb 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Manage node colors",+ "listMindmapManageLineColors": "Manage line colors","listMindmapDocumentLayout": "Document layout","fullCheckSnapshot": "Full content check","fullCheckSnapshotTip": "Read all local files to detect content changes even when size and modification time are unchanged, and create a snapshot if needed; resources are not downloaded for this check, and large workspaces may take longer",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 1aa8c13aff..8241aab3a1 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Gestionar colores de nodos",+ "listMindmapManageLineColors": "Gestionar colores de líneas","listMindmapDocumentLayout": "Diseño del documento","fullCheckSnapshot": "Comprobación completa del contenido","fullCheckSnapshotTip": "Leer todos los archivos locales para detectar cambios de contenido aunque no cambien el tamaño ni la fecha de modificación, y crear una instantánea si es necesario; no se descargan recursos para esta comprobación y los espacios de trabajo grandes pueden tardar más",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex a3cff138ed..f4237b3e55 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Gérer les couleurs des nœuds",+ "listMindmapManageLineColors": "Gérer les couleurs des lignes","listMindmapDocumentLayout": "Disposition du document","fullCheckSnapshot": "Vérification complète du contenu","fullCheckSnapshotTip": "Lire tous les fichiers locaux pour détecter les changements de contenu même si leur taille et leur date de modification restent identiques, puis créer un instantané si nécessaire ; aucune ressource n’est téléchargée pour cette vérification et les grands espaces de travail peuvent demander plus de temps",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 1c21a08e2d..1783d65f76 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "ניהול צבעי צמתים",+ "listMindmapManageLineColors": "ניהול צבעי קווים","listMindmapDocumentLayout": "פריסת המסמך","fullCheckSnapshot": "בדיקת תוכן מלאה","fullCheckSnapshotTip": "קריאת כל הקבצים המקומיים לזיהוי שינויי תוכן גם כשהגודל וזמן השינוי נשארו זהים, ויצירת תמונת מצב לפי הצורך; משאבים לא יורדו לצורך הבדיקה, וסביבות עבודה גדולות עשויות לדרוש זמן רב יותר",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex fddd1e7064..9a38f7cca7 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "नोड के रंग प्रबंधित करें",+ "listMindmapManageLineColors": "रेखाओं के रंग प्रबंधित करें","listMindmapDocumentLayout": "दस्तावेज़ का लेआउट","fullCheckSnapshot": "सामग्री की पूरी जाँच","fullCheckSnapshotTip": "आकार और संशोधन समय समान रहने पर भी सामग्री में बदलाव खोजने के लिए सभी स्थानीय फ़ाइलें पढ़ें और ज़रूरत होने पर स्नैपशॉट बनाएँ; इस जाँच के लिए संसाधन डाउनलोड नहीं होंगे और बड़े कार्यक्षेत्रों में अधिक समय लग सकता है",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 73e4b55657..8f36d8dacc 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Kelola warna simpul",+ "listMindmapManageLineColors": "Kelola warna garis","listMindmapDocumentLayout": "Tata letak dokumen","fullCheckSnapshot": "Pemeriksaan isi menyeluruh","fullCheckSnapshotTip": "Baca semua berkas lokal untuk mendeteksi perubahan isi meskipun ukuran dan waktu modifikasi tetap sama, lalu buat snapshot jika diperlukan; sumber daya tidak diunduh untuk pemeriksaan ini dan ruang kerja besar dapat memerlukan waktu lebih lama",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 624bcb03c1..b9a483868e 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Gestisci i colori dei nodi",+ "listMindmapManageLineColors": "Gestisci i colori delle linee","listMindmapDocumentLayout": "Layout del documento","fullCheckSnapshot": "Verifica completa del contenuto","fullCheckSnapshotTip": "Legge tutti i file locali per rilevare modifiche al contenuto anche se dimensioni e data di modifica restano invariate, creando un’istantanea se necessario; non vengono scaricate risorse per questa verifica e gli spazi di lavoro grandi possono richiedere più tempo",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 37787165ac..a387e9b6e3 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "ノードの色を管理",+ "listMindmapManageLineColors": "線の色を管理","listMindmapDocumentLayout": "ドキュメントのレイアウト","fullCheckSnapshot": "内容の完全チェック","fullCheckSnapshotTip": "ローカルの全ファイルを読み取り、サイズと更新日時が変わらない内容の変更も検出し、必要ならスナップショットを作成します。チェックのためのリソースのダウンロードは行わず、大きなワークスペースでは時間がかかる場合があります",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 5930a94319..c639f5c7d5 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "노드 색상 관리",+ "listMindmapManageLineColors": "선 색상 관리","listMindmapDocumentLayout": "문서 레이아웃","fullCheckSnapshot": "전체 내용 검사","fullCheckSnapshotTip": "모든 로컬 파일을 읽어 크기와 수정 시간이 같아도 내용 변경을 감지하고 필요하면 스냅샷을 만듭니다. 검사를 위해 리소스를 다운로드하지 않으며 큰 작업 공간에서는 시간이 더 걸릴 수 있습니다",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex d4d956cfef..44e4e9f476 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Knoopkleuren beheren",+ "listMindmapManageLineColors": "Lijnkleuren beheren","listMindmapDocumentLayout": "Documentindeling","fullCheckSnapshot": "Volledige inhoudscontrole","fullCheckSnapshotTip": "Lees alle lokale bestanden om inhoudswijzigingen te vinden, ook als grootte en wijzigingstijd gelijk blijven, en maak zo nodig een momentopname; bronnen worden hiervoor niet gedownload en grote werkruimten kunnen meer tijd kosten",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 3894f2201d..a05f51ee13 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Zarządzaj kolorami węzłów",+ "listMindmapManageLineColors": "Zarządzaj kolorami linii","listMindmapDocumentLayout": "Układ dokumentu","fullCheckSnapshot": "Pełna kontrola zawartości","fullCheckSnapshotTip": "Odczytaj wszystkie pliki lokalne, aby wykryć zmiany zawartości mimo niezmienionego rozmiaru i czasu modyfikacji, i w razie potrzeby utwórz migawkę; zasoby nie są pobierane na potrzeby tej kontroli, a duże obszary robocze mogą wymagać więcej czasu",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 7f56b29a33..28316c267d 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Gerenciar cores dos nós",+ "listMindmapManageLineColors": "Gerenciar cores das linhas","listMindmapDocumentLayout": "Layout do documento","fullCheckSnapshot": "Verificação completa do conteúdo","fullCheckSnapshotTip": "Ler todos os arquivos locais para detectar alterações no conteúdo mesmo com tamanho e data de modificação inalterados, e criar um instantâneo se necessário; recursos não são baixados para esta verificação e espaços de trabalho grandes podem demorar mais",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 3c5b1aa6ba..f71a406179 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Управление цветами узлов",+ "listMindmapManageLineColors": "Управление цветами линий","listMindmapDocumentLayout": "Макет документа","fullCheckSnapshot": "Полная проверка содержимого","fullCheckSnapshotTip": "Прочитать все локальные файлы, чтобы найти изменения содержимого даже при неизменных размере и времени изменения, и при необходимости создать снимок; ресурсы для проверки не загружаются, а большие рабочие пространства могут потребовать больше времени",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex fd8d5703cd..889054427a 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Spravovať farby uzlov",+ "listMindmapManageLineColors": "Spravovať farby čiar","listMindmapDocumentLayout": "Rozloženie dokumentu","fullCheckSnapshot": "Úplná kontrola obsahu","fullCheckSnapshotTip": "Prečítať všetky lokálne súbory na zistenie zmien obsahu aj pri nezmenenej veľkosti a čase úpravy a podľa potreby vytvoriť snímku; zdroje sa na túto kontrolu nesťahujú a veľké pracovné priestory môžu vyžadovať viac času",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 01bed930d1..84d837075a 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Управљај бојама чворова",+ "listMindmapManageLineColors": "Управљај бојама линија","listMindmapDocumentLayout": "Распоред документа","fullCheckSnapshot": "Потпуна провера садржаја","fullCheckSnapshotTip": "Прочитајте све локалне датотеке да бисте открили промене садржаја и када су величина и време измене исти и по потреби направите снимак; ресурси се не преузимају ради ове провере, а велики радни простори могу захтевати више времена",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 8d4731c38d..0bc2e170d4 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "จัดการสีโหนด",+ "listMindmapManageLineColors": "จัดการสีเส้น","listMindmapDocumentLayout": "เค้าโครงเอกสาร","fullCheckSnapshot": "ตรวจสอบเนื้อหาทั้งหมด","fullCheckSnapshotTip": "อ่านไฟล์ภายในเครื่องทั้งหมดเพื่อตรวจหาการเปลี่ยนแปลงของเนื้อหา แม้ขนาดและเวลาแก้ไขจะเท่าเดิม และสร้างสแนปช็อตเมื่อจำเป็น โดยจะไม่ดาวน์โหลดทรัพยากรเพื่อการตรวจสอบนี้ และพื้นที่ทำงานขนาดใหญ่อาจใช้เวลานานขึ้น",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex ec9b86967b..b9452bf44e 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Düğüm renklerini yönet",+ "listMindmapManageLineColors": "Çizgi renklerini yönet","listMindmapDocumentLayout": "Belge düzeni","fullCheckSnapshot": "Tam içerik denetimi","fullCheckSnapshotTip": "Boyut ve değiştirilme zamanı aynı kalsa bile içerik değişikliklerini bulmak için tüm yerel dosyaları okuyun ve gerekirse anlık görüntü oluşturun; bu denetim için kaynaklar indirilmez ve büyük çalışma alanlarında daha uzun sürebilir",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex fc2f9d0963..e683e4e5a8 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "Керувати кольорами вузлів",+ "listMindmapManageLineColors": "Керувати кольорами ліній","listMindmapDocumentLayout": "Макет документа","fullCheckSnapshot": "Повна перевірка вмісту","fullCheckSnapshotTip": "Прочитати всі локальні файли, щоб виявити зміни вмісту навіть за незмінних розміру та часу зміни, і за потреби створити знімок; ресурси для перевірки не завантажуються, а великі робочі простори можуть потребувати більше часу",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex b2c575997e..076623c554 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "管理节点配色",+ "listMindmapManageLineColors": "管理连线颜色","listMindmapDocumentLayout": "文档布局","fullCheckSnapshot": "完整校验","fullCheckSnapshotTip": "读取所有本地文件,检查大小和修改时间未变的内容变化,必要时创建快照;不会为校验主动下载资源,大型工作空间可能耗时较长",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 07f369016f..304459d6eb 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "listMindmapManageNodeColors": "管理節點配色",+ "listMindmapManageLineColors": "管理連線顏色","listMindmapDocumentLayout": "文件版面配置","fullCheckSnapshot": "完整校驗","fullCheckSnapshotTip": "讀取所有本機檔案,檢查大小與修改時間未變的內容變更,必要時建立快照;不會為校驗主動下載資源,大型工作空間可能耗時較長",diff --git a/app/src/assets/scss/protyle/_mindmap-view.scss b/app/src/assets/scss/protyle/_mindmap-view.scssindex 754ac354b2..8ad883c186 100644--- a/app/src/assets/scss/protyle/_mindmap-view.scss+++ b/app/src/assets/scss/protyle/_mindmap-view.scss@@ -955,6 +955,21 @@pointer-events: none;}+ &__palette-row {+ display: flex;+ align-items: flex-start;+ min-width: 0;++ .mindmap-view__palette {+ flex: 1;+ order: 0;+ }++ > .color__square {+ flex-shrink: 0;+ }+ }+&__palette {display: flex;flex-wrap: nowrap;diff --git a/app/src/protyle/render/listMindmap/colors.test.ts b/app/src/protyle/render/listMindmap/colors.test.tsnew file mode 100644index 0000000000..563cbc1bc1--- /dev/null+++ b/app/src/protyle/render/listMindmap/colors.test.ts@@ -0,0 +1,105 @@+import * as assert from "node:assert/strict";+import test from "node:test";+import {readFileSync} from "node:fs";+import {runInNewContext} from "node:vm";+import {createSourceFile, isPropertyAssignment, ScriptTarget, transpileModule} from "typescript";+import {getListMindmapLineColors, getListMindmapNodeColors, getListMindmapNodeColorMenu} from "./colors";+import {normalizeInlineStyles} from "../../toolbar/inlineStyle";++const labels = {color: "Color", errorStyle: "Error", warningStyle: "Warning", infoStyle: "Info", successStyle: "Success",+ listMindmapNodeColor: "Node color", colorFont: "Font color", colorPrimary: "Background color"};++test("default node and line palettes have thirteen colors and retain existing semantic pairs", () => {+ const data = normalizeInlineStyles({});+ const before = JSON.stringify(data);+ for (const mode of ["light", "dark"] as const) {+ const nodes = getListMindmapNodeColors(data, labels, mode);+ const lines = getListMindmapLineColors(data, labels, mode);+ assert.equal(nodes.length, 13);+ assert.equal(lines.length, 13);+ assert.deepEqual(nodes.slice(0, 4).map(item => [item.color, item.backgroundColor]),+ ["error", "warning", "info", "success"].map(id => [`var(--b3-card-${id}-color)`, `var(--b3-card-${id}-background)`]));+ assert.deepEqual(nodes.slice(4).map(item => [item.color, item.backgroundColor]),+ Array.from({length: 9}, (_, i) => [`var(--b3-font-color${i + 5})`, `var(--b3-font-background${i + 5})`]));+ assert.deepEqual(lines.map(item => item.value), Array.from({length: 13}, (_, i) => `var(--b3-font-color${i + 1})`));+ }+ assert.equal(JSON.stringify(data), before, "reading palettes does not migrate or overwrite workspace colors");+});++test("workspace custom colors, hidden entries, ordering and light/dark values remain effective", () => {+ const combinedID = "20260821120000-abcdefg";+ const hiddenID = "20260821120000-bcdefgh";+ const lineID = "20260821120000-cdefghi";+ const data = normalizeInlineStyles({version: 2,+ styles: [+ {id: combinedID, name: "Custom pair", light: {color: "#112233", backgroundColor: "#ddeeff"},+ dark: {color: "#abcdef", backgroundColor: "#223344"}},+ {id: hiddenID, name: "Hidden pair", hidden: true, light: {color: "#112233", backgroundColor: "#ddeeff"},+ dark: {color: "#abcdef", backgroundColor: "#223344"}},+ {id: lineID, name: "Custom line", light: {color: "#123456"}, dark: {color: "#fedcba"}},+ ],+ builtin: {hidden: {style1: ["warning"], color: [2], backgroundColor: [6]},+ styles: [{id: "info", light: {color: "#112233", backgroundColor: "#ddeeff"},+ dark: {color: "#abcdef", backgroundColor: "#223344"}}]},+ order: {style1: [combinedID, "success", "info", "warning", "error", hiddenID],+ backgroundColor: ["13", "6", "5"], color: [lineID, "13", "2", "1"]},+ });+ const before = JSON.stringify(data);+ for (const mode of ["light", "dark"] as const) {+ const nodes = getListMindmapNodeColors(data, labels, mode);+ assert.deepEqual(nodes.slice(0, 4).map(item => item.label), ["Custom pair", "Success", "Info", "Error"]);+ assert.equal(nodes.some(item => item.label === "Hidden pair" || item.label === "Warning"), false);+ assert.deepEqual(nodes.slice(4, 6).map(item => item.label), ["Color 13", "Color 5"]);+ assert.equal(nodes.some(item => item.backgroundColor === "var(--b3-font-background6)"), false);+ assert.deepEqual(nodes[2].preview, mode === "light" ?+ {color: "#112233", backgroundColor: "#ddeeff"} : {color: "#abcdef", backgroundColor: "#223344"});+ assert.match(nodes[0].color, new RegExp(mode === "light" ? "#112233" : "#abcdef"));+ const lines = getListMindmapLineColors(data, labels, mode);+ assert.deepEqual(lines.slice(0, 3).map(item => item.label), ["Custom line", "Color 13", "Color 1"]);+ assert.match(lines[0].value, new RegExp(mode === "light" ? "#123456" : "#fedcba"));+ assert.equal(lines.some(item => item.value === "var(--b3-font-color2)"), false);+ }+ assert.equal(JSON.stringify(data), before);+});++test("desktop and mobile node settings open all three existing color managers from the palette anchor", () => {+ const source = createSourceFile("index.ts", readFileSync("src/protyle/render/listMindmap/index.ts", "utf8"),+ ScriptTarget.ES2021, true);+ let callback = "";+ const visit = (node: import("typescript").Node) => {+ if (isPropertyAssignment(node) && node.name.getText(source) === "onManageNodeColors") {+ callback = node.initializer.getText(source);+ }+ node.forEachChild(visit);+ };+ visit(source);+ assert.ok(callback);+ const compiled = transpileModule(`globalThis.openSettings = ${callback};`,+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;+ for (const mobile of [false, true]) {+ const selected: string[] = [];+ const entries: IMenu[] = [];+ const placements: unknown[] = [];+ const anchor = {getBoundingClientRect: () => ({left: 20, bottom: 100, height: 26})};+ const context: any = {+ getListMindmapNodeColorMenu, isMobile: () => mobile, window: {siyuan: {languages: labels}},+ openInlineStyleDialog: (type: string) => selected.push(type),+ toggleMenu: ({target, build}: {target: unknown, build: (menu: unknown, session: unknown) => void}) => {+ assert.equal(target, anchor, "the shared menu owner is the fixed settings button");+ build(undefined, {show: (open: () => void) => open()});+ },+ Menu: class {+ addItem(item: IMenu) { entries.push(item); }+ open(position: unknown) { placements.push(position); }+ fullscreen(position: unknown) { placements.push(position); }+ },+ };+ runInNewContext(compiled, context);+ context.openSettings(anchor);+ assert.deepEqual(JSON.parse(JSON.stringify(placements)), [mobile ? "bottom" : {x: 20, y: 100, h: 26}]);+ assert.equal(selected.length, 0, "opening the menu does not open a dialog or change colors");+ assert.deepEqual(entries.map(item => item.label), ["Node color", "Font color", "Background color"]);+ entries.forEach(item => item.click(undefined, undefined));+ assert.deepEqual(selected, ["style1", "color", "backgroundColor"]);+ }+});diff --git a/app/src/protyle/render/listMindmap/colors.ts b/app/src/protyle/render/listMindmap/colors.tsnew file mode 100644index 0000000000..5a5e78bba5--- /dev/null+++ b/app/src/protyle/render/listMindmap/colors.ts@@ -0,0 +1,44 @@+import {+ BUILTIN_INLINE_STYLE_IDS, getBuiltinColorPropertyValue, getBuiltinInlineStylePreview,+ getBuiltinInlineStylePropertyValue, getInlineStyleByID, getInlineStylePreview, getInlineStylePropertyValue,+ getVisibleOrderedStyleKeys, isBuiltinOrderKey,+} from "../../toolbar/inlineStyle";+import type {IInlineStyles, TBuiltinInlineStyleID, TInlineStyleMode, TInlineStyleType} from "../../toolbar/inlineStyle";++export const getListMindmapLineColors = (data: IInlineStyles, labels: Record<string, string>, mode: TInlineStyleMode) =>+ getVisibleOrderedStyleKeys("color", data).map(key => {+ if (isBuiltinOrderKey("color", key)) {+ return {label: `${labels.color} ${key}`, value: getBuiltinColorPropertyValue(Number(key), "color")};+ }+ const style = getInlineStyleByID(key, data);+ return {label: style.name, value: getInlineStylePropertyValue(style, "color", mode)};+ });++export const getListMindmapNodeColors = (data: IInlineStyles, labels: Record<string, string>, mode: TInlineStyleMode): {+ label: string, color: string, backgroundColor: string, preview?: {color: string, backgroundColor: string},+}[] => {+ const combined = getVisibleOrderedStyleKeys("style1", data).map(key => {+ if (isBuiltinOrderKey("style1", key)) {+ const id = key as TBuiltinInlineStyleID;+ return {label: labels[`${key}Style`],+ color: getBuiltinInlineStylePropertyValue(id, "color"),+ backgroundColor: getBuiltinInlineStylePropertyValue(id, "backgroundColor"),+ preview: getBuiltinInlineStylePreview(id, mode, data)};+ }+ const style = getInlineStyleByID(key, data);+ return {label: style.name, ...getInlineStylePreview(style, mode)};+ });+ // The first four font colors already have semantic combined styles. Complete the+ // remaining pairs without changing their variables or the workspace configuration.+ const remaining = getVisibleOrderedStyleKeys("backgroundColor", data)+ .filter(key => isBuiltinOrderKey("backgroundColor", key) && Number(key) > BUILTIN_INLINE_STYLE_IDS.length)+ .map(key => ({label: `${labels.color} ${key}`,+ color: getBuiltinColorPropertyValue(Number(key), "color"),+ backgroundColor: getBuiltinColorPropertyValue(Number(key), "backgroundColor")}));+ return [...combined, ...remaining];+};++export const getListMindmapNodeColorMenu = (labels: Record<string, string>, select: (type: TInlineStyleType) => void): IMenu[] =>+ [{label: labels.listMindmapNodeColor, icon: "iconTheme", click: () => select("style1")},+ {label: labels.colorFont, icon: "iconFont", click: () => select("color")},+ {label: labels.colorPrimary, icon: "iconTheme", click: () => select("backgroundColor")}];diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.tsindex e80f4dbe43..b2dd943691 100644--- a/app/src/protyle/render/listMindmap/index.ts+++ b/app/src/protyle/render/listMindmap/index.ts@@ -21,12 +21,7 @@ import {previewDocImage} from "../../preview/image";import {suspendBlockPopover} from "../../../block/popover";import {matchHotKey} from "../../util/hotKey";import {setFullscreen} from "../../breadcrumb/action";-import {- getBuiltinColorPropertyValue, getBuiltinInlineStylePreview, getBuiltinInlineStylePropertyValue,- getInlineStyleByID, getInlineStylePreview, getInlineStylePropertyValue,- getInlineStylesCache, getVisibleOrderedStyleKeys, isBuiltinOrderKey,- TBuiltinInlineStyleID,-} from "../../toolbar/inlineStyle";+import {getCurrentInlineStyleMode, getInlineStylesCache} from "../../toolbar/inlineStyle";import {openInlineStyleDialog} from "../../toolbar/inlineStyleDialog";import {addListMindmapNode, cleanListMindmapHTML, deleteListMindmapNode,@@ -41,6 +36,7 @@ import {syncListMindmapHeight} from "./height";import {bindListMindmapResize} from "./resize";import {setBlockHeight} from "../../gutter/height";import {ListMindmapView} from "./view";+import {getListMindmapLineColors, getListMindmapNodeColors, getListMindmapNodeColorMenu} from "./colors";import {openListMindmapEditor} from "./editor";import {focusListMindmap} from "./create";import {getListMindmapFoldStates, getListMindmapSiblingFoldStates} from "./fold";@@ -373,32 +369,19 @@ class ListMindmapController {restoreFullscreenChrome = undefined;}},- colors: () => {- const type = "color";- 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`],- color: getBuiltinInlineStylePropertyValue(key as TBuiltinInlineStyleID, "color"),- backgroundColor: getBuiltinInlineStylePropertyValue(key as TBuiltinInlineStyleID, "backgroundColor"),- preview: getBuiltinInlineStylePreview(key as TBuiltinInlineStyleID)};- }- const style = getInlineStyleByID(key, data);- return {label: style.name, ...getInlineStylePreview(style)};- });- },- onManageNodeColors: () => openInlineStyleDialog("style1"),+ colors: () => getListMindmapLineColors(getInlineStylesCache(), window.siyuan.languages, getCurrentInlineStyleMode()),+ nodeColors: () => getListMindmapNodeColors(getInlineStylesCache(), window.siyuan.languages, getCurrentInlineStyleMode()),+ onManageNodeColors: anchor => toggleMenu({target: anchor, build: (_menu, session) => {+ const menu = new Menu();+ getListMindmapNodeColorMenu(window.siyuan.languages, type => openInlineStyleDialog(type))+ .forEach(item => menu.addItem(item));+ if (isMobile()) {+ session.show(() => menu.fullscreen("bottom"));+ } else {+ const rect = anchor.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height}));+ }+ }}),onManageLineColors: () => openInlineStyleDialog("color"),finishEdit: () => this.activeEditor?.finish(),onExit: async () => {diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.tsindex 3395a682a4..42e6862b4f 100644--- a/app/src/protyle/render/listMindmap/model.test.ts+++ b/app/src/protyle/render/listMindmap/model.test.ts@@ -1203,6 +1203,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,let undo = 0;let redo = 0;let settingsOpened = 0;+ const colorSettings: {kind: string, anchor?: HTMLButtonElement}[] = [];let overflowExpand: ((level: number | "expandAll" | "foldAll") => void) | undefined;let panMenu: {active: boolean, toggle: () => void};let finishAllowed: boolean | Promise<boolean> = true;@@ -1212,6 +1213,8 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,colors: () => [{label: "Appearance background", value: "var(--b3-font-background1)"}],nodeColors: () => [{label: "Appearance combined", color: "var(--b3-font-color1)",backgroundColor: "var(--b3-font-background1)", preview: {color: "#112233", backgroundColor: "#ddeeff"}}],+ onManageNodeColors: (anchor: HTMLButtonElement) => colorSettings.push({kind: "node", anchor}),+ onManageLineColors: () => colorSettings.push({kind: "line"}),onFullscreen: (enter: boolean) => fullscreenChanges.push(enter),onInteractionStart: () => {interactions++;@@ -2225,12 +2228,24 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,const popup = host.querySelector<HTMLElement>(".mindmap-view__inspector-popover");const palettes = popup.querySelectorAll<HTMLElement>(".mindmap-view__palette");check.equal(palettes.length, 2);- check.equal(palettes[0].previousElementSibling.textContent, "listMindmapNodeColor");- check.equal(palettes[1].previousElementSibling.textContent, "listMindmapLineColor");+ check.equal(palettes[0].getAttribute("aria-label"), "listMindmapNodeColor");+ check.equal(palettes[1].getAttribute("aria-label"), "listMindmapLineColor");+ check.equal(popup.children.length, 2, "the popup has only two compact rows without visible headings");+ const managers = ["listMindmapManageNodeColors", "listMindmapManageLineColors"]+ .map(key => popup.querySelector<HTMLButtonElement>(`[aria-label="${key}"]`));+ check.deepEqual(managers.map(control => control.querySelector("use").getAttribute("xlink:href")),+ ["#iconFont", "#iconLine"], "distinct icons identify the two settings controls");+ check.equal(managers[0].getBoundingClientRect().right, managers[1].getBoundingClientRect().right,+ "settings stay in one fixed right-hand column with unequal custom palette sizes");+ check.ok(palettes[1].getBoundingClientRect().top >= palettes[0].getBoundingClientRect().bottom,+ "node colors are visually above line colors");+ const rowsHeight = Array.from(popup.children).reduce((height, row) => height + row.getBoundingClientRect().height, 0);+ check.ok(popup.offsetHeight <= Math.ceil(rowsHeight + 20),+ "the popup contains only the two rows, padding and their gap, including native scrollbars");for (const palette of palettes) {const buttons = Array.from(palette.children) as HTMLElement[];check.equal(new Set(buttons.map(button => button.offsetTop)).size, 1, "each palette keeps one row");- check.ok(palette.getBoundingClientRect().right <= popup.getBoundingClientRect().right);+ check.ok(palette.getBoundingClientRect().right <= palette.nextElementSibling.getBoundingClientRect().left);if (width < 760) {check.ok(palette.scrollWidth > palette.clientWidth, "narrow palettes scroll horizontally");}@@ -2239,9 +2254,46 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,check.equal(palettes[1].scrollWidth, palettes[1].clientWidth,"the normal line palette fits one row on a wide canvas");}+ const beforeSettings = nodeStyles.length;+ managers[0].focus();+ check.equal(host.querySelector('[role="tooltip"]').textContent, "listMindmapManageNodeColors");+ managers[0].click();+ managers[1].click();+ check.deepEqual(colorSettings.slice(-2), [{kind: "node", anchor: managers[0]}, {kind: "line"}]);+ check.equal(nodeStyles.length, beforeSettings, "opening settings does not apply colors");+ const managerLeft = managers[1].getBoundingClientRect().left;+ palettes[1].scrollLeft = palettes[1].scrollWidth;+ check.equal(managers[1].getBoundingClientRect().left, managerLeft, "scrolling colors never scrolls the settings button");palettes[1].querySelector<HTMLButtonElement>('[aria-label="Line 14"]').click();check.deepEqual(nodeStyles.at(-1), [view.getSelectedIds(), {lineColor: "rgb(14, 0, 0)"}]);}+ options.nodeColors = () => Array.from({length: 13}, (_, i) => ({label: `Color ${i}`, color: `rgb(${i}, 0, 0)`, backgroundColor: "",+ preview: {color: `rgb(${i}, 0, 0)`, backgroundColor: ""}}));+ options.colors = () => Array.from({length: 13}, (_, i) => ({label: `Line ${i}`, value: `rgb(${i}, 0, 0)`}));+ view.renderInspector();+ inspector.querySelector<HTMLButtonElement>('[aria-label="color"]').click();+ const equalPalettes = host.querySelectorAll<HTMLElement>(".mindmap-view__inspector-popover .mindmap-view__palette");+ check.equal(equalPalettes[0].children.length, 14, "default and thirteen color cells occupy each row");+ check.equal(equalPalettes[1].children.length, 14);+ Array.from(equalPalettes[0].children).forEach((control, i) => {+ const nodeCell = control.getBoundingClientRect();+ const lineCell = equalPalettes[1].children[i].getBoundingClientRect();+ check.equal(nodeCell.left, lineCell.left, "equal default palettes align every column");+ check.equal(nodeCell.width, lineCell.width);+ check.equal(nodeCell.height, lineCell.height);+ });+ host.focus();+ host.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true}));+ const paletteSelection = view.getSelectedIds();+ const touchColorPoint = centerPoint(inspector.querySelector('[aria-label="color"]'));+ await require("electron").ipcRenderer.invoke("mindmap-view-native-touch", [+ {type: "touchStart", touchPoints: [{id: 1, ...touchColorPoint}]},+ {type: "touchEnd", touchPoints: []},+ ]);+ await settle();+ check.equal(host.querySelector<HTMLElement>(".mindmap-view__inspector-popover").hidden, false,+ "a native touch tap opens the same compact two-row palette");+ check.deepEqual(view.getSelectedIds(), paletteSelection, "opening the palette by touch preserves the selected nodes");options.colors = originalLineColors;view.focusNode(beta);host.style.cssText = originalHostStyle;@@ -2331,7 +2383,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,view.focusNode(beta);inspector.querySelector<HTMLButtonElement>('[aria-label="color"]').click();check.equal(inspector.querySelectorAll('[role="group"]').length, 0, "palettes are kept out of the main bar");- const nodePalette = nodePopup.querySelector<HTMLElement>('[role="group"][aria-label="color"]');+ const nodePalette = nodePopup.querySelector<HTMLElement>('[role="group"][aria-label="listMindmapNodeColor"]');const nodeColorButton = nodePalette.querySelector<HTMLButtonElement>('[aria-label="Appearance combined"]');check.equal(nodeColorButton.textContent, "A");check.equal(nodeColorButton.classList.contains("color__square"), true);@@ -2349,7 +2401,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,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");- nodePopup.querySelector<HTMLButtonElement>('[aria-label="color"] [aria-label="default"]').click();+ nodePopup.querySelector<HTMLButtonElement>('[aria-label="listMindmapNodeColor"] [aria-label="default"]').click();check.deepEqual(nodeStyles[nodeStyles.length - 1], [beta, {textColor: "", backgroundColor: ""}]);model.metadata.nodes[beta].backgroundColor = "";model.metadata.nodes[beta].textColor = "";diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.tsindex 2dc3d54b27..e6143f18b9 100644--- a/app/src/protyle/render/listMindmap/view.ts+++ b/app/src/protyle/render/listMindmap/view.ts@@ -40,7 +40,7 @@ export interface ListMindmapViewOptions {label: string, color: string, backgroundColor: string,preview?: {color: string, backgroundColor: string},}[];- onManageNodeColors?: () => void;+ onManageNodeColors?: (anchor: HTMLButtonElement) => void;onManageLineColors?: () => void;onFullscreen?: (enter: boolean, button: HTMLButtonElement) => void;onInteractionStart?: (event: PointerEvent) => () => void;@@ -3705,7 +3705,7 @@ export class ListMindmapView {};const palette = createElement("div", "mindmap-view__palette");palette.setAttribute("role", "group");- palette.setAttribute("aria-label", this.label("color"));+ palette.setAttribute("aria-label", this.label("listMindmapNodeColor"));[{label: this.label("default"), color: "", backgroundColor: "", preview: undefined},...(this.options.nodeColors?.() || [])].forEach(item => {const selected = panel.ids.every(id => {@@ -3721,12 +3721,14 @@ export class ListMindmapView {control.style.backgroundColor = item.preview?.backgroundColor ?? item.backgroundColor;palette.append(control);});+ const row = createElement("div", "mindmap-view__palette-row");+ row.append(palette);if (this.options.onManageNodeColors) {- palette.append(button("manageColors", "iconSettings", this.options.onManageNodeColors));+ const manage = button("listMindmapManageNodeColors", "iconFont", () => this.options.onManageNodeColors(manage));+ manage.setAttribute("aria-haspopup", "menu");+ row.append(manage);}- const title = createElement("div", "ft__smaller ft__on-surface");- title.textContent = this.label("listMindmapNodeColor");- this.inspectorPopover.append(title, palette);+ this.inspectorPopover.append(row);if (panel.ids.length > 1) {const lines = createElement("div", "mindmap-view__palette");lines.setAttribute("role", "group");@@ -3737,12 +3739,12 @@ export class ListMindmapView {control.style.backgroundColor = item.value || "var(--b3-theme-background)";lines.append(control);});+ const lineRow = createElement("div", "mindmap-view__palette-row");+ lineRow.append(lines);if (this.options.onManageLineColors) {- lines.append(button("manageColors", "iconSettings", this.options.onManageLineColors));+ lineRow.append(button("listMindmapManageLineColors", "iconLine", this.options.onManageLineColors));}- const lineTitle = createElement("div", "ft__smaller ft__on-surface");- lineTitle.textContent = this.label("listMindmapLineColor");- this.inspectorPopover.append(lineTitle, lines);+ this.inspectorPopover.append(lineRow);}} else {const row = createElement("div", "mindmap-view__node-width");@@ -3839,7 +3841,7 @@ export class ListMindmapView {palette.append(button);});if (this.options.onManageLineColors) {- palette.append(squareButton("manageColors", "iconSettings", this.options.onManageLineColors));+ palette.append(squareButton("listMindmapManageLineColors", "iconLine", this.options.onManageLineColors));}this.inspector.append(palette);};