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 icon support
Adorian Doranac50f438f0d1
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex f8493e80a9..fa3884f191 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3353,6 +3353,7 @@"add-column-placeholder": "Enter column name...","edit-note-title": "Click to edit note title","edit-column-title": "Click to edit column title",+ "change-column-icon": "Change column icon","column-already-exists": "This column already exists on the board.","column-definition-save-error": "The columns were saved on the board, but could not be saved to the status attribute.","status-alias": "Status"diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 613e37dcb3..be315072af 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -75,6 +75,50 @@ describe("BoardApi column mutations", () => {expect(saved).toHaveLength(0);});+ it("keeps the icon of every column it reorders", () => {+ const { api, saved } = createApi(+ { columns: [ { value: "To Do", icon: "bx bx-list-ul" }, { value: "Done" } ] },+ [ "To Do", "Done" ]+ );++ api.reorderColumn(0, 2);++ expect(saved.at(-1)?.columns)+ .toEqual([ { value: "Done" }, { value: "To Do", icon: "bx bx-list-ul" } ]);+ });++ it("stores an icon, creating the entry a resolved column may not have yet", async () => {+ const { api, saved } = createApi({ columns: [ { value: "To Do" } ] }, [ "To Do", "Done" ]);++ await api.setColumnIcon("To Do", "bx bx-list-ul");+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do", icon: "bx bx-list-ul" } ]);++ // "Done" is resolved from the definition, so nothing has written it down yet.+ await api.setColumnIcon("Done", "bx bx-check");+ expect(saved.at(-1)?.columns).toEqual([+ { value: "To Do", icon: "bx bx-list-ul" },+ { value: "Done", icon: "bx bx-check" }+ ]);+ });++ it("clears the icon back to the default rather than storing an empty one", async () => {+ const { api, saved } = createApi(+ { columns: [ { value: "To Do", icon: "bx bx-list-ul" } ] }, [ "To Do" ]);++ await api.setColumnIcon("To Do", undefined);++ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do" } ]);+ });++ it("keeps the icon of a column it renames", async () => {+ const { api, saved } = createApi(+ { columns: [ { value: "Done", icon: "bx bx-check" } ] }, [ "Done" ]);++ await api.renameColumn("Done", "Shipped");++ expect(saved.at(-1)?.columns).toEqual([ { value: "Shipped", icon: "bx bx-check" } ]);+ });+it("records what each column it renames away or deletes became", async () => {const { api, pendingRenames } = createApi({ columns: [ { value: "To Do" }, { value: "Done" } ] },diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 468a25f5b7..2c39dacf5e 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -106,6 +106,29 @@ 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.+ *+ * 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.+ */+ async setColumnIcon(column: string, icon: string | undefined) {+ const columns = this.viewConfig?.columns ?? [];+ const withIcon = (stored: BoardColumnData) => {+ const updated = { ...stored };+ if (icon) {+ updated.icon = icon;+ } else {+ delete updated.icon;+ }+ return updated;+ };++ this.storeColumns(columns.some(col => col.value === column)+ ? columns.map(col => col.value === column ? withIcon(col) : col)+ : [ ...columns, withIcon({ value: column }) ]);+ }+reorderColumn(fromIndex: number, toIndex: number) {if (!this.columns || fromIndex === toIndex) return;@@ -124,8 +147,15 @@ export default class BoardApi {// `columns` is derived render state and can lag behind the persisted config (it is rebuilt// only once the view re-renders), so anything it hasn't caught up with yet is kept at the// end instead of being dropped from the config.+ const storedColumns = new Map(+ (this.viewConfig?.columns ?? []).map(col => [ col.value, col ]));const missingColumns = (this.viewConfig?.columns ?? []).filter(col => !newColumns.includes(col.value));- this.storeColumns([ ...newColumns.map(value => ({ value })), ...missingColumns ]);+ this.storeColumns([+ // Reordering moves the entries, so each keeps the icon it holds rather than being+ // rebuilt from its name.+ ...newColumns.map(value => storedColumns.get(value) ?? { value }),+ ...missingColumns+ ]);return newColumns;}diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 734bb74522..319b8063fb 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -10,10 +10,12 @@ import froca from "../../../services/froca";import { t } from "../../../services/i18n";import { DragData, TREE_CLIPBOARD_TYPE } from "../../note_tree";import Icon from "../../react/Icon";+import { IconPickerButton } from "../../react/IconPicker";import NoteLink from "../../react/NoteLink";import { BoardActionsContext, BoardDragStateContext, TitleEditor } from ".";import BoardApi from "./api";import Card, { CARD_CLIPBOARD_TYPE, CardDragData } from "./card";+import { DEFAULT_COLUMN_ICON } from "./columns";import { openColumnContextMenu } from "./context_menu";interface DragContext {@@ -25,6 +27,7 @@ interface DragContext {export default function Column({column,columnIndex,+ icon,isDraggingColumn,columnItems,api,@@ -34,6 +37,8 @@ export default function Column({isInRelationMode}: {columnItems?: { note: FNote, branch: FBranch }[];+ /** The stored icon class, absent until one is picked. Unused in relation mode. */+ icon?: string,isDraggingColumn: boolean,api: BoardApi,parentNote: FNote,@@ -109,6 +114,18 @@ export default function Column({onKeyDown={handleTitleKeyDown}tabIndex={300}>+ {/* In relation mode the column is a note, and NoteLink already shows that note's+ own icon, which is not the board's to change. */}+ {!isInRelationMode && (+ <IconPickerButton+ className="column-icon"+ icon={icon ?? DEFAULT_COLUMN_ICON}+ title={t("board_view.change-column-icon")}+ onSelect={(picked) => api.setColumnIcon(column, picked)}+ onReset={icon ? () => api.setColumnIcon(column, undefined) : undefined}+ />+ )}+{!isEditing ? (<><span className="title">diff --git a/apps/client/src/widgets/collections/board/columns.ts b/apps/client/src/widgets/collections/board/columns.tsindex 9cece1c940..614db9884e 100644--- a/apps/client/src/widgets/collections/board/columns.ts+++ b/apps/client/src/widgets/collections/board/columns.ts@@ -14,6 +14,9 @@ export const BOARD_TEMPLATE_ID = "_template_board";/** The label a board groups by when `#board:groupBy` does not name one. */export const DEFAULT_GROUP_BY = "status";+/** The icon a column shows until one is picked for it. */+export const DEFAULT_COLUMN_ICON = "bx bx-circle";+export interface BoardStatusDefinition {/** The definition attribute, wherever it is owned. */attribute: FAttribute;diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.tsindex f2abee437b..98d4f7490f 100644--- a/apps/client/src/widgets/collections/board/data.spec.ts+++ b/apps/client/src/widgets/collections/board/data.spec.ts@@ -145,6 +145,33 @@ describe("Board data", () => {expect(data.byColumn.get("Shipped")?.map(item => item.note.title)).toEqual([ "First" ]);});+ it("keeps the icon of a column whose entry the rewrite moves to its new name", async () => {+ const board = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { title: "First", "#status": "To Do" },+ { title: "Second", "#status": "Shipped" }+ ]+ });++ // The config still names the column as it was, the window the rewrite lands in.+ const data = await getBoardData(+ board,+ "status",+ { columns: [ { value: "To Do" }, { value: "Done", icon: "bx bx-check" } ] },+ false,+ [],+ new Map([ [ "Done", "Shipped" ] ])+ );++ expect(data.newPersistedData?.columns).toEqual([+ { value: "To Do" },+ { value: "Shipped", icon: "bx bx-check" }+ ]);+ });+it("is forgotten once every source has caught up, freeing the name", async () => {const pending = new Map([ [ "Done", "Shipped" ] ]);await getBoardData(diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex 9cd3a72822..f024727bdf 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -1,7 +1,7 @@import FBranch from "../../../entities/fbranch";import FNote from "../../../entities/fnote";import { resolveBoardColumns } from "./columns";-import { BoardViewData } from "./index";+import { BoardColumnData, BoardViewData } from "./index";export type ColumnMap = Map<string, {branch: FBranch;@@ -52,17 +52,45 @@ export async function getBoardData(// or every refresh would save.const hasChanges = persistedColumns.length !== columns.length|| persistedColumns.some((value, index) => columns[index] !== value);+ const storedColumns = indexColumnsByResolvedName(persistedData, pendingRenames);return {byColumn,columns,newPersistedData: hasChanges- ? { ...persistedData, columns: columns.map(value => ({ value })) }+ ? {+ ...persistedData,+ columns: columns.map(value => storedColumns.get(value) ?? { value })+ }: undefined,isInRelationMode: groupByColumn.startsWith("~")};}+/**+ * The stored column entries, each under the name it now resolves to.+ *+ * An entry holds more than the name, so rebuilding the config from the resolved names alone would+ * drop the icon of every column on any refresh that rewrites it. A rename carries the entry across+ * to the new name, the same substitution {@link resolveBoardColumns} makes.+ */+function indexColumnsByResolvedName(+ persistedData: BoardViewData,+ pendingRenames: ReadonlyMap<string, string | undefined>+) {+ const byName = new Map<string, BoardColumnData>();++ for (const column of persistedData.columns ?? []) {+ const { value } = column;+ const name = pendingRenames.has(value) ? pendingRenames.get(value) : value;+ if (name) {+ byName.set(name, { ...column, value: name });+ }+ }++ return byName;+}+/** Drops every pending rename whose old value none of the given column sources lists any more. */function prunePendingRenames(pendingRenames: Map<string, string | undefined>, sources: string[][]) {for (const oldValue of [ ...pendingRenames.keys() ]) {diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex bfccc29772..80d7181140 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -70,6 +70,29 @@ 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. */+.board-view-container .board-column h3 {+ --note-icon-custom-color: initial;+ --note-icon-custom-background-color: initial;+ --note-icon-hover-custom-background-color: initial;+}++.board-view-container .board-column h3 > .column-icon {+ /* Sized down from the note header's button, whose scale suits a toolbar rather than a heading. */+ --note-icon-size: 1.15em;+ --note-icon-container-padding-size: 0.15em;++ flex-shrink: 0;+ margin-inline-end: 0.4em;+}++.board-view-container .board-column h3 > .column-icon button.note-icon {+ /* Cap height rather than the glyph box, so the icon sits on the title's own line. */+ line-height: 1;+ color: inherit;+}+.board-view-container .board-column h3 a {text-decoration: none;color: inherit;diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 3c8e7d1431..49b69df427 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -12,6 +12,7 @@ import froca from "../../../services/froca";import { buildNote } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";import BoardView, { BoardViewData } from ".";+import { DEFAULT_COLUMN_ICON } from "./columns";// Stands in for the server: by the time the bulk action resolves, the notes carry the new value,// which is what makes the old column empty rather than merely renamed.@@ -71,6 +72,12 @@ function Harness({ note, noteIds, initialConfig }: { note: ReturnType<typeof bui);}+/** The icon class each column header wears, which is the class its picker button carries. */+function columnIcons(container: HTMLElement) {+ return [ ...container.querySelectorAll(".board-column h3 > .column-icon button") ]+ .map(el => [ ...el.classList ].filter(name => name.startsWith("bx")).join(" "));+}+function columnTitles(container: HTMLElement) {return [ ...container.querySelectorAll(".board-column h3 .title") ].map(el => el.textContent);}@@ -164,7 +171,11 @@ describe("Board column rename", () => {}});- async function setup() {+ const DEFAULT_CONFIG: BoardViewData = {+ columns: [ { value: "To Do" }, { value: "Doing" }, { value: "Done" } ]+ };++ async function setup(config: BoardViewData = DEFAULT_CONFIG) {const note = buildNote({title: "Board","#collection": "",@@ -172,9 +183,9 @@ describe("Board column rename", () => {"#label:status(inheritable)":"promoted,alias=Status,single,select,options=To Do;Doing;Done",children: [- { id: "rcard1", title: "First", "#status": "To Do" },- { id: "rcard2", title: "Second", "#status": "Doing" },- { id: "rcard3", title: "Third", "#status": "Done" }+ { title: "First", "#status": "To Do" },+ { title: "Second", "#status": "Doing" },+ { title: "Third", "#status": "Done" }]});@@ -185,13 +196,7 @@ describe("Board column rename", () => {await act(async () => {render(<ParentComponent.Provider value={new Component()}>- <Harness- note={note}- noteIds={[ "rcard1", "rcard2", "rcard3" ]}- initialConfig={{- columns: [ { value: "To Do" }, { value: "Doing" }, { value: "Done" } ]- }}- />+ <Harness note={note} noteIds={note.getChildNoteIds()} initialConfig={config} /></ParentComponent.Provider>,mountPoint);@@ -248,8 +253,8 @@ describe("Board column rename", () => {"#label:status(inheritable)":"promoted,alias=Status,single,select,options=Doing;Shipped",children: [- { id: "ocard1", title: "Fourth", "#status": "Doing" },- { id: "ocard2", title: "Fifth", "#status": "Shipped" }+ { title: "Fourth", "#status": "Doing" },+ { title: "Fifth", "#status": "Shipped" }]});@@ -258,7 +263,7 @@ describe("Board column rename", () => {<ParentComponent.Provider value={new Component()}><Harnessnote={other}- noteIds={[ "ocard1", "ocard2" ]}+ noteIds={other.getChildNoteIds()}initialConfig={{ columns: [ { value: "Doing" }, { value: "Shipped" } ] }}/></ParentComponent.Provider>,@@ -271,6 +276,29 @@ describe("Board column rename", () => {expect(columnTitles(container)).toEqual([ "Doing", "Shipped" ]);});+ it("shows each column's icon, defaulting it, and keeps it while editing", async () => {+ const { container } = await setup({+ columns: [+ { value: "To Do" },+ { value: "Doing", icon: "bx bx-run" },+ { value: "Done" }+ ]+ });++ expect(columnIcons(container))+ .toEqual([ DEFAULT_COLUMN_ICON, "bx bx-run", DEFAULT_COLUMN_ICON ]);++ // The editor covers the title and its button, so the icon is still the one on the left.+ const column = container.querySelectorAll<HTMLElement>(".board-column")[1];+ await act(async () => {+ column.querySelector<HTMLElement>("h3 .edit-icon")?.click();+ await flush();+ });++ expect(column.querySelector("h3 input")).toBeTruthy();+ expect(column.querySelector("h3 > .column-icon button")?.className).toContain("bx bx-run");+ });+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 f18a7295d2..e1709141a7 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -28,6 +28,8 @@ export interface BoardViewData {export interface BoardColumnData {value: string;+ /** The icon class shown before the title, absent until one is picked. */+ icon?: string;}interface CardDrag {@@ -134,6 +136,11 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCsetDraggedColumn, setDropPosition, setDropTarget]);+ // 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 ])),+ [ viewConfig ]);+const boardDragState = useMemo<BoardDragState>(() => ({branchIdToEdit,columnNameToEdit,@@ -248,6 +255,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCapi={api}parentNote={parentNote}column={column}+ icon={columnIcons.get(column)}columnIndex={index}columnItems={byColumn.get(column)}isDraggingColumn={draggedColumn?.column === column}