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
client/collections/board: add custom color support for columns
Adorian Doran00516885b470
diff --git a/apps/client/src/stylesheets/theme-next-dark.css b/apps/client/src/stylesheets/theme-next-dark.cssindex 1c7364a01a..ff5354fd0f 100644--- a/apps/client/src/stylesheets/theme-next-dark.css+++ b/apps/client/src/stylesheets/theme-next-dark.css@@ -396,6 +396,9 @@--space-usage-donut-hover-saturation: 90%;--space-usage-donut-hover-lightness: 80%;+ --board-column-with-hue-background-saturation: 14%;+ --board-column-with-hue-background-lightness: 23%;+--space-usage-donut-selected-saturation: 90%;--space-usage-donut-selected-lightness: 80%;}@@ -467,7 +470,8 @@ body .todo-list input[type="checkbox"]:not(:checked):before {.geo-detail-sheet.with-hue,.nested-note-list-item.with-hue,.note-book-card.with-hue .note-book-header,-.ck-template-icon.with-hue {+.ck-template-icon.with-hue,+.board-column h3 {--note-icon-custom-background-color: hsl(var(--custom-color-hue), 15.8%, 30.9%);--note-icon-custom-color: hsl(var(--custom-color-hue), 100%, 76.5%);--note-icon-hover-custom-background-color: hsl(var(--custom-color-hue), 28.3%, 36.7%);diff --git a/apps/client/src/stylesheets/theme-next-light.css b/apps/client/src/stylesheets/theme-next-light.cssindex f04ce136fe..fc2e0ca9db 100644--- a/apps/client/src/stylesheets/theme-next-light.css+++ b/apps/client/src/stylesheets/theme-next-light.css@@ -395,6 +395,9 @@--space-usage-donut-hover-saturation: 57%;--space-usage-donut-hover-lightness: 68%;+ --board-column-with-hue-background-saturation: 26%;+ --board-column-with-hue-background-lightness: 86%;+--space-usage-donut-selected-saturation: 35%;--space-usage-donut-selected-lightness: 45%;@@ -440,7 +443,8 @@.geo-detail-sheet.with-hue,.nested-note-list-item.with-hue,.note-book-card.with-hue .note-book-header,-.ck-template-icon.with-hue {+.ck-template-icon.with-hue,+.board-column h3 {--note-icon-custom-background-color: hsl(var(--custom-color-hue), 44.5%, 43.1%);--note-icon-custom-color: hsl(var(--custom-color-hue), 91.3%, 91%);--note-icon-hover-custom-background-color: hsl(var(--custom-color-hue), 55.1%, 50.2%);diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex be315072af..d72b2a39cf 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -110,6 +110,20 @@ describe("BoardApi column mutations", () => {expect(saved.at(-1)?.columns).toEqual([ { value: "To Do" } ]);});+ it("stores a colour beside the icon, without either clearing the other", async () => {+ const { api, saved } = createApi({ columns: [ { value: "To Do" } ] }, [ "To Do" ]);++ await api.setColumnIcon("To Do", "bx bx-list-ul");+ await api.setColumnColor("To Do", "#e64d4d");+ expect(saved.at(-1)?.columns).toEqual([+ { value: "To Do", icon: "bx bx-list-ul", color: "#e64d4d" }+ ]);++ // Clearing one leaves the other where it is.+ await api.setColumnColor("To Do", null);+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do", icon: "bx bx-list-ul" } ]);+ });+it("keeps the icon of a column it renames", async () => {const { api, saved } = createApi({ columns: [ { value: "Done", icon: "bx bx-check" } ] }, [ "Done" ]);diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 2c39dacf5e..246ef878e7 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -106,27 +106,35 @@ export default class BoardApi {.map(col => col.value === oldValue ? { ...col, value: newValue } : col));}+ /** Stores the icon a column shows, or clears it back to the default when given nothing. */+ async setColumnIcon(column: string, icon: string | undefined) {+ this.updateColumn(column, { icon });+ }++ /** Stores the colour a column is tinted with, or clears it when given nothing. */+ async setColumnColor(column: string, color: string | null) {+ this.updateColumn(column, { color: color ?? undefined });+ }+/**- * Stores the icon a column shows, or clears it back to the default when given nothing.+ * Writes properties onto a column, dropping each one given as nothing so that it goes back to+ * its default rather than being stored empty.** The column may have no stored entry at all: one resolved from the definition or from a value- * a note carries is shown without ever being written, so picking an icon for it creates one.+ * a note carries is shown without ever being written, so the first pick for it creates one.*/- async setColumnIcon(column: string, icon: string | undefined) {+ private updateColumn(column: string, patch: Partial<BoardColumnData>) {const columns = this.viewConfig?.columns ?? [];- const withIcon = (stored: BoardColumnData) => {- const updated = { ...stored };- if (icon) {- updated.icon = icon;- } else {- delete updated.icon;- }+ const patched = (stored: BoardColumnData): BoardColumnData => {+ const updated = { ...stored, ...patch };+ if (!updated.icon) delete updated.icon;+ if (!updated.color) delete updated.color;return updated;};this.storeColumns(columns.some(col => col.value === column)- ? columns.map(col => col.value === column ? withIcon(col) : col)- : [ ...columns, withIcon({ value: column }) ]);+ ? columns.map(col => col.value === column ? patched(col) : col)+ : [ ...columns, patched({ value: column }) ]);}reorderColumn(fromIndex: number, toIndex: number) {diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 319b8063fb..f99e6d3321 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -1,11 +1,13 @@+import clsx from "clsx";import { Fragment } from "preact";-import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";+import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";import { JSX } from "preact/jsx-runtime";import FBranch from "../../../entities/fbranch";import FNote from "../../../entities/fnote";import { ContextMenuEvent } from "../../../menus/context_menu";import branches from "../../../services/branches";+import { getHue, parseColor } from "../../../services/css_class_manager";import froca from "../../../services/froca";import { t } from "../../../services/i18n";import { DragData, TREE_CLIPBOARD_TYPE } from "../../note_tree";@@ -28,6 +30,7 @@ export default function Column({column,columnIndex,icon,+ color,isDraggingColumn,columnItems,api,@@ -39,6 +42,8 @@ export default function Column({columnItems?: { note: FNote, branch: FBranch }[];/** The stored icon class, absent until one is picked. Unused in relation mode. */icon?: string,+ /** The stored CSS colour, absent until one is picked. */+ color?: string,isDraggingColumn: boolean,api: BoardApi,parentNote: FNote,@@ -60,8 +65,14 @@ export default function Column({}, [column]);const handleContextMenu = useCallback((e: ContextMenuEvent) => {- openColumnContextMenu(api, e, column);- }, [ api, column ]);+ openColumnContextMenu(api, e, column, color);+ }, [ api, column, color ]);++ // A fully desaturated colour has no hue to tint with, and leaves the column plain.+ const hue = useMemo(() => {+ const parsed = color ? parseColor(color) : undefined;+ return parsed ? getHue(parsed) : undefined;+ }, [ color ]);const handleTitleKeyDown = useCallback((e: KeyboardEvent) => {if (e.key === "F2") {@@ -97,12 +108,17 @@ export default function Column({return (<div- className={`board-column ${dropTarget === column && draggedCard?.fromColumn !== column ? 'drag-over' : ''}`}+ className={clsx("board-column", {+ "drag-over": dropTarget === column && draggedCard?.fromColumn !== column,+ // The class the themes key a hue off, worn here as anywhere else that carries one.+ "with-hue": hue !== undefined+ })}onDragOver={isAnyColumnDragging ? handleColumnDragOver : handleDragOver}onDragLeave={handleDragLeave}onDrop={handleDrop}style={{- display: !isVisible ? "none" : undefined+ display: !isVisible ? "none" : undefined,+ "--board-column-custom-hue": hue}}><h3diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.tsnew file mode 100644index 0000000000..04687ca23d--- /dev/null+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts@@ -0,0 +1,72 @@+import { h, render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++import contextMenu, { ContextMenuEvent } from "../../../menus/context_menu";+import BoardApi from "./api";+import { openColumnContextMenu } from "./context_menu";++describe("Board column context menu", () => {+ let container: HTMLElement | undefined;++ afterEach(() => {+ vi.restoreAllMocks();+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ /** Renders the colour picker the menu offers for a column already carrying `color`. */+ async function openPicker(api: BoardApi, color?: string) {+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});+ const event = {+ preventDefault: () => {},+ stopPropagation: () => {},+ pageX: 0,+ pageY: 0+ } as ContextMenuEvent;++ openColumnContextMenu(api, event, "To Do", color);++ const items = show.mock.calls[0][0].items ?? [];+ const custom = items.find(item => item && "kind" in item && item.kind === "custom");+ if (!custom || !("componentFn" in custom)) {+ throw new Error("expected a colour picker in the menu");+ }++ const element = document.createElement("div");+ container = element;+ document.body.appendChild(element);+ // Rendered as a component, the way the menu itself does it, so its hooks have a context.+ await act(async () => {+ render(h(custom.componentFn, {}), element);+ });++ return element;+ }++ it("shows the column's own colour as the selected one", async () => {+ const api = { setColumnColor: vi.fn() } as unknown as BoardApi;+ const picker = await openPicker(api, "#4d99e6");++ const selected = picker.querySelector<HTMLElement>(".color-cell.selected");+ expect(selected?.style.getPropertyValue("--color")).toBe("#4d99e6");+ });++ it("writes a pick to the column, and a clear back to no colour", async () => {+ const api = { setColumnColor: vi.fn() } as unknown as BoardApi;+ const picker = await openPicker(api);++ // The reset cell leads the row, so the first plain cell after it is a preset.+ const preset = picker+ .querySelectorAll<HTMLElement>(".color-cell:not(.color-cell-reset)")[0];+ await act(async () => preset.click());+ expect(api.setColumnColor)+ .toHaveBeenLastCalledWith("To Do", preset.style.getPropertyValue("--color"));++ await act(async () => picker.querySelector<HTMLElement>(".color-cell-reset")?.click());+ expect(api.setColumnColor).toHaveBeenLastCalledWith("To Do", null);+ });+});diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.tsindex d7ae56a52c..e486f52ed7 100644--- a/apps/client/src/widgets/collections/board/context_menu.ts+++ b/apps/client/src/widgets/collections/board/context_menu.ts@@ -1,3 +1,5 @@+import { useState } from "preact/hooks";+import FNote from "../../../entities/fnote";import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker";import contextMenu, { ContextMenuEvent } from "../../../menus/context_menu";@@ -6,9 +8,12 @@ import branches from "../../../services/branches";import dialog from "../../../services/dialog";import { getArchiveMenuItem } from "../../../menus/context_menu_utils";import { t } from "../../../services/i18n";+import ColorPicker from "../../react/ColorPicker";import Api from "./api";-export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column: string) {+export function openColumnContextMenu(+ api: Api, event: ContextMenuEvent, column: string, color?: string+) {event.preventDefault();event.stopPropagation();@@ -27,12 +32,37 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:await api.removeColumn(column);}+ },+ { kind: "separator" },+ {+ kind: "custom",+ componentFn: () => ColumnColorPicker({ api, column, color })}],selectMenuItemHandler() {}});}+/**+ * The colour a column is tinted with, picked the way a note's is.+ *+ * It holds the pick rather than reading it back from the board, since the menu is rendered once and+ * the board redrawing underneath does not reach it. `note-color-picker` is what the menu styles the+ * row through, so the class is worn here too.+ */+function ColumnColorPicker({ api, column, color }: { api: Api, column: string, color?: string }) {+ const [ currentColor, setCurrentColor ] = useState(color ?? null);++ return ColorPicker({+ className: "note-color-picker",+ currentValue: currentColor,+ onChange: (picked) => {+ setCurrentColor(picked);+ api.setColumnColor(column, picked);+ }+ });+}+export function openNoteContextMenu(api: Api, event: ContextMenuEvent, note: FNote, branchId: string, column: string) {event.preventDefault();event.stopPropagation();diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex 80d7181140..33809836a9 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -1,3 +1,9 @@+/* Defaults for a theme that sets none of its own; the light values, the app's own default look. */+:where(:root) {+ --board-column-with-hue-background-saturation: 26%;+ --board-column-with-hue-background-lightness: 86%;+}+.board-view {position: relative;height: 100%;@@ -48,6 +54,15 @@ body.mobile .board-view-container .board-add-column {scroll-snap-align: center;}+/* Ahead of `.drag-over`, which matches just as specifically and has to keep winning. */+.board-view-container .board-column.with-hue {+ background-color: hsl(+ var(--board-column-custom-hue),+ var(--board-column-with-hue-background-saturation),+ var(--board-column-with-hue-background-lightness)+ );+}+.board-view-container .board-column.drag-over {border-color: var(--main-text-color);background-color: var(--hover-item-background-color);@@ -70,12 +85,12 @@ body.mobile .board-view-container .board-add-column {align-items: center;}-/* The board note's colour class sits on an ancestor and would dress the icon in that note's hue.- `initial` rather than `unset`: these inherit, so unsetting lets the ancestor's values back in. */+/* The column's own hue, or none: an ancestor carries the board note's colour class, which would+ otherwise dress the icon in that note's hue. `initial` rather than `unset` for the fallback,+ since this inherits and unsetting lets the ancestor's value back in. The themes re-derive the+ icon colours from this, keyed on the same selector. */.board-view-container .board-column h3 {- --note-icon-custom-color: initial;- --note-icon-custom-background-color: initial;- --note-icon-hover-custom-background-color: initial;+ --custom-color-hue: var(--board-column-custom-hue, initial);}.board-view-container .board-column h3 > .column-icon {diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 49b69df427..29739fc858 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -299,6 +299,26 @@ describe("Board column rename", () => {expect(column.querySelector("h3 > .column-icon button")?.className).toContain("bx bx-run");});+ it("tints only the columns given a colour that has a hue", async () => {+ const { container } = await setup({+ columns: [+ { value: "To Do", color: "#4d99e6" },+ { value: "Doing", color: "#808080" },+ { value: "Done" }+ ]+ });++ const columns = [ ...container.querySelectorAll<HTMLElement>(".board-column") ];+ const hues = columns+ .map(column => column.style.getPropertyValue("--board-column-custom-hue"));++ expect(Math.round(Number(hues[0]))).toBe(210);+ // Grey has no hue of its own, leaving the column as plain as one with no colour.+ expect(hues.slice(1)).toEqual([ "", "" ]);+ expect(columns.map(column => column.classList.contains("with-hue")))+ .toEqual([ true, false, false ]);+ });+it("keeps the cards of the renamed column under it", async () => {const { container } = await setup();diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex e1709141a7..ee5528e1b8 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -30,6 +30,8 @@ export interface BoardColumnData {value: string;/** The icon class shown before the title, absent until one is picked. */icon?: string;+ /** The CSS colour the column is tinted with, absent until one is picked. */+ color?: string;}interface CardDrag {@@ -137,8 +139,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC]);// Read off the config rather than off `columns`, which the resolver hands back as names alone.- const columnIcons = useMemo(- () => new Map((viewConfig?.columns ?? []).map(({ value, icon }) => [ value, icon ])),+ const storedColumns = useMemo(+ () => new Map((viewConfig?.columns ?? []).map(stored => [ stored.value, stored ])),[ viewConfig ]);const boardDragState = useMemo<BoardDragState>(() => ({@@ -255,7 +257,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCapi={api}parentNote={parentNote}column={column}- icon={columnIcons.get(column)}+ icon={storedColumns.get(column)?.icon}+ color={storedColumns.get(column)?.color}columnIndex={index}columnItems={byColumn.get(column)}isDraggingColumn={draggedColumn?.column === column}