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
Update Color Picker
BeatLink28e293a7299e
diff --git a/apps/client/src/menus/custom-items/NoteColorPicker.css b/apps/client/src/menus/custom-items/NoteColorPicker.cssindex c39065fafc..a208370e21 100644--- a/apps/client/src/menus/custom-items/NoteColorPicker.css+++ b/apps/client/src/menus/custom-items/NoteColorPicker.css@@ -83,4 +83,4 @@background-image: url(./custom-color.png);background-size: cover;--foreground: transparent;-}\ No newline at end of file+}diff --git a/apps/client/src/menus/custom-items/NoteColorPicker.tsx b/apps/client/src/menus/custom-items/NoteColorPicker.tsxindex 847ae484e6..2344d40a2e 100644--- a/apps/client/src/menus/custom-items/NoteColorPicker.tsx+++ b/apps/client/src/menus/custom-items/NoteColorPicker.tsx@@ -1,31 +1,29 @@import "./NoteColorPicker.css";-import { t } from "../../services/i18n";-import { useCallback, useEffect, useRef, useState} from "preact/hooks";-import {ComponentChildren} from "preact";-import attributes from "../../services/attributes";+import clsx from "clsx";import Color, { ColorInstance } from "color";-import Debouncer from "../../utils/debouncer";+import { ComponentChildren } from "preact";+import { useCallback, useEffect, useRef, 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";--const COLOR_PALETTE = [- "#e64d4d", "#e6994d", "#e5e64d", "#99e64d", "#4de64d", "#4de699",- "#4de5e6", "#4d99e6", "#4d4de6", "#994de6", "#e64db3"-];+import Debouncer from "../../utils/debouncer";export interface NoteColorPickerProps {/** The target Note instance or its ID string. */note: FNote | string | null;}+/**+ * Note-bound variant of {@link ColorPicker}: reads the current color from the note's `color` label+ * and writes picks back to it. For a plain controlled picker, use {@link ColorPicker} directly.+ */export default function NoteColorPicker(props: NoteColorPickerProps) {- if (!props.note) return null;-const [note, setNote] = useState<FNote | null>(null);const [currentColor, setCurrentColor] = useState<string | null>(null);- const [isCustomColor, setIsCustomColor] = useState<boolean>(false);useEffect(() => {const retrieveNote = async (noteId: string) => {@@ -33,7 +31,7 @@ export default function NoteColorPicker(props: NoteColorPickerProps) {if (noteInstance) {setNote(noteInstance);}- }+ };if (typeof props.note === "string") {retrieveNote(props.note); // Get the note from the given ID string@@ -43,20 +41,10 @@ export default function NoteColorPicker(props: NoteColorPickerProps) {}, []);useEffect(() => {- const colorLabel = note?.getLabel("color")?.value ?? null;- if (colorLabel) {- let color = tryParseColor(colorLabel);- if (color) {- setCurrentColor(color.hex().toLowerCase());- }- }+ setCurrentColor(note?.getLabel("color")?.value ?? null);}, [note]);- useEffect(() => {- setIsCustomColor(currentColor !== null && COLOR_PALETTE.indexOf(currentColor) === -1);- }, [currentColor])-- const onColorCellClicked = useCallback((color: string | null) => {+ const onChange = useCallback((color: string | null) => {if (note) {if (color !== null) {attributes.setLabel(note.noteId, "color", color);@@ -66,16 +54,53 @@ export default function NoteColorPicker(props: NoteColorPickerProps) {setCurrentColor(color);}- }, [note, currentColor]);+ }, [note]);- return <div className="note-color-picker">+ if (!props.note) return null;++ return <ColorPicker+ 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={(currentColor === null)}- isDisabled={(note === null)}- onSelect={onColorCellClicked}>+ 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">@@ -84,21 +109,21 @@ export default function NoteColorPicker(props: NoteColorPickerProps) {</ColorCell>- {COLOR_PALETTE.map((color) => (+ {presets.map((color) => (<ColorCell key={color}- tooltip={t("note-color.set-color")}- color={color}- isSelected={(color === currentColor)}- isDisabled={(note === null)}- onSelect={onColorCellClicked} />+ tooltip={t("note-color.set-color")}+ color={color}+ isSelected={(color === normalizedValue)}+ isDisabled={disabled}+ onSelect={onChange} />))}<CustomColorCell tooltip={t("note-color.set-custom-color")}- color={currentColor}- isSelected={isCustomColor}- isDisabled={(note === null)}- onSelect={onColorCellClicked} />- </div>+ color={normalizedValue}+ isSelected={isCustomColor}+ isDisabled={disabled}+ onSelect={onChange} />+ </div>;}interface ColorCellProps {@@ -113,13 +138,13 @@ interface ColorCellProps {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.onSelect?.(props.color)}>+ "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>;}@@ -138,14 +163,14 @@ function CustomColorCell(props: ColorCellProps) {return () => {colorInputDebouncer.current?.destroy();- }+ };}, []);useEffect(() => {if (props.isSelected && pickedColor === null) {setPickedColor(props.color);}- }, [props.isSelected])+ }, [props.isSelected]);useEffect(() => {callbackRef.current = props.onSelect;@@ -160,25 +185,26 @@ function CustomColorCell(props: ColorCellProps) {}, [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}>+ 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}>+ color={pickedColor}+ className={clsx("custom-color-cell", {+ "custom-color-cell-empty": (pickedColor === null)+ })}+ onSelect={onSelect}><input ref={colorInput}- type="color"- value={pickedColor ?? props.color ?? "#40bfbf"}- onChange={() => {colorInputDebouncer.current?.updateValue(colorInput.current?.value ?? null)}}- style="width: 0; height: 0; opacity: 0" />+ 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>+ </div>;}function getForegroundColor(backgroundColor: string | null) {@@ -186,14 +212,14 @@ function getForegroundColor(backgroundColor: string | null) {const colorHsl = tryParseColor(backgroundColor)?.hsl();if (colorHsl) {- let l = colorHsl.lightness();+ const l = colorHsl.lightness();return colorHsl.saturationl(0).lightness(l >= 50 ? 0 : 100).hex();- } else {- return "inherit";}+ return "inherit";+}-function tryParseColor(colorStr: string): ColorInstance | null {+export function tryParseColor(colorStr: string): ColorInstance | null {try {return new Color(colorStr);} catch(ex) {diff --git a/apps/client/src/services/frontend_script_api_preact.ts b/apps/client/src/services/frontend_script_api_preact.tsindex 28783cc9db..bee0660b2a 100644--- a/apps/client/src/services/frontend_script_api_preact.ts+++ b/apps/client/src/services/frontend_script_api_preact.ts@@ -1,13 +1,14 @@import { createContext, Fragment, h, VNode } from "preact";import * as hooks from "preact/hooks";+import NoteColorPicker, { ColorPicker } 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";import Admonition from "../widgets/react/Admonition";import Button from "../widgets/react/Button";-import Calendar from "../widgets/collections/calendar/calendar";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";@@ -28,7 +29,6 @@ import NoteAutocomplete from "../widgets/react/NoteAutocomplete";import NoteLink from "../widgets/react/NoteLink";import RawHtml from "../widgets/react/RawHtml";import Slider from "../widgets/react/Slider";-import Table from "../widgets/collections/table/tabulator";import RightPanelWidget from "../widgets/sidebar/RightPanelWidget";export interface WidgetDefinition {@@ -95,6 +95,7 @@ export const preactAPI = Object.freeze({LoadingSpinner,Modal,NoteAutocomplete,+ NoteColorPicker,NoteLink,RawHtml,Slider,diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsxindex 248e546881..2569af11a2 100644--- a/apps/client/src/widgets/PromotedAttributes.tsx+++ b/apps/client/src/widgets/PromotedAttributes.tsx@@ -2,12 +2,13 @@ import "./PromotedAttributes.css";import { DefinitionObject, LabelType, UpdateAttributeResponse } from "@triliumnext/commons";import clsx from "clsx";-import { ComponentChild, createElement, HTMLInputTypeAttribute, InputHTMLAttributes, MouseEventHandler, TargetedEvent, TargetedInputEvent } from "preact";-import { Dispatch, StateUpdater, useCallback, useEffect, useRef, useState } from "preact/hooks";+import { ComponentChild, createElement, HTMLInputTypeAttribute, InputHTMLAttributes, MouseEventHandler, TargetedEvent } from "preact";+import { Dispatch, StateUpdater, useCallback, useEffect, useState } from "preact/hooks";import 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";@@ -254,7 +255,12 @@ function LabelInput(props: CellProps & { inputId: string }) {return (<div className="input-group">{inputNode}- { definition.labelType === "color" && <ColorPicker {...props} onChange={onChangeListener} inputId={inputId} />}+ { definition.labelType === "color" && (+ <ColorPicker+ currentValue={valueAttr.value || null}+ onChange={(color) => updateAttribute(note, cell, componentId, color ?? "", setCells)}+ />+ )}{ definition.labelType === "url" && (<InputButtonclassName="open-external-link-button"@@ -274,47 +280,6 @@ function LabelInput(props: CellProps & { inputId: string }) {}--// We insert a separate input since the color input does not support empty value.-// This is a workaround to allow clearing the color input.-function ColorPicker({ cell, onChange, inputId }: CellProps & {- onChange: (e: TargetedEvent<HTMLInputElement, Event>) => Promise<void>,- inputId: string;-}) {- const defaultColor = "#ffffff";- const colorInputRef = useRef<HTMLInputElement>(null);- return (- <>- <input- ref={colorInputRef}- className="form-control promoted-attribute-input"- type="color"- value={cell.valueAttr.value || defaultColor}- onChange={onChange}- />- <InputButton- icon="bx bxs-tag-x"- title={t("promoted_attributes.remove_color")}- onClick={(e) => {- // Indicate to the user the color was reset.- if (colorInputRef.current) {- colorInputRef.current.value = defaultColor;- }-- // Trigger the actual attribute change by injecting it into the hidden field.- const inputEl = document.getElementById(inputId) as HTMLInputElement | null;- if (!inputEl) return;- inputEl.value = "";- onChange({- ...e,- target: inputEl- } as unknown as TargetedInputEvent<HTMLInputElement>);- }}- />- </>- );-}-function RelationInput({ inputId, ...props }: CellProps & { inputId: string }) {return (<NoteAutocompletediff --git a/apps/client/src/widgets/react/ColorPicker.css b/apps/client/src/widgets/react/ColorPicker.cssdeleted file mode 100644index 2caa2c56d9..0000000000--- a/apps/client/src/widgets/react/ColorPicker.css+++ /dev/null@@ -1,70 +0,0 @@-.tn-color-picker {- .tn-color-picker-trigger {- display: inline-flex;- align-items: center;- gap: 0.4em;- min-width: 0;- }-- .tn-color-picker-trigger-swatch {- flex: 0 0 auto;- width: 1.1em;- height: 1.1em;- border-radius: 50%;- border: 1px solid var(--main-border-color);- }-- .tn-color-picker-trigger-label {- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-- .tn-color-picker-grid {- display: flex;- flex-wrap: wrap;- gap: 0.35em;- padding: 0.6em;- max-width: 14em;- }-- .tn-color-picker-swatch {- width: 1.5em;- height: 1.5em;- padding: 0;- border-radius: 50%;- border: 2px solid transparent;- cursor: pointer;-- &.active {- border-color: var(--main-text-color);- }- }-- .tn-color-picker-custom {- display: flex;- align-items: center;- gap: 0.5em;- padding: 0.3em 0.6em;- cursor: pointer;-- input[type="color"] {- width: 1.6em;- height: 1.6em;- padding: 0;- border: 1px solid var(--main-border-color);- border-radius: 0.25em;- background: none;- cursor: pointer;- }- }-- .tn-color-picker-clear {- display: flex;- align-items: center;- gap: 0.3em;- width: 100%;- padding: 0.3em 0.6em;- text-align: start;- }-}diff --git a/apps/client/src/widgets/react/ColorPicker.spec.tsx b/apps/client/src/widgets/react/ColorPicker.spec.tsxdeleted file mode 100644index 2405fc5e05..0000000000--- a/apps/client/src/widgets/react/ColorPicker.spec.tsx+++ /dev/null@@ -1,64 +0,0 @@-import type { ComponentChildren } from "preact";-import { describe, expect, it, vi } from "vitest";--import { renderInto } from "../../test/render";--// ColorPicker's popover is a themed `Dropdown` whose children only exist in the DOM while open-// (Bootstrap-driven state that happy-dom can't flip). Stub it to render the trigger + menu content-// inline so we can exercise ColorPicker's own logic (swatches, native input, clear) directly.-vi.mock("./Dropdown", () => ({- default: ({ text, children }: { text: ComponentChildren; children: ComponentChildren }) => (- <div className="dropdown-stub">- <div className="dropdown-stub-trigger">{text}</div>- <div className="dropdown-stub-menu">{children}</div>- </div>- )-}));--import ColorPicker from "./ColorPicker";--describe("ColorPicker", () => {- it("renders a preset swatch grid and marks the current value active", () => {- const container = renderInto(<ColorPicker currentValue="#43a047" onChange={vi.fn()} />);- const swatches = container.querySelectorAll(".tn-color-picker-swatch");- expect(swatches.length).toBeGreaterThan(1);-- const active = container.querySelectorAll(".tn-color-picker-swatch.active");- expect(active).toHaveLength(1);- expect((active[0] as HTMLElement).getAttribute("title")).toBe("#43a047");- });-- it("uses the provided presets and emits the picked color", () => {- const onChange = vi.fn();- const container = renderInto(<ColorPicker currentValue="" presets={[ "#111111", "#222222" ]} onChange={onChange} />);-- const swatches = container.querySelectorAll<HTMLButtonElement>(".tn-color-picker-swatch");- expect(swatches).toHaveLength(2);-- swatches[1].click();- expect(onChange).toHaveBeenCalledExactlyOnceWith("#222222");- });-- it("offers the browser's native color input and emits its value", () => {- const onChange = vi.fn();- const container = renderInto(<ColorPicker currentValue="#ff8800" onChange={onChange} />);-- const nativeInput = container.querySelector<HTMLInputElement>(".tn-color-picker-custom input[type=\"color\"]");- expect(nativeInput).not.toBeNull();- if (!nativeInput) return;- // A valid 6-digit hex is round-tripped into the native input's value.- expect(nativeInput.value).toBe("#ff8800");-- nativeInput.value = "#00ccff";- nativeInput.dispatchEvent(new Event("input", { bubbles: true }));- expect(onChange).toHaveBeenLastCalledWith("#00ccff");- });-- it("clears the value via the clear action", () => {- const onChange = vi.fn();- const container = renderInto(<ColorPicker currentValue="#ff8800" onChange={onChange} />);-- container.querySelector<HTMLButtonElement>(".tn-color-picker-clear")?.click();- expect(onChange).toHaveBeenCalledExactlyOnceWith("");- });-});diff --git a/apps/client/src/widgets/react/ColorPicker.tsx b/apps/client/src/widgets/react/ColorPicker.tsxdeleted file mode 100644index 4e4c13c4c9..0000000000--- a/apps/client/src/widgets/react/ColorPicker.tsx+++ /dev/null@@ -1,96 +0,0 @@-import "./ColorPicker.css";--import clsx from "clsx";--import Dropdown from "./Dropdown";-import Icon from "./Icon";--/** Curated default preset palette, using Trilium note-color-friendly CSS colors. */-const DEFAULT_PRESETS = [- "#e53935", "#fb8c00", "#fdd835", "#43a047", "#00897b",- "#00acc1", "#1e88e5", "#3949ab", "#8e24aa", "#d81b60",- "#6d4c41", "#757575", "#000000", "#ffffff"-];--interface ColorPickerProps {- /** The current CSS color (e.g. `#ff8800`). Empty string means "no color". */- currentValue: string;- onChange(newValue: string): void;- /** Preset swatches shown in the grid. Defaults to a curated palette. */- presets?: string[];- /** Tooltip / accessible label for the trigger. */- title?: string;- disabled?: boolean;- className?: string;-}--/**- * A color picker combining preset swatches with the browser's native color picker.- *- * The trigger is a swatch + label; the popover (a themed {@link Dropdown}) shows a grid of preset- * swatches plus a native `<input type="color">` for arbitrary colors and a clear action. Value is a CSS- * color string (`onChange("")` clears it). Theme-styled via `ColorPicker.css` / `--main-*` variables.- */-export default function ColorPicker({ currentValue, onChange, presets = DEFAULT_PRESETS, title, disabled, className }: ColorPickerProps) {- const normalizeColorForInput = (color: string): string => {- const trimmed = (color || "").trim();- if (/^#[0-9a-f]{3}$/i.test(trimmed)) {- // Expand 3-digit hex to 6-digit for the native color input.- return `#${trimmed[1]}${trimmed[1]}${trimmed[2]}${trimmed[2]}${trimmed[3]}${trimmed[3]}`;- }- if (/^#[0-9a-f]{6}$/i.test(trimmed)) {- return trimmed.toLowerCase();- }- // Fallback for invalid or unsupported color formats (e.g., "red").- return "#000000";- };-- return (- <Dropdown- className={clsx("tn-color-picker", className)}- noSelectButtonStyle- hideToggleArrow- disabled={disabled}- title={title}- text={- <span className="tn-color-picker-trigger">- <span className="tn-color-picker-trigger-swatch" style={{ background: currentValue || "transparent" }} />- <span className="tn-color-picker-trigger-label">{currentValue || title || "Choose color"}</span>- </span>- }- >- <div className="tn-color-picker-grid">- {presets.map((color) => {- const isActive = (currentValue || "").trim().toLowerCase() === (color || "").trim().toLowerCase();- return (- <button- key={color}- type="button"- title={color}- className={clsx("tn-color-picker-swatch", { "active": isActive })}- style={{ background: color }}- onClick={() => onChange(color)}- />- )- })}- </div>-- <label className="tn-color-picker-custom">- <input- type="color"- value={normalizeColorForInput(currentValue)}- onInput={(e) => onChange(e.currentTarget.value)}- />- <span>Custom…</span>- </label>-- <button- type="button"- className="tn-color-picker-clear tn-low-profile"- onClick={() => onChange("")}- >- <Icon icon="bx bx-x" /> Clear- </button>- </Dropdown>- );-}diff --git a/packages/commons/src/lib/script_api_preact.ts b/packages/commons/src/lib/script_api_preact.tsindex 4bdec5f005..584896b20e 100644--- a/packages/commons/src/lib/script_api_preact.ts+++ b/packages/commons/src/lib/script_api_preact.ts@@ -125,10 +125,9 @@ interface ExternallyControlledCollapsibleProps {export declare const ExternallyControlledCollapsible: FunctionComponent<ExternallyControlledCollapsibleProps>;interface ColorPickerProps {- currentValue: string;- onChange(newValue: string): void;+ currentValue: string | null;+ onChange(newValue: string | null): void;presets?: string[];- title?: string;disabled?: boolean;className?: string;}@@ -353,6 +352,12 @@ interface NoteAutocompleteProps {}export declare const NoteAutocomplete: FunctionComponent<NoteAutocompleteProps>;+interface NoteColorPickerProps {+ /** The target note instance (FNote) or its ID string. */+ note: unknown | string | null;+}+export declare const NoteColorPicker: FunctionComponent<NoteColorPickerProps>;+interface NoteLinkProps {className?: string;containerClassName?: string;