An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve mind map themes and fold transitions https://github.com/siyuan-note/siyuan/issues/20800
Daniela5c024756262
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.syindex a4113decac..1ff7b7c02f 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy@@ -8,7 +8,7 @@"title": "Formatting elements","title-img": "background-color:#269;background-image: linear-gradient(white 2px, transparent 2px),linear-gradient(90deg, white 2px, transparent 2px),linear-gradient(rgba(255,255,255,.3) 1px, transparent 1px),linear-gradient(90deg, rgba(255,255,255,.3) 1px, transparent 1px);background-size: 100px 100px, 100px 100px, 20px 20px, 20px 20px;background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;","type": "doc",- "updated": "20261024124505"+ "updated": "20261024134401"},"Children": [{@@ -2279,7 +2279,7 @@"Type": "NodeParagraph","Properties": {"id": "20261022102848-11epv5y",- "updated": "20261022122318"+ "updated": "20261024134401"},"Children": [{@@ -2311,7 +2311,7 @@},{"Type": "NodeText",- "Data": " to choose Colorful, Soft, Forest, Ocean, Sunset, Lavender, or Monochrome for the current map. First-level branches receive colors from the palette, and descendants inherit their branch color. Reordering branches preserves their assigned colors. New nodes follow the map's palette automatically. Manual node and line colors are retained. Choosing Default removes the palette while preserving manual colors and the canvas background. The theme does not change node content, structure, or folding states."+ "Data": " to choose Colorful, Soft, Forest, Ocean, Sunset, Lavender, or Monochrome for the current map. The theme uses transparent backgrounds and a consistent text color at every level. The root is larger, and the root and first-level branches use a stronger font weight. Colors distinguish branch lines, with a heavier main trunk and finer lines at deeper levels. Theme text and lines adapt to the canvas brightness. Reordering branches preserves their assigned colors. New nodes follow the map's palette automatically. Manual colors, font sizes, and font weights take precedence. Choosing Default removes the palette while preserving manual colors and the canvas background. Existing maps keep their saved colors; select the theme again to apply the new layered style. The theme does not change node content, structure, or folding states."}]},@@ -2402,7 +2402,7 @@"Type": "NodeParagraph","Properties": {"id": "20261003225941-mxlfdrn",- "updated": "20261003225941"+ "updated": "20261024133605"},"Children": [{@@ -2425,7 +2425,7 @@},{"Type": "NodeText",- "Data": " on macOS) and click a node's fold button to fold or expand sibling branches under the same parent. If any sibling branch is expanded, all are folded; otherwise, all are expanded. Deeper folding states are preserved. A normal click only toggles the current node."+ "Data": " on macOS) and click a node's fold button to fold or expand sibling branches under the same parent. If any sibling branch is expanded, all are folded; otherwise, all are expanded. Deeper folding states are preserved. A normal click only toggles the current node. Expansion and folding use a short transition for nodes and lines. The animation follows the system's reduced motion preference."}]},diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.syindex 21e5fb690e..e374f30b38 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy@@ -8,7 +8,7 @@"title": "排版元素","title-img": "background-color: hsl(2, 57%, 40%);background-image: repeating-linear-gradient(transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(270deg, transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(125deg, transparent, transparent 2px, rgba(0,0,0,.2) 2px, rgba(0,0,0,.2) 3px, transparent 3px, transparent 5px, rgba(0,0,0,.2) 5px);","type": "doc",- "updated": "20261024124505"+ "updated": "20261024134401"},"Children": [{@@ -2249,7 +2249,7 @@"Type": "NodeParagraph","Properties": {"id": "20261022102848-idam1p2",- "updated": "20261022122318"+ "updated": "20261024134401"},"Children": [{@@ -2281,7 +2281,7 @@},{"Type": "NodeText",- "Data": " 中为当前导图选择缤纷、柔和、森林、海洋、日落、薰衣草或黑白配色。一级分支按色卡分配颜色,后代节点继承所属分支的颜色;调整分支顺序会保留原有配色,新增节点自动跟随导图配色。已有的节点和线条手工配色会保留。选择默认可移除色卡,并保留手工配色和画布背景。主题不会改变节点内容、结构或折叠状态。"+ "Data": " 中为当前导图选择缤纷、柔和、森林、海洋、日落、薰衣草或黑白配色。主题为所有层级使用透明背景和统一的文字色。根节点字号更大,与一级分支一起采用较粗字重。分支连线按色卡配色,主干较粗,深层连线较细。主题文字和连线会适配画布明暗。调整分支顺序会保留原有配色,新增节点自动跟随导图配色。手工设置的颜色、字号和字重优先于主题。选择默认可移除色卡,并保留手工配色和画布背景。旧导图保留原有配色,重新选择主题后应用新的分层样式。主题不会改变节点内容、结构或折叠状态。"}]},@@ -2372,7 +2372,7 @@"Type": "NodeParagraph","Properties": {"id": "20261003225941-hge6x3e",- "updated": "20261003225941"+ "updated": "20261024133605"},"Children": [{@@ -2395,7 +2395,7 @@},{"Type": "NodeText",- "Data": ")并点击节点的折叠按钮,可统一折叠或展开同一父节点下的兄弟分支。只要还有兄弟分支展开,就统一折叠;全部折叠时,则统一展开。更深层节点的折叠状态保持不变。普通点击只切换当前节点。"+ "Data": ")并点击节点的折叠按钮,可统一折叠或展开同一父节点下的兄弟分支。只要还有兄弟分支展开,就统一折叠;全部折叠时,则统一展开。更深层节点的折叠状态保持不变。普通点击只切换当前节点。展开和折叠时,节点与连线会短暂过渡;系统开启减少动态效果时不播放动画。"}]},diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.syindex 61541f5459..738e95cdaa 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy@@ -8,7 +8,7 @@"title": "排版元素","title-img": "background-color: hsl(2, 57%, 40%);background-image: repeating-linear-gradient(transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(270deg, transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(125deg, transparent, transparent 2px, rgba(0,0,0,.2) 2px, rgba(0,0,0,.2) 3px, transparent 3px, transparent 5px, rgba(0,0,0,.2) 5px);","type": "doc",- "updated": "20261024124505"+ "updated": "20261024134401"},"Children": [{@@ -2247,7 +2247,7 @@"Type": "NodeParagraph","Properties": {"id": "20261022102848-dz75ii8",- "updated": "20261022122318"+ "updated": "20261024134401"},"Children": [{@@ -2279,7 +2279,7 @@},{"Type": "NodeText",- "Data": " 中為目前心智圖選擇繽紛、柔和、森林、海洋、日落、薰衣草或黑白配色。一級分支依色卡分配顏色,後代節點繼承所屬分支的顏色;調整分支順序會保留原有配色,新增節點自動跟隨心智圖配色。既有的節點和線條手動配色會保留。選擇預設可移除色卡,並保留手動配色和畫布背景。主題不會改變節點內容、結構或摺疊狀態。"+ "Data": " 中為目前心智圖選擇繽紛、柔和、森林、海洋、日落、薰衣草或黑白配色。主題為所有層級使用透明背景和統一的文字色。根節點字級較大,與一級分支一同採用較粗字重。分支連線依色卡配色,主幹較粗,深層連線較細。主題文字與連線會配合畫布明暗調整。調整分支順序會保留原有配色,新增節點自動跟隨心智圖配色。手動設定的顏色、字級和字重優先於主題。選擇預設可移除色卡,並保留手動配色和畫布背景。既有心智圖保留原有配色,重新選擇主題後套用新的分層樣式。主題不會改變節點內容、結構或摺疊狀態。"}]},@@ -2370,7 +2370,7 @@"Type": "NodeParagraph","Properties": {"id": "20261003225941-6yr63oi",- "updated": "20261003225941"+ "updated": "20261024133605"},"Children": [{@@ -2393,7 +2393,7 @@},{"Type": "NodeText",- "Data": ")並點擊節點的摺疊按鈕,可統一摺疊或展開同一父節點下的兄弟分支。只要還有兄弟分支展開,就統一摺疊;全部摺疊時,則統一展開。更深層節點的摺疊狀態保持不變。一般點擊只切換目前節點。"+ "Data": ")並點擊節點的摺疊按鈕,可統一摺疊或展開同一父節點下的兄弟分支。只要還有兄弟分支展開,就統一摺疊;全部摺疊時,則統一展開。更深層節點的摺疊狀態保持不變。一般點擊只切換目前節點。展開與摺疊時,節點與連線會短暫過渡;系統啟用減少動態效果時不播放動畫。"}]},diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.syindex 106dfc0f8e..17117e8020 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy@@ -9,7 +9,7 @@"title": "書式要素","title-img": "background-color:#269;background-image: linear-gradient(white 2px, transparent 2px),linear-gradient(90deg, white 2px, transparent 2px),linear-gradient(rgba(255,255,255,.3) 1px, transparent 1px),linear-gradient(90deg, rgba(255,255,255,.3) 1px, transparent 1px);background-size: 100px 100px, 100px 100px, 20px 20px, 20px 20px;background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;","type": "doc",- "updated": "20261024124505"+ "updated": "20261024134401"},"Children": [{@@ -2384,7 +2384,7 @@"Type": "NodeParagraph","Properties": {"id": "20261022102848-sbqeaum",- "updated": "20261022122318"+ "updated": "20261024134401"},"Children": [{@@ -2412,7 +2412,7 @@},{"Type": "NodeText",- "Data": " で、現在のマップにカラフル、ソフト、フォレスト、海、夕日、ラベンダー、モノクロの配色を選択できます。第 1 階層のブランチにパレットの色を割り当て、子孫ノードは所属するブランチの色を継承します。並べ替えても割り当てた色は保持され、新しいノードも配色に従います。手動で設定したノードや線の色は保持されます。デフォルトを選ぶとパレットを解除し、手動の色と背景は保持します。テーマはノードの内容、構造、折りたたみ状態を変更しません。"+ "Data": " で、現在のマップにカラフル、ソフト、フォレスト、海、夕日、ラベンダー、モノクロの配色を選択できます。テーマでは、すべての階層の背景を透明にし、文字色を統一します。ルートノードは文字を大きくし、ルートノードと第 1 階層のブランチは文字を太くします。ブランチの接続線はパレットで色分けし、幹の線を太く、深い階層の線を細くします。テーマの文字色と接続線はキャンバスの明暗に合わせて調整されます。並べ替えても割り当てた色は保持され、新しいノードも配色に従います。手動で設定した色、文字サイズ、文字の太さはテーマより優先されます。デフォルトを選ぶとパレットを解除し、手動の色と背景は保持します。既存のマップは保存済みの配色を保持します。新しい階層別スタイルを適用するには、テーマを選び直してください。テーマはノードの内容、構造、折りたたみ状態を変更しません。"}]},@@ -2499,7 +2499,7 @@"Type": "NodeParagraph","Properties": {"id": "20261003225941-37evcb1",- "updated": "20261003225941"+ "updated": "20261024133605"},"Children": [{@@ -2518,7 +2518,7 @@},{"Type": "NodeText",- "Data": ")を押しながらノードの折りたたみボタンをクリックすると、同じ親ノード配下の兄弟ブランチをまとめて折りたたむ、または展開できます。展開されている兄弟ブランチがあればすべて折りたたみ、すべて折りたたまれていれば展開します。さらに深い階層の折りたたみ状態は保持されます。通常のクリックは現在のノードのみを切り替えます。"+ "Data": ")を押しながらノードの折りたたみボタンをクリックすると、同じ親ノード配下の兄弟ブランチをまとめて折りたたむ、または展開できます。展開されている兄弟ブランチがあればすべて折りたたみ、すべて折りたたまれていれば展開します。さらに深い階層の折りたたみ状態は保持されます。通常のクリックは現在のノードのみを切り替えます。展開と折りたたみでは、ノードと接続線に短いアニメーションを表示します。システムでアニメーションを抑える設定が有効な場合、アニメーションは表示しません。"}]},diff --git a/app/src/protyle/render/listMindmap/appearance.test.ts b/app/src/protyle/render/listMindmap/appearance.test.tsindex 8d4f730416..e6ec5c2a78 100644--- a/app/src/protyle/render/listMindmap/appearance.test.ts+++ b/app/src/protyle/render/listMindmap/appearance.test.ts@@ -26,11 +26,13 @@ const makeModel = (): ListMindmapModel => {test("appearance validates optional colors and rejects unsupported formats", () => {assert.ok(isListMindmapAppearance({version: 1, palette: [], extension: "retained"}));for (const preset of LIST_MINDMAP_PALETTES) {- assert.ok(isListMindmapAppearance({version: 1, palette: preset.colors, backgroundColor: "#AABBCC"}));+ assert.ok(isListMindmapAppearance({version: 1, palette: preset.colors, rootColor: preset.rootColor, backgroundColor: "#AABBCC"}));}for (const value of [null, [], {}, {version: 2, palette: []}, {version: 1, palette: "red"},{version: 1, palette: ["red"]}, {version: 1, palette: Array(25).fill("#123456")},- {version: 1, palette: [], backgroundColor: null}, {version: 1, palette: [], backgroundColor: "url(x)"}]) {+ {version: 1, palette: [], backgroundColor: null}, {version: 1, palette: [], backgroundColor: "url(x)"},+ ...[null, "", "red", "url(x)", 123, []].map(rootColor => ({version: 1, palette: [] as string[], rootColor})),+ ...[null, "", "flat", "unknown", 123, []].map(nodeStyle => ({version: 1, palette: [] as string[], nodeStyle}))]) {assert.equal(isListMindmapAppearance(value), false);}});@@ -57,12 +59,15 @@ test("all seven built-in palettes remain selectable after reload and provide reamodel.metadata = JSON.parse(JSON.stringify(model.metadata));assert.deepEqual(themes().filter(item => item.checked).map(item => item.id), [preset.id]);assert.deepEqual(model.metadata.appearance.palette, preset.colors);+ assert.equal(model.metadata.appearance.rootColor, preset.rootColor);+ assert.equal(model.metadata.appearance.nodeStyle, "layered");+ assert.ok(!preset.colors.includes(preset.rootColor), "root colors remain separate from every branch color");assert.equal(model.metadata.appearance.backgroundColor, "#ffffff");assert.equal(model.metadata.nodes.a.textColor, "red");- for (const [index, color] of preset.colors.entries()) {+ for (const [index, color] of [...preset.colors, preset.rootColor].entries()) {const lightFill = preset.id === "soft" ||(["lavender", "monochrome"].includes(preset.id) && index >= 4);- assert.equal(getMindmapTextColor(color), lightFill ? "#000000" : "#ffffff",+ assert.equal(getMindmapTextColor(color), lightFill && index < preset.colors.length ? "#000000" : "#ffffff",`${preset.id} branch ${index + 1} retains its intended foreground`);const foreground = luminance(getMindmapTextColor(color));const background = luminance(color);@@ -92,11 +97,90 @@ for (const fixture of [assert.equal(JSON.stringify(model.metadata), before, "opening the menu never migrates document colors");themes.find(item => item.id === fixture.id).click(undefined, undefined);assert.deepEqual(model.metadata.appearance.palette, preset.colors);+ assert.equal(model.metadata.appearance.rootColor, preset.rootColor);assert.equal(model.metadata.appearance.backgroundColor, "#ffffff");assert.deepEqual(model.metadata.nodes.a, {branchColor: 2, textColor: "#ff0000"});});}+test("root colors are opt-in for every existing palette and preserve branch slots, manual styles and undo snapshots", () => {+ for (const preset of LIST_MINDMAP_PALETTES) {+ const model = makeModel();+ model.metadata.appearance = {version: 1, palette: [...preset.colors], backgroundColor: "#ffffff"};+ model.metadata.nodes.root = {backgroundColor: "#fed7aa", bold: true};+ assignListMindmapBranchColors(model);+ const before = JSON.stringify(model.metadata);+ const legacy = resolveListMindmapColors(model);+ assert.equal(legacy.get("root").backgroundColor, legacy.get("a").backgroundColor);+ const themes = () => getListMindmapAppearanceMenu(model.metadata, update => update(model.metadata), {},+ {id: "connectorStyle", label: "Connectors"}).submenu as IMenu[];+ const paletteMenu = () => themes().find(item => item.id === "theme").submenu as IMenu[];+ assert.equal(paletteMenu().find(item => item.id === preset.id).checked, true);+ assert.equal(JSON.stringify(model.metadata), before, "reading and opening a menu never migrate old colors");+ paletteMenu().find(item => item.id === preset.id).click(undefined, undefined);+ const after = JSON.stringify(model.metadata);+ const styled = resolveListMindmapColors(model);+ assert.equal(styled.get("root").backgroundColor, "transparent");+ assert.equal(styled.get("root").lineColor, preset.rootColor);+ assert.notEqual(styled.get("a").backgroundColor, legacy.get("a").backgroundColor);+ assert.equal(styled.get("a1").backgroundColor, "transparent");+ assert.deepEqual(model.metadata.appearance.palette, preset.colors, "layered styling retains the saved branch palette");+ assert.deepEqual(model.metadata.nodes.root, {backgroundColor: "#fed7aa", bold: true});+ model.metadata = JSON.parse(before);+ assert.deepEqual(resolveListMindmapColors(model), legacy, "undo restores the exact legacy root and branch colors");+ model.metadata = JSON.parse(after);+ assert.deepEqual(resolveListMindmapColors(model), styled, "redo and reload retain the independent root color");+ clearListMindmapManualColors(model.metadata);+ assert.deepEqual(model.metadata.nodes.root, {bold: true});+ assert.equal(model.metadata.appearance.rootColor, preset.rootColor, "clearing manual colors retains the root theme");+ assert.equal(model.metadata.nodes.a.branchColor, 0);+ assert.equal(model.metadata.nodes.b.branchColor, 1);+ model.metadata.appearance.rootColor = "#ff0000";+ assert.equal(paletteMenu().some(item => item.checked), false, "a different root color is not the built-in preset");+ paletteMenu().find(item => item.id === "default").click(undefined, undefined);+ assert.equal(model.metadata.appearance.rootColor, undefined);+ assert.equal(model.metadata.appearance.nodeStyle, undefined);+ assert.equal(resolveListMindmapColors(model).size, 0);+ }+});++test("layered palettes combine transparent nodes, neutral text, hierarchical typography and colored lines on every canvas", () => {+ const luminance = (color: string) => color.match(/[a-f\d]{2}/gi).map(channel => parseInt(channel, 16) / 255)+ .map(channel => channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4)+ .reduce((sum, channel, index) => sum + channel * [.2126, .7152, .0722][index], 0);+ const contrast = (a: string, b: string) => (Math.max(luminance(a), luminance(b)) + .05) /+ (Math.min(luminance(a), luminance(b)) + .05);+ for (const preset of LIST_MINDMAP_PALETTES) {+ for (const canvas of ["#ffffff", "#1e1e1e", ...LIST_MINDMAP_PALETTES[1].colors]) {+ const model = makeModel();+ model.metadata.appearance = {version: 1, palette: [...preset.colors], rootColor: preset.rootColor, nodeStyle: "layered"};+ assignListMindmapBranchColors(model);+ const before = JSON.stringify(model.metadata);+ const colors = resolveListMindmapColors(model, canvas);+ assert.equal(colors.get("root").lineColor, preset.rootColor);+ assert.equal(colors.get("a").lineColor, colors.get("a1").lineColor, "descendants inherit their branch line color");+ assert.notEqual(colors.get("a").lineColor, colors.get("b").lineColor, "colors distinguish different branches");+ assert.deepEqual(["root", "a", "a1"].map(id => colors.get(id).fontSize), [20, 16, 14]);+ assert.deepEqual(["root", "a", "a1"].map(id => colors.get(id).bold), [true, true, false]);+ assert.deepEqual(["root", "a", "a1"].map(id => colors.get(id).lineWidth), [2.25, 1.75, 1.25]);+ for (const [id, style] of colors) {+ assert.equal(style.backgroundColor, "transparent", `${preset.id} ${id} has no theme background`);+ assert.equal(style.textColor, colors.get("root").textColor, "text stays consistent instead of competing with colored lines");+ assert.ok(contrast(style.textColor, canvas) >= 4.5, `${preset.id} ${id} text on ${canvas}`);+ assert.ok(contrast(getMindmapLineColor(style.lineColor, canvas), canvas) >= 3,+ `${preset.id} ${id} line on ${canvas}`);+ }+ model.root.children.reverse();+ assert.deepEqual(resolveListMindmapColors(model, canvas), colors, "reordering preserves branch colors and levels");+ model.metadata = JSON.parse(before);+ assert.deepEqual(resolveListMindmapColors(model, canvas), colors, "reload retains the layered style");+ assert.equal(JSON.stringify(model.metadata), before);+ model.metadata.appearance.backgroundColor = canvas;+ assert.deepEqual(resolveListMindmapColors(model, "#123456"), colors, "saved canvas colors override application colors");+ }+ }+});+test("branch identity survives reordering, theme changes, insertion, reparenting and serialized reload", () => {const model = makeModel();const before = JSON.stringify(model.metadata);@@ -144,7 +228,7 @@ test("theme lines contrast with every canvas preset while retaining sufficiently};for (const background of ["#ffffff", "#1e1e1e", ...LIST_MINDMAP_PALETTES[1].colors]) {for (const preset of LIST_MINDMAP_PALETTES) {- for (const color of preset.colors) {+ for (const color of [...preset.colors, preset.rootColor]) {const adjusted = getMindmapLineColor(color, background);assert.ok(contrast(adjusted, background) >= 3, `${preset.id} ${color} on ${background}`);if (contrast(color, background) >= 3) {@@ -177,7 +261,9 @@ test("appearance menu preserves manual colors and non-color metadata until expliassert.equal(model.metadata.appearance.backgroundColor, "#1e1e1e");choose("theme", "soft");assert.equal(model.metadata.appearance.backgroundColor, "#1e1e1e");+ assert.equal(model.metadata.appearance.rootColor, LIST_MINDMAP_PALETTES[1].rootColor);choose("theme", "default");+ assert.equal(model.metadata.appearance.rootColor, undefined);assert.equal(resolveListMindmapColors(model).size, 0);clearListMindmapManualColors(model.metadata);assert.deepEqual(model.metadata.nodes.a, {bold: true});@@ -187,10 +273,10 @@ test("appearance menu preserves manual colors and non-color metadata until expliassert.equal(model.metadata.appearance.backgroundColor, "#1e1e1e");});-const contrastCases = (source: string, css: string) => {+const contrastCases = async (source: string, css: string) => {const check = require("node:assert/strict");const api = new Function("Constants", "mathRender", "tabsRender", "destroyTabsRender", source +- "; return {ListMindmapView, readListMindmap, retagMindmapBranch, getMindmapLineColor, LIST_MINDMAP_PALETTES};")({+ "; return {ListMindmapView, readListMindmap, retagMindmapBranch, getMindmapLineColor, resolveListMindmapColors, LIST_MINDMAP_PALETTES};")({CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap", CUSTOM_SY_LIST_MINDMAP_DATA: "custom-sy-list-mindmap-data",}, async () => {}, () => {}, () => {});const sheet = document.createElement("style");@@ -200,11 +286,12 @@ const contrastCases = (source: string, css: string) => {lute.SetKramdownIAL(true);lute.SetProtyleWYSIWYG(true);const holder = document.createElement("div");- holder.innerHTML = lute.Md2BlockDOM("- Root\n - Empty\n - Quote\n");+ holder.innerHTML = lute.Md2BlockDOM("- Root\n - Empty\n - Deep\n - Quote\n");const list = holder.firstElementChild as HTMLElement;api.retagMindmapBranch(list, true);const model = api.readListMindmap(list);const [emptyNode, quoteNode] = model.root.children;+ const deepNode = emptyNode.children[0];emptyNode.contentBlocks[0].querySelector("[contenteditable]").textContent = "";const quoteHolder = document.createElement("div");quoteHolder.innerHTML = lute.Md2BlockDOM("> Quoted text\n\n> Second paragraph\n");@@ -272,11 +359,14 @@ const contrastCases = (source: string, css: string) => {const context = view.canvas.getContext("2d");const stroke = context.stroke.bind(context);const lines: string[] = [];- context.stroke = (path: Path2D) => { lines.push(computedColor(context.strokeStyle)); stroke(path); };+ const widths: number[] = [];+ context.stroke = (path: Path2D) => { lines.push(computedColor(context.strokeStyle)); widths.push(context.lineWidth); stroke(path); };// 固定几何位置,绘制断言不依赖隐藏窗口的动画帧调度。view.positions = new Map([model.root, emptyNode, quoteNode].map((node, index) => [node.id,{id: node.id, x: index ? 180 : 20, y: index * 80, width: 120, height: 40}]));view.edges = [emptyNode, quoteNode].map(node => ({from: model.root.id, to: node.id}));+ view.positions.set(deepNode.id, {id: deepNode.id, x: 340, y: 80, width: 120, height: 40});+ view.edges.push({from: emptyNode.id, to: deepNode.id});for (const preset of api.LIST_MINDMAP_PALETTES) {for (const background of ["#ffffff", "#1e1e1e"]) {for (const printLayout of [false, true]) {@@ -284,7 +374,9 @@ const contrastCases = (source: string, css: string) => {view.readOnly = printLayout;document.documentElement.style.setProperty("--b3-theme-background", background);for (const savedBackground of [undefined, background]) {- model.metadata.appearance = {version: 1, palette: preset.colors, backgroundColor: savedBackground};+ model.metadata.appearance = {version: 1, palette: preset.colors, rootColor: preset.rootColor,+ backgroundColor: savedBackground};+ model.metadata.connectorStyle = "rounded";model.metadata.nodes[quoteNode.id] = {lineColor: "#abcdef"};const before = JSON.stringify(model.metadata);view.update(model);@@ -293,13 +385,100 @@ const contrastCases = (source: string, css: string) => {check.ok(lines.includes(computedColor(api.getMindmapLineColor(preset.colors[0], background))),`theme lines adapt to canvas: ${preset.id} ${background} ${savedBackground} ${printLayout} ${JSON.stringify(lines)}`);check.ok(lines.includes("rgb(171, 205, 239)"), "manual line colors stay authoritative");+ check.ok(lines.includes(computedColor(api.getMindmapLineColor(preset.rootColor, background))),+ "the common trunk follows the independent root color in editing and print rendering");check.equal(JSON.stringify(model.metadata), before, "contrast correction never rewrites document colors");check.equal(getComputedStyle(view.nodeElements.get(emptyNode.id)).backgroundColor,computedColor(preset.colors[0]), "node fill retains its saved palette color");+ check.equal(getComputedStyle(view.nodeElements.get(model.root.id)).backgroundColor,+ computedColor(preset.rootColor), "the root renders its independent saved color");}}}}+ for (const preset of api.LIST_MINDMAP_PALETTES) {+ model.metadata.appearance = {version: 1, palette: preset.colors, rootColor: preset.rootColor, nodeStyle: "layered"};+ for (const printLayout of [false, true]) {+ view.options.printLayout = printLayout;+ view.readOnly = printLayout;+ for (const background of ["#ffffff", "#1e1e1e"]) {+ document.documentElement.style.setProperty("--b3-theme-background", background);+ view.update(model);+ const expected = api.resolveListMindmapColors(model, background);+ for (const [id, colors] of expected) {+ const element = view.nodeElements.get(id);+ check.equal(getComputedStyle(element).backgroundColor, "rgba(0, 0, 0, 0)",+ "all levels render without a theme fill in editing and print views");+ check.equal(getComputedStyle(element).color, computedColor(colors.textColor));+ check.equal(getComputedStyle(element).fontSize, `${colors.fontSize}px`);+ check.equal(getComputedStyle(element).fontWeight, colors.bold ? "600" : "400");+ }+ widths.length = 0;+ view.draw();+ [2.25, 1.75, 1.25].forEach(width => check.ok(widths.includes(width),+ "real canvas rendering keeps trunks stronger than deeper branch lines"));+ const quote = view.nodeElements.get(quoteNode.id);+ check.equal(getComputedStyle(quote.querySelector(".bq .p")).color, getComputedStyle(quote).color,+ "layered quote text inherits the neutral theme foreground");+ const empty = view.nodeElements.get(emptyNode.id);+ check.equal(getComputedStyle(view.getContentHost(emptyNode.id), "::before").color, getComputedStyle(empty).color,+ "layered placeholders retain their branch foreground in editing and print views");+ for (const node of [model.root, emptyNode, deepNode]) {+ const previous = model.metadata.nodes[node.id];+ model.metadata.nodes[node.id] = {...previous, backgroundColor: "#2563eb", fontSize: 22, bold: false, italic: true};+ view.update(model);+ const element = view.nodeElements.get(node.id);+ check.equal(getComputedStyle(element).backgroundColor, "rgb(37, 99, 235)",+ "manual backgrounds remain authoritative at every level");+ check.equal(getComputedStyle(element).color, "rgb(255, 255, 255)",+ "manual solid fills retain a readable foreground on a transparent theme");+ check.equal(getComputedStyle(element).fontSize, "22px", "manual font sizes take precedence over theme hierarchy");+ check.equal(getComputedStyle(element).fontWeight, "400", "explicit normal weight overrides theme emphasis");+ check.equal(getComputedStyle(element).fontStyle, "italic");+ if (previous) {+ model.metadata.nodes[node.id] = previous;+ } else {+ delete model.metadata.nodes[node.id];+ }+ }+ }+ }+ }+ host.style.setProperty("--b3-mindmap-line-width", "3");+ widths.length = 0;+ view.draw();+ [4.5, 3.5, 2.5].forEach(width => check.ok(widths.includes(width),+ "theme CSS scales the base line width while retaining the new preset's hierarchy"));+ model.metadata.nodes[model.root.id] = {lineWidth: 4};+ widths.length = 0;+ view.draw();+ check.ok(widths.every(width => width === 4), "saved manual line widths override theme CSS and built-in hierarchy");+ delete model.metadata.nodes[model.root.id];+ host.style.removeProperty("--b3-mindmap-line-width");+ view.options.printLayout = false;+ view.readOnly = false;+ view.update(model);+ view.setEditing(deepNode.id);+ const editorHost = view.getContentHost(deepNode.id);+ const editorContent = document.createElement("div");+ editorContent.textContent = "Unsaved editor content";+ editorHost.replaceChildren(editorContent);+ const metadataBeforeThemeChange = JSON.stringify(model.metadata);+ document.documentElement.style.setProperty("--b3-theme-background", "#ffffff");+ await new Promise(resolve => setTimeout(resolve, 0));+ check.equal(getComputedStyle(view.nodeElements.get(deepNode.id)).color,+ computedColor(api.resolveListMindmapColors(model, "#ffffff").get(deepNode.id).textColor),+ "application theme changes refresh layered foregrounds without a document reload");+ check.equal(editorHost.firstElementChild, editorContent, "theme changes preserve the active editor DOM");+ check.equal(view.editingId, deepNode.id);+ check.equal(JSON.stringify(model.metadata), metadataBeforeThemeChange);+ model.metadata.appearance.palette = [];+ view.update(model);+ view.nodeElements.forEach((element: HTMLElement) => {+ check.equal(element.style.fontSize, "", "removing the theme restores legacy font sizing");+ check.equal(element.style.fontWeight, "");+ check.equal(element.style.fontStyle, "");+ });context.stroke = stroke;view.destroy();return "mindmap-contrast-ok";diff --git a/app/src/protyle/render/listMindmap/appearance.ts b/app/src/protyle/render/listMindmap/appearance.tsindex f5aff2f71f..e68cf1c717 100644--- a/app/src/protyle/render/listMindmap/appearance.ts+++ b/app/src/protyle/render/listMindmap/appearance.ts@@ -3,20 +3,22 @@ import type {ListMindmapMetadata, ListMindmapModel, ListMindmapNodeStyle} from "export interface ListMindmapAppearance {version: 1;palette: string[];+ rootColor?: string;+ nodeStyle?: "layered";backgroundColor?: string;}-export const LIST_MINDMAP_PALETTES: {id: string, label: string, colors: string[], previousColors?: string[][]}[] = [- {id: "colorful", label: "listMindmapPaletteColorful", colors: ["#2563eb", "#dc2626", "#15803d", "#9333ea", "#c2410c", "#0e7490"]},- {id: "soft", label: "listMindmapPaletteSoft", colors: ["#bfdbfe", "#fecaca", "#bbf7d0", "#e9d5ff", "#fed7aa", "#a5f3fc"]},- {id: "forest", label: "listMindmapPaletteForest", colors: ["#166534", "#047857", "#4d7c0f", "#0f766e", "#3f6212", "#15803d"]},- {id: "ocean", label: "listMindmapPaletteOcean", colors: ["#0c4a6e", "#0369a1", "#0277b4", "#087e9b", "#087f75", "#0f766e"],+export const LIST_MINDMAP_PALETTES: {id: string, label: string, rootColor: string, colors: string[], previousColors?: string[][]}[] = [+ {id: "colorful", label: "listMindmapPaletteColorful", rootColor: "#1e293b", colors: ["#2563eb", "#dc2626", "#15803d", "#9333ea", "#c2410c", "#0e7490"]},+ {id: "soft", label: "listMindmapPaletteSoft", rootColor: "#64748b", colors: ["#bfdbfe", "#fecaca", "#bbf7d0", "#e9d5ff", "#fed7aa", "#a5f3fc"]},+ {id: "forest", label: "listMindmapPaletteForest", rootColor: "#14532d", colors: ["#166534", "#047857", "#4d7c0f", "#0f766e", "#3f6212", "#15803d"]},+ {id: "ocean", label: "listMindmapPaletteOcean", rootColor: "#082f49", colors: ["#0c4a6e", "#0369a1", "#0277b4", "#087e9b", "#087f75", "#0f766e"],previousColors: [["#0c4a6e", "#0369a1", "#0284c7", "#0891b2", "#0d9488", "#0f766e"]]},- {id: "sunset", label: "listMindmapPaletteSunset", colors: ["#9a3412", "#c2410c", "#c94c0d", "#be123c", "#9f1239", "#7e22ce"],+ {id: "sunset", label: "listMindmapPaletteSunset", rootColor: "#7c2d12", colors: ["#9a3412", "#c2410c", "#c94c0d", "#be123c", "#9f1239", "#7e22ce"],previousColors: [["#9a3412", "#c2410c", "#ea580c", "#be123c", "#9f1239", "#7e22ce"]]},- {id: "lavender", label: "listMindmapPaletteLavender", colors: ["#4c1d95", "#6d28d9", "#7c3aed", "#9842db", "#c084fc", "#e9d5ff"],+ {id: "lavender", label: "listMindmapPaletteLavender", rootColor: "#3b0764", colors: ["#4c1d95", "#6d28d9", "#7c3aed", "#9842db", "#c084fc", "#e9d5ff"],previousColors: [["#4c1d95", "#6d28d9", "#7c3aed", "#a855f7", "#c084fc", "#e9d5ff"]]},- {id: "monochrome", label: "listMindmapPaletteMonochrome", colors: ["#1f2937", "#374151", "#4b5563", "#6b7280", "#9ca3af", "#d1d5db"]},+ {id: "monochrome", label: "listMindmapPaletteMonochrome", rootColor: "#111827", colors: ["#1f2937", "#374151", "#4b5563", "#6b7280", "#9ca3af", "#d1d5db"]},];export const isMindmapColor = (value: unknown): value is string =>@@ -29,6 +31,8 @@ export const isListMindmapAppearance = (value: unknown): value is ListMindmapAppconst data = value as Record<string, unknown>;return data.version === 1 && Array.isArray(data.palette) && data.palette.length <= 24 &&data.palette.every(isMindmapColor) &&+ (data.rootColor === undefined || isMindmapColor(data.rootColor)) &&+ (data.nodeStyle === undefined || data.nodeStyle === "layered") &&(data.backgroundColor === undefined || data.backgroundColor === "" || isMindmapColor(data.backgroundColor));};@@ -67,21 +71,29 @@ const getMindmapLuminance = (color: string) => {export const getMindmapTextColor = (color: string) =>getMindmapLuminance(color) > .179 ? "#000000" : "#ffffff";-// 只调整主题连线的显示色,避免浅色线融入浅色画布、深色线融入深色画布。-export const getMindmapLineColor = (color: string, background: string) => {- if (!/^#[0-9a-f]{6}$/i.test(background)) {- const rgb = background.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*1)?\)$/);- if (!rgb) {- return color;- }- background = "#" + rgb.slice(1).map(value => Number(value).toString(16).padStart(2, "0")).join("");+const getMindmapHexColor = (color: string) => {+ if (/^#[0-9a-f]{6}$/i.test(color)) {+ return color;+ }+ const rgb = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*1)?\)$/);+ return rgb ? "#" + rgb.slice(1).map(value => Number(value).toString(16).padStart(2, "0")).join("") : undefined;+};++const mixMindmapColor = (color: string, background: string, ratio: number) => "#" + [1, 3, 5].map(index =>+ Math.round(parseInt(color.slice(index, index + 2), 16) * ratio ++ parseInt(background.slice(index, index + 2), 16) * (1 - ratio)).toString(16).padStart(2, "0")).join("");++const getMindmapContrastColor = (color: string, background: string, minimum: number) => {+ background = getMindmapHexColor(background);+ if (!background) {+ return color;}const luminance = getMindmapLuminance(background);const contrast = (value: string) => {const line = getMindmapLuminance(value);return (Math.max(line, luminance) + .05) / (Math.min(line, luminance) + .05);};- if (contrast(color) >= 3) {+ if (contrast(color) >= minimum) {return color;}const target = luminance > .179 ? 0 : 255;@@ -89,25 +101,39 @@ export const getMindmapLineColor = (color: string, background: string) => {for (let step = 1; step <= 100; step++) {const adjusted = "#" + channels.map(value => Math.round(value + (target - value) * step / 100).toString(16).padStart(2, "0")).join("");- if (contrast(adjusted) >= 3) {+ if (contrast(adjusted) >= minimum) {return adjusted;}}return color;};-export const resolveListMindmapColors = (model: ListMindmapModel) => {+// 只调整主题连线的显示色,避免浅色线融入浅色画布、深色线融入深色画布。+export const getMindmapLineColor = (color: string, background: string) => getMindmapContrastColor(color, background, 3);++export const resolveListMindmapColors = (model: ListMindmapModel, canvasColor?: string) => {const result = new Map<string, ListMindmapNodeStyle>();const palette = model.metadata.appearance?.palette;if (!palette?.length) {return result;}- const pending = [{node: model.root, color: palette[0]}];+ // 缺少独立根节点色的导图沿用色卡首色,读取时不改写已有外观。+ const appearance = model.metadata.appearance;+ const background = getMindmapHexColor(appearance.backgroundColor || canvasColor || "#ffffff") || "#ffffff";+ const foreground = getMindmapContrastColor(getMindmapLuminance(background) > .179 ? "#334155" : "#e2e8f0", background, 4.5);+ const pending = [{node: model.root, color: appearance.rootColor || palette[0], level: 0}];while (pending.length) {- const {node, color} = pending.pop();- result.set(node.id, {backgroundColor: color, textColor: getMindmapTextColor(color), lineColor: color});+ const {node, color, level} = pending.pop();+ if (appearance.nodeStyle === "layered") {+ result.set(node.id, {backgroundColor: "transparent",+ textColor: foreground, fontSize: level === 0 ? 20 : level === 1 ? 16 : 14, bold: level < 2,+ lineColor: node === model.root ? color : mixMindmapColor(color, background, .65),+ lineWidth: level === 0 ? 2.25 : level === 1 ? 1.75 : 1.25});+ } else {+ result.set(node.id, {backgroundColor: color, textColor: getMindmapTextColor(color), lineColor: color});+ }node.children.forEach((child, index) => pending.push({node: child, color: node === model.root ?- palette[(model.metadata.nodes[child.id]?.branchColor ?? index) % palette.length] : color}));+ palette[(model.metadata.nodes[child.id]?.branchColor ?? index) % palette.length] : color, level: level + 1}));}return result;};@@ -134,14 +160,18 @@ export const getListMindmapAppearanceMenu = (metadata: ListMindmapMetadata,{id: "default", iconHTML: "", label: labels.default, checked: !palette.length,click: () => change(data => {data.appearance = {...data.appearance, version: 1, palette: []};+ delete data.appearance.rootColor;+ delete data.appearance.nodeStyle;})},...LIST_MINDMAP_PALETTES.map(preset => ({id: preset.id, iconHTML: `<span class="b3-menu__icon b3-menu__icon--color" style="background-color:${preset.colors[0]}"></span>`,label: labels[preset.label],- checked: [preset.colors, ...preset.previousColors || []]+ checked: (metadata.appearance?.rootColor === undefined || metadata.appearance.rootColor === preset.rootColor) &&+ [preset.colors, ...preset.previousColors || []].some(colors => JSON.stringify(palette) === JSON.stringify(colors)),click: () => change(data => {- data.appearance = {...data.appearance, version: 1, palette: [...preset.colors]};+ data.appearance = {...data.appearance, version: 1, palette: [...preset.colors],+ rootColor: preset.rootColor, nodeStyle: "layered"};}),})),]},diff --git a/app/src/protyle/render/listMindmap/arrows.test.ts b/app/src/protyle/render/listMindmap/arrows.test.tsindex 99a0a1119e..3f14233b3d 100644--- a/app/src/protyle/render/listMindmap/arrows.test.ts+++ b/app/src/protyle/render/listMindmap/arrows.test.ts@@ -5,7 +5,7 @@ import {runInNewContext} from "node:vm";import {createSourceFile, isClassDeclaration, ScriptTarget, transpileModule} from "typescript";import type {ListMindmapRelation} from "./model";import {buildListMindmapConnectors} from "./connectors";-import {getMindmapLineColor} from "./appearance";+import {getMindmapLineColor, resolveListMindmapColors} from "./appearance";// 执行实际绘制和命中方法,画布替身仅记录路径与箭头,避免依赖图形显示环境。const source = createSourceFile("view.ts", readFileSync("src/protyle/render/listMindmap/view.ts", "utf8"),@@ -34,8 +34,10 @@ const setup = (arrowDirection?: ListMindmapRelation["arrowDirection"]) => {const polygons: Point[][] = [];const strokes: TestPath[] = [];const strokeStyles: string[] = [];+ const strokeAlphas: number[] = [];const context = {strokeStyle: "",+ globalAlpha: 1,strokeHit: false,setTransform: () => {}, clearRect: () => {}, translate: () => {}, scale: () => {},setLineDash: () => {}, closePath: () => {}, save: () => {}, restore: () => {}, resetTransform: () => {},@@ -46,6 +48,7 @@ const setup = (arrowDirection?: ListMindmapRelation["arrowDirection"]) => {stroke: (path: TestPath) => {strokes.push(path);strokeStyles.push(context.strokeStyle);+ strokeAlphas.push(context.globalAlpha);},isPointInStroke: () => context.strokeHit,};@@ -79,9 +82,31 @@ const setup = (arrowDirection?: ListMindmapRelation["arrowDirection"]) => {relationRoutes: new Map([["r", [{x: 100, y: 10}, {x: 0, y: 10}]]]),routingObstacles: (): unknown[] => [], drawRelationPreview: () => {}, drawSummaries: () => {}, renderRouteControls: () => {},});- return {target, context, polygons, strokes, strokeStyles, element};+ return {target, context, polygons, strokes, strokeStyles, strokeAlphas, element};};+test("opening branches fade with their shared trunk while already visible siblings keep their trunk opaque", () => {+ for (const connectorStyle of ["spline", "bezier", "orthogonal", "rounded"]) {+ const {target, strokeAlphas} = setup();+ target.model.root.id = "root";+ Object.assign(target.model.metadata, {connectorStyle, relations: []});+ target.positions = new Map([+ ["root", {id: "root", x: 20, y: 100, width: 100, height: 40}],+ ["a", {id: "a", x: 160, y: 0, width: 100, height: 40}],+ ["b", {id: "b", x: 160, y: 200, width: 100, height: 40}],+ ]);+ target.edges = [{from: "root", to: "a"}, {from: "root", to: "b"}];+ target.foldOpacities = new Map([["a", .4], ["b", .4]]);+ target.draw();+ assert.ok(strokeAlphas.length >= 2 && strokeAlphas.every(alpha => alpha === .4),+ "the common trunk does not jump to full opacity before its branches appear");+ strokeAlphas.length = 0;+ target.foldOpacities.delete("b");+ target.draw();+ assert.deepEqual(strokeAlphas, ["orthogonal", "rounded"].includes(connectorStyle) ? [1, .4, 1] : [.4, 1]);+ }+});+test("shared orthogonal trunks keep the default color and stay outside branch selection in every renderer", () => {for (const connectorStyle of ["orthogonal", "rounded"]) {for (const printLayout of [false, true]) {@@ -112,12 +137,11 @@ test("palette colors reach hierarchy paths and parent trunks while manual line cfor (const connectorStyle of ["spline", "bezier", "orthogonal", "rounded"]) {for (const printLayout of [false, true]) {const {target, strokeStyles} = setup();- target.model.root.id = "root";- Object.assign(target.model.metadata, {connectorStyle, relations: [], nodes: {a: {lineColor: "#abcdef"}}});- target.themeColors = new Map([- ["root", {lineColor: "#111111"}], ["a", {lineColor: "#222222"}],- ["b", {lineColor: "#333333"}], ["c", {lineColor: "#333333"}],- ]);+ target.model.root = {id: "root", children: [{id: "a", children: []},+ {id: "b", children: [{id: "c", children: []}]}]};+ Object.assign(target.model.metadata, {connectorStyle, relations: [], nodes: {a: {lineColor: "#abcdef"}},+ appearance: {version: 1, palette: ["#222222", "#333333"], rootColor: "#111111"}});+ target.themeColors = resolveListMindmapColors(target.model);target.options.printLayout = printLayout;target.readOnly = printLayout;target.positions = new Map([diff --git a/app/src/protyle/render/listMindmap/clipboard.test.ts b/app/src/protyle/render/listMindmap/clipboard.test.tsindex 26f6b80fb2..3e11a1d378 100644--- a/app/src/protyle/render/listMindmap/clipboard.test.ts+++ b/app/src/protyle/render/listMindmap/clipboard.test.ts@@ -52,7 +52,7 @@ const browserCases = async (source: string, css: string) => {const model = api.readListMindmap(list);const [a, b, c] = model.root.children;model.metadata.nodes[a.id] = {backgroundColor: "red"};- model.metadata.appearance = {version: 1, palette: ["#2563eb", "#15803d"], backgroundColor: "#1e1e1e"};+ model.metadata.appearance = {version: 1, palette: ["#2563eb", "#15803d"], rootColor: "#1e293b", nodeStyle: "layered", backgroundColor: "#1e1e1e"};api.assignListMindmapBranchColors(model);model.metadata.relations = [{id: Lute.NewNodeID(), from: a.id, to: b.id, label: "Inside"},@@ -75,7 +75,7 @@ const browserCases = async (source: string, css: string) => {for (const placement of ["child", "after"]) {const destination = list.cloneNode(true) as HTMLElement;const destinationModel = api.readListMindmap(destination);- destinationModel.metadata.appearance = {version: 1, palette: ["#166534", "#047857"], backgroundColor: "#ffffff"};+ destinationModel.metadata.appearance = {version: 1, palette: ["#166534", "#047857"], rootColor: "#14532d", nodeStyle: "layered", backgroundColor: "#ffffff"};api.writeListMindmapMetadata(destination, destinationModel.metadata);const pasted = api.pasteMindmapBranches(destination, payload, c.id, placement, lute);check.ok(pasted);@@ -131,7 +131,7 @@ const browserCases = async (source: string, css: string) => {document.body.append(list);const model = api.readListMindmap(list);const [a, b] = model.root.children;- model.metadata.appearance = {version: 1, palette: ["#2563eb", "#15803d"], backgroundColor: "#1e1e1e"};+ model.metadata.appearance = {version: 1, palette: ["#2563eb", "#15803d"], rootColor: "#1e293b", backgroundColor: "#1e1e1e"};api.assignListMindmapBranchColors(model);model.metadata.nodes[a.id].backgroundColor = "red";model.metadata.nodes[a.id].textColor = "white";@@ -243,6 +243,8 @@ const browserCases = async (source: string, css: string) => {check.equal(preview.viewport.style.backgroundColor, "rgb(30, 30, 30)");check.equal(preview.nodeElements.get(a.id).style.backgroundColor, "rgb(37, 99, 235)","read-only HTML and PDF layout render the saved palette");+ check.equal(preview.nodeElements.get(model.root.id).style.backgroundColor, "rgb(30, 41, 59)",+ "read-only HTML and PDF layout retain the independent root color");preview.destroy();previewHost.remove();}diff --git a/app/src/protyle/render/listMindmap/connectorMenu.test.ts b/app/src/protyle/render/listMindmap/connectorMenu.test.tsindex 93c7092e69..f87318d01f 100644--- a/app/src/protyle/render/listMindmap/connectorMenu.test.ts+++ b/app/src/protyle/render/listMindmap/connectorMenu.test.ts@@ -144,6 +144,10 @@ test("desktop and mobile connector menus persist one undoable change and preservassert.equal(transactions.at(-1).before, beforeTheme);assert.equal(JSON.parse(list.outerHTML).nodes.child.lineColor, "red", "theme changes retain manual overrides");assert.equal(JSON.parse(list.outerHTML).nodes.child.branchColor, 0, "branch slots are saved with the same snapshot");+ assert.equal(JSON.parse(list.outerHTML).appearance.rootColor, "#1e293b",+ "the root theme color is saved in the same document transaction on desktop and mobile");+ assert.equal(JSON.parse(list.outerHTML).appearance.nodeStyle, "layered",+ "the layered style is saved with the root and branch palette on both platforms");const themed = list.outerHTML;data = JSON.parse(beforeTheme);assert.equal(JSON.parse(list.outerHTML).appearance, undefined, "undo restores the unthemed document");diff --git a/app/src/protyle/render/listMindmap/foldAnimation.test.ts b/app/src/protyle/render/listMindmap/foldAnimation.test.tsnew file mode 100644index 0000000000..e8e2af8134--- /dev/null+++ b/app/src/protyle/render/listMindmap/foldAnimation.test.ts@@ -0,0 +1,187 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import test from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isClassDeclaration, ScriptTarget, transpileModule} from "typescript";+import {layoutListMindmapSummaries} from "./summary";++const source = createSourceFile("view.ts", readFileSync("src/protyle/render/listMindmap/view.ts", "utf8"), ScriptTarget.Latest, true);+const declaration = source.statements.find(isClassDeclaration);+const methods = declaration.members.filter(member => ["animateFold", "positionNodes"].includes(member.name?.getText(source)));+assert.equal(methods.length, 2);+const compiled = transpileModule(`class View {${methods.map(member => member.getText(source)).join("\n")}} globalThis.View = View;`, {+ compilerOptions: {target: ScriptTarget.ES2021},+}).outputText;++const setup = (expanding = false) => {+ let sequence = 0;+ let reduced = false;+ const frames = new Map<number, (time: number) => void>();+ const sandbox: any = {+ Map, Set, performance: {now: () => 0}, layoutListMindmapSummaries,+ requestAnimationFrame: (callback: (time: number) => void) => { frames.set(++sequence, callback); return sequence; },+ cancelAnimationFrame: (id: number) => frames.delete(id),+ window: {matchMedia: () => ({matches: reduced})},+ };+ runInNewContext(compiled, sandbox);+ const view = new sandbox.View();+ const position = (id: string, x: number, y: number) => ({id, x, y, width: 100, height: 40});+ const expanded = new Map([+ ["root", position("root", 20, 100)], ["a", position("a", 180, 50)],+ ["leaf", position("leaf", 340, 50)], ["b", position("b", 180, 150)],+ ]);+ const collapsed = new Map([+ ["root", position("root", 20, 80)], ["a", position("a", 180, 50)], ["b", position("b", 180, 110)],+ ]);+ const expandedEdges = [{from: "root", to: "a"}, {from: "a", to: "leaf"}, {from: "root", to: "b"}];+ const collapsedEdges = expandedEdges.filter(edge => edge.to !== "leaf");+ const previous = expanding ? collapsed : expanded;+ const target = expanding ? expanded : collapsed;+ const previousOffset = {x: 10, y: expanding ? 40 : 20};+ const targetOffset = {x: 10, y: expanding ? 20 : 40};+ const leaf = {id: "leaf", parentId: "a", children: [] as {id: string}[]};+ const a = {id: "a", parentId: "root", children: [leaf]};+ const b = {id: "b", parentId: "root", children: [] as {id: string}[]};+ const root = {id: "root", children: [a, b]};+ const draws: {leaf: number, sibling: number, alpha: number, root: number}[] = [];+ Object.assign(view, {+ model: {root, nodes: new Map([root, a, b, leaf].map(node => [node.id, node])),+ metadata: {version: 1, nodes: {}, relations: [], summaries: []}},+ options: {}, positions: target, edges: expanding ? expandedEdges : collapsedEdges,+ summaryPositions: new Map(), relationRoutes: new Map([["old-route", []]]),+ nodeElements: new Map([...expanded.keys()].map(id => [id, {style: {}, hidden: false, inert: false}])),+ offsetX: targetOffset.x, offsetY: targetOffset.y,+ draw: () => draws.push({leaf: view.positions.get("leaf")?.x, sibling: view.positions.get("b").y,+ alpha: view.foldOpacities?.get("leaf"), root: view.positions.get("root").y + view.offsetY}),+ });+ view.positionNodes();+ const snapshot = JSON.stringify(view.model.metadata);+ return {view, previous, target, previousOffset, draws, frames,+ start: () => view.animateFold(previous, expanding ? collapsedEdges : expandedEdges, previousOffset, new Map()),+ reduce: () => reduced = true,+ advance: (time: number) => {+ const callbacks = [...frames.values()];+ frames.clear();+ callbacks.forEach(callback => callback(time));+ },+ unchanged: () => assert.equal(JSON.stringify(view.model.metadata), snapshot),+ };+};++test("folding moves and fades outgoing nodes with their edges while keeping the anchor fixed", () => {+ const fixture = setup();+ const {view, draws, target} = fixture;+ fixture.start();+ assert.equal(view.nodeElements.get("leaf").hidden, false);+ assert.equal(view.nodeElements.get("leaf").inert, true, "a collapsing child cannot receive input");+ assert.ok(view.edges.some((edge: {to: string}) => edge.to === "leaf"));+ fixture.advance(90);+ const middle = draws.at(-1);+ assert.ok(middle.leaf < 340 && middle.leaf > 280, "the child retracts toward its parent attachment");+ assert.ok(middle.sibling < 150 && middle.sibling > 110, "adjacent branches move smoothly into the freed space");+ assert.ok(middle.alpha > 0 && middle.alpha < 1, "node and connector drawing share the same opacity");+ assert.ok(draws.every(draw => draw.root === 120), "offset interpolation keeps the operation node fixed");+ fixture.advance(180);+ assert.equal(view.positions, target);+ assert.equal(view.nodeElements.get("leaf").hidden, true);+ assert.equal(view.nodeElements.get("leaf").inert, false);+ assert.equal(view.nodeElements.get("leaf").style.opacity, "");+ assert.equal(view.edges.some((edge: {to: string}) => edge.to === "leaf"), false);+ assert.equal(view.stopFoldAnimation, undefined);+ assert.equal(fixture.frames.size, 0);+ fixture.unchanged();+});++test("expanding uses a longer balanced transition before restoring exact geometry without temporary styles", () => {+ const fixture = setup(true);+ fixture.start();+ const {view, draws, target} = fixture;+ assert.equal(view.nodeElements.get("leaf").hidden, false);+ assert.equal(view.nodeElements.get("leaf").style.opacity, "0");+ assert.equal(view.positions.get("leaf").x, 304);+ fixture.advance(70);+ assert.ok(draws.at(-1).alpha > 0 && draws.at(-1).alpha < .25, "the first quarter no longer consumes most of the opening movement");+ fixture.advance(140);+ assert.ok(draws.at(-1).leaf > 304 && draws.at(-1).leaf < 340);+ assert.ok(draws.at(-1).alpha > .35 && draws.at(-1).alpha < .65, "the opening remains visibly in progress at its midpoint");+ fixture.advance(180);+ assert.ok(view.stopFoldAnimation, "opening outlasts the shorter collapse duration");+ fixture.advance(280);+ assert.equal(view.positions, target);+ assert.equal(view.nodeElements.get("leaf").inert, false);+ assert.equal(view.nodeElements.get("leaf").style.left, "340px");+ assert.equal(view.foldOpacities, undefined);+ assert.equal(fixture.frames.size, 0);+ fixture.unchanged();+});++test("a newly expanded subtree preserves row and column spacing throughout its entrance", () => {+ const fixture = setup(true);+ fixture.previous.delete("a");+ fixture.previous.delete("b");+ fixture.start();+ for (const time of [0, 70, 140, 210]) {+ fixture.advance(time);+ const positions = fixture.view.positions;+ assert.equal(positions.get("b").y - positions.get("a").y, 100,+ "sibling labels never pile up at the collapsed parent's center");+ assert.equal(positions.get("leaf").x - positions.get("a").x, 160,+ "parent and child text retain their full horizontal separation");+ assert.ok(Math.abs(positions.get("root").y + fixture.view.offsetY - 120) < 1e-9);+ }+ fixture.advance(280);+ assert.equal(fixture.frames.size, 0);+ fixture.unchanged();+});++test("interruptions finish once, cancel scheduled frames and cannot let stale callbacks restore old geometry", () => {+ const fixture = setup();+ fixture.start();+ const staleFrame = [...fixture.frames.values()][0];+ const finish = fixture.view.stopFoldAnimation;+ fixture.advance(40);+ finish();+ const drawCount = fixture.draws.length;+ fixture.view.positions = new Map();+ staleFrame(160);+ finish();+ assert.equal(fixture.view.positions.size, 0, "canceled callbacks never overwrite a later layout");+ assert.equal(fixture.draws.length, drawCount);+ assert.equal(fixture.frames.size, 0);+ assert.equal(fixture.view.stopFoldAnimation, undefined);+ fixture.unchanged();+});++test("reduced motion, print and destroyed views skip motion and a preference change ends an active transition", () => {+ for (const mode of ["reduced", "print", "printing", "destroyed"]) {+ const fixture = setup();+ if (mode === "reduced") {+ fixture.reduce();+ } else if (mode === "print") {+ fixture.view.options.printLayout = true;+ } else if (mode === "printing") {+ fixture.view.printTransform = {};+ } else {+ fixture.view.destroyed = true;+ }+ fixture.start();+ assert.equal(fixture.view.positions, fixture.target);+ assert.equal(fixture.frames.size, 0, mode);+ assert.equal(fixture.view.stopFoldAnimation, undefined);+ fixture.unchanged();+ }+ const fixture = setup(true);+ fixture.start();+ fixture.reduce();+ fixture.advance(30);+ assert.equal(fixture.view.positions, fixture.target);+ assert.equal(fixture.frames.size, 0);+ assert.equal(fixture.view.nodeElements.get("leaf").inert, false);+ const destroyed = setup();+ destroyed.start();+ const drawCount = destroyed.draws.length;+ destroyed.view.destroyed = true;+ destroyed.advance(30);+ assert.equal(destroyed.draws.length, drawCount, "teardown does not draw a destroyed canvas");+ assert.equal(destroyed.frames.size, 0);+});diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.tsindex 7ce3cd7bba..e979113815 100644--- a/app/src/protyle/render/listMindmap/model.test.ts+++ b/app/src/protyle/render/listMindmap/model.test.ts@@ -89,8 +89,8 @@ test("compact view spacing retains draggable relations without expanding unrelattypescript.ScriptTarget.ES2021, true);const declaration = source.statements.find(typescript.isClassDeclaration);const methods = declaration.members.filter(member =>- ["refreshLayout", "resizeViewport", "getViewportAnchorY"].includes(member.name?.getText(source)));- assert.equal(methods.length, 3);+ ["refreshLayout", "positionNodes", "resizeViewport", "getViewportAnchorY"].includes(member.name?.getText(source)));+ assert.equal(methods.length, 4);const compiled = typescript.transpileModule(`class View {${methods.map(member => member.getText(source)).join("\n")}} globalThis.View = View;`, {compilerOptions: {target: typescript.ScriptTarget.ES2021},}).outputText;@@ -192,8 +192,12 @@ test("appearance metadata is additive and rejects invalid palettes and branch slconst appearance = {version: 1, palette: ["#123456", "#abcdef"], backgroundColor: "#ffffff", extension: "keep"};const source = JSON.stringify({...base, appearance});assert.equal(JSON.stringify(parseListMindmapMetadata(source)), source);+ const withRootColor = JSON.stringify({...base, appearance: {...appearance, rootColor: "#112233", nodeStyle: "layered"}});+ assert.equal(JSON.stringify(parseListMindmapMetadata(withRootColor)), withRootColor);for (const invalid of [null, [], {}, {...appearance, version: 2}, {...appearance, palette: ["red"]},- {...appearance, backgroundColor: "url(x)"}]) {+ {...appearance, backgroundColor: "url(x)"},+ ...[null, "", "red", "url(x)", 123].map(rootColor => ({...appearance, rootColor})),+ ...[null, "", "flat", "unknown", 123].map(nodeStyle => ({...appearance, nodeStyle}))]) {const value = JSON.stringify({...base, appearance: invalid});assert.throws(() => parseListMindmapMetadata(value), /Invalid list mindmap metadata/);}@@ -1248,6 +1252,14 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,};const frame = () => new Promise<void>(resolve => requestAnimationFrame(() => resolve()));const settle = async () => { await frame(); await frame(); };+ const settleFold = async (current: {stopFoldAnimation?: () => void}) => {+ await settle();+ const deadline = performance.now() + 1000;+ while (current.stopFoldAnimation && performance.now() < deadline) {+ await frame();+ }+ check.equal(current.stopFoldAnimation, undefined, "fold transitions finish without leaving a pending frame");+ };const enableHand = (targetHost: HTMLElement) => {targetHost.querySelector<HTMLButtonElement>('[aria-label="more"]').click();check.ok(panMenu);@@ -3105,8 +3117,30 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,pressDelete();check.deepEqual(deletions, [beta]);const beforeCollapse = nodeElement(model.root.id).getBoundingClientRect();+ const foldContext = readonly.canvas.getContext("2d");+ const originalStroke = foldContext.stroke.bind(foldContext);+ const foldAlphas: number[] = [];+ foldContext.stroke = (path?: Path2D) => {+ foldAlphas.push(foldContext.globalAlpha);+ if (path) {+ originalStroke(path);+ } else {+ originalStroke();+ }+ };nodeElement(model.root.id).querySelector<HTMLButtonElement>(".mindmap-view__fold").click();await settle();+ if (!window.matchMedia("(prefers-reduced-motion: reduce)").matches) {+ check.ok(readonly.stopFoldAnimation, "a user fold starts a visible transition");+ check.equal(nodeElement(alpha).hidden, false, "outgoing children remain visible during the transition");+ check.equal(nodeElement(alpha).inert, true, "outgoing children cannot receive pointer or keyboard input");+ check.ok(Number(nodeElement(alpha).style.opacity) > 0 && Number(nodeElement(alpha).style.opacity) < 1);+ check.ok(foldAlphas.some(alpha => alpha > 0 && alpha < 1), "real canvas connectors fade together with their nodes");+ check.ok(Math.abs(nodeElement(model.root.id).getBoundingClientRect().y - beforeCollapse.y) < 1,+ "the root stays anchored throughout the animation");+ }+ await settleFold(readonly);+ foldContext.stroke = originalStroke;const afterCollapse = nodeElement(model.root.id).getBoundingClientRect();check.ok(Math.abs(afterCollapse.y - beforeCollapse.y) < 1, "collapse keeps the root at its screen position");check.equal(nodeElement(alpha).hidden, true);@@ -3114,12 +3148,19 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,check.equal(foldedButton.querySelector("span").textContent, String(model.nodes.size - 1));check.equal(getComputedStyle(foldedButton).visibility, "visible");foldedButton.click();- await settle();+ await settleFold(readonly);check.equal(nodeElement(alpha).hidden, false);const afterExpand = nodeElement(model.root.id).getBoundingClientRect();check.ok(Math.abs(afterExpand.y - afterCollapse.y) < 1, "expansion keeps the root stable after size observers settle");check.ok(Math.abs(afterExpand.x - afterCollapse.x) < 1, "expansion preserves horizontal position");check.equal(list.outerHTML, persistedBeforeFold);+ foldedButton.click();+ await settle();+ foldedButton.click();+ await settleFold(readonly);+ check.equal(nodeElement(alpha).hidden, false, "rapid fold reversals finish in the latest requested state");+ check.equal(nodeElement(alpha).style.opacity, "");+ check.equal(nodeElement(alpha).inert, false);const levelSelect = host.querySelector<HTMLSelectElement>(".mindmap-view__level-select");check.deepEqual(Array.from(levelSelect.options).map(option => option.value),["", "expandAll", "foldAll", "1", "2", "3", "4", "5", "6"]);@@ -3129,7 +3170,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,const beforeLevel = nodeElement(alpha).getBoundingClientRect();levelSelect.value = "1";levelSelect.dispatchEvent(new Event("change", {bubbles: true}));- await settle();+ await settleFold(readonly);check.equal(nodeElement(levelChild).hidden, true);check.equal(nodeElement(alpha).hidden, false);check.equal(readonly.selectedId, alpha, "a hidden selection moves to its visible ancestor");@@ -3138,12 +3179,12 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,check.equal(list.outerHTML, persistedBeforeFold, "exported and read-only level changes never write the list");levelSelect.value = "foldAll";levelSelect.dispatchEvent(new Event("change", {bubbles: true}));- await settle();+ await settleFold(readonly);check.equal(nodeElement(alpha).hidden, true);check.equal(readonly.selectedId, model.root.id);levelSelect.value = "expandAll";levelSelect.dispatchEvent(new Event("change", {bubbles: true}));- await settle();+ await settleFold(readonly);check.equal(nodeElement(levelChild).hidden, false);check.equal(list.outerHTML, persistedBeforeFold);readonly.destroy();@@ -3188,7 +3229,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,await clickMouse(levelButton);levelView.clearSelection();chooseLevel(1);- await settle();+ await settleFold(levelView);check.equal(levelSaves, 1);check.equal(levelView.selectedId, alpha, "menu clicks retain the selection anchor despite outside-pointer dismissal");check.equal(nodeElement(levelChild).hidden, true);@@ -3196,20 +3237,20 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,levelSaveAllowed = false;levelButton.click();chooseLevel("expandAll");- await settle();+ await settleFold(levelView);check.equal(nodeElement(levelChild).hidden, true, "failed saves do not apply optimistic folding overrides");levelSaveAllowed = true;levelButton.click();chooseLevel("expandAll");- await settle();+ await settleFold(levelView);check.equal(nodeElement(levelChild).hidden, false);levelButton.click();chooseLevel("foldAll");- await settle();+ await settleFold(levelView);check.equal(nodeElement(alpha).hidden, true, "the virtual center participates in batch folding");levelButton.click();chooseLevel(1);- await settle();+ await settleFold(levelView);check.equal(nodeElement(alpha).hidden, false, "level selection expands a previously folded virtual center");levelView.destroy();@@ -3250,7 +3291,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,siblingElement(id).querySelector(".mindmap-view__fold").dispatchEvent(new MouseEvent("click", {bubbles: true, altKey,}));- await settle();+ await settleFold(siblingView);};await settle();const navigateSibling = (key: string, expected: string) => {diff --git a/app/src/protyle/render/listMindmap/preview.test.ts b/app/src/protyle/render/listMindmap/preview.test.tsindex a17205a5be..26432e7571 100644--- a/app/src/protyle/render/listMindmap/preview.test.ts+++ b/app/src/protyle/render/listMindmap/preview.test.ts@@ -185,7 +185,7 @@ const cases = async (source: string, css: string, formulas: string[]) => {nodes: {} as Record<string, {width?: number}>, relations: [] as {id: string}[],}};const view = Object.assign(new api.MindmapPreviewView(), {- options: {}, viewport: document.createElement("div"), persistedLocked: false,+ options: {host: map}, viewport: document.createElement("div"), persistedLocked: false,nodeElements: new Map([[node.id, nodeElement]]), folded: new Map(), selectedIds: new Set(),renderTask: () => {}, destroyContentViews: () => {},label: (key: string) => key, updateRelations: () => {}, updateSummaries: () => {},@@ -288,8 +288,8 @@ test("special block previews cannot acquire document writes or lose unsupportedassert.equal(methods.length, 2);const viewSource = createSourceFile("view.ts", readFileSync(path.join(__dirname, "view.ts"), "utf8"), ScriptTarget.Latest, true);const viewClass = viewSource.statements.find(isClassDeclaration);- const viewMethods = viewClass.members.filter(member => ["update", "getContentHost"].includes(member.name?.getText(viewSource)));- assert.equal(viewMethods.length, 2);+ const viewMethods = viewClass.members.filter(member => ["update", "updateColors", "getContentHost"].includes(member.name?.getText(viewSource)));+ assert.equal(viewMethods.length, 3);const katexDirectory = path.resolve(__dirname, "../../../../stage/protyle/js/katex");const katex = require(path.join(katexDirectory, "katex.min.js"));const formulas = ["x", "\\frac{y}{x}", "AAA=" + "A".repeat(40)].map(value =>diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.tsindex 7f9f2d1a2e..44c1a8f2fb 100644--- a/app/src/protyle/render/listMindmap/view.ts+++ b/app/src/protyle/render/listMindmap/view.ts@@ -157,6 +157,8 @@ export class ListMindmapView {private tooltipButton?: HTMLButtonElement;private readonly colorProbe = createElement("span", "mindmap-view__color-probe");private positions = new Map<string, ListMindmapPosition>();+ private foldOpacities?: Map<string, number>;+ private stopFoldAnimation?: () => void;private edges: {from: string, to: string}[] = [];private bounds = {width: 1, height: 1};private selectedId?: string;@@ -272,11 +274,19 @@ export class ListMindmapView {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());+ ["pointerdown", "keydown"].forEach(type =>+ this.listen(options.host, type, () => this.stopFoldAnimation?.(), {capture: true}));+ const refreshTheme = () => {+ if (this.model.metadata.appearance?.nodeStyle === "layered") {+ this.updateColors();+ }+ this.refreshLayout();+ };+ const themeObserver = new MutationObserver(refreshTheme);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(document.head, "load", refreshTheme, {capture: true});this.listen(this.viewport, "pointerdown", this.pointerDown);this.listen(this.viewport, "pointermove", this.pointerMove);this.listen(this.viewport, "pointerleave", () => this.setHoveredLine());@@ -339,6 +349,7 @@ export class ListMindmapView {event.stopPropagation();}));this.listen(window, "beforeprint", () => {+ this.stopFoldAnimation?.();if (this.pointer?.relation) {this.cancelPointer();}@@ -726,6 +737,7 @@ export class ListMindmapView {}public update(model: ListMindmapModel) {+ this.stopFoldAnimation?.();if (this.pointer?.relation || this.pointer?.selection || this.pointer?.touchNode) {this.cancelPointer();}@@ -733,8 +745,6 @@ export class ListMindmapView {return;}this.model = model;- this.themeColors = resolveListMindmapColors(model);- this.viewport.style.backgroundColor = model.metadata.appearance?.backgroundColor || "";this.selectedIds.forEach(id => {if (!model.nodes.has(id)) {this.selectedIds.delete(id);@@ -812,19 +822,9 @@ export class ListMindmapView {element.classList.toggle("mindmap-view__node--root", id === model.root.id);this.renderTask(element, id);element.classList.toggle("mindmap-view__node--branch", node.children.length > 0);- element.classList.toggle("mindmap-view__node--colored", this.themeColors.has(id));const style = model.metadata.nodes[id];element.style.width = style?.width ? `${Math.max(32, style.width)}px` : "";element.style.maxWidth = style?.width ? "none" : "";- const background = style?.backgroundColor || this.themeColors.get(id)?.backgroundColor || "";- element.style.backgroundColor = background;- element.style.color = style?.textColor || (this.themeColors.has(id) && isMindmapColor(background) ?- getMindmapTextColor(background) : this.themeColors.get(id)?.textColor) || "";- if (this.themeColors.has(id)) {- element.style.setProperty("--mindmap-node-text-color", element.style.color);- } else {- element.style.removeProperty("--mindmap-node-text-color");- }const collapsed = this.folded.get(id) ?? node.collapsed;element.setAttribute("aria-expanded", String(!collapsed));const fold = element.querySelector<HTMLButtonElement>(".mindmap-view__fold");@@ -976,6 +976,7 @@ export class ListMindmapView {this.selectedSummary = undefined;this.inspector.hidden = true;}+ this.updateColors();this.updateRelations();this.updateSummaries();this.updateSelection();@@ -983,6 +984,33 @@ export class ListMindmapView {this.refreshLayout();}+ // 主题变更只刷新节点外观,保留正在编辑的正文和画布状态。+ private updateColors() {+ if (this.destroyed) {+ return;+ }+ this.viewport.style.backgroundColor = this.model.metadata.appearance?.backgroundColor || "";+ this.themeColors = resolveListMindmapColors(this.model, getComputedStyle(this.options.host).backgroundColor);+ this.nodeElements.forEach((element, id) => {+ const style = this.model.metadata.nodes[id];+ const themed = this.themeColors.get(id);+ const background = style?.backgroundColor || themed?.backgroundColor || "";+ element.classList.toggle("mindmap-view__node--colored", !!themed);+ element.style.backgroundColor = background;+ element.style.color = style?.textColor || (themed && style?.backgroundColor && isMindmapColor(background) ?+ getMindmapTextColor(background) : themed?.textColor) || "";+ element.style.fontSize = themed?.fontSize ? `${style?.fontSize ?? themed.fontSize}px` : "";+ element.style.fontWeight = themed?.fontSize ? (style?.bold === undefined ? (themed.bold ? "600" : "400") :+ style.bold ? "700" : "400") : "";+ element.style.fontStyle = themed?.fontSize && style?.italic !== undefined ? (style.italic ? "italic" : "normal") : "";+ if (themed) {+ element.style.setProperty("--mindmap-node-text-color", element.style.color);+ } else {+ element.style.removeProperty("--mindmap-node-text-color");+ }+ });+ }+public getContentHost(id: string): HTMLElement | undefined {return this.nodeElements.get(id)?.querySelector<HTMLElement>(".mindmap-view__content");}@@ -1110,6 +1138,7 @@ export class ListMindmapView {}this.frame = requestAnimationFrame(() => {this.frame = 0;+ this.stopFoldAnimation?.();if (this.pointer?.relation) {return;}@@ -1119,6 +1148,9 @@ export class ListMindmapView {this.resizeViewport();const previousPositions = this.positions;const previousSummaries = this.summaryPositions;+ const previousEdges = this.edges;+ const previousOffset = {x: this.offsetX, y: this.offsetY};+ const animateFold = !!this.foldAnchor && !this.initialFit;// 同一帧内先恢复测量,布局完成后再隐藏折叠后代,避免展开时读取到零尺寸。this.nodeElements.forEach(element => element.hidden = false);const makeLayoutNode = (id: string): ListMindmapLayoutNode => {@@ -1235,14 +1267,7 @@ export class ListMindmapView {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 - (id === this.model.root.id ? 1 : 3)}px`;- }- });+ this.positionNodes();// 编辑、折叠或调整路径时固定操作节点,避免整棵树随布局边界跳动。const current = anchorId ? this.positions.get(anchorId) : undefined;if (previous && current) {@@ -1287,9 +1312,120 @@ export class ListMindmapView {}this.draw();}+ if (animateFold && (previousPositions.size !== this.positions.size ||+ [...previousPositions.keys()].some(id => !this.positions.has(id)))) {+ this.animateFold(previousPositions, previousEdges, previousOffset, summarySizes);+ }});}+ private positionNodes() {+ this.nodeElements.forEach((element, id) => {+ const position = this.positions.get(id);+ element.hidden = !position;+ element.inert = !!this.foldOpacities?.has(id);+ element.style.opacity = this.foldOpacities?.has(id) ? String(this.foldOpacities.get(id)) : "";+ if (position) {+ element.style.left = `${position.x}px`;+ element.style.top = `${position.y - (id === this.model.root.id ? 1 : 3)}px`;+ }+ });+ }++ private animateFold(previous: Map<string, ListMindmapPosition>, previousEdges: {from: string, to: string}[],+ previousOffset: {x: number, y: number}, summarySizes: Map<string, {width: number, height: number}>) {+ if (this.destroyed || this.printTransform || this.options.printLayout || !previous.size ||+ !previous.has(this.model.root.id) ||+ window.matchMedia("(prefers-reduced-motion: reduce)").matches) {+ return;+ }+ const target = this.positions;+ const targetEdges = this.edges;+ const targetSummaries = this.summaryPositions;+ const targetOffset = {x: this.offsetX, y: this.offsetY};+ const expanding = [...target.keys()].some(id => !previous.has(id));+ const duration = expanding ? 280 : 180;+ const changed = new Set([...previous.keys(), ...target.keys()]);+ const endpoints = new Map<string, {from: ListMindmapPosition, to: ListMindmapPosition}>();+ const attachment = (id: string, positions: Map<string, ListMindmapPosition>, size: ListMindmapPosition) => {+ let parent = this.model.nodes.get(id)?.parentId;+ while (parent && !positions.has(parent)) {+ parent = this.model.nodes.get(parent)?.parentId;+ }+ const anchor = positions.get(parent) || positions.get(this.model.root.id);+ return {...size, x: anchor.x + anchor.width, y: anchor.y + (anchor.height - size.height) / 2};+ };+ // 新分支保留内部排版,仅随可见祖先滑入,避免展开中途把多行正文挤到一起。+ const entrance = (id: string) => {+ let parent = this.model.nodes.get(id)?.parentId;+ while (parent && (!previous.has(parent) || !target.has(parent))) {+ parent = this.model.nodes.get(parent)?.parentId;+ }+ const from = previous.get(parent) || previous.get(this.model.root.id);+ const to = target.get(parent) || target.get(this.model.root.id);+ const position = target.get(id);+ return {...position, x: position.x + from.x - to.x - 36, y: position.y + from.y - to.y};+ };+ changed.forEach(id => endpoints.set(id, {+ from: previous.get(id) || entrance(id),+ to: target.get(id) || attachment(id, target, previous.get(id)),+ }));+ const targetChildren = new Set(targetEdges.map(edge => edge.to));+ this.edges = [...targetEdges, ...previousEdges.filter(edge => !targetChildren.has(edge.to))];+ let frame = 0;+ let active = true;+ const finish = () => {+ if (!active) {+ return;+ }+ active = false;+ cancelAnimationFrame(frame);+ this.stopFoldAnimation = undefined;+ this.foldOpacities = undefined;+ this.positions = target;+ this.edges = targetEdges;+ this.summaryPositions = targetSummaries;+ this.offsetX = targetOffset.x;+ this.offsetY = targetOffset.y;+ this.relationRoutes.clear();+ this.positionNodes();+ if (!this.destroyed) {+ this.draw();+ }+ };+ this.stopFoldAnimation = finish;+ const started = performance.now();+ const step = (now: number) => {+ if (!active) {+ return;+ }+ const progress = Math.min(1, Math.max(0, (now - started) / duration));+ if (progress === 1 || this.destroyed || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {+ finish();+ return;+ }+ const eased = expanding ? (progress < .5 ? 2 * progress ** 2 : 1 - (-2 * progress + 2) ** 2 / 2) :+ 1 - (1 - progress) ** 3;+ this.positions = new Map();+ this.foldOpacities = new Map();+ endpoints.forEach(({from, to}, id) => {+ this.positions.set(id, {...to, x: from.x + (to.x - from.x) * eased,+ y: from.y + (to.y - from.y) * eased});+ if (!previous.has(id) || !target.has(id)) {+ this.foldOpacities.set(id, target.has(id) ? eased : 1 - eased);+ }+ });+ this.offsetX = previousOffset.x + (targetOffset.x - previousOffset.x) * eased;+ this.offsetY = previousOffset.y + (targetOffset.y - previousOffset.y) * eased;+ this.summaryPositions = layoutListMindmapSummaries(this.model, this.positions, summarySizes);+ this.relationRoutes.clear();+ this.positionNodes();+ this.draw();+ frame = requestAnimationFrame(step);+ };+ step(started);+ }+private updateSummaries() {this.summaryElements.forEach((element, id) => {if (!this.model.metadata.summaries?.some(summary => summary.id === id)) {@@ -1435,6 +1571,9 @@ export class ListMindmapView {if (!element) {return;}+ const opacity = Math.min(...summary.nodeIds.map(id => this.foldOpacities?.get(id) ?? 1));+ element.style.opacity = this.foldOpacities ? String(opacity) : "";+ element.inert = summary.nodeIds.some(id => this.foldOpacities?.has(id));element.hidden = !position;if (!position) {return;@@ -1447,6 +1586,7 @@ export class ListMindmapView {const style = resolveStyle(summary.color, selected, hovered);context.strokeStyle = style.color;context.lineWidth = style.width;+ context.globalAlpha = opacity;context.setLineDash([]);context.stroke(path);this.linePaths.push({id: summary.id, relation: false, summary: true, path});@@ -1457,6 +1597,7 @@ export class ListMindmapView {element.classList.toggle("mindmap-view__node--selected", selected);element.setAttribute("aria-pressed", String(selected));});+ context.globalAlpha = 1;}private updateRelations() {@@ -1871,9 +2012,9 @@ export class ListMindmapView {return colors.get(key);};const resolveLineStyle = (styles: typeof lineStyles, color: string, width: number, fallback: string,- selected: boolean, hovered: boolean) => {+ selected: boolean, hovered: boolean, themeWidth = 1.5) => {const baseColor = resolveColor(styles[0].color, fallback);- const baseWidth = width || styles[0].width || 1.5;+ const baseWidth = width || (styles[0].width || 1.5) / 1.5 * themeWidth;const stateStyle = selected ? styles[2] : hovered ? styles[1] : undefined;return {// 显式颜色始终优先,状态颜色缺省时沿用普通主题色。@@ -1894,14 +2035,24 @@ export class ListMindmapView {};const connectors = buildListMindmapConnectors(this.model.root.id, this.positions, this.edges,this.model.metadata.connectorStyle || "bezier", () => new Path2D());+ const trunkOpacities = new Map<string, number>();+ if (this.foldOpacities) {+ this.edges.forEach(edge => {+ if (this.positions.has(edge.to)) {+ trunkOpacities.set(edge.from, Math.max(trunkOpacities.get(edge.from) ?? 0,+ this.foldOpacities.get(edge.to) ?? 1));+ }+ });+ }const rootStyle = this.model.metadata.nodes[this.model.root.id] || {};connectors.trunks.forEach((path, index) => {const id = connectors.trunkParents[index];const style = this.themeColors?.size ? {...rootStyle, ...this.model.metadata.nodes[id]} : rootStyle;const trunkStyle = resolveLineStyle(lineStyles, style.lineColor || themeLineColor(id),- style.lineWidth, defaultLine, false, false);+ style.lineWidth, defaultLine, false, false, this.themeColors?.get(id)?.lineWidth);context.strokeStyle = trunkStyle.color;context.lineWidth = trunkStyle.width;+ context.globalAlpha = Math.min(this.foldOpacities?.get(id) ?? 1, trunkOpacities.get(id) ?? 1);context.setLineDash(style.lineDash ? [6, 4] : []);context.stroke(path);});@@ -1912,9 +2063,10 @@ export class ListMindmapView {const selected = this.selectedEdge === id;const hovered = this.hoveredLine === `edge:${id}`;const lineStyle = resolveLineStyle(lineStyles, style.lineColor || themeLineColor(id),- style.lineWidth, defaultLine, selected, hovered);+ style.lineWidth, defaultLine, selected, hovered, this.themeColors?.get(id)?.lineWidth);context.strokeStyle = lineStyle.color;context.lineWidth = lineStyle.width;+ context.globalAlpha = this.foldOpacities?.get(id) ?? 1;context.setLineDash(style.lineDash ? [6, 4] : []);context.stroke(path);});@@ -1922,6 +2074,9 @@ export class ListMindmapView {const from = this.positions.get(relation.from);const to = this.positions.get(relation.to);const element = this.relationElements.get(relation.id);+ const opacity = Math.min(this.foldOpacities?.get(relation.from) ?? 1, this.foldOpacities?.get(relation.to) ?? 1);+ element.style.opacity = this.foldOpacities ? String(opacity) : "";+ element.inert = !!(this.foldOpacities?.has(relation.from) || this.foldOpacities?.has(relation.to));element.hidden = !from || !to || !relation.label?.trim();if (!from || !to) {return;@@ -1948,6 +2103,7 @@ export class ListMindmapView {const baseWidth = lineStyle.baseWidth;context.strokeStyle = lineStyle.color;context.lineWidth = lineStyle.width;+ context.globalAlpha = opacity;const emphasis = Math.max(0, context.lineWidth - baseWidth);element.classList.toggle("mindmap-view__relation--hover", hovered);context.setLineDash(relation.dash === false ? [] : [5, 4]);@@ -1974,6 +2130,7 @@ export class ListMindmapView {element.style.top = `${labelPoint.y}px`;}});+ context.globalAlpha = 1;this.drawRelationPreview(context, resolveColor(relationStyles[0].color, primary), relationStyles[0].width || 1.5);this.drawSummaries(context, (color, selected, hovered) =>resolveLineStyle(summaryStyles, color, undefined, defaultLine, selected, hovered));@@ -2991,6 +3148,7 @@ export class ListMindmapView {}private wheel = (event: WheelEvent) => {+ this.stopFoldAnimation?.();if (this.locked || this.viewport.contains((event.target as HTMLElement).closest(".mindmap-view__node--editing"))) {return;}@@ -3105,6 +3263,7 @@ export class ListMindmapView {}public fit(maxScale = 1) {+ this.stopFoldAnimation?.();const width = this.viewport.clientWidth;const height = this.viewport.clientHeight;if (!this.positions.size || !width || !height) {@@ -3755,6 +3914,7 @@ export class ListMindmapView {}private enterFullscreen() {+ this.stopFoldAnimation?.();if (this.destroyed || this.fullscreenMarker) {return;}@@ -3787,6 +3947,7 @@ export class ListMindmapView {}private exitFullscreen() {+ this.stopFoldAnimation?.();if (!this.fullscreenMarker) {return;}@@ -3895,6 +4056,7 @@ export class ListMindmapView {return;}this.destroyed = true;+ this.stopFoldAnimation?.();cancelAnimationFrame(this.drawFrame);this.drawFrame = 0;clearTimeout(this.linkTimer);diff --git a/kernel/model/transaction_mindmap_appearance.go b/kernel/model/transaction_mindmap_appearance.goindex 9040b26216..14677834d0 100644--- a/kernel/model/transaction_mindmap_appearance.go+++ b/kernel/model/transaction_mindmap_appearance.go@@ -20,6 +20,15 @@ func validListMindmapAppearance(value any) bool {return false}}+ if value, exists := data["rootColor"]; exists {+ color, ok := value.(string)+ if !ok || !listMindmapColorPattern.MatchString(color) {+ return false+ }+ }+ if value, exists := data["nodeStyle"]; exists && value != "layered" {+ return false+ }if value, exists := data["backgroundColor"]; exists {color, ok := value.(string)if !ok || color != "" && !listMindmapColorPattern.MatchString(color) {diff --git a/kernel/model/transaction_mindmap_appearance_crypto_test.go b/kernel/model/transaction_mindmap_appearance_crypto_test.goindex 12b209deea..3505d19aec 100644--- a/kernel/model/transaction_mindmap_appearance_crypto_test.go+++ b/kernel/model/transaction_mindmap_appearance_crypto_test.go@@ -82,10 +82,14 @@ func TestListMindmapAppearanceEncrypted(t *testing.T) {}var data map[string]any_ = json.Unmarshal([]byte(original), &data)- data["appearance"] = map[string]any{"version": 1, "palette": []string{"#2563eb", "#15803d"}, "backgroundColor": "#1e1e1e"}+ appearance := map[string]any{"version": 1, "palette": []string{"#2563eb", "#15803d"}, "backgroundColor": "#1e1e1e"}+ data["appearance"] = appearance+ legacyStyled, _ := json.Marshal(data)+ appearance["rootColor"] = "#1e293b"+ appearance["nodeStyle"] = "layered"data["nodes"].(map[string]any)[ids[1]].(map[string]any)["branchColor"] = 0styled, _ := json.Marshal(data)- for _, value := range []string{string(styled), original, string(styled)} {+ for _, value := range []string{string(legacyStyled), string(styled), string(legacyStyled), original, string(styled)} {attrs, _ := json.Marshal(map[string]string{listMindmapMetadataAttr: value})tx := &Transaction{DoOperations: []*Operation{{Action: "setAttrs", ID: list.ID, Data: string(attrs)}}}if err = PerformTxSync(tx); err != nil {@@ -96,13 +100,13 @@ func TestListMindmapAppearanceEncrypted(t *testing.T) {t.Fatalf("appearance update or undo lost metadata: %v", readErr)}ciphertext, _ := os.ReadFile(filename)- if !util.IsCiphertext(ciphertext) || bytes.Contains(ciphertext, []byte("palette")) {+ if !util.IsCiphertext(ciphertext) || bytes.Contains(ciphertext, []byte("palette")) || bytes.Contains(ciphertext, []byte("rootColor")) {t.Fatal("appearance update wrote plaintext")}}relative, _ := filepath.Rel(util.WorkspaceDir, historyFile)_, _, content, _, err := GetDocHistoryContent(relative, "", false)- if err != nil || !strings.Contains(content, "Legacy summary") || strings.Contains(content, "#2563eb") {+ if err != nil || !strings.Contains(content, "Legacy summary") || strings.Contains(content, "#2563eb") || strings.Contains(content, "#1e293b") {t.Fatalf("legacy history cannot recover the original content: %v", err)}archivePath := exportSYZip(boxID, "/", "Appearance", []string{tree.Path}, false)@@ -121,6 +125,7 @@ func TestListMindmapAppearanceEncrypted(t *testing.T) {exported, err := io.ReadAll(reader)_ = reader.Close()if err != nil || !json.Valid(exported) || !bytes.Contains(exported, []byte("#2563eb")) ||+ !bytes.Contains(exported, []byte("#1e293b")) || !bytes.Contains(exported, []byte("layered")) ||!bytes.Contains(exported, []byte("Legacy summary")) {t.Fatalf("export lost the appearance or legacy content: %v", err)}diff --git a/kernel/model/transaction_mindmap_appearance_test.go b/kernel/model/transaction_mindmap_appearance_test.goindex 87881cf651..5f887f43c8 100644--- a/kernel/model/transaction_mindmap_appearance_test.go+++ b/kernel/model/transaction_mindmap_appearance_test.go@@ -8,40 +8,48 @@ import (func TestPruneListMindmapAppearance(t *testing.T) {for _, version := range []string{"1", "2"} {- _, list, _ := mindmapTestTree()- appearance := `{"version":1,"palette":["#123456","#abcdef"],"backgroundColor":"#ffffff","extension":9007199254740993}`- original := `{"version":` + version + `,"appearance":` + appearance +- `,"nodes":{"child":{"branchColor":2,"lineColor":"red"},"deleted":{}},"relations":[]}`- list.SetIALAttr(listMindmapMetadataAttr, original)- next, changed := pruneListMindmapMetadata(list)- if !changed || strings.Contains(next, "deleted") || !strings.Contains(next, appearance) ||- !strings.Contains(next, `"branchColor":2`) || !strings.Contains(next, `"lineColor":"red"`) {- t.Fatalf("appearance or manual colors were lost during pruning: %s", next)- }- list.SetIALAttr(listMindmapMetadataAttr, next)- if again, changed := pruneListMindmapMetadata(list); changed || again != next {- t.Fatal("appearance normalization is not idempotent")- }- for _, invalid := range []string{`null`, `[]`, `{}`, `{"version":2,"palette":[]}`,- `{"version":1,"palette":["red"]}`, `{"version":1,"palette":[],"backgroundColor":"url(x)"}`} {- data := strings.Replace(original, appearance, invalid, 1)- list.SetIALAttr(listMindmapMetadataAttr, data)- if next, changed := pruneListMindmapMetadata(list); changed || next != data {- t.Fatalf("invalid or newer appearance was changed: %s", next)+ for _, rootColor := range []string{"", `"rootColor":"#112233",`, `"rootColor":"#112233","nodeStyle":"layered",`} {+ _, list, _ := mindmapTestTree()+ appearance := `{"version":1,` + rootColor + `"palette":["#123456","#abcdef"],"backgroundColor":"#ffffff","extension":9007199254740993}`+ original := `{"version":` + version + `,"appearance":` + appearance ++ `,"nodes":{"child":{"branchColor":2,"lineColor":"red"},"deleted":{}},"relations":[]}`+ list.SetIALAttr(listMindmapMetadataAttr, original)+ next, changed := pruneListMindmapMetadata(list)+ if !changed || strings.Contains(next, "deleted") || !strings.Contains(next, appearance) ||+ !strings.Contains(next, `"branchColor":2`) || !strings.Contains(next, `"lineColor":"red"`) {+ t.Fatalf("appearance or manual colors were lost during pruning: %s", next)}- }- for _, slot := range []string{`-1`, `0.5`, `null`, `"1"`, `9007199254740992`} {- data := strings.Replace(original, `"branchColor":2`, `"branchColor":`+slot, 1)- list.SetIALAttr(listMindmapMetadataAttr, data)- if next, changed := pruneListMindmapMetadata(list); changed || next != data {- t.Fatalf("invalid branch color was changed: %s", next)+ list.SetIALAttr(listMindmapMetadataAttr, next)+ if again, changed := pruneListMindmapMetadata(list); changed || again != next {+ t.Fatal("appearance normalization is not idempotent")+ }+ for _, invalid := range []string{`null`, `[]`, `{}`, `{"version":2,"palette":[]}`,+ `{"version":1,"palette":["red"]}`, `{"version":1,"palette":[],"backgroundColor":"url(x)"}`,+ `{"version":1,"palette":[],"rootColor":null}`, `{"version":1,"palette":[],"rootColor":""}`,+ `{"version":1,"palette":[],"rootColor":"red"}`, `{"version":1,"palette":[],"rootColor":"url(x)"}`,+ `{"version":1,"palette":[],"rootColor":123}`, `{"version":1,"palette":[],"nodeStyle":null}`,+ `{"version":1,"palette":[],"nodeStyle":"unknown"}`, `{"version":1,"palette":[],"nodeStyle":[]}`} {+ data := strings.Replace(original, appearance, invalid, 1)+ list.SetIALAttr(listMindmapMetadataAttr, data)+ if next, changed := pruneListMindmapMetadata(list); changed || next != data {+ t.Fatalf("invalid or newer appearance was changed: %s", next)+ }+ }+ for _, slot := range []string{`-1`, `0.5`, `null`, `"1"`, `9007199254740992`} {+ data := strings.Replace(original, `"branchColor":2`, `"branchColor":`+slot, 1)+ list.SetIALAttr(listMindmapMetadataAttr, data)+ if next, changed := pruneListMindmapMetadata(list); changed || next != data {+ t.Fatalf("invalid branch color was changed: %s", next)+ }}}}}func TestValidListMindmapAppearance(t *testing.T) {- for _, source := range []string{`{"version":1,"palette":[]}`, `{"version":1,"palette":["#AbCdEf"],"backgroundColor":""}`} {+ for _, source := range []string{`{"version":1,"palette":[]}`, `{"version":1,"palette":["#AbCdEf"],"backgroundColor":""}`,+ `{"version":1,"palette":["#AbCdEf"],"rootColor":"#112233"}`, `{"version":1,"palette":[],"rootColor":"#AABBCC"}`,+ `{"version":1,"palette":["#AbCdEf"],"rootColor":"#112233","nodeStyle":"layered"}`} {var value any_ = json.Unmarshal([]byte(source), &value)if !validListMindmapAppearance(value) {