Skip to content

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

:art: Improve mind map palette and connector contrast https://github.com/siyuan-note/siyuan/issues/20800

Daniele95d4708b1d4
diff --git a/app/src/protyle/render/listMindmap/appearance.test.ts b/app/src/protyle/render/listMindmap/appearance.test.ts
index 2369d45fcb..8d4f730416 100644
--- a/app/src/protyle/render/listMindmap/appearance.test.ts
+++ b/app/src/protyle/render/listMindmap/appearance.test.ts
@@ -1,7 +1,7 @@
import * as assert from "node:assert/strict";
import test from "node:test";
import {assignListMindmapBranchColors, clearListMindmapManualColors, getListMindmapAppearanceMenu,
- getMindmapTextColor, isListMindmapAppearance, LIST_MINDMAP_PALETTES, resolveListMindmapColors} from "./appearance";
+ getMindmapLineColor, getMindmapTextColor, isListMindmapAppearance, LIST_MINDMAP_PALETTES, resolveListMindmapColors} from "./appearance";
import type {ListMindmapModel, ListMindmapNode} from "./model";
import {execFile} from "node:child_process";
import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
@@ -59,7 +59,11 @@ test("all seven built-in palettes remain selectable after reload and provide rea
assert.deepEqual(model.metadata.appearance.palette, preset.colors);
assert.equal(model.metadata.appearance.backgroundColor, "#ffffff");
assert.equal(model.metadata.nodes.a.textColor, "red");
- for (const color of preset.colors) {
+ for (const [index, color] of preset.colors.entries()) {
+ const lightFill = preset.id === "soft" ||
+ (["lavender", "monochrome"].includes(preset.id) && index >= 4);
+ assert.equal(getMindmapTextColor(color), lightFill ? "#000000" : "#ffffff",
+ `${preset.id} branch ${index + 1} retains its intended foreground`);
const foreground = luminance(getMindmapTextColor(color));
const background = luminance(color);
const contrast = (Math.max(foreground, background) + .05) / (Math.min(foreground, background) + .05);
@@ -68,6 +72,31 @@ test("all seven built-in palettes remain selectable after reload and provide rea
}
});
+for (const fixture of [
+ {id: "ocean", colors: ["#0c4a6e", "#0369a1", "#0284c7", "#0891b2", "#0d9488", "#0f766e"]},
+ {id: "sunset", colors: ["#9a3412", "#c2410c", "#ea580c", "#be123c", "#9f1239", "#7e22ce"]},
+ {id: "lavender", colors: ["#4c1d95", "#6d28d9", "#7c3aed", "#a855f7", "#c084fc", "#e9d5ff"]},
+]) {
+ test(`previous ${fixture.id} palettes retain saved colors and selection until explicitly reapplied`, () => {
+ const model = makeModel();
+ const preset = LIST_MINDMAP_PALETTES.find(preset => preset.id === fixture.id);
+ const previous = fixture.colors;
+ model.metadata.appearance = {version: 1, palette: previous, backgroundColor: "#ffffff"};
+ model.metadata.nodes.a = {branchColor: 2, textColor: "#ff0000"};
+ const before = JSON.stringify(model.metadata);
+ const menu = getListMindmapAppearanceMenu(model.metadata, update => update(model.metadata), {},
+ {id: "connectorStyle", label: "Connectors"});
+ const themes = (menu.submenu as IMenu[]).find(item => item.id === "theme").submenu as IMenu[];
+ assert.deepEqual(themes.filter(item => item.checked).map(item => item.id), [fixture.id]);
+ assert.equal(resolveListMindmapColors(model).get("a").backgroundColor, previous[2]);
+ 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.backgroundColor, "#ffffff");
+ assert.deepEqual(model.metadata.nodes.a, {branchColor: 2, textColor: "#ff0000"});
+ });
+}
+
test("branch identity survives reordering, theme changes, insertion, reparenting and serialized reload", () => {
const model = makeModel();
const before = JSON.stringify(model.metadata);
@@ -103,6 +132,32 @@ test("branch identity survives reordering, theme changes, insertion, reparenting
}
});
+test("theme lines contrast with every canvas preset while retaining sufficiently visible colors", () => {
+ const luminance = (color: string) => {
+ const linear = 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);
+ return linear.reduce((sum, channel, index) => sum + channel * [.2126, .7152, .0722][index], 0);
+ };
+ const contrast = (line: string, background: string) => {
+ const values = [luminance(line), luminance(background)];
+ return (Math.max(...values) + .05) / (Math.min(...values) + .05);
+ };
+ for (const background of ["#ffffff", "#1e1e1e", ...LIST_MINDMAP_PALETTES[1].colors]) {
+ for (const preset of LIST_MINDMAP_PALETTES) {
+ for (const color of preset.colors) {
+ const adjusted = getMindmapLineColor(color, background);
+ assert.ok(contrast(adjusted, background) >= 3, `${preset.id} ${color} on ${background}`);
+ if (contrast(color, background) >= 3) {
+ assert.equal(adjusted, color, "visible theme lines retain their original color");
+ }
+ }
+ }
+ }
+ assert.equal(getMindmapLineColor("#bfdbfe", "rgb(255, 255, 255)"), getMindmapLineColor("#bfdbfe", "#ffffff"));
+ assert.equal(getMindmapLineColor("#166534", "rgba(30, 30, 30, 1)"), getMindmapLineColor("#166534", "#1e1e1e"));
+ assert.equal(getMindmapLineColor("#166534", "rgba(0, 0, 0, 0)"), "#166534");
+});
+
test("appearance menu preserves manual colors and non-color metadata until explicit reset", () => {
const model = makeModel();
model.metadata.nodes.a = {textColor: "red", backgroundColor: "blue", lineColor: "green", bold: true};
@@ -135,7 +190,7 @@ test("appearance menu preserves manual colors and non-color metadata until expli
const contrastCases = (source: string, css: string) => {
const check = require("node:assert/strict");
const api = new Function("Constants", "mathRender", "tabsRender", "destroyTabsRender", source +
- "; return {ListMindmapView, readListMindmap, retagMindmapBranch};")({
+ "; return {ListMindmapView, readListMindmap, retagMindmapBranch, getMindmapLineColor, 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");
@@ -214,11 +269,43 @@ const contrastCases = (source: string, css: string) => {
check.equal(getComputedStyle(view.nodeElements.get(quoteNode.id).querySelector(".bq")).color,
computedColor(surface), "removing a palette restores the application quote color");
}
+ 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); };
+ // 固定几何位置,绘制断言不依赖隐藏窗口的动画帧调度。
+ 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}));
+ for (const preset of api.LIST_MINDMAP_PALETTES) {
+ for (const background of ["#ffffff", "#1e1e1e"]) {
+ for (const printLayout of [false, true]) {
+ view.options.printLayout = printLayout;
+ 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.nodes[quoteNode.id] = {lineColor: "#abcdef"};
+ const before = JSON.stringify(model.metadata);
+ view.update(model);
+ lines.length = 0;
+ view.draw();
+ 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.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");
+ }
+ }
+ }
+ }
+ context.stroke = stroke;
view.destroy();
return "mindmap-contrast-ok";
};
-test("palette quote text and placeholders stay readable while manual colors and legacy styles survive", {
+test("palette text and canvas connectors stay readable while manual colors and legacy styles survive", {
timeout: 20000,
skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
}, async () => {
@@ -237,12 +324,14 @@ test("palette quote text and placeholders stay readable while manual colors and
app.setPath("userData", ${JSON.stringify(path.join(dir, "profile"))});
app.commandLine.appendSwitch("disable-gpu");
app.whenReady().then(async () => {
- const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false,
+ backgroundThrottling: false}});
try {
await win.loadURL("data:text/html,<html><body></body></html>");
await win.webContents.executeJavaScript(require("fs").readFileSync(${JSON.stringify(path.resolve("stage/protyle/js/lute/lute.min.js"))}, "utf8"));
console.log(await win.webContents.executeJavaScript(${JSON.stringify(
- `const __name = value => value; (${contrastCases.toString()})(${JSON.stringify(source)}, ${JSON.stringify(css)})`)}));
+ `const __name = value => value; (async () => { try { return await (${contrastCases.toString()})` +
+ `(${JSON.stringify(source)}, ${JSON.stringify(css)}); } catch (error) { return error.stack; } })()`)}));
win.destroy(); app.exit(0);
} catch (error) { console.error(error); win.destroy(); app.exit(1); }
});`, "utf8");
diff --git a/app/src/protyle/render/listMindmap/appearance.ts b/app/src/protyle/render/listMindmap/appearance.ts
index c721c9b075..f5aff2f71f 100644
--- a/app/src/protyle/render/listMindmap/appearance.ts
+++ b/app/src/protyle/render/listMindmap/appearance.ts
@@ -6,13 +6,16 @@ export interface ListMindmapAppearance {
backgroundColor?: string;
}
-export const LIST_MINDMAP_PALETTES = [
+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", "#0284c7", "#0891b2", "#0d9488", "#0f766e"]},
- {id: "sunset", label: "listMindmapPaletteSunset", colors: ["#9a3412", "#c2410c", "#ea580c", "#be123c", "#9f1239", "#7e22ce"]},
- {id: "lavender", label: "listMindmapPaletteLavender", colors: ["#4c1d95", "#6d28d9", "#7c3aed", "#a855f7", "#c084fc", "#e9d5ff"]},
+ {id: "ocean", label: "listMindmapPaletteOcean", 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"],
+ previousColors: [["#9a3412", "#c2410c", "#ea580c", "#be123c", "#9f1239", "#7e22ce"]]},
+ {id: "lavender", label: "listMindmapPaletteLavender", 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"]},
];
@@ -52,13 +55,45 @@ export const assignListMindmapBranchColors = (model: ListMindmapModel) => {
return changed;
};
-// 文字颜色按实际填充色的相对亮度选择,浅色与深色画布使用同一份文档配色。
-export const getMindmapTextColor = (color: string) => {
+const getMindmapLuminance = (color: string) => {
const values = [1, 3, 5].map(index => {
const value = parseInt(color.slice(index, index + 2), 16) / 255;
return value <= .04045 ? value / 12.92 : Math.pow((value + .055) / 1.055, 2.4);
});
- return values[0] * .2126 + values[1] * .7152 + values[2] * .0722 > .179 ? "#000000" : "#ffffff";
+ return values[0] * .2126 + values[1] * .7152 + values[2] * .0722;
+};
+
+// 文字颜色按实际填充色的相对亮度选择,浅色与深色画布使用同一份文档配色。
+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 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) {
+ return color;
+ }
+ const target = luminance > .179 ? 0 : 255;
+ const channels = [1, 3, 5].map(index => parseInt(color.slice(index, index + 2), 16));
+ 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) {
+ return adjusted;
+ }
+ }
+ return color;
};
export const resolveListMindmapColors = (model: ListMindmapModel) => {
@@ -103,7 +138,8 @@ export const getListMindmapAppearanceMenu = (metadata: ListMindmapMetadata,
...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: JSON.stringify(palette) === JSON.stringify(preset.colors),
+ checked: [preset.colors, ...preset.previousColors || []]
+ .some(colors => JSON.stringify(palette) === JSON.stringify(colors)),
click: () => change(data => {
data.appearance = {...data.appearance, version: 1, palette: [...preset.colors]};
}),
diff --git a/app/src/protyle/render/listMindmap/arrows.test.ts b/app/src/protyle/render/listMindmap/arrows.test.ts
index 32d0a46d2b..cc743c5ce0 100644
--- a/app/src/protyle/render/listMindmap/arrows.test.ts
+++ b/app/src/protyle/render/listMindmap/arrows.test.ts
@@ -5,6 +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";
// 执行实际绘制和命中方法,画布替身仅记录路径与箭头,避免依赖图形显示环境。
const source = createSourceFile("view.ts", readFileSync("src/protyle/render/listMindmap/view.ts", "utf8"),
@@ -49,6 +50,7 @@ const setup = (arrowDirection?: ListMindmapRelation["arrowDirection"]) => {
};
const sandbox: any = {
buildListMindmapConnectors,
+ getMindmapLineColor,
Path2D: TestPath, window: {devicePixelRatio: 1},
// 绘制入口会取消上一帧的合并绘制请求,替身环境没有帧调度
cancelAnimationFrame: () => {}, requestAnimationFrame: () => 1,
diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.ts
index 0e0e980f04..5358991197 100644
--- a/app/src/protyle/render/listMindmap/view.ts
+++ b/app/src/protyle/render/listMindmap/view.ts
@@ -22,7 +22,7 @@ import {getListMindmapSummaryParentID, getListMindmapSummaryRange, getListMindma
layoutListMindmapSummaries} from "./summary";
import type {ListMindmapSummary, ListMindmapSummaryPosition, ListMindmapSummaryRange} from "./summary";
import {buildListMindmapConnectors, buildListMindmapSummaryConnector} from "./connectors";
-import {getMindmapTextColor, isMindmapColor, resolveListMindmapColors} from "./appearance";
+import {getMindmapLineColor, getMindmapTextColor, isMindmapColor, resolveListMindmapColors} from "./appearance";
export interface ListMindmapViewOptions {
host: HTMLElement;
@@ -1934,13 +1934,23 @@ export class ListMindmapView {
baseWidth,
};
};
+ const canvasColor = this.themeColors?.size ? resolveColor(this.model.metadata.appearance?.backgroundColor ||
+ theme.getPropertyValue("--b3-theme-background").trim(), "#ffffff") : "";
+ const paletteLines = new Map<string, string>();
+ const themeLineColor = (id: string) => {
+ const color = this.themeColors?.get(id)?.lineColor;
+ if (color && !paletteLines.has(color)) {
+ paletteLines.set(color, getMindmapLineColor(color, canvasColor));
+ }
+ return paletteLines.get(color);
+ };
const connectors = buildListMindmapConnectors(this.model.root.id, this.positions, this.edges,
this.model.metadata.connectorStyle || "bezier", () => new Path2D());
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 || this.themeColors?.get(id)?.lineColor,
+ const trunkStyle = resolveLineStyle(lineStyles, style.lineColor || themeLineColor(id),
style.lineWidth, defaultLine, false, false);
context.strokeStyle = trunkStyle.color;
context.lineWidth = trunkStyle.width;
@@ -1953,7 +1963,7 @@ export class ListMindmapView {
context.beginPath();
const selected = this.selectedEdge === id;
const hovered = this.hoveredLine === `edge:${id}`;
- const lineStyle = resolveLineStyle(lineStyles, style.lineColor || this.themeColors?.get(id)?.lineColor,
+ const lineStyle = resolveLineStyle(lineStyles, style.lineColor || themeLineColor(id),
style.lineWidth, defaultLine, selected, hovered);
context.strokeStyle = lineStyle.color;
context.lineWidth = lineStyle.width;