Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(mind-map): let the node panel set text, background and branch colors
Elian Dorandfb366611de8
diff --git a/apps/client/src/menus/custom-items/NoteColorPicker.spec.tsx b/apps/client/src/menus/custom-items/NoteColorPicker.spec.tsxindex 118553153f..8aa6d5aad6 100644--- a/apps/client/src/menus/custom-items/NoteColorPicker.spec.tsx+++ b/apps/client/src/menus/custom-items/NoteColorPicker.spec.tsx@@ -1,9 +1,9 @@-import { ComponentChild, render } from "preact";+import { render } from "preact";import { act } from "preact/test-utils";import { beforeEach, describe, expect, it, vi } from "vitest";-// `isMobile()` is read at render time inside CustomColorCell; mock the module so both the-// desktop (no handler) and mobile (stopPropagation) branches can be exercised.+// `isMobile()` is read at render time inside the picker's custom colour cell; mock the module so+// the note-bound tests don't depend on the device detection.const isMobileMock = vi.fn(() => false);vi.mock("../../services/utils", async (importOriginal) => ({...(await importOriginal<typeof import("../../services/utils")>()),@@ -22,21 +22,8 @@ vi.mock("../../services/attributes", () => ({import froca from "../../services/froca";import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";-import NoteColorPicker, { ColorPicker, DEFAULT_COLOR_PALETTE, tryParseColor } from "./NoteColorPicker";--/**- * Mounts a `ColorPicker` inside `act()` so the mount effects run — in particular the one that- * constructs the `Debouncer` behind the native colour input. Rendering outside `act()` leaves that- * effect pending, and input changes are then silently dropped.- */-async function renderColorPicker(vnode: ComponentChild) {- let container: HTMLElement | undefined;- await act(async () => {- container = renderInto(vnode);- });- if (!container) throw new Error("render produced no container");- return container;-}+import { DEFAULT_COLOR_PALETTE } from "../../widgets/react/ColorPicker";+import NoteColorPicker from "./NoteColorPicker";/** Renders and lets the mount effects (froca lookup, colour sync) settle. */async function renderNotePicker(note: Parameters<typeof NoteColorPicker>[0]["note"]) {@@ -48,6 +35,12 @@ async function renderNotePicker(note: Parameters<typeof NoteColorPicker>[0]["not// flushed within this same act() block.await new Promise((resolve) => setTimeout(resolve, 0));});+ // act() only flushes the mount effect on its way out, so a lookup that resolves after that+ // point updates the state too late for the block above. Give it a second flush, otherwise+ // whether the picker is settled depends on how warm the module graph happens to be.+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ });if (!container) throw new Error("render produced no container");return container;}@@ -65,196 +58,6 @@ function resetCell(container: HTMLElement) {return container.querySelector<HTMLElement>(".color-cell-reset");}-function customCell(container: HTMLElement) {- return container.querySelector<HTMLElement>(".custom-color-cell");-}--describe("tryParseColor", () => {- it("parses valid colors and returns null for invalid input", () => {- expect(tryParseColor("#ff0000")?.hex().toLowerCase()).toBe("#ff0000");- expect(tryParseColor("red")?.hex().toLowerCase()).toBe("#ff0000");-- // The invalid branch logs via console.error; silence it so the run stays clean.- const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});- expect(tryParseColor("definitely-not-a-color")).toBeNull();- expect(consoleError).toHaveBeenCalled();- consoleError.mockRestore();- });-});--describe("ColorPicker", () => {- beforeEach(() => {- vi.clearAllMocks();- isMobileMock.mockReturnValue(false);- });-- it("renders a reset cell, one cell per preset and a custom cell", () => {- const container = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);-- expect(container.querySelector(".note-color-picker")).not.toBeNull();- expect(resetCell(container)).not.toBeNull();- expect(customCell(container)).not.toBeNull();- expect(presetCells(container)).toHaveLength(DEFAULT_COLOR_PALETTE.length);- // Each preset drives its swatch colour through the `--color` custom property.- expect(presetCells(container)[0].getAttribute("style")).toContain(DEFAULT_COLOR_PALETTE[0]);- });-- it("accepts a custom preset list and an extra class name", () => {- const container = renderInto(- <ColorPicker currentValue={null} onChange={vi.fn()} presets={["#111111", "#222222"]} className="extra" />);-- expect(container.querySelector(".note-color-picker")?.classList.contains("extra")).toBe(true);- expect(presetCells(container)).toHaveLength(2);- });-- it("marks the reset cell selected when there is no colour", () => {- const container = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);-- expect(resetCell(container)?.classList.contains("selected")).toBe(true);- expect(presetCells(container).some((cell) => cell.classList.contains("selected"))).toBe(false);- });-- it("marks the matching preset selected, normalising the incoming colour", () => {- // Given in a different notation and casing than the palette entry it must match.- const container = renderInto(<ColorPicker currentValue="RGB(230, 77, 77)" onChange={vi.fn()} />);-- const selected = presetCells(container).filter((cell) => cell.classList.contains("selected"));- expect(selected).toHaveLength(1);- expect(selected[0].getAttribute("style")).toContain(DEFAULT_COLOR_PALETTE[0]);- expect(resetCell(container)?.classList.contains("selected")).toBe(false);- // A colour that is in the palette is not "custom".- expect(customCell(container)?.classList.contains("selected")).toBe(false);- });-- it("marks the custom cell selected for a colour outside the palette", () => {- const container = renderInto(<ColorPicker currentValue="#123456" onChange={vi.fn()} />);-- expect(customCell(container)?.classList.contains("selected")).toBe(true);- expect(presetCells(container).some((cell) => cell.classList.contains("selected"))).toBe(false);- });-- it("treats an unparseable current value as no colour", () => {- const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});- const container = renderInto(<ColorPicker currentValue="not-a-color" onChange={vi.fn()} />);- consoleError.mockRestore();-- expect(resetCell(container)?.classList.contains("selected")).toBe(true);- });-- it("reports the picked preset colour and null when cleared", () => {- const onChange = vi.fn();- const container = renderInto(<ColorPicker currentValue={null} onChange={onChange} />);-- presetCells(container)[2].click();- expect(onChange).toHaveBeenLastCalledWith(DEFAULT_COLOR_PALETTE[2]);-- resetCell(container)?.click();- expect(onChange).toHaveBeenLastCalledWith(null);- });-- it("marks cells disabled and swallows clicks when disabled", () => {- const onChange = vi.fn();- const container = renderInto(<ColorPicker currentValue={null} onChange={onChange} disabled />);-- expect(cells(container).every((cell) => cell.classList.contains("disabled-color-cell"))).toBe(true);- expect(container.querySelector<HTMLInputElement>("input[type=color]")?.disabled).toBe(true);-- presetCells(container)[0].click();- resetCell(container)?.click();- expect(onChange).not.toHaveBeenCalled();- });-- it("debounces the native colour input and reports the picked value once", async () => {- vi.useFakeTimers();- try {- const onChange = vi.fn();- const container = await renderColorPicker(<ColorPicker currentValue={null} onChange={onChange} />);- const input = container.querySelector<HTMLInputElement>("input[type=color]");- expect(input).not.toBeNull();- if (!input) return;-- // Two rapid changes within the debounce interval collapse into a single report.- await act(async () => {- input.value = "#aabbcc";- input.dispatchEvent(new Event("change", { bubbles: true }));- input.value = "#ddeeff";- input.dispatchEvent(new Event("change", { bubbles: true }));- });- expect(onChange).not.toHaveBeenCalled();-- await act(async () => { vi.advanceTimersByTime(250); });- expect(onChange).toHaveBeenCalledTimes(1);- expect(onChange).toHaveBeenCalledWith("#ddeeff");- } finally {- vi.useRealTimers();- }- });-- it("re-reports the already picked custom colour when the custom cell is clicked again", async () => {- vi.useFakeTimers();- try {- const onChange = vi.fn();- const container = await renderColorPicker(<ColorPicker currentValue={null} onChange={onChange} />);- const input = container.querySelector<HTMLInputElement>("input[type=color]");- if (!input) return;-- await act(async () => {- input.value = "#aabbcc";- input.dispatchEvent(new Event("change", { bubbles: true }));- });- await act(async () => { vi.advanceTimersByTime(250); });- onChange.mockClear();-- // The cell's handler re-opens the native picker via `input.click()`. Under happy-dom- // that click bubbles back up to the same cell and recurses, so stub it out — the- // behaviour under test is the re-emission, not the native dialog.- const nativeClick = vi.spyOn(input, "click").mockImplementation(() => {});-- // Clicking the cell after a colour was picked re-emits it (rather than only- // re-opening the native picker).- await act(async () => { customCell(container)?.click(); });- expect(onChange).toHaveBeenCalledWith("#aabbcc");- expect(nativeClick).toHaveBeenCalled();- } finally {- vi.useRealTimers();- }- });-- it("stops click propagation on the custom cell only on mobile", () => {- isMobileMock.mockReturnValue(true);- const mobileContainer = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);- const mobileWrapper = mobileContainer.querySelector(".custom-color-cell")?.parentElement;- const mobileEvent = new MouseEvent("click", { bubbles: true, cancelable: true });- const mobileStop = vi.spyOn(mobileEvent, "stopPropagation");- mobileWrapper?.dispatchEvent(mobileEvent);- expect(mobileStop).toHaveBeenCalled();-- isMobileMock.mockReturnValue(false);- const desktopContainer = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);- const desktopWrapper = desktopContainer.querySelector(".custom-color-cell")?.parentElement;- const desktopEvent = new MouseEvent("click", { bubbles: true, cancelable: true });- const desktopStop = vi.spyOn(desktopEvent, "stopPropagation");- desktopWrapper?.dispatchEvent(desktopEvent);- expect(desktopStop).not.toHaveBeenCalled();- });-- it("derives a contrasting foreground for light and dark custom colours", () => {- // Light background -> black foreground; dark background -> white.- const light = renderInto(<ColorPicker currentValue="#eeeeee" onChange={vi.fn()} />);- const lightWrapper = light.querySelector(".custom-color-cell")?.parentElement;- expect(lightWrapper?.getAttribute("style")?.toLowerCase()).toContain("#000000");-- const dark = renderInto(<ColorPicker currentValue="#111111" onChange={vi.fn()} />);- const darkWrapper = dark.querySelector(".custom-color-cell")?.parentElement;- expect(darkWrapper?.getAttribute("style")?.toLowerCase()).toContain("#ffffff");-- // No colour at all falls back to `inherit`.- const none = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);- const noneWrapper = none.querySelector(".custom-color-cell")?.parentElement;- expect(noneWrapper?.getAttribute("style")).toContain("inherit");- });-});-describe("NoteColorPicker", () => {beforeEach(() => {vi.clearAllMocks();@@ -265,6 +68,12 @@ describe("NoteColorPicker", () => {expect(renderInto(<NoteColorPicker note={null} />).innerHTML).toBe("");});+ it("keeps the class the themes style the context-menu picker with", async () => {+ const container = await renderNotePicker(buildNote({ title: "Classy" }));++ expect(container.querySelector(".color-picker.note-color-picker")).not.toBeNull();+ });+it("renders the note's current colour as the selected preset", async () => {const note = buildNote({ title: "Coloured", "#color": DEFAULT_COLOR_PALETTE[1] });@@ -319,17 +128,20 @@ describe("NoteColorPicker", () => {await act(async () => {container = renderInto(<NoteColorPicker note={null} />);});- expect(container!.innerHTML).toBe("");+ expect(container?.innerHTML).toBe("");// Re-render into the same container so Preact updates the existing component instance// (a fresh `renderInto` would mount a brand new one and hide the bug).await act(async () => {- render(<NoteColorPicker note={note} />, container!);+ if (container) {+ render(<NoteColorPicker note={note} />, container);+ }await new Promise((resolve) => setTimeout(resolve, 0));});+ if (!container) throw new Error("render produced no container");- expect(cells(container!).some((cell) => cell.classList.contains("disabled-color-cell"))).toBe(false);- const selected = presetCells(container!).filter((cell) => cell.classList.contains("selected"));+ expect(cells(container).some((cell) => cell.classList.contains("disabled-color-cell"))).toBe(false);+ const selected = presetCells(container).filter((cell) => cell.classList.contains("selected"));expect(selected).toHaveLength(1);expect(selected[0].getAttribute("style")).toContain(DEFAULT_COLOR_PALETTE[2]);});diff --git a/apps/client/src/menus/custom-items/NoteColorPicker.tsx b/apps/client/src/menus/custom-items/NoteColorPicker.tsxindex 50298ec69b..472821130b 100644--- a/apps/client/src/menus/custom-items/NoteColorPicker.tsx+++ b/apps/client/src/menus/custom-items/NoteColorPicker.tsx@@ -1,16 +1,10 @@-import "./NoteColorPicker.css";--import clsx from "clsx";-import Color, { ColorInstance } from "color";-import { ComponentChildren } from "preact";-import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useCallback, useEffect, useState } from "preact/hooks";import FNote from "../../entities/fnote";import attributes from "../../services/attributes";import froca from "../../services/froca";import { t } from "../../services/i18n";-import { isMobile } from "../../services/utils";-import Debouncer from "../../utils/debouncer";+import ColorPicker from "../../widgets/react/ColorPicker";export interface NoteColorPickerProps {/** The target Note instance or its ID string. */@@ -59,172 +53,13 @@ export default function NoteColorPicker(props: NoteColorPickerProps) {if (!props.note) return null;return <ColorPicker+ className="note-color-picker"currentValue={currentColor}onChange={onChange}- disabled={note === null} />;-}--/** Curated default preset palette, using Trilium note-color-friendly CSS colors. */-export const DEFAULT_COLOR_PALETTE = [- "#e64d4d", "#e6994d", "#e5e64d", "#99e64d", "#4de64d", "#4de699",- "#4de5e6", "#4d99e6", "#4d4de6", "#994de6", "#e64db3"-];--export interface ColorPickerProps {- /** The current CSS color (e.g. `#ff8800`). `null` means "no color". */- currentValue: string | null;- /** Called with the newly picked color, or `null` when the color is cleared. */- onChange(newValue: string | null): void;- /** Preset swatches shown in the row. Defaults to a curated palette. */- presets?: string[];- disabled?: boolean;- className?: string;-}--/**- * A row of preset color swatches plus a "clear" cell and a custom cell backed by the browser's- * native `<input type="color">`.- *- * This is a controlled component: it renders `currentValue` and reports picks through `onChange`- * (`onChange(null)` clears). It has no knowledge of notes or attributes — for the note-bound- * variant that reads and writes the `color` label, see {@link NoteColorPicker}.- */-export function ColorPicker({ currentValue, onChange, presets = DEFAULT_COLOR_PALETTE, disabled, className }: ColorPickerProps) {- const normalizedValue = currentValue ? tryParseColor(currentValue)?.hex().toLowerCase() ?? null : null;- const isCustomColor = normalizedValue !== null && presets.indexOf(normalizedValue) === -1;-- return <div className={clsx("note-color-picker", className)}>-- <ColorCell className="color-cell-reset"- tooltip={t("note-color.clear-color")}- color={null}- isSelected={(normalizedValue === null)}- isDisabled={disabled}- onSelect={onChange}>-- {/* https://pictogrammers.com/library/mdi/icon/close/ */}- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">- <path d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" />- </svg>- </ColorCell>--- {presets.map((color) => (- <ColorCell key={color}- tooltip={t("note-color.set-color")}- color={color}- isSelected={(color === normalizedValue)}- isDisabled={disabled}- onSelect={onChange} />- ))}-- <CustomColorCell tooltip={t("note-color.set-custom-color")}- color={normalizedValue}- isSelected={isCustomColor}- isDisabled={disabled}- onSelect={onChange} />- </div>;-}--interface ColorCellProps {- children?: ComponentChildren,- className?: string,- tooltip?: string,- color: string | null,- isSelected: boolean,- isDisabled?: boolean,- onSelect?: (color: string | null) => void-}--function ColorCell(props: ColorCellProps) {- return <div className={clsx(props.className, {- "color-cell": true,- "selected": props.isSelected,- "disabled-color-cell": props.isDisabled- })}- style={`${(props.color !== null) ? `--color: ${props.color}` : ""}`}- title={props.tooltip}- onClick={() => !props.isDisabled && props.onSelect?.(props.color)}>- {props.children}- </div>;-}--function CustomColorCell(props: ColorCellProps) {- const [pickedColor, setPickedColor] = useState<string | null>(null);- const colorInput = useRef<HTMLInputElement>(null);- const colorInputDebouncer = useRef<Debouncer<string | null> | null>(null);- const callbackRef = useRef(props.onSelect);-- useEffect(() => {- colorInputDebouncer.current = new Debouncer(250, (color) => {- callbackRef.current?.(color);- setPickedColor(color);- });-- return () => {- colorInputDebouncer.current?.destroy();- };- }, []);-- useEffect(() => {- if (props.isSelected && pickedColor === null) {- setPickedColor(props.color);- }- }, [props.isSelected]);-- useEffect(() => {- callbackRef.current = props.onSelect;- }, [props.onSelect]);-- const onSelect = useCallback(() => {- if (pickedColor !== null) {- callbackRef.current?.(pickedColor);- }-- colorInput.current?.click();- }, [pickedColor]);-- return <div style={`--foreground: ${getForegroundColor(props.color)};`}- onClick={isMobile() ? (e) => {- // The color picker dropdown will close on some browser if the parent context menu is- // dismissed, so stop the click propagation to prevent dismissing the menu.- e.stopPropagation();- } : undefined}>- <ColorCell {...props}- color={pickedColor}- className={clsx("custom-color-cell", {- "custom-color-cell-empty": (pickedColor === null)- })}- onSelect={onSelect}>-- <input ref={colorInput}- type="color"- disabled={props.isDisabled}- value={pickedColor ?? props.color ?? "#40bfbf"}- onChange={() => {colorInputDebouncer.current?.updateValue(colorInput.current?.value ?? null);}}- style="width: 0; height: 0; opacity: 0" />- </ColorCell>- </div>;-}--function getForegroundColor(backgroundColor: string | null) {- if (backgroundColor === null) return "inherit";-- const colorHsl = tryParseColor(backgroundColor)?.hsl();- if (colorHsl) {- const l = colorHsl.lightness();- return colorHsl.saturationl(0).lightness(l >= 50 ? 0 : 100).hex();- }- return "inherit";--}--export function tryParseColor(colorStr: string): ColorInstance | null {- try {- return new Color(colorStr);- } catch(ex) {- console.error(ex);- }-- return null;+ disabled={note === null}+ tooltips={{+ clear: t("note-color.clear-color"),+ set: t("note-color.set-color"),+ setCustom: t("note-color.set-custom-color")+ }} />;}diff --git a/apps/client/src/services/frontend_script_api_preact.ts b/apps/client/src/services/frontend_script_api_preact.tsindex bee0660b2a..de0f711251 100644--- a/apps/client/src/services/frontend_script_api_preact.ts+++ b/apps/client/src/services/frontend_script_api_preact.ts@@ -1,7 +1,7 @@import { createContext, Fragment, h, VNode } from "preact";import * as hooks from "preact/hooks";-import NoteColorPicker, { ColorPicker } from "../menus/custom-items/NoteColorPicker";+import NoteColorPicker from "../menus/custom-items/NoteColorPicker";import Calendar from "../widgets/collections/calendar/calendar";import Table from "../widgets/collections/table/tabulator";import ActionButton from "../widgets/react/ActionButton";@@ -9,6 +9,7 @@ import Admonition from "../widgets/react/Admonition";import Button from "../widgets/react/Button";import CKEditor from "../widgets/react/CKEditor";import Collapsible, { ExternallyControlledCollapsible } from "../widgets/react/Collapsible";+import ColorPicker from "../widgets/react/ColorPicker";import Dropdown from "../widgets/react/Dropdown";import FormCheckbox from "../widgets/react/FormCheckbox";import FormDropdownList from "../widgets/react/FormDropdownList";diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 3f5c2969b5..1b50a6e7d7 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3199,6 +3199,11 @@"set-color": "Set note color","set-custom-color": "Set custom note color"},+ "color-picker": {+ "clear-color": "Clear color",+ "set-color": "Set color",+ "set-custom-color": "Set custom color"+ },"popup-editor": {"maximize": "Switch to full editor","attachment_title": "Attachment: {{title}}"@@ -3517,7 +3522,10 @@"link": "Link","linkBidirectional": "Bidirectional Link","clickTips": "Please click the target node",- "summary": "Summary"+ "summary": "Summary",+ "text-color": "Text",+ "background-color": "Background",+ "branch-color": "Branch"},"llm": {"disabled_placeholder": "AI features are turned off. Enable them to configure providers and MCP.",diff --git a/apps/client/src/widgets/PromotedAttributes.spec.tsx b/apps/client/src/widgets/PromotedAttributes.spec.tsxindex a94afbf690..01e91d9891 100644--- a/apps/client/src/widgets/PromotedAttributes.spec.tsx+++ b/apps/client/src/widgets/PromotedAttributes.spec.tsx@@ -438,7 +438,7 @@ describe("PromotedAttributesContent rendering", () => {buildCell(note, { definition: { labelType: "color" }, value: "#123456" })]);- expect(container.querySelector(".note-color-picker")).not.toBeNull();+ expect(container.querySelector(".color-picker")).not.toBeNull();// The raw input is kept but hidden, the picker drives the value.expect(container.querySelector("input.promoted-attribute-input")?.getAttribute("type")).toBe("hidden");});diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsxindex b42766f8b7..a161e3987e 100644--- a/apps/client/src/widgets/PromotedAttributes.tsx+++ b/apps/client/src/widgets/PromotedAttributes.tsx@@ -8,7 +8,6 @@ import { Dispatch, StateUpdater, useCallback, useEffect, useState } from "preactimport NoteContext from "../components/note_context";import FAttribute from "../entities/fattribute";import FNote from "../entities/fnote";-import { ColorPicker } from "../menus/custom-items/NoteColorPicker";import { Attribute } from "../services/attribute_parser";import attributes from "../services/attributes";import { t } from "../services/i18n";@@ -18,6 +17,7 @@ import ws from "../services/ws";import LabelValueInput from "./attribute_widgets/label_value_input";import MultiValueInput from "./attribute_widgets/multi_value_input";import RelationValuesInput from "./attribute_widgets/relation_values_input";+import ColorPicker from "./react/ColorPicker";import { useNoteContext, useNoteLabel, useTriliumEvent, useUniqueName } from "./react/hooks";import NoteAutocomplete from "./react/NoteAutocomplete";diff --git a/apps/client/src/menus/custom-items/NoteColorPicker.css b/apps/client/src/widgets/react/ColorPicker.csssimilarity index 74%rename from apps/client/src/menus/custom-items/NoteColorPicker.cssrename to apps/client/src/widgets/react/ColorPicker.cssindex a208370e21..08cfe9a341 100644--- a/apps/client/src/menus/custom-items/NoteColorPicker.css+++ b/apps/client/src/widgets/react/ColorPicker.css@@ -1,16 +1,20 @@+/*+ * The `--note-color-picker-*` names predate the picker becoming generic; they are kept because the+ * themes override them for the picker embedded in the note context menu.+ */:root {--note-color-picker-clear-color-cell-background: var(--primary-button-background-color);--note-color-picker-clear-color-cell-color: var(--main-background-color);--note-color-picker-clear-color-cell-selection-outline-color: var(--primary-button-border-color);}-.note-color-picker {+.color-picker {display: flex;gap: 8px;justify-content: space-between;}-.note-color-picker .color-cell {+.color-picker .color-cell {--color-picker-cell-size: 14px;width: var(--color-picker-cell-size);@@ -19,15 +23,15 @@background-color: var(--color);}-.note-color-picker .color-cell:not(.selected):hover {+.color-picker .color-cell:not(.selected):hover {transform: scale(1.2);}-.note-color-picker .color-cell.disabled-color-cell {+.color-picker .color-cell.disabled-color-cell {cursor: not-allowed;}-.note-color-picker .color-cell.selected {+.color-picker .color-cell.selected {outline: 2px solid var(--outline-color, var(--color));outline-offset: 2px;}@@ -36,7 +40,7 @@* RESET COLOR CELL*/-.note-color-picker .color-cell-reset {+.color-picker .color-cell-reset {--color: var(--note-color-picker-clear-color-cell-background);--outline-color: var(--note-color-picker-clear-color-cell-selection-outline-color);@@ -46,7 +50,7 @@align-items: center;}-.note-color-picker .color-cell-reset svg {+.color-picker .color-cell-reset svg {width: var(--color-picker-cell-size);height: var(--color-picker-cell-size);fill: var(--note-color-picker-clear-color-cell-color);@@ -56,7 +60,7 @@* CUSTOM COLOR CELL*/- .note-color-picker .custom-color-cell::before {+ .color-picker .custom-color-cell::before {position: absolute;content: "\ed35";display: flex;@@ -72,14 +76,14 @@color: var(--foreground);}-.note-color-picker .custom-color-cell {+.color-picker .custom-color-cell {position: relative;display: flex;justify-content: center;overflow: hidden;}-.note-color-picker .custom-color-cell.custom-color-cell-empty {+.color-picker .custom-color-cell.custom-color-cell-empty {background-image: url(./custom-color.png);background-size: cover;--foreground: transparent;diff --git a/apps/client/src/widgets/react/ColorPicker.spec.tsx b/apps/client/src/widgets/react/ColorPicker.spec.tsxnew file mode 100644index 0000000000..677fd0ab78--- /dev/null+++ b/apps/client/src/widgets/react/ColorPicker.spec.tsx@@ -0,0 +1,257 @@+import { ComponentChild } from "preact";+import { act } from "preact/test-utils";+import { beforeEach, describe, expect, it, vi } from "vitest";++// `isMobile()` is read at render time inside CustomColorCell; mock the module so both the+// desktop (no handler) and mobile (stopPropagation) branches can be exercised.+const isMobileMock = vi.fn(() => false);+vi.mock("../../services/utils", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../services/utils")>()),+ isMobile: () => isMobileMock()+}));++import { renderInto } from "../../test/render";+import ColorPicker, { DEFAULT_COLOR_PALETTE, tryParseColor } from "./ColorPicker";++/**+ * Mounts a `ColorPicker` inside `act()` so the mount effects run — in particular the one that+ * constructs the `Debouncer` behind the native colour input. Rendering outside `act()` leaves that+ * effect pending, and input changes are then silently dropped.+ */+async function renderColorPicker(vnode: ComponentChild) {+ let container: HTMLElement | undefined;+ await act(async () => {+ container = renderInto(vnode);+ });+ if (!container) throw new Error("render produced no container");+ return container;+}++function cells(container: HTMLElement) {+ return Array.from(container.querySelectorAll<HTMLElement>(".color-cell"));+}++function presetCells(container: HTMLElement) {+ return cells(container).filter((cell) =>+ !cell.classList.contains("color-cell-reset") && !cell.classList.contains("custom-color-cell"));+}++function resetCell(container: HTMLElement) {+ return container.querySelector<HTMLElement>(".color-cell-reset");+}++function customCell(container: HTMLElement) {+ return container.querySelector<HTMLElement>(".custom-color-cell");+}++describe("tryParseColor", () => {+ it("parses valid colors and returns null for invalid input", () => {+ expect(tryParseColor("#ff0000")?.hex().toLowerCase()).toBe("#ff0000");+ expect(tryParseColor("red")?.hex().toLowerCase()).toBe("#ff0000");++ // The invalid branch logs via console.error; silence it so the run stays clean.+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ expect(tryParseColor("definitely-not-a-color")).toBeNull();+ expect(consoleError).toHaveBeenCalled();+ consoleError.mockRestore();+ });+});++describe("ColorPicker", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ isMobileMock.mockReturnValue(false);+ });++ it("renders a reset cell, one cell per preset and a custom cell", () => {+ const container = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);++ expect(container.querySelector(".color-picker")).not.toBeNull();+ expect(resetCell(container)).not.toBeNull();+ expect(customCell(container)).not.toBeNull();+ expect(presetCells(container)).toHaveLength(DEFAULT_COLOR_PALETTE.length);+ // Each preset drives its swatch colour through the `--color` custom property.+ expect(presetCells(container)[0].getAttribute("style")).toContain(DEFAULT_COLOR_PALETTE[0]);+ });++ it("accepts a custom preset list and an extra class name", () => {+ const container = renderInto(+ <ColorPicker currentValue={null} onChange={vi.fn()} presets={["#111111", "#222222"]} className="extra" />);++ expect(container.querySelector(".color-picker")?.classList.contains("extra")).toBe(true);+ expect(presetCells(container)).toHaveLength(2);+ });++ it("marks the reset cell selected when there is no colour", () => {+ const container = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);++ expect(resetCell(container)?.classList.contains("selected")).toBe(true);+ expect(presetCells(container).some((cell) => cell.classList.contains("selected"))).toBe(false);+ });++ it("marks the matching preset selected, normalising the incoming colour", () => {+ // Given in a different notation and casing than the palette entry it must match.+ const container = renderInto(<ColorPicker currentValue="RGB(230, 77, 77)" onChange={vi.fn()} />);++ const selected = presetCells(container).filter((cell) => cell.classList.contains("selected"));+ expect(selected).toHaveLength(1);+ expect(selected[0].getAttribute("style")).toContain(DEFAULT_COLOR_PALETTE[0]);+ expect(resetCell(container)?.classList.contains("selected")).toBe(false);+ // A colour that is in the palette is not "custom".+ expect(customCell(container)?.classList.contains("selected")).toBe(false);+ });++ it("marks the custom cell selected for a colour outside the palette", () => {+ const container = renderInto(<ColorPicker currentValue="#123456" onChange={vi.fn()} />);++ expect(customCell(container)?.classList.contains("selected")).toBe(true);+ expect(presetCells(container).some((cell) => cell.classList.contains("selected"))).toBe(false);+ });++ it("treats an unparseable current value as no colour", () => {+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ const container = renderInto(<ColorPicker currentValue="not-a-color" onChange={vi.fn()} />);+ consoleError.mockRestore();++ expect(resetCell(container)?.classList.contains("selected")).toBe(true);+ });++ it("selects nothing at all when indeterminate, but still reports picks", () => {+ // Several targets that disagree: neither the matching preset, the reset cell nor the custom+ // cell may claim to hold the answer.+ const onChange = vi.fn();+ const inPalette = renderInto(<ColorPicker currentValue={DEFAULT_COLOR_PALETTE[0]} onChange={onChange} indeterminate />);+ expect(cells(inPalette).some((cell) => cell.classList.contains("selected"))).toBe(false);++ const outsidePalette = renderInto(<ColorPicker currentValue="#123456" onChange={onChange} indeterminate />);+ expect(cells(outsidePalette).some((cell) => cell.classList.contains("selected"))).toBe(false);++ const unset = renderInto(<ColorPicker currentValue={null} onChange={onChange} indeterminate />);+ expect(cells(unset).some((cell) => cell.classList.contains("selected"))).toBe(false);++ presetCells(unset)[1].click();+ expect(onChange).toHaveBeenCalledWith(DEFAULT_COLOR_PALETTE[1]);+ });++ it("uses the caller's tooltips when given", () => {+ const container = renderInto(+ <ColorPicker currentValue={null} onChange={vi.fn()} tooltips={{ clear: "Wipe it", set: "Paint it", setCustom: "Pick it" }} />);++ expect(resetCell(container)?.title).toBe("Wipe it");+ expect(presetCells(container)[0].title).toBe("Paint it");+ expect(customCell(container)?.title).toBe("Pick it");+ });++ it("reports the picked preset colour and null when cleared", () => {+ const onChange = vi.fn();+ const container = renderInto(<ColorPicker currentValue={null} onChange={onChange} />);++ presetCells(container)[2].click();+ expect(onChange).toHaveBeenLastCalledWith(DEFAULT_COLOR_PALETTE[2]);++ resetCell(container)?.click();+ expect(onChange).toHaveBeenLastCalledWith(null);+ });++ it("marks cells disabled and swallows clicks when disabled", () => {+ const onChange = vi.fn();+ const container = renderInto(<ColorPicker currentValue={null} onChange={onChange} disabled />);++ expect(cells(container).every((cell) => cell.classList.contains("disabled-color-cell"))).toBe(true);+ expect(container.querySelector<HTMLInputElement>("input[type=color]")?.disabled).toBe(true);++ presetCells(container)[0].click();+ resetCell(container)?.click();+ expect(onChange).not.toHaveBeenCalled();+ });++ it("debounces the native colour input and reports the picked value once", async () => {+ vi.useFakeTimers();+ try {+ const onChange = vi.fn();+ const container = await renderColorPicker(<ColorPicker currentValue={null} onChange={onChange} />);+ const input = container.querySelector<HTMLInputElement>("input[type=color]");+ expect(input).not.toBeNull();+ if (!input) return;++ // Two rapid changes within the debounce interval collapse into a single report.+ await act(async () => {+ input.value = "#aabbcc";+ input.dispatchEvent(new Event("change", { bubbles: true }));+ input.value = "#ddeeff";+ input.dispatchEvent(new Event("change", { bubbles: true }));+ });+ expect(onChange).not.toHaveBeenCalled();++ await act(async () => { vi.advanceTimersByTime(250); });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith("#ddeeff");+ } finally {+ vi.useRealTimers();+ }+ });++ it("re-reports the already picked custom colour when the custom cell is clicked again", async () => {+ vi.useFakeTimers();+ try {+ const onChange = vi.fn();+ const container = await renderColorPicker(<ColorPicker currentValue={null} onChange={onChange} />);+ const input = container.querySelector<HTMLInputElement>("input[type=color]");+ if (!input) return;++ await act(async () => {+ input.value = "#aabbcc";+ input.dispatchEvent(new Event("change", { bubbles: true }));+ });+ await act(async () => { vi.advanceTimersByTime(250); });+ onChange.mockClear();++ // The cell's handler re-opens the native picker via `input.click()`. Under happy-dom+ // that click bubbles back up to the same cell and recurses, so stub it out — the+ // behaviour under test is the re-emission, not the native dialog.+ const nativeClick = vi.spyOn(input, "click").mockImplementation(() => {});++ // Clicking the cell after a colour was picked re-emits it (rather than only+ // re-opening the native picker).+ await act(async () => { customCell(container)?.click(); });+ expect(onChange).toHaveBeenCalledWith("#aabbcc");+ expect(nativeClick).toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it("stops click propagation on the custom cell only on mobile", () => {+ isMobileMock.mockReturnValue(true);+ const mobileContainer = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);+ const mobileWrapper = mobileContainer.querySelector(".custom-color-cell")?.parentElement;+ const mobileEvent = new MouseEvent("click", { bubbles: true, cancelable: true });+ const mobileStop = vi.spyOn(mobileEvent, "stopPropagation");+ mobileWrapper?.dispatchEvent(mobileEvent);+ expect(mobileStop).toHaveBeenCalled();++ isMobileMock.mockReturnValue(false);+ const desktopContainer = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);+ const desktopWrapper = desktopContainer.querySelector(".custom-color-cell")?.parentElement;+ const desktopEvent = new MouseEvent("click", { bubbles: true, cancelable: true });+ const desktopStop = vi.spyOn(desktopEvent, "stopPropagation");+ desktopWrapper?.dispatchEvent(desktopEvent);+ expect(desktopStop).not.toHaveBeenCalled();+ });++ it("derives a contrasting foreground for light and dark custom colours", () => {+ // Light background -> black foreground; dark background -> white.+ const light = renderInto(<ColorPicker currentValue="#eeeeee" onChange={vi.fn()} />);+ const lightWrapper = light.querySelector(".custom-color-cell")?.parentElement;+ expect(lightWrapper?.getAttribute("style")?.toLowerCase()).toContain("#000000");++ const dark = renderInto(<ColorPicker currentValue="#111111" onChange={vi.fn()} />);+ const darkWrapper = dark.querySelector(".custom-color-cell")?.parentElement;+ expect(darkWrapper?.getAttribute("style")?.toLowerCase()).toContain("#ffffff");++ // No colour at all falls back to `inherit`.+ const none = renderInto(<ColorPicker currentValue={null} onChange={vi.fn()} />);+ const noneWrapper = none.querySelector(".custom-color-cell")?.parentElement;+ expect(noneWrapper?.getAttribute("style")).toContain("inherit");+ });+});diff --git a/apps/client/src/widgets/react/ColorPicker.tsx b/apps/client/src/widgets/react/ColorPicker.tsxnew file mode 100644index 0000000000..5a7d9b8dcd--- /dev/null+++ b/apps/client/src/widgets/react/ColorPicker.tsx@@ -0,0 +1,186 @@+import "./ColorPicker.css";++import clsx from "clsx";+import Color, { ColorInstance } from "color";+import { ComponentChildren } from "preact";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";++import { t } from "../../services/i18n";+import { isMobile } from "../../services/utils";+import Debouncer from "../../utils/debouncer";++/** Curated default preset palette, using Trilium note-color-friendly CSS colors. */+export const DEFAULT_COLOR_PALETTE = [+ "#e64d4d", "#e6994d", "#e5e64d", "#99e64d", "#4de64d", "#4de699",+ "#4de5e6", "#4d99e6", "#4d4de6", "#994de6", "#e64db3"+];++export interface ColorPickerProps {+ /** The current CSS color (e.g. `#ff8800`). `null` means "no color". */+ currentValue: string | null;+ /** Called with the newly picked color, or `null` when the color is cleared. */+ onChange(newValue: string | null): void;+ /** Preset swatches shown in the row. Defaults to a curated palette. */+ presets?: string[];+ /**+ * Renders no cell as selected, for when the picker stands for several targets that don't agree+ * on a color. Picking still applies to all of them.+ */+ indeterminate?: boolean;+ disabled?: boolean;+ className?: string;+ /** Overrides the cell tooltips, for callers that can word them more specifically. */+ tooltips?: {+ clear?: string;+ set?: string;+ setCustom?: string;+ };+}++/**+ * A row of preset color swatches plus a "clear" cell and a custom cell backed by the browser's+ * native `<input type="color">`.+ *+ * This is a controlled component: it renders `currentValue` and reports picks through `onChange`+ * (`onChange(null)` clears). It has no knowledge of notes or attributes — for the note-bound+ * variant that reads and writes the `color` label, see `NoteColorPicker`.+ */+export default function ColorPicker({ currentValue, onChange, presets = DEFAULT_COLOR_PALETTE, indeterminate, disabled, className, tooltips }: ColorPickerProps) {+ const normalizedValue = currentValue ? tryParseColor(currentValue)?.hex().toLowerCase() ?? null : null;+ const isCustomColor = !indeterminate && normalizedValue !== null && presets.indexOf(normalizedValue) === -1;++ return <div className={clsx("color-picker", className)}>++ <ColorCell className="color-cell-reset"+ tooltip={tooltips?.clear ?? t("color-picker.clear-color")}+ color={null}+ isSelected={(!indeterminate && normalizedValue === null)}+ isDisabled={disabled}+ onSelect={onChange}>++ {/* https://pictogrammers.com/library/mdi/icon/close/ */}+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">+ <path d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" />+ </svg>+ </ColorCell>+++ {presets.map((color) => (+ <ColorCell key={color}+ tooltip={tooltips?.set ?? t("color-picker.set-color")}+ color={color}+ isSelected={(!indeterminate && color === normalizedValue)}+ isDisabled={disabled}+ onSelect={onChange} />+ ))}++ <CustomColorCell tooltip={tooltips?.setCustom ?? t("color-picker.set-custom-color")}+ color={normalizedValue}+ isSelected={isCustomColor}+ isDisabled={disabled}+ onSelect={onChange} />+ </div>;+}++interface ColorCellProps {+ children?: ComponentChildren,+ className?: string,+ tooltip?: string,+ color: string | null,+ isSelected: boolean,+ isDisabled?: boolean,+ onSelect?: (color: string | null) => void+}++function ColorCell(props: ColorCellProps) {+ return <div className={clsx(props.className, {+ "color-cell": true,+ "selected": props.isSelected,+ "disabled-color-cell": props.isDisabled+ })}+ style={`${(props.color !== null) ? `--color: ${props.color}` : ""}`}+ title={props.tooltip}+ onClick={() => !props.isDisabled && props.onSelect?.(props.color)}>+ {props.children}+ </div>;+}++function CustomColorCell(props: ColorCellProps) {+ const [pickedColor, setPickedColor] = useState<string | null>(null);+ const colorInput = useRef<HTMLInputElement>(null);+ const colorInputDebouncer = useRef<Debouncer<string | null> | null>(null);+ const callbackRef = useRef(props.onSelect);++ useEffect(() => {+ colorInputDebouncer.current = new Debouncer(250, (color) => {+ callbackRef.current?.(color);+ setPickedColor(color);+ });++ return () => {+ colorInputDebouncer.current?.destroy();+ };+ }, []);++ useEffect(() => {+ if (props.isSelected && pickedColor === null) {+ setPickedColor(props.color);+ }+ }, [props.isSelected]);++ useEffect(() => {+ callbackRef.current = props.onSelect;+ }, [props.onSelect]);++ const onSelect = useCallback(() => {+ if (pickedColor !== null) {+ callbackRef.current?.(pickedColor);+ }++ colorInput.current?.click();+ }, [pickedColor]);++ return <div style={`--foreground: ${getForegroundColor(props.color)};`}+ onClick={isMobile() ? (e) => {+ // The color picker dropdown will close on some browser if the parent context menu is+ // dismissed, so stop the click propagation to prevent dismissing the menu.+ e.stopPropagation();+ } : undefined}>+ <ColorCell {...props}+ color={pickedColor}+ className={clsx("custom-color-cell", {+ "custom-color-cell-empty": (pickedColor === null)+ })}+ onSelect={onSelect}>++ <input ref={colorInput}+ type="color"+ disabled={props.isDisabled}+ value={pickedColor ?? props.color ?? "#40bfbf"}+ onChange={() => {colorInputDebouncer.current?.updateValue(colorInput.current?.value ?? null);}}+ style="width: 0; height: 0; opacity: 0" />+ </ColorCell>+ </div>;+}++function getForegroundColor(backgroundColor: string | null) {+ if (backgroundColor === null) return "inherit";++ const colorHsl = tryParseColor(backgroundColor)?.hsl();+ if (colorHsl) {+ const l = colorHsl.lightness();+ return colorHsl.saturationl(0).lightness(l >= 50 ? 0 : 100).hex();+ }+ return "inherit";++}++export function tryParseColor(colorStr: string): ColorInstance | null {+ try {+ return new Color(colorStr);+ } catch(ex) {+ console.error(ex);+ }++ return null;+}diff --git a/apps/client/src/menus/custom-items/custom-color.png b/apps/client/src/widgets/react/custom-color.pngsimilarity index 100%rename from apps/client/src/menus/custom-items/custom-color.pngrename to apps/client/src/widgets/react/custom-color.pngdiff --git a/apps/client/src/widgets/type_widgets/MindMap.tsx b/apps/client/src/widgets/type_widgets/MindMap.tsxindex 7c6036ad1e..f466fe5fef 100644--- a/apps/client/src/widgets/type_widgets/MindMap.tsx+++ b/apps/client/src/widgets/type_widgets/MindMap.tsx@@ -188,7 +188,8 @@ export default function MindMap({ note, ntxId, noteContext }: TypeWidgetProps) {onKeyDown}}>- {!isReadOnly && selectedNodes.length > 0 && <MindMapNodePanel />}+ {!isReadOnly && selectedNodes.length > 0 && apiRef.current &&+ <MindMapNodePanel mind={apiRef.current} nodes={selectedNodes} />}</MindElixir>);}diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css b/apps/client/src/widgets/type_widgets/MindMapNodePanel.cssindex 3389724e60..ccb12dac47 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.css+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.css@@ -19,3 +19,22 @@.mind-map-container:fullscreen .mind-map-node-panel {top: calc(20px + env(safe-area-inset-top));}++.mind-map-node-panel .mind-map-node-panel-section + .mind-map-node-panel-section {+ margin-top: 16px;+}++.mind-map-node-panel .mind-map-node-panel-section-label {+ margin-bottom: 8px;+ font-size: .85em;+ font-weight: 550;+ text-transform: uppercase;+ letter-spacing: .75pt;+ opacity: .75;+}++/* The palettes are wider than the panel, so they wrap instead of spreading across a single row. */+.mind-map-node-panel .color-picker {+ flex-wrap: wrap;+ justify-content: flex-start;+}diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsxnew file mode 100644index 0000000000..4ddb6ea31f--- /dev/null+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.spec.tsx@@ -0,0 +1,152 @@+import type { MindElixirInstance, NodeObj } from "mind-elixir";+import { describe, expect, it, vi } from "vitest";++import { renderInto } from "../../test/render";+import { DEFAULT_COLOR_PALETTE } from "../react/ColorPicker";+import MindMapNodePanel, { getCommonValue, MIXED } from "./MindMapNodePanel";++const THEME_PALETTE = ["#dd7878", "#ea76cb", "#8839ef"];++function buildNode(node: Partial<NodeObj> = {}): NodeObj {+ return { id: "n1", topic: "Node", ...node };+}++/**+ * A stand-in for the Mind Elixir instance exposing only what the panel touches: the theme palette,+ * the live selection and `reshapeNode`.+ */+function buildMind(nodes: NodeObj[]) {+ const reshapeNode = vi.fn();+ const mind = {+ theme: { palette: THEME_PALETTE },+ currentNodes: nodes.map((nodeObj) => ({ nodeObj })),+ reshapeNode+ } as unknown as MindElixirInstance;+ return { mind, reshapeNode };+}++function section(container: HTMLElement, index: number) {+ const sections = container.querySelectorAll<HTMLElement>(".mind-map-node-panel-section");+ return sections[index];+}++function presetCells(root: HTMLElement) {+ return Array.from(root.querySelectorAll<HTMLElement>(".color-cell")).filter((cell) =>+ !cell.classList.contains("color-cell-reset") && !cell.classList.contains("custom-color-cell"));+}++describe("getCommonValue", () => {+ it("reports the shared value, the absence of one, and disagreement", () => {+ const read = (node: NodeObj) => node.style?.color;++ expect(getCommonValue([], read)).toBeNull();+ expect(getCommonValue([buildNode()], read)).toBeNull();+ expect(getCommonValue([buildNode({ style: { color: "#ff0000" } })], read)).toBe("#ff0000");+ expect(getCommonValue([+ buildNode({ style: { color: "#ff0000" } }),+ buildNode({ style: { color: "#ff0000" } })+ ], read)).toBe("#ff0000");+ expect(getCommonValue([+ buildNode({ style: { color: "#ff0000" } }),+ buildNode({ style: { color: "#00ff00" } })+ ], read)).toBe(MIXED);+ expect(getCommonValue([+ buildNode({ style: { color: "#ff0000" } }),+ buildNode()+ ], read)).toBe(MIXED);+ });++ it("treats a blanked-out value the same as an unset one", () => {+ // Clearing a color writes an empty string rather than removing the property, so the two+ // spellings of "no color" have to agree.+ const read = (node: NodeObj) => node.style?.color;++ expect(getCommonValue([buildNode({ style: { color: "" } })], read)).toBeNull();+ expect(getCommonValue([+ buildNode({ style: { color: "" } }),+ buildNode()+ ], read)).toBeNull();+ });+});++describe("MindMapNodePanel", () => {+ it("offers the theme palette for branches and the default one for text and background", () => {+ const nodes = [buildNode()];+ const { mind } = buildMind(nodes);++ const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);++ expect(presetCells(section(container, 0))).toHaveLength(DEFAULT_COLOR_PALETTE.length);+ expect(presetCells(section(container, 1))).toHaveLength(DEFAULT_COLOR_PALETTE.length);+ expect(presetCells(section(container, 2))).toHaveLength(THEME_PALETTE.length);+ });++ it("shows the colors the selection already carries", () => {+ const nodes = [buildNode({+ style: { color: DEFAULT_COLOR_PALETTE[1], background: DEFAULT_COLOR_PALETTE[2] },+ branchColor: THEME_PALETTE[0]+ })];+ const { mind } = buildMind(nodes);++ const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);++ const selectedIn = (index: number) => presetCells(section(container, index))+ .findIndex((cell) => cell.classList.contains("selected"));+ expect(selectedIn(0)).toBe(1);+ expect(selectedIn(1)).toBe(2);+ expect(selectedIn(2)).toBe(0);+ });++ it("selects nothing for a property the selected nodes disagree on", () => {+ const nodes = [+ buildNode({ id: "a", style: { color: DEFAULT_COLOR_PALETTE[0] } }),+ buildNode({ id: "b", style: { color: DEFAULT_COLOR_PALETTE[1] } })+ ];+ const { mind } = buildMind(nodes);++ const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);++ const textCells = Array.from(section(container, 0).querySelectorAll(".color-cell"));+ expect(textCells.some((cell) => cell.classList.contains("selected"))).toBe(false);+ // The properties they do agree on are still shown as unset.+ const backgroundReset = section(container, 1).querySelector(".color-cell-reset");+ expect(backgroundReset?.classList.contains("selected")).toBe(true);+ });++ it("patches every selected node, and blanks the property when a color is cleared", () => {+ const nodes = [buildNode({ id: "a" }), buildNode({ id: "b" })];+ const { mind, reshapeNode } = buildMind(nodes);++ const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);++ presetCells(section(container, 0))[3].click();+ expect(reshapeNode).toHaveBeenCalledTimes(2);+ expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { style: { color: DEFAULT_COLOR_PALETTE[3] } });+ expect(reshapeNode).toHaveBeenNthCalledWith(2, mind.currentNodes[1], { style: { color: DEFAULT_COLOR_PALETTE[3] } });++ reshapeNode.mockClear();+ section(container, 1).querySelector<HTMLElement>(".color-cell-reset")?.click();+ expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { style: { background: "" } });++ reshapeNode.mockClear();+ presetCells(section(container, 2))[1].click();+ expect(reshapeNode).toHaveBeenNthCalledWith(1, mind.currentNodes[0], { branchColor: THEME_PALETTE[1] });+ });++ it("keeps clicks and key presses from reaching the map underneath", () => {+ const nodes = [buildNode()];+ const { mind } = buildMind(nodes);++ const container = renderInto(<MindMapNodePanel mind={mind} nodes={nodes} />);+ const panel = container.querySelector(".mind-map-node-panel");++ for (const event of [+ new MouseEvent("mousedown", { bubbles: true, cancelable: true }),+ new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key: "Delete" })+ ]) {+ const stopPropagation = vi.spyOn(event, "stopPropagation");+ panel?.dispatchEvent(event);+ expect(stopPropagation).toHaveBeenCalled();+ }+ });+});diff --git a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsxindex dbad7dc7d5..9d12daeccc 100644--- a/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx+++ b/apps/client/src/widgets/type_widgets/MindMapNodePanel.tsx@@ -1,10 +1,36 @@import "./MindMapNodePanel.css";+import type { MindElixirInstance, NodeObj } from "mind-elixir";+import { ComponentChildren } from "preact";++import { t } from "../../services/i18n";+import ColorPicker from "../react/ColorPicker";++interface MindMapNodePanelProps {+ mind: MindElixirInstance;+ /** The currently selected nodes; the panel edits all of them at once. */+ nodes: NodeObj[];+}+/**- * Floating panel displayed over a mind map while at least one node is selected, meant to host the+ * Floating panel displayed over a mind map while at least one node is selected, holding the* formatting controls for the selection.*/-export default function MindMapNodePanel() {+export default function MindMapNodePanel({ mind, nodes }: MindMapNodePanelProps) {+ const textColor = getCommonValue(nodes, (node) => node.style?.color);+ const backgroundColor = getCommonValue(nodes, (node) => node.style?.background);+ const branchColor = getCommonValue(nodes, (node) => node.branchColor);++ /**+ * Applies a patch to every selected node. The selection is read back from the instance rather+ * than taken from the props, so that the elements the patch is applied to are the live ones.+ */+ function patchSelectedNodes(patch: Partial<NodeObj>) {+ for (const topic of mind.currentNodes) {+ mind.reshapeNode(topic, patch);+ }+ }+return (<divclassName="mind-map-node-panel"@@ -12,7 +38,71 @@ export default function MindMapNodePanel() {onMouseDown={(e) => e.stopPropagation()}onKeyDown={(e) => e.stopPropagation()}>- Hello world+ <PanelSection label={t("mind-map.text-color")}>+ <ColorPicker+ {...toPickerValue(textColor)}+ // Mind Elixir only ever assigns the style properties it is given and never+ // resets the ones it isn't, so clearing has to blank the property explicitly.+ onChange={(color) => patchSelectedNodes({ style: { color: color ?? "" } })}+ />+ </PanelSection>++ <PanelSection label={t("mind-map.background-color")}>+ <ColorPicker+ {...toPickerValue(backgroundColor)}+ onChange={(color) => patchSelectedNodes({ style: { background: color ?? "" } })}+ />+ </PanelSection>++ <PanelSection label={t("mind-map.branch-color")}>+ <ColorPicker+ // The branches of a map are drawn from the theme's own palette, so those are+ // the colors offered here.+ presets={mind.theme.palette}+ {...toPickerValue(branchColor)}+ onChange={(color) => patchSelectedNodes({ branchColor: color ?? "" })}+ />+ </PanelSection>+ </div>+ );+}++/** Turns the outcome of {@link getCommonValue} into the matching {@link ColorPicker} state. */+function toPickerValue(value: string | null | typeof MIXED) {+ return {+ currentValue: (value !== MIXED ? value : null),+ indeterminate: (value === MIXED)+ };+}++function PanelSection({ label, children }: { label: string, children: ComponentChildren }) {+ return (+ <div className="mind-map-node-panel-section">+ <div className="mind-map-node-panel-section-label">{label}</div>+ {children}</div>);}++/** Returned instead of a value when the selected nodes don't agree on one. */+export const MIXED = Symbol("mixed");++/**+ * Reads one property off every given node, returning the value they share, `null` if none of them+ * has one, or {@link MIXED} if they disagree. Values that are unset and values that were blanked+ * out (see {@link MindMapNodePanel}) count as the same thing.+ */+export function getCommonValue(nodes: NodeObj[], read: (node: NodeObj) => string | undefined): string | null | typeof MIXED {+ let common: string | null | undefined;++ for (const node of nodes) {+ const value = read(node) || null;+ if (common === undefined) {+ common = value;+ } else if (common !== value) {+ return MIXED;+ }+ }++ return common ?? null;+}