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 an option to adjust the width of the columns
Adorian Doran62abca0e2d93
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 538c74992d..c4e0709ab1 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -739,6 +739,7 @@"is_hidden": "Keeps a task state out of the pickers, without deleting it or the notes already in it.","max_nesting_depth": "How many levels of children a table shows. Notes cannot be reordered while it is set.","include_archived": "Includes archived notes in this collection, which are otherwise left out.",+ "board_card_width": "For board collections, how wide the columns are drawn: <code>narrow</code>, <code>medium</code> or <code>wide</code>. Ignored on mobile, which draws them at a width of its own.","enable_inbox_column": "For board collections, shows the inbox column, which lists all child notes that are not assigned to a board column.","board_card_redirect_to": "On a board card, opening the card jumps to the note this points at instead of opening the card itself.","sort_columns": "For board collections, the order the columns sort their cards in, which a column follows unless it is given an order of its own. Holds <code>title</code>, <code>creationDate</code> or <code>attr:</code> followed by a promoted attribute's name.",@@ -3529,6 +3530,10 @@"sort": "Sort","sort-manually": "Manually","default-card-order": "Default card order",+ "column-width": "Column width",+ "column-width-narrow": "Narrow (default)",+ "column-width-medium": "Medium",+ "column-width-wide": "Wide","default-card-order-description": "How cards are sorted in each column, unless you choose different sorting options for a particular column.","sort-board-default": "Board's default","reset-column-sorting": "Reset sorting options to default for all columns",diff --git a/apps/client/src/widgets/attribute_widgets/attr_help.ts b/apps/client/src/widgets/attribute_widgets/attr_help.tsindex 75bbacbdd0..a8a07125d0 100644--- a/apps/client/src/widgets/attribute_widgets/attr_help.ts+++ b/apps/client/src/widgets/attribute_widgets/attr_help.ts@@ -157,6 +157,7 @@ export const ATTR_HELP: AttrHelpMap = {maxNestingDepth: t("attribute_detail.max_nesting_depth"),includeArchived: t("attribute_detail.include_archived"),enableInboxColumn: t("attribute_detail.enable_inbox_column"),+ boardCardWidth: t("attribute_detail.board_card_width"),sortColumns: t("attribute_detail.sort_columns"),sortColumnsDescending: t("attribute_detail.sort_columns_descending"),"calendar:view": t("attribute_detail.calendar_view"),diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 97e88f7e95..e6fb7c446e 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import appContext from "../../../components/app_context";import FAttribute from "../../../entities/fattribute";@@ -2440,3 +2440,64 @@ describe("a selection of cards", () => {expect(branches.moveAfterBranch).not.toHaveBeenCalled();});});++describe("how wide the board draws its columns", () => {+ afterEach(() => vi.restoreAllMocks());++ it("reads the label, falling back to the default for a width it does not offer", () => {+ const width = (label?: string) => createApi(+ {}, [], buildNote(label ? { title: "Board", "#boardCardWidth": label }+ : { title: "Board" })).api.columnWidth;++ expect(width()).toBe("narrow");+ expect(width("medium")).toBe("medium");+ expect(width("wide")).toBe("wide");+ expect(width("enormous")).toBe("narrow");+ });++ it("writes the label for a width other than the default", async () => {+ const board = buildNote({ title: "Board" });+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);+ const { api } = createApi({}, [], board);++ await api.setColumnWidth("wide");++ expect(setLabel).toHaveBeenCalledWith(board.noteId, "boardCardWidth", "wide");+ });++ /** Kept tidy: a board drawn at the default width carries no label for it at all. */+ it("takes the label off for the default width", async () => {+ const board = buildNote({ title: "Board", "#boardCardWidth": "wide" });+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);+ const removeLabel = vi.spyOn(attributes, "removeOwnedLabelByName")+ .mockResolvedValue(true);+ const { api } = createApi({}, [], board);++ await api.setColumnWidth("narrow");++ expect(removeLabel).toHaveBeenCalledWith(board, "boardCardWidth");+ expect(setLabel).not.toHaveBeenCalled();+ });++ /** Dropping its own label there would hand the board the inherited width straight back. */+ it("writes the default out where the board inherits another width", async () => {+ const parent = buildNote({+ title: "Parent",+ "#boardCardWidth(inheritable)": "wide",+ children: [ { title: "Board" } ]+ });+ const board = froca.getNoteFromCache(parent.getChildNoteIds()[0]);+ if (!board) throw new Error("expected the board to be in froca");+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);+ const removeLabel = vi.spyOn(attributes, "removeOwnedLabelByName")+ .mockResolvedValue(true);+ const { api } = createApi({}, [], board);++ expect(api.columnWidth).toBe("wide");++ await api.setColumnWidth("narrow");++ expect(setLabel).toHaveBeenCalledWith(board.noteId, "boardCardWidth", "narrow");+ expect(removeLabel).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex b73fca0a45..3f4181e719 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -25,8 +25,9 @@ import {import { BoardColumnData, BoardViewData } from ".";import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";import {- type BoardStatusDefinition, canStoreColumnsInDefinition, DEFAULT_COLUMN_ICON,- DEFAULT_GROUP_BY, INBOX_COLUMN, INBOX_COLUMN_ICON+ type BoardStatusDefinition, canStoreColumnsInDefinition, COLUMN_WIDTH_LABEL, type ColumnWidth,+ DEFAULT_COLUMN_ICON, DEFAULT_COLUMN_WIDTH, DEFAULT_GROUP_BY, INBOX_COLUMN, INBOX_COLUMN_ICON,+ parseColumnWidth} from "./columns";import { readColumns, writeColumns } from "./column_storage";import { ColumnItem, ColumnMap } from "./data";@@ -657,6 +658,33 @@ export default class BoardApi {await attributes.setBooleanWithInheritance(this.parentNote, "includeArchived", shown);}+ /** How wide the board draws its columns, which the board turns into a class of its own. */+ get columnWidth() {+ return parseColumnWidth(this.parentNote?.getLabelValue(COLUMN_WIDTH_LABEL));+ }++ /**+ * Sets how wide the columns are drawn.+ *+ * The default takes the label off the board note, which keeps it tidy. A board that inherits a+ * width from a template or a parent writes the default out instead: dropping its own label+ * there would hand the board the inherited width back.+ */+ async setColumnWidth(width: ColumnWidth) {+ const note = this.parentNote;+ if (!note) return;++ const inherited = note.getAttributes("label", COLUMN_WIDTH_LABEL)+ .find(attribute => attribute.noteId !== note.noteId);+ if (width === DEFAULT_COLUMN_WIDTH+ && parseColumnWidth(inherited?.value) === DEFAULT_COLUMN_WIDTH) {+ await attributes.removeOwnedLabelByName(note, COLUMN_WIDTH_LABEL);+ return;+ }++ await attributes.setLabel(note.noteId, COLUMN_WIDTH_LABEL, width);+ }+/** The note limit set for a column, absent if disabled. */getColumnLimit(column: string) {return this.storedColumns.find(col => col.value === column)?.limit;diff --git a/apps/client/src/widgets/collections/board/columns.spec.ts b/apps/client/src/widgets/collections/board/columns.spec.tsindex 6936796a2a..eb26bb02c0 100644--- a/apps/client/src/widgets/collections/board/columns.spec.ts+++ b/apps/client/src/widgets/collections/board/columns.spec.ts@@ -9,6 +9,7 @@ import {BOARD_TEMPLATE_ID,canStoreColumnsInDefinition,getStatusDefinition,+ parseColumnWidth,resolveBoardColumns} from "./columns";@@ -205,3 +206,17 @@ describe("the inbox column", () => {.toEqual([ "", "To Do" ]);});});++describe("parseColumnWidth", () => {+ /** The label is the user's to write by hand, so it can name a width the board does not have. */+ it("reads the three widths and falls back to the narrow default", () => {+ expect(parseColumnWidth("narrow")).toBe("narrow");+ expect(parseColumnWidth("medium")).toBe("medium");+ expect(parseColumnWidth("wide")).toBe("wide");++ expect(parseColumnWidth("enormous")).toBe("narrow");+ expect(parseColumnWidth("")).toBe("narrow");+ expect(parseColumnWidth(null)).toBe("narrow");+ expect(parseColumnWidth(undefined)).toBe("narrow");+ });+});diff --git a/apps/client/src/widgets/collections/board/columns.ts b/apps/client/src/widgets/collections/board/columns.tsindex 3604ed442f..1c1d65935b 100644--- a/apps/client/src/widgets/collections/board/columns.ts+++ b/apps/client/src/widgets/collections/board/columns.ts@@ -32,6 +32,25 @@ export const INBOX_COLUMN = "";/** Default icon for the inbox column, used instead of the standard one until another is picked. */export const INBOX_COLUMN_ICON = "bx bxs-inbox";+/** The label naming how wide the board draws its columns. */+export const COLUMN_WIDTH_LABEL = "boardCardWidth";++/** The widths the board offers, in the order the properties dialog lists them. */+export const COLUMN_WIDTHS = [ "narrow", "medium", "wide" ] as const;++export type ColumnWidth = typeof COLUMN_WIDTHS[number];++/** The width a board with no label of its own draws its columns at. */+export const DEFAULT_COLUMN_WIDTH: ColumnWidth = "narrow";++/**+ * Reads a stored width, falling back to the default for anything the board does not offer. The+ * label is the user's to edit by hand, so it can name a width that does not exist.+ */+export function parseColumnWidth(value: string | null | undefined) {+ return COLUMN_WIDTHS.find(width => width === value) ?? DEFAULT_COLUMN_WIDTH;+}+export interface BoardStatusDefinition {/** The definition attribute, wherever it is owned. */attribute: FAttribute;diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex e7ad197c68..7267ba5b18 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -16,7 +16,12 @@/* Matches the height a normal header takes, so a collapsed column reads as one turned onits side. */--board-collapsed-column-width: 2.25em;- --board-column-width: 275px;+ /* The three widths the board properties offer, and the one in use. Each is its own variable so+ a theme can change one width without taking over which of them a board picks. */+ --board-column-width-narrow: 275px;+ --board-column-width-medium: 325px;+ --board-column-width-wide: 400px;+ --board-column-width: var(--board-column-width-narrow);--board-column-border-width: 2px;--board-collapse-duration: 1s;--board-collapse-duration-quick: 0.3s;@@ -110,6 +115,20 @@ body.mobile .board-view-container.board-dragging {scroll-behavior: auto;}+/* Set from `#boardCardWidth`. The columns and everything measured against them read the width off+ this one variable, so only the board itself names which of the three is in use. */+.board-view.board-narrow-columns {+ --board-column-width: var(--board-column-width-narrow);+}++.board-view.board-medium-columns {+ --board-column-width: var(--board-column-width-medium);+}++.board-view.board-wide-columns {+ --board-column-width: var(--board-column-width-wide);+}+.board-view-container .board-column {width: var(--board-column-width);flex-shrink: 0;diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 536581e754..932c16d88f 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -4354,3 +4354,64 @@ describe("a column windowed for its size", () => {return mountPoint;}});++describe("how wide the board draws its columns", () => {+ let container: HTMLElement | undefined;++ afterEach(() => {+ saved.length = 0;+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ /**+ * The width itself is CSS, which happy-dom does not resolve. What the board answers for is the+ * class it carries, off which the stylesheet picks one of the three widths.+ */+ it("carries the width its label names, and the default where it names none", async () => {+ expect((await draw(undefined)).className).toContain("board-narrow-columns");+ expect((await draw("wide")).className).toContain("board-wide-columns");+ // A width nobody offers is drawn at the default rather than given a class of its own.+ expect((await draw("enormous")).className).toContain("board-narrow-columns");+ });++ async function draw(width: string | undefined) {+ if (container) {+ render(null, container);+ container.remove();+ }++ const note = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ ...(width ? { "#boardCardWidth": width } : {}),+ children: [ { title: "First", "#status": "To Do" } ]+ });++ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);++ await act(async () => {+ render(+ <ParentComponent.Provider value={new Component()}>+ <Harness+ note={note}+ noteIds={[ ...note.getChildNoteIds() ]}+ initialConfig={{ columns: [ { value: "To Do" } ] }}+ />+ </ParentComponent.Provider>,+ mountPoint+ );+ });+ await act(async () => { await flush(); });++ const board = mountPoint.querySelector<HTMLElement>(".board-view");+ if (!board) throw new Error("expected the board to be drawn");+ return board;+ }+});diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 28e0de6c3b..16042ebcc7 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -53,7 +53,10 @@ import { forgetWindowHeights } from "./windowing";import { BoardDropStateContext, DropStateStore } from "./drop_state";import BoardApi from "./api";import { adoptLegacyColumns, readColumns } from "./column_storage";-import { DEFAULT_COLUMN_ICON, DEFAULT_GROUP_BY, getStatusDefinition, INBOX_COLUMN } from "./columns";+import {+ COLUMN_WIDTH_LABEL, DEFAULT_COLUMN_ICON, DEFAULT_COLUMN_WIDTH, DEFAULT_GROUP_BY,+ getStatusDefinition, INBOX_COLUMN, parseColumnWidth+} from "./columns";import Column, { EXPAND_MS, placeCard, settleCards } from "./column";import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";import ColumnLimitDialog from "./column_limit";@@ -351,6 +354,8 @@ export default function BoardView({let viewConfig = adoptedConfig ?? storedConfig;const [ includeArchived ] = useNoteLabelBoolean(parentNote, "includeArchived");const [ inboxEnabled ] = useNoteLabelBoolean(parentNote, "enableInboxColumn");+ const [ storedColumnWidth ] =+ useNoteLabelWithDefault(parentNote, COLUMN_WIDTH_LABEL, DEFAULT_COLUMN_WIDTH);/** Every card the board holds, which an active filter narrows before the cards are drawn. */const [ allByColumn, setAllByColumn ] = useState<ColumnMap>();const [ columns, setColumns ] = useState<string[]>();@@ -1198,7 +1203,7 @@ export default function BoardView({: undefined;return (- <div className={clsx("board-view", {+ <div className={clsx("board-view", `board-${parseColumnWidth(storedColumnWidth)}-columns`, {frozen: isFrozen,"editing-open": branchIdToEdit !== undefined || insertingColumns.size > 0})}>diff --git a/apps/client/src/widgets/collections/board/properties.spec.tsx b/apps/client/src/widgets/collections/board/properties.spec.tsxindex 6c14985dbd..4c0860469c 100644--- a/apps/client/src/widgets/collections/board/properties.spec.tsx+++ b/apps/client/src/widgets/collections/board/properties.spec.tsx@@ -62,6 +62,8 @@ describe("Board properties", () => {let labels: Record<string, string>;/** What the board was asked to do with the order it holds. */let sorting: string[];+ /** The widths the board was asked to draw its columns at. */+ let widths: string[];/** Draws the dialog again, for a test that changed what the board says. */let draw: () => void;@@ -70,6 +72,7 @@ describe("Board properties", () => {storedAttributes = [];toggled = [];sorting = [];+ widths = [];labels = { includeArchived: "true" };container = document.createElement("div");document.body.appendChild(container);@@ -102,7 +105,8 @@ describe("Board properties", () => {setDefaultSortDirection: async (isDescending: boolean) => {sorting.push(`descending:${isDescending}`);},- resetColumnSortsToDefault: async () => { sorting.push("reset"); }+ resetColumnSortsToDefault: async () => { sorting.push("reset"); },+ setColumnWidth: async (width: string) => { widths.push(width); }} as unknown as BoardApi;draw = () => act(() => {@@ -154,7 +158,7 @@ describe("Board properties", () => {const rows = general()?.querySelectorAll(".tn-card-section:not(.tn-card-section-nested)") ?? [];- expect(rows.length).toBe(3);+ expect(rows.length).toBe(4);expect(toggleAt(0)?.classList.contains("on")).toBe(false);expect(toggleAt(1)?.classList.contains("on")).toBe(true);});@@ -217,6 +221,44 @@ describe("Board properties", () => {}});+ describe("how wide it draws its columns", () => {+ it("offers the three widths the board knows", () => {+ // happy-dom does not follow which option Preact marks as selected, so what the board+ // holds is covered by `parseColumnWidth` and the api instead.+ expect([ ...(picker()?.options ?? []) ].map((option) => option.textContent)).toEqual([+ "board_view.column-width-narrow",+ "board_view.column-width-medium",+ "board_view.column-width-wide"+ ]);+ });++ it("asks the board for the width that was picked", () => {+ const select = picker();+ if (!select) throw new Error("expected a width picker on the board properties");++ act(() => {+ select.value = "medium";+ select.dispatchEvent(new Event("change", { bubbles: true }));+ });++ expect(widths).toEqual([ "medium" ]);+ });++ /** A phone lays the columns out at a width of its own, so there is nothing to pick. */+ it("is left out on mobile", () => {+ window.glob.device = "mobile";+ act(() => { render(null, container); });+ draw();++ expect(picker()).toBeFalsy();+ window.glob.device = "desktop";+ });++ function picker() {+ return general()?.querySelector<HTMLSelectElement>("select");+ }+ });+it("holds the promoted attributes, in the board's own words and from its own config", () => {const card = dialog()?.querySelector<HTMLElement>(".attributes-stub");diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsxindex a971fbfc95..da95f94ed3 100644--- a/apps/client/src/widgets/collections/board/properties.tsx+++ b/apps/client/src/widgets/collections/board/properties.tsx@@ -5,9 +5,11 @@ import { useCallback } from "preact/hooks";import type FNote from "../../../entities/fnote";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";+import { isMobile } from "../../../services/utils";import { Card, CardSection, OptionCardSection } from "../../react/Card";+import FormSelect from "../../react/FormSelect";import FormToggle from "../../react/FormToggle";-import { useNoteLabelBoolean } from "../../react/hooks";+import { useNoteLabelBoolean, useNoteLabelWithDefault } from "../../react/hooks";import Modal from "../../react/Modal";import PromotedAttributesCard from "../../react/PromotedAttributesCard";import TemplateSelectionCard from "../../react/TemplateSelectionCard";@@ -15,6 +17,7 @@ import type { PromotedAttribute } from "../promoted_attributes";import SortDropdown from "../SortDropdown";import { parseSortKey } from "../sorting";import BoardApi from "./api";+import { COLUMN_WIDTH_LABEL, DEFAULT_COLUMN_WIDTH, parseColumnWidth } from "./columns";import { useBoardSort } from "./sort";/** The board's settings, other than its columns and cards. */@@ -66,6 +69,8 @@ export default function BoardProperties({ api, note, shown, onClose }: {function General({ api, note }: { api: BoardApi, note: FNote }) {const [ inboxShown ] = useNoteLabelBoolean(note, "enableInboxColumn");const [ archivedShown ] = useNoteLabelBoolean(note, "includeArchived");+ const [ columnWidth ] =+ useNoteLabelWithDefault(note, COLUMN_WIDTH_LABEL, DEFAULT_COLUMN_WIDTH);const defaultSort = useBoardSort(note);// Every column at once, and a column's own order is not kept anywhere else: the reader is asked// before it goes.@@ -98,6 +103,26 @@ function General({ api, note }: { api: BoardApi, note: FNote }) {/></OptionCardSection>+ {/* A phone draws the columns at a width of its own, so there is nothing to pick. */}+ {!isMobile() && (+ <OptionCardSection+ name="board-column-width"+ label={t("board_view.column-width")}+ >+ <FormSelect+ values={[+ { value: "narrow", title: t("board_view.column-width-narrow") },+ { value: "medium", title: t("board_view.column-width-medium") },+ { value: "wide", title: t("board_view.column-width-wide") }+ ]}+ keyProperty="value"+ titleProperty="title"+ currentValue={parseColumnWidth(columnWidth)}+ onChange={(width) => api.setColumnWidth(parseColumnWidth(width))}+ />+ </OptionCardSection>+ )}+<OptionCardSectionname="board-sort-cards"label={t("board_view.default-card-order")}diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.tsindex 270b7f3c09..57595e6e4c 100644--- a/packages/commons/src/lib/builtin_attributes.ts+++ b/packages/commons/src/lib/builtin_attributes.ts@@ -271,6 +271,9 @@ const BUILTIN_ATTRIBUTES = [{ type: "label", name: "enableInboxColumn", valueType: "boolean", hasUserValue: true },// Carried by a card that stands in for another note: opening it navigates there instead.{ type: "relation", name: "boardCardRedirectTo" },+ // How wide the board draws its columns. Absent for the narrow default.+ { type: "label", name: "boardCardWidth", valueType: "select", hasUserValue: true,+ selectOptions: [ "narrow", "medium", "wide" ] },// The order a board offers for its columns, which its properties apply to every column at once.{ type: "label", name: "sortColumns", valueType: "text", hasUserValue: true },{ type: "label", name: "sortColumnsDescending", valueType: "boolean", hasUserValue: true },