Skip to content

Build your personal knowledge base with Trilium Notes

feat(board): leave the editing controls out of a read-only board

Elian Doran02e7296932f3
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index e5d3763c38..26b27652e1 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -147,6 +147,8 @@ export default class BoardApi {
noteContext: NoteContext | null | undefined;
/** Opens a note where the board's host shows notes, in place of the quick edit popup. */
onOpenNote: ((noteId: string) => void) | undefined;
+ /** Whether the board only shows its cards, set by the board on every render. */
+ isReadOnly = false;
/**
* Stands in for the stored collapse flags while a filter is on, set by the board on every
@@ -1486,7 +1488,9 @@ export default class BoardApi {
}
startEditing(branchId: string) {
- this.setBranchIdToEdit(branchId);
+ if (!this.isReadOnly) {
+ this.setBranchIdToEdit(branchId);
+ }
}
dismissEditingTitle() {
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index ef0fcb8602..731dd62125 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -149,7 +149,8 @@ function Card({
selection.clear();
}
- const cards = api.getCards(selection.keys);
+ // A read-only board offers only what concerns the card itself, so the menu is this card's.
+ const cards = api.isReadOnly ? [] : api.getCards(selection.keys);
openNoteContextMenu(api, e, {
note,
branchId: branch.branchId,
@@ -237,6 +238,11 @@ function Card({
}, [ setBranchIdToEdit, branch ]);
const handleKeyDown = useCallback((e: KeyboardEvent) => {
+ // Both keys edit the board.
+ if (api.isReadOnly) {
+ return;
+ }
+
if (e.key === "Enter" && !e.ctrlKey) {
// Enter adds a card the way it adds a row in a spreadsheet, and Space is what opens
// one. Shift adds it above instead of below.
@@ -245,7 +251,7 @@ function Card({
} else if (e.key === "F2") {
setBranchIdToEdit(branch.branchId);
}
- }, [ branch, index, setBranchIdToEdit, onInsert ]);
+ }, [ api, branch, index, setBranchIdToEdit, onInsert ]);
useEffect(() => {
editorRef.current?.focus();
@@ -363,7 +369,7 @@ function Card({
badges={isOutsideFilter && <OutsideFilterBadge />}
/>
</div>
- {isRailDrawn && overlayHost.current && (
+ {isRailDrawn && overlayHost.current && !api.isReadOnly && (
<CardToolbar
host={overlayHost.current}
isLeaving={!isRailShown}
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index ff7e5ca602..59543945f7 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -1,6 +1,6 @@
import clsx from "clsx";
import { Fragment, TargetedMouseEvent, TargetedWheelEvent } from "preact";
-import { flushSync } from "preact/compat";
+import { flushSync, lazy, Suspense } from "preact/compat";
import {
useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState
} from "preact/hooks";
@@ -17,7 +17,6 @@ import { isMobile } from "../../../services/utils";
import { DragData, TREE_CLIPBOARD_TYPE } from "../../note_tree";
import ActionButton from "../../react/ActionButton";
import Icon from "../../react/Icon";
-import { IconPickerButton } from "../../react/IconPicker";
import { useIsOnScreen, useLingeringTrue, useStaticTooltip } from "../../react/hooks";
import { useFlip } from "../../react/flip";
import { useScrollFade } from "../../react/scroll_fade";
@@ -463,7 +462,7 @@ export default function Column({
}, [ column, isActive, isPeeked, setActiveColumn ]);
// Only for a sorted column. The arrow shows which way the order runs.
- const sortButton = sort && (
+ const sortButton = sort && !api.isReadOnly && (
<ActionButton
className="column-sort"
icon={sort.isDescending ? "bx bx-sort-down" : "bx bx-sort-up"}
@@ -531,6 +530,10 @@ export default function Column({
}, [ color ]);
const handleTitleKeyDown = useCallback((e: KeyboardEvent) => {
+ if (api.isReadOnly) {
+ return;
+ }
+
if (e.key === "F2" && !isCollapsed) {
setColumnNameToEdit(column);
}
@@ -556,7 +559,7 @@ export default function Column({
beginInsert(0);
}
}
- }, [ beginInsert, beginNewItem, collapse, column, isCollapsed, isSorted ]);
+ }, [ api, beginInsert, beginNewItem, collapse, column, isCollapsed, isSorted ]);
const overlayHost = useContext(BoardOverlayHostContext);
/** Whether the heading holds the focus, which on mobile floats the column's rail. */
@@ -664,7 +667,7 @@ export default function Column({
// The field a card is inserted in, drawn where the reader asked for the card. The same field
// as the one below the column, so a card is made the same way wherever it goes.
- const insertField = insertBefore && (
+ const insertField = insertBefore && !api.isReadOnly && (
<AddNewItem
api={api}
cardTemplates={cardTemplates}
@@ -775,15 +778,19 @@ export default function Column({
) : (<>
{/* 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={api.getColumnIcon(column) ?? DEFAULT_COLUMN_ICON}
- title={t("board_view.change-column-icon")}
- onSelect={(picked) => api.setColumnIcon(column, picked)}
- onReset={icon ? () => api.setColumnIcon(column, undefined) : undefined}
- />
- )}
+ {!isInRelationMode && (api.isReadOnly
+ ? <StaticColumnIcon api={api} column={column} />
+ : (
+ <Suspense fallback={<StaticColumnIcon api={api} column={column} />}>
+ <IconPickerButton
+ className="column-icon"
+ icon={api.getColumnIcon(column) ?? DEFAULT_COLUMN_ICON}
+ title={t("board_view.change-column-icon")}
+ onSelect={(picked) => api.setColumnIcon(column, picked)}
+ onReset={icon ? () => api.setColumnIcon(column, undefined) : undefined}
+ />
+ </Suspense>
+ ))}
{!isEditing ? (
<>
@@ -866,7 +873,7 @@ export default function Column({
<div ref={roomRef} className="board-drop-room" />
</div>}
- {isRailDrawn && overlayHost.current && (
+ {isRailDrawn && overlayHost.current && !api.isReadOnly && (
<ColumnToolbar
host={overlayHost.current}
isLeaving={!isRailShown}
@@ -877,7 +884,7 @@ export default function Column({
onFocusOut={handleHeaderFocusOut}
/>
)}
- {!isCollapsed && <AddNewItem
+ {!isCollapsed && !api.isReadOnly && <AddNewItem
api={api}
cardTemplates={cardTemplates}
column={column}
@@ -890,6 +897,18 @@ export default function Column({
);
}
+/**
+ * Loaded once a column can change its icon, so a read-only board never loads the picker and the
+ * grid of every icon pack it brings.
+ */
+const IconPickerButton = lazy(() => import("../../react/IconPicker")
+ .then(({ IconPickerButton: button }) => ({ default: button })));
+
+/** The column's icon on its ring, as the picker's button draws it, for a column that cannot change it. */
+function StaticColumnIcon({ api, column }: { api: BoardApi; column: string }) {
+ return <Icon className="column-icon static" icon={api.getColumnIcon(column) ?? DEFAULT_COLUMN_ICON} />;
+}
+
/**
* Puts a card where a transform says, easing it there unless the board is drawing a still frame.
*
diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.ts
index a24cd70e7b..3d1bbda628 100644
--- a/apps/client/src/widgets/collections/board/context_menu.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.ts
@@ -2,7 +2,7 @@ import { useState } from "preact/hooks";
import type { CommandNames } from "../../../components/app_context";
import FNote from "../../../entities/fnote";
-import contextMenu, { ContextMenuEvent, MenuItem } from "../../../menus/context_menu";
+import contextMenu, { ContextMenuEvent, MenuHandler, MenuItem } from "../../../menus/context_menu";
import { getArchiveMenuItems, menuName } from "../../../menus/context_menu_utils";
import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker";
import link_context_menu from "../../../menus/link_context_menu";
@@ -66,6 +66,18 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:
// What the column is, which a collapsed column that is not the inbox has nothing of. Kept in
// a group of its own only while it holds something, or the menu opens on a divider.
+ const copyReference: MenuItem<string> = {
+ title: t("board_view.copy-reference"),
+ uiIcon: "bx bx-copy",
+ handler: async () => copyReferenceWithToast(await api.getColumnReference(column.value))
+ };
+
+ // Everything else the menu offers changes the board.
+ if (api.isReadOnly) {
+ contextMenu.show({ x: event.pageX, y: event.pageY, items: [ copyReference ], selectMenuItemHandler() {} });
+ return;
+ }
+
const identity: MenuItem<string>[] = [
...(column.canRename ? [ {
title: t("board_view.rename-column"),
@@ -79,11 +91,7 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:
checked: column.nested,
handler: () => api.setInboxNested(!column.nested)
} ] : []),
- {
- title: t("board_view.copy-reference"),
- uiIcon: "bx bx-copy",
- handler: async () => copyReferenceWithToast(await api.getColumnReference(column.value))
- }
+ copyReference
];
contextMenu.show({
@@ -555,26 +563,34 @@ export function openNoteContextMenu(api: Api, event: ContextMenuEvent, target: N
const identity: MenuItem<CommandNames>[] = !isSingle ? [] : [
// Space opens the same popup for the card the cursor stands on.
{ ...link_context_menu.getQuickEditItem(), shortcut: "Space" },
- {
+ ...(api.isReadOnly ? [] : [ {
title: t("board_view.edit-title"),
uiIcon: "bx bx-rename",
shortcut: "F2",
handler: () => api.startEditing(branchId)
- },
+ } ]),
link_context_menu.getOpenNoteItem(event),
{
title: t("board_view.copy-reference"),
uiIcon: "bx bx-copy",
handler: () => copyReferenceWithToast(api.getCardReference(note.noteId))
- },
- { kind: "separator" }
+ }
];
+ const selectMenuItemHandler: MenuHandler<CommandNames> = ({ command }) =>
+ link_context_menu.handleLinkContextMenuItem(command, event, note.noteId);
+
+ // What a read-only board's menu keeps: the card's own entries, which change nothing.
+ if (api.isReadOnly) {
+ contextMenu.show({ x: event.pageX, y: event.pageY, items: identity, selectMenuItemHandler });
+ return;
+ }
contextMenu.show({
x: event.pageX,
y: event.pageY,
items: [
...identity,
+ ...(identity.length ? [ { kind: "separator" } as MenuItem<CommandNames> ] : []),
...placement,
{ kind: "header", title: api.getStatusLabel() },
...buildColumnItems(api, target),
@@ -606,7 +622,7 @@ export function openNoteContextMenu(api: Api, event: ContextMenuEvent, target: N
: CardsColorPicker({ notes })
}
],
- selectMenuItemHandler: ({ command }) => link_context_menu.handleLinkContextMenuItem(command, event, note.noteId),
+ selectMenuItemHandler
});
}
diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.css
index 9edd9d053a..503775692f 100644
--- a/apps/client/src/widgets/collections/board/index.css
+++ b/apps/client/src/widgets/collections/board/index.css
@@ -288,6 +288,18 @@ body.mobile .board-view-container .board-add-column {
margin-inline-end: 0.4em;
}
+.board-view-container .board-column h3 > .column-icon.static {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: calc(1em + var(--note-icon-container-padding-size) * 2);
+ height: calc(1em + var(--note-icon-container-padding-size) * 2);
+ border-radius: 50%;
+ background: var(--note-icon-custom-background-color, var(--note-icon-background-color));
+ color: var(--note-icon-custom-color, var(--note-icon-color));
+ font-size: var(--note-icon-size);
+}
+
.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;
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index b4c5d86a5b..c1666227b7 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -5600,3 +5600,90 @@ describe("Column toolbar on mobile", () => {
show.mockRestore();
});
});
+
+describe("BoardView, read-only", () => {
+ let container: HTMLElement | undefined;
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ saved.length = 0;
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ async function setup() {
+ const note = buildNote({
+ title: "Board",
+ "#collection": "",
+ "#viewType": "board",
+ "#readOnly": "",
+ children: [
+ { id: "roCard1", title: "First", "#status": "To Do" },
+ { id: "roCard2", title: "Second", "#status": "Done" }
+ ]
+ });
+ 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={{}} />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ });
+ await act(async () => { await flush(); });
+ return mountPoint;
+ }
+
+ /** The titles of the entries of the menu last shown. */
+ const menuTitles = (show: { mock: { calls: unknown[][] } }) =>
+ ((show.mock.calls.at(-1)?.[0] as { items: { title?: string }[] } | undefined)?.items ?? [])
+ .map((item) => item.title);
+
+ it("offers no way to add a card or a column, nor to rename either", async () => {
+ const board = await setup();
+ const column = board.querySelector<HTMLElement>(".board-column");
+ const card = board.querySelector<HTMLElement>(".board-note");
+ expect(column === null || card === null).toBe(false);
+
+ expect(board.querySelector(".board-new-item")).toBeNull();
+ expect(board.querySelector(".board-add-column")).toBeNull();
+ expect(board.querySelector(".board-column h3 > .column-icon.static")).not.toBeNull();
+ expect(board.querySelector(".board-column h3 > .column-icon button")).toBeNull();
+
+ await act(async () => {
+ if (column) startEditingTitle(column);
+ card?.dispatchEvent(new KeyboardEvent("keydown", { key: "F2", bubbles: true }));
+ card?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ await flush();
+ });
+ expect(board.querySelector(".board-column h3.editing")).toBeNull();
+ expect(board.querySelectorAll(".board-note.editing, .board-new-item").length).toBe(0);
+ });
+
+ it("keeps only the entries that change nothing in the menus, and shows none for the board", async () => {
+ const board = await setup();
+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
+
+ await withTabManager(async () => {
+ board.querySelector(".board-note")?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+ });
+ const cardMenu = menuTitles(show);
+ expect(cardMenu).toContain("board_view.copy-reference");
+ expect(cardMenu).not.toContain("board_view.edit-title");
+ expect(cardMenu).not.toContain("board_view.delete-note");
+
+ board.querySelector(".board-column h3")?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+ expect(menuTitles(show)).toEqual([ "board_view.copy-reference" ]);
+
+ const calls = show.mock.calls.length;
+ board.querySelector(".board-view-container")
+ ?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+ expect(show.mock.calls.length).toBe(calls);
+ });
+});
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 24a503acd4..5a4edef605 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -38,7 +38,7 @@ import { FormListItem } from "../../react/FormList";
import FormTextArea from "../../react/FormTextArea";
import FormTextBox from "../../react/FormTextBox";
import {
- useContextualShortcutHints, useLingeringTrue, useNoteContext, useNoteLabel,
+ useContextualShortcutHints, useEffectiveReadOnly, useLingeringTrue, useNoteContext, useNoteLabel,
useNoteLabelBoolean, useNoteLabelWithDefault, useNoteTypeOptions, useSetContextData,
useTrackedElement, useTriliumEvent
} from "../../react/hooks";
@@ -363,6 +363,7 @@ export default function BoardView({
note: parentNote, noteIds, viewConfig: storedConfig, saveConfig, onOpenNote
}: ViewModeProps<BoardViewData>) {
const { noteContext } = useNoteContext();
+ const isReadOnly = useEffectiveReadOnly(parentNote, noteContext);
const [ requestedGroupBy, setRequestedGroupBy ] =
useNoteLabelWithDefault(parentNote, "board:groupBy", DEFAULT_GROUP_BY);
/**
@@ -605,6 +606,7 @@ export default function BoardView({
// pane other than the focused one.
api.noteContext = noteContext;
api.onOpenNote = onOpenNote;
+ api.isReadOnly = isReadOnly;
// Every member is one of useState's own setters, so this value is built once and never changes
// identity -- a drag cannot reach anything that reads only this.
const collapseAllColumns = useCallback(() => {
@@ -622,7 +624,8 @@ export default function BoardView({
const openBoardMenu = useCallback((event: ContextMenuEvent) => {
// Only the ground the columns stand on. A column and a card answer for their own presses,
// and what they leave alone, such as the button that makes a card, is left alone here too.
- if ((event.target as HTMLElement)?.closest(".board-column, .board-add-column")) {
+ // Every entry of the board's menu changes the board.
+ if (isReadOnly || (event.target as HTMLElement)?.closest(".board-column, .board-add-column")) {
return;
}
@@ -634,7 +637,7 @@ export default function BoardView({
onCollapseAll: collapseAllColumns,
onExpandAll: expandAllColumns
});
- }, [ api, collapseAllColumns, expandAllColumns, inboxEnabled, includeArchived ]);
+ }, [ api, collapseAllColumns, expandAllColumns, inboxEnabled, includeArchived, isReadOnly ]);
// Read from the api rather than from the prop, since a pick moves the api's own copy ahead of
// the board's; keyed on the prop so that a change from anywhere else is followed too.
@@ -1525,14 +1528,14 @@ export default function BoardView({
</div>
- <AddNewColumn
+ {!isReadOnly && <AddNewColumn
api={api}
isInRelationMode={isInRelationMode}
columnCount={shownColumns.length}
onCreated={setCreatedColumn}
isCreating={isCreatingColumn}
setIsCreating={setIsCreatingColumn}
- />
+ />}
{/* Where what is being carried is put. Preact draws the layer and never
its contents, so the copy is not among the children it places. */}
<div className="board-drag-layer" />