Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: allow columns to be collapsed

Adorian Doran4635ba712b76
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 62df2a45b2..c7348a0b7a 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3403,6 +3403,7 @@
"add-column-placeholder": "Enter column name...",
"edit-note-title": "Click to edit note title",
"rename-column": "Rename column",
+ "collapse-column": "Collapse column",
"set-limit": "Set limit...",
"set-limit-ok": "Set limit",
"limit-capacity": "Warn for exceeding the column capacity",
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index 789523ec0a..8f9041ecc0 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -1061,6 +1061,32 @@ describe("renaming a column to nothing", () => {
});
});
+describe("collapsing a column", () => {
+ it("stores the flag and clears it rather than storing it false", async () => {
+ const { api, saved } = createApi(
+ { columns: [ { value: "To Do" }, { value: "Done" } ] }, [ "To Do", "Done" ]);
+
+ expect(api.isColumnCollapsed("To Do")).toBe(false);
+
+ await api.setColumnCollapsed("To Do", true);
+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do", collapsed: true }, { value: "Done" } ]);
+
+ await api.setColumnCollapsed("To Do", false);
+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do" }, { value: "Done" } ]);
+ });
+
+ it("leaves the column's other properties alone", async () => {
+ const { api, saved } = createApi(
+ { columns: [ { value: "To Do", icon: "bx bx-star", limit: 3 } ] }, [ "To Do" ]);
+
+ await api.setColumnCollapsed("To Do", true);
+
+ expect(saved.at(-1)?.columns).toEqual([
+ { value: "To Do", icon: "bx bx-star", limit: 3, collapsed: true }
+ ]);
+ });
+});
+
describe("reordering columns the board is not showing all of", () => {
/**
* A column the config keeps but the board does not show, such as a disabled inbox, is missing
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index c6f216da27..df349e72ed 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -417,6 +417,16 @@ export default class BoardApi {
this.updateColumn(column, { archived });
}
+ /** Whether a column is stored as collapsed, which draws it as a strip without its cards. */
+ isColumnCollapsed(column: string) {
+ return !!this.viewConfig?.columns?.find(col => col.value === column)?.collapsed;
+ }
+
+ /** Collapses a column to a strip, or opens it again. */
+ async setColumnCollapsed(column: string, collapsed: boolean) {
+ this.updateColumn(column, { collapsed });
+ }
+
/**
* Writes properties onto a column, dropping each one given as nothing so that it goes back to
* its default rather than being stored empty.
@@ -431,6 +441,7 @@ export default class BoardApi {
if (!updated.icon) delete updated.icon;
if (!updated.color) delete updated.color;
if (!updated.archived) delete updated.archived;
+ if (!updated.collapsed) delete updated.collapsed;
if (!updated.displayName) delete updated.displayName;
if (!updated.limit) delete updated.limit;
return updated;
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index a1b425db7b..373995b72d 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -40,6 +40,8 @@ export default function Column({
icon,
color,
archived,
+ collapsed,
+ isActive,
nested,
limit,
isDraggingColumn,
@@ -57,6 +59,10 @@ export default function Column({
color?: string,
/** Whether the column is archived. Only ever rendered while archived notes are shown. */
archived?: boolean,
+ /** Whether the column is stored as collapsed. Selecting it opens it without clearing this. */
+ collapsed?: boolean,
+ /** Whether this is the column the reader is working in, which opens it while it is collapsed. */
+ isActive?: boolean,
/** Whether the inbox also collects notes deeper than the board's direct children. */
nested?: boolean,
/** The note limit, absent if disabled. */
@@ -76,7 +82,8 @@ export default function Column({
} & DragContext) {
const [ isVisible, setVisible ] = useState(true);
const [ isCreatingNewItem, setIsCreatingNewItem ] = useState(false);
- const { setColumnNameToEdit, setColumnLimitToEdit } = useContext(BoardActionsContext);
+ const { setColumnNameToEdit, setColumnLimitToEdit, setActiveColumn } =
+ useContext(BoardActionsContext);
const { branchIdToEdit, columnNameToEdit, dropTarget, draggedCard, dropPosition } = useContext(BoardDragStateContext);
const isEditing = (columnNameToEdit === column);
const editorRef = useRef<HTMLInputElement>(null);
@@ -86,6 +93,38 @@ export default function Column({
// Read here rather than in the badge: the column body shows an outline as well.
const isOverLimit = limit !== undefined && (columnItems?.length ?? 0) > limit;
+ const isCollapsed = !!collapsed && !isActive;
+
+ // Reported on the way in only. A column opened by being selected closes when another one is
+ // selected, so nothing here watches for focus leaving: the menu, the icon picker and the limit
+ // dialog all render outside the column, and each would otherwise close it as it opened.
+ const select = useCallback(() => setActiveColumn(column), [ column, setActiveColumn ]);
+
+ // A press on the header may be the start of a drag, which must leave the column as it is: the
+ // strip is what the reader takes hold of to move it. A click settles which one it was, a drag
+ // producing none. Focus arriving while the pointer is down is that same press, so only focus
+ // reached by keyboard opens the column.
+ const isPointerDown = useRef(false);
+ const handlePointerDown = useCallback(() => {
+ isPointerDown.current = true;
+
+ const release = () => {
+ isPointerDown.current = false;
+ controller.abort();
+ };
+ // A drag ends with `dragend` and no `pointerup` at all, so both have to release it.
+ const controller = new AbortController();
+ document.addEventListener("pointerup", release, { signal: controller.signal });
+ document.addEventListener("dragend", release, { signal: controller.signal });
+ }, []);
+
+ // Focus reaching a column closes whichever one was open, and opens nothing: a collapsed column
+ // is walked onto without being disturbed, and is opened by a click or by Space instead.
+ const handleFocusIn = useCallback(() => {
+ if (!isActive) {
+ setActiveColumn(undefined);
+ }
+ }, [ isActive, setActiveColumn ]);
const openMenu = useCallback((e: ContextMenuEvent) => {
openColumnContextMenu(api, e, {
@@ -94,6 +133,8 @@ export default function Column({
index: columnIndex,
color,
archived,
+ collapsed,
+ canRename: !isCollapsed,
nested,
onEditTitle: () => setColumnNameToEdit(column),
onNewItem: () => setIsCreatingNewItem(true),
@@ -101,6 +142,14 @@ export default function Column({
setColumnNameToEdit(await api.insertColumn(column, direction));
},
onSetLimit: () => setColumnLimitToEdit(column),
+ onCollapse: (collapse) => {
+ api.setColumnCollapsed(column, collapse);
+ // The menu is opened from the column, which is therefore the open one. Closing it
+ // here is what shows the reader that anything happened.
+ if (collapse) {
+ setActiveColumn(undefined);
+ }
+ },
onMoveColumn: (toIndex) => {
onMoveColumn(columnIndex, toIndex);
// Asked for by name: the move draws the board again, and the heading the menu was
@@ -109,8 +158,8 @@ export default function Column({
}
});
}, [
- api, column, color, archived, nested, columns, columnIndex,
- setColumnNameToEdit, setColumnLimitToEdit, onMoveColumn, onFocusColumn
+ api, column, color, archived, collapsed, isCollapsed, nested, columns, columnIndex,
+ setColumnNameToEdit, setColumnLimitToEdit, setActiveColumn, onMoveColumn, onFocusColumn
]);
// A fully desaturated colour has no hue to tint with, and leaves the column plain.
@@ -120,10 +169,10 @@ export default function Column({
}, [ color ]);
const handleTitleKeyDown = useCallback((e: KeyboardEvent) => {
- if (e.key === "F2") {
+ if (e.key === "F2" && !isCollapsed) {
setColumnNameToEdit(column);
}
- }, [ column ]);
+ }, [ column, isCollapsed ]);
/** Allow using mouse wheel to scroll inside card, while also maintaining column horizontal scrolling. */
const handleScroll = useCallback((event: JSX.TargetedWheelEvent<HTMLDivElement>) => {
@@ -159,8 +208,12 @@ export default function Column({
// The class the themes key a hue off, worn here as anywhere else that carries one.
"with-hue": hue !== undefined,
"board-column-archived": archived,
- "over-limit": isOverLimit
+ "over-limit": isOverLimit,
+ collapsed: isCollapsed
})}
+ onFocusIn={handleFocusIn}
+ onPointerDown={handlePointerDown}
+ onClick={select}
onDragOver={isAnyColumnDragging ? handleColumnDragOver : handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
@@ -178,6 +231,29 @@ export default function Column({
onKeyDown={handleTitleKeyDown}
tabIndex={300}
>
+ {isCollapsed ? (
+ <>
+ <ActionButton
+ className="column-menu"
+ icon="bx bx-dots-vertical-rounded"
+ text={t("board_view.column-menu")}
+ onClick={(e) => {
+ e.stopPropagation();
+ openMenu(e);
+ }}
+ />
+ <CountBadge items={columnItems} limit={limit} isOver={isOverLimit} />
+ <span className="title">
+ {isInRelationMode
+ ? <NoteLink notePath={column} />
+ : api.getColumnTitle(column)}
+ </span>
+ <Icon
+ className="column-icon"
+ icon={api.getColumnIcon(column) ?? DEFAULT_COLUMN_ICON}
+ />
+ </>
+ ) : (<>
{/* 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 && (
@@ -228,9 +304,10 @@ export default function Column({
mode={isInRelationMode && column !== INBOX_COLUMN ? "relation" : "normal"}
/>
)}
+ </>)}
</h3>
- <div className="board-column-content" onWheel={handleScroll}>
+ {!isCollapsed && <div className="board-column-content" onWheel={handleScroll}>
{(columnItems ?? []).map(({ note, branch }, index) => {
const showIndicatorBefore = dropPosition?.column === column &&
dropPosition.index === index &&
@@ -265,7 +342,7 @@ export default function Column({
isCreating={isCreatingNewItem}
setIsCreating={setIsCreatingNewItem}
/>
- </div>
+ </div>}
</div>
);
}
@@ -396,7 +473,8 @@ ${warning}` : counts}
}
function useDragging({ column, columnIndex, columnItems, isEditing, api, parentNote }: DragContext & { isEditing: boolean, api: BoardApi, parentNote: FNote }) {
- const { setDraggedColumn, setDropTarget, setDropPosition } = useContext(BoardActionsContext);
+ const { setDraggedColumn, setDropTarget, setDropPosition, setActiveColumn } =
+ useContext(BoardActionsContext);
const { draggedColumn, dropPosition } = useContext(BoardDragStateContext);
/** Needed to track if current column is dragged in real-time, since {@link draggedColumn} is populated one render cycle later. */
const isDraggingRef = useRef(false);
@@ -407,7 +485,15 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentN
isDraggingRef.current = true;
e.dataTransfer!.effectAllowed = 'move';
e.dataTransfer!.setData('text/plain', column);
- setDraggedColumn({ column, index: columnIndex });
+
+ const element = (e.currentTarget as HTMLElement).closest<HTMLElement>(".board-column");
+ setDraggedColumn({
+ column,
+ index: columnIndex,
+ size: element
+ ? { width: element.offsetWidth, height: element.offsetHeight }
+ : undefined
+ });
e.stopPropagation(); // Prevent card drag from interfering
}, [column, columnIndex, setDraggedColumn, isEditing]);
@@ -422,6 +508,9 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentN
e.preventDefault();
setDropTarget(column);
+ // A collapsed column opens to take the card and stays open afterwards, so the card can be
+ // placed among the ones already there.
+ setActiveColumn(column);
// Calculate drop position based on mouse position
const cards = Array.from((e.currentTarget as HTMLElement)?.querySelectorAll('.board-note'));
@@ -442,7 +531,7 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentN
if (!(dropPosition?.column === column && dropPosition.index === newIndex)) {
setDropPosition({ column, index: newIndex });
}
- }, [column, setDropTarget, dropPosition, setDropPosition, isEditing]);
+ }, [column, setDropTarget, setActiveColumn, dropPosition, setDropPosition, isEditing]);
const handleDragLeave = useCallback((e: DragEvent) => {
const relatedTarget = e.relatedTarget as HTMLElement;
diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.ts
index 8a675d907c..045a57abf9 100644
--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts
@@ -31,15 +31,16 @@ describe("Board column context menu", () => {
function openMenu(
api: BoardApi,
column: {
- value?: string, color?: string, archived?: boolean,
- columns?: string[], index?: number, nested?: boolean
+ value?: string, color?: string, archived?: boolean, collapsed?: boolean,
+ canRename?: boolean, columns?: string[], index?: number, nested?: boolean
} = {},
callbacks: {
onEditTitle?: () => void,
onNewItem?: () => void,
onAddColumn?: (direction: "before" | "after") => void,
onMoveColumn?: (toIndex: number) => void,
- onSetLimit?: () => void
+ onSetLimit?: () => void,
+ onCollapse?: (collapsed: boolean) => void
} = {}
) {
const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
@@ -56,12 +57,14 @@ describe("Board column context menu", () => {
value: "To Do",
columns: [ "To Do" ],
index: 0,
+ canRename: true,
...column,
onEditTitle: callbacks.onEditTitle ?? (() => {}),
onNewItem: callbacks.onNewItem ?? (() => {}),
onAddColumn: callbacks.onAddColumn ?? (() => {}),
onMoveColumn: callbacks.onMoveColumn ?? (() => {}),
- onSetLimit: callbacks.onSetLimit ?? (() => {})
+ onSetLimit: callbacks.onSetLimit ?? (() => {}),
+ onCollapse: callbacks.onCollapse ?? (() => {})
});
// The spy outlives one call, so it is the menu just opened that is read back.
@@ -116,6 +119,43 @@ describe("Board column context menu", () => {
expect(api.setColumnArchived).toHaveBeenLastCalledWith("To Do", false);
});
+ /** One entry that carries the state, rather than two that swap places under the pointer. */
+ it("offers one collapse entry, checked while the column is collapsed", () => {
+ const onCollapse = vi.fn();
+ const entryOf = (collapsed: boolean) => {
+ const found = openMenu({} as BoardApi, { collapsed }, { onCollapse }).find(item =>
+ item && "uiIcon" in item && item.uiIcon === "bx bx-collapse-horizontal");
+ if (!found || !("handler" in found)) throw new Error("expected a collapse entry");
+ return found;
+ };
+
+ // The check sits after the title, the entry keeping its own icon ahead of it.
+ const unchecked = entryOf(false);
+ expect("trailingIcon" in unchecked && unchecked.trailingIcon).toBeUndefined();
+ unchecked.handler?.(unchecked, {} as never);
+ expect(onCollapse).toHaveBeenLastCalledWith(true);
+
+ const checked = entryOf(true);
+ expect("trailingIcon" in checked && checked.trailingIcon).toBe("bx bx-check");
+ checked.handler?.(checked, {} as never);
+ expect(onCollapse).toHaveBeenLastCalledWith(false);
+ });
+
+ /** The strip has no title to edit, so the menu does not offer to edit one either. */
+ it("offers no rename while the column is drawn as a strip", () => {
+ // A column offers no rename only while it is drawn as a strip, which is a stored collapse.
+ const icons = (canRename: boolean) =>
+ openMenu({} as BoardApi, { canRename, collapsed: !canRename })
+ .filter(item => item && "uiIcon" in item)
+ .map(item => item && "uiIcon" in item ? item.uiIcon : undefined);
+
+ expect(icons(true)).toContain("bx bx-edit-alt");
+ expect(icons(false)).not.toContain("bx bx-edit-alt");
+ // Everything else the menu offers is still there.
+ expect(icons(false)).toContain("bx bx-collapse-horizontal");
+ expect(icons(false)).toContain("bx bx-trash");
+ });
+
/**
* The inbox holds a name of its own, so it is renamed like any other column; what it has not is
* anything to archive, and it is put away by the board's own setting instead.
@@ -165,7 +205,8 @@ describe("Board column context menu", () => {
const titled = openMenu({} as BoardApi).filter(item => item && "uiIcon" in item);
expect(titled.map(item => "uiIcon" in item ? item.uiIcon : undefined))
.toEqual([
- "bx bx-edit-alt", "bx bx-tachometer", "bx bx-plus", "bx bx-link",
+ "bx bx-edit-alt", "bx bx-collapse-horizontal", "bx bx-tachometer",
+ "bx bx-plus", "bx bx-link",
"bx bx-columns", "bx bx-horizontal-left", "bx bx-archive", "bx bx-trash"
]);
});
diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.ts
index 89ba359bd7..fc909ec016 100644
--- a/apps/client/src/widgets/collections/board/context_menu.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.ts
@@ -23,6 +23,10 @@ interface ColumnMenuTarget {
index: number;
color?: string;
archived?: boolean;
+ /** Whether the column is stored as collapsed, which the menu offers to undo. */
+ collapsed?: boolean;
+ /** Whether the title can be edited, which the strip a collapsed column is drawn as cannot. */
+ canRename: boolean;
/** Whether the inbox also collects notes deeper than the board's direct children. */
nested?: boolean;
/** Puts the title into its inline editor, the menu being the only way there besides F2. */
@@ -35,6 +39,8 @@ interface ColumnMenuTarget {
onMoveColumn: (toIndex: number) => void;
/** Opens the dialog that sets the column's note limit. */
onSetLimit: () => void;
+ /** Collapses the column or opens it for good, the board drawing the change straight away. */
+ onCollapse: (collapsed: boolean) => void;
}
export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column: ColumnMenuTarget) {
@@ -47,11 +53,17 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:
x: event.pageX,
y: event.pageY,
items: [
- {
+ ...(column.canRename ? [ {
title: t("board_view.rename-column"),
uiIcon: "bx bx-edit-alt",
shortcut: "F2",
handler: column.onEditTitle
+ } ] : []),
+ {
+ title: t("board_view.collapse-column"),
+ uiIcon: "bx bx-collapse-horizontal",
+ trailingIcon: column.collapsed ? "bx bx-check" : undefined,
+ handler: () => column.onCollapse(!column.collapsed)
},
{
title: t("board_view.set-limit"),
diff --git a/apps/client/src/widgets/collections/board/drag.spec.tsx b/apps/client/src/widgets/collections/board/drag.spec.tsx
index a9bdbeca02..50e68822fb 100644
--- a/apps/client/src/widgets/collections/board/drag.spec.tsx
+++ b/apps/client/src/widgets/collections/board/drag.spec.tsx
@@ -158,8 +158,25 @@ describe("Board drag and drop", () => {
expect(branches.moveAfterBranch).not.toHaveBeenCalled();
});
+ /**
+ * A collapsed column draws no cards, so the drop has nowhere to place one until it opens. It
+ * stays open after the pointer leaves, which is what lets the card be aimed within it.
+ */
+ it("opens a collapsed column a card is dragged over, and leaves it open", async () => {
+ const { columns } = await renderBoard({ collapsed: true });
+
+ expect(columns[0].classList.contains("collapsed")).toBe(true);
+
+ await drag(columns[0], "dragover", { types: [ CARD_CLIPBOARD_TYPE ] }, 50);
+ expect(columns[0].classList.contains("collapsed")).toBe(false);
+ expect(columns[0].querySelectorAll(".board-note")).toHaveLength(2);
+
+ await drag(columns[0], "dragleave", { types: [ CARD_CLIPBOARD_TYPE ] });
+ expect(columns[0].classList.contains("collapsed")).toBe(false);
+ });
+
/** A board of one column of two cards, each given a height the pointer can be placed in. */
- async function renderBoard() {
+ async function renderBoard({ collapsed }: { collapsed?: boolean } = {}) {
const note = buildNote({
title: "Board",
"#collection": "",
@@ -182,7 +199,7 @@ describe("Board drag and drop", () => {
notePath={`root/${note.noteId}`}
noteIds={[ ...note.getChildNoteIds() ]}
highlightedTokens={null}
- viewConfig={{ columns: [ { value: "To Do" } ] }}
+ viewConfig={{ columns: [ { value: "To Do", collapsed } ] }}
saveConfig={() => {}}
media="screen"
onReady={() => {}}
@@ -286,6 +303,35 @@ describe("Board column reordering", () => {
.toEqual([ "To Do", "Done", "Doing" ]);
});
+ /**
+ * The gap held open while a column is carried stands in for that column, and a collapsed one
+ * is a strip. A placeholder of the stock width would promise a space the column will not fill.
+ */
+ it("holds open a gap the size of the column being dragged", async () => {
+ const { columns, board } = await renderColumns();
+ for (const [ name, value ] of Object.entries({ offsetWidth: 36, offsetHeight: 140 })) {
+ Object.defineProperty(columns[0], name, { value, configurable: true });
+ }
+
+ await dragColumn(columns[0], "dragstart");
+ await dragColumn(columns[2], "dragover", 280);
+
+ const placeholder = board.querySelector<HTMLElement>(".column-drop-placeholder");
+ expect(placeholder?.style.width).toBe("36px");
+ expect(placeholder?.style.height).toBe("140px");
+ });
+
+ /** happy-dom lays nothing out, which is what an element with no size on screen reports too. */
+ it("leaves the gap at its stock size when the column measures nothing", async () => {
+ const { columns, board } = await renderColumns();
+
+ await dragColumn(columns[0], "dragstart");
+ await dragColumn(columns[2], "dragover", 280);
+
+ const placeholder = board.querySelector<HTMLElement>(".column-drop-placeholder");
+ expect(placeholder?.style.width).toBe("");
+ });
+
it("hides the column being dragged, and shows it again once let go", async () => {
const { columns } = await renderColumns();
diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.css
index 5ac84d0fbf..a995e50870 100644
--- a/apps/client/src/widgets/collections/board/index.css
+++ b/apps/client/src/widgets/collections/board/index.css
@@ -13,6 +13,11 @@
--board-limit-exceeded-background: #c62828;
/* Half opacity: the badge is the main warning, the outline supports it. */
--board-limit-exceeded-outline: #c6282880;
+ /* Matches the height a normal header takes, so a collapsed column reads as one turned on
+ its side. */
+ --board-collapsed-column-width: 2.25em;
+ --board-collapse-duration: 1s;
+
--board-focus-outline-saturation: 55%;
--board-focus-outline-lightness: 45%;
/* Follows the theme of its own accord, so neither theme has to name it again. */
@@ -54,7 +59,9 @@ body.mobile .board-view-container {
/* A column with no colour of its own is painted rather than composed: the tinted shades come
from one lightness, which does not answer for a plain one as well. */
background-color: var(--board-column-background);
- transition: border-color 0.2s ease;
+ /* Opening is instant, so a click or a drag reaches the cards at once. Closing is eased below:
+ the transition that runs is the one the element carries once the class has changed. */
+ transition: border-color 0.2s ease, width 0s;
overflow-y: auto;
max-height: 100%;
display: flex;
@@ -526,3 +533,66 @@ body.mobile .board-view-container .board-add-column {
animation: none;
}
}
+
+.board-view-container .board-column.collapsed {
+ width: var(--board-collapsed-column-width);
+ overflow: hidden;
+ /* Width is what the columns beside it are placed against, so easing it is what makes them slide
+ rather than jump. Nothing composited can do this: the shift is the point. */
+ transition: border-color 0.2s ease, width var(--board-collapse-duration) ease;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .board-view-container .board-column.collapsed {
+ transition: border-color 0.2s ease;
+ }
+}
+
+/* The strip is the whole column, so what is focused is ringed round the column. Round the header
+ inside it the ring would be clipped, an element's own overflow cutting off its descendants. */
+.board-view-container .board-column.collapsed:focus-within {
+ outline: 3px solid var(--board-focus-outline-color, var(--board-focus-outline-plain-color));
+ outline-offset: 0;
+}
+
+.board-view-container .board-column.collapsed h3:focus {
+ outline: none;
+}
+
+/* The strip's own width, taken at once, so the header stands where it will end up and only the
+ space beside it shrinks. */
+.board-view-container .board-column.collapsed h3 {
+ width: var(--board-collapsed-column-width);
+ flex-direction: column;
+ gap: 0.4em;
+ padding: 0.35em 0;
+ border-bottom: none;
+}
+
+/* The header stacks, so the margins that spaced these out in a row would throw them off centre. */
+.board-view-container .board-column.collapsed h3 > .column-icon,
+.board-view-container .board-column.collapsed h3 > .column-menu,
+.board-view-container .board-column.collapsed h3 > .counter-badge {
+ margin: 0;
+}
+
+/* The title and the count are turned on their side and read from the bottom up. `sideways-lr`
+ says this in one word, but is too new to rely on, so the box is turned the rest of the way
+ instead. The menu button keeps its own orientation. */
+.board-view-container .board-column.collapsed h3 > .title,
+.board-view-container .board-column.collapsed h3 > .counter-badge {
+ writing-mode: vertical-rl;
+ transform: rotate(180deg);
+}
+
+/* The pill turns with the count, so its padding is swapped to keep it as narrow as the strip. */
+.board-view-container .board-column.collapsed h3 > .counter-badge {
+ padding: 0.6em 0.1em;
+}
+
+.board-view-container .board-column.collapsed h3 > .title {
+ max-height: 12em;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index c9b72e456d..3d136dab37 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -120,6 +120,232 @@ function columnTitles(container: HTMLElement) {
return [ ...container.querySelectorAll(".board-column h3 .title") ].map(el => el.textContent);
}
+describe("Collapsed board columns", () => {
+ let container: HTMLElement | undefined;
+
+ afterEach(() => {
+ saved.length = 0;
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ /** A board whose first column is stored collapsed and holds two cards. */
+ async function setup() {
+ const note = buildNote({
+ title: "Board",
+ "#collection": "",
+ "#viewType": "board",
+ children: [
+ { id: "card1", title: "First", "#status": "To Do" },
+ { id: "card2", title: "Second", "#status": "To Do" },
+ { id: "card3", title: "Third", "#status": "Done" }
+ ]
+ });
+ const host = new Component();
+ const mountPoint = document.createElement("div");
+ container = mountPoint;
+ document.body.appendChild(mountPoint);
+
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={host}>
+ <Harness
+ note={note}
+ noteIds={[ ...note.getChildNoteIds() ]}
+ initialConfig={{ columns: [
+ { value: "To Do", collapsed: true }, { value: "Done" }
+ ] }}
+ />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ });
+ await act(async () => { await flush(); });
+
+ return { mountPoint };
+ }
+
+ const columnAt = (container: HTMLElement, index: number) =>
+ [ ...container.querySelectorAll(".board-column") ][index] as HTMLElement;
+
+ const isCollapsed = (container: HTMLElement, index: number) =>
+ columnAt(container, index).classList.contains("collapsed");
+
+ const cardCount = (container: HTMLElement, index: number) =>
+ columnAt(container, index).querySelectorAll(".board-note").length;
+
+ /** Selects a column the way a click on it does, press and release included. */
+ async function select(container: HTMLElement, index: number) {
+ const column = columnAt(container, index);
+ await act(async () => {
+ column.dispatchEvent(new Event("pointerdown", { bubbles: true }));
+ document.dispatchEvent(new Event("pointerup", { bubbles: true }));
+ column.dispatchEvent(new Event("click", { bubbles: true }));
+ });
+ }
+
+ /** Takes hold of the header and drags it, which is how a column is moved. */
+ async function dragHeader(container: HTMLElement, index: number) {
+ const header = columnAt(container, index).querySelector("h3");
+ await act(async () => {
+ header?.dispatchEvent(new Event("pointerdown", { bubbles: true }));
+ header?.dispatchEvent(new Event("focusin", { bubbles: true }));
+ header?.dispatchEvent(new Event("dragstart", { bubbles: true }));
+ });
+ }
+
+ it("draws a stored collapsed column as a strip without its cards", async () => {
+ const { mountPoint } = await setup();
+
+ expect(isCollapsed(mountPoint, 0)).toBe(true);
+ expect(cardCount(mountPoint, 0)).toBe(0);
+ // The count is what the strip reports in place of the cards.
+ expect(columnAt(mountPoint, 0).querySelector(".counter-badge")?.textContent).toBe("2");
+
+ // Every other column is untouched.
+ expect(isCollapsed(mountPoint, 1)).toBe(false);
+ expect(cardCount(mountPoint, 1)).toBe(1);
+ });
+
+ it("opens the column when it is selected and closes it when another one is", async () => {
+ const { mountPoint } = await setup();
+
+ await select(mountPoint, 0);
+ expect(isCollapsed(mountPoint, 0)).toBe(false);
+ expect(cardCount(mountPoint, 0)).toBe(2);
+
+ await select(mountPoint, 1);
+ expect(isCollapsed(mountPoint, 0)).toBe(true);
+ expect(cardCount(mountPoint, 0)).toBe(0);
+ });
+
+ /**
+ * The strip is what the reader takes hold of to move the column, so opening it under the
+ * pointer would both hide what is being dragged and drag the opened column instead.
+ */
+ it("stays closed while its header is dragged", async () => {
+ const { mountPoint } = await setup();
+
+ await dragHeader(mountPoint, 0);
+ expect(isCollapsed(mountPoint, 0)).toBe(true);
+
+ // The drag ends without a `pointerup`, and the column still opens on the next click.
+ await act(async () => {
+ columnAt(mountPoint, 0).querySelector("h3")
+ ?.dispatchEvent(new Event("dragend", { bubbles: true }));
+ });
+ await select(mountPoint, 0);
+ expect(isCollapsed(mountPoint, 0)).toBe(false);
+ });
+
+ /** The header is walked onto without opening the column, which Space is for. */
+ it("leaves the column closed when focus reaches its header", async () => {
+ const { mountPoint } = await setup();
+
+ await act(async () => {
+ columnAt(mountPoint, 0).querySelector("h3")
+ ?.dispatchEvent(new Event("focusin", { bubbles: true }));
+ });
+
+ expect(isCollapsed(mountPoint, 0)).toBe(true);
+ });
+
+ it("closes an open column when focus reaches another one", async () => {
+ const { mountPoint } = await setup();
+
+ await select(mountPoint, 0);
+ expect(isCollapsed(mountPoint, 0)).toBe(false);
+
+ await act(async () => {
+ columnAt(mountPoint, 1).querySelector("h3")
+ ?.dispatchEvent(new Event("focusin", { bubbles: true }));
+ });
+
+ expect(isCollapsed(mountPoint, 0)).toBe(true);
+ });
+
+ /**
+ * The limit dialog, the icon picker and the context menu all render outside the column, so
+ * focus leaving it is not a reason to close it. Only another column being selected is.
+ */
+ it("stays open while a control rendered outside it is used", async () => {
+ const { mountPoint } = await setup();
+
+ await select(mountPoint, 0);
+ expect(isCollapsed(mountPoint, 0)).toBe(false);
+
+ // What opening a portalled dialog does to the column: focus goes somewhere else entirely.
+ const elsewhere = document.createElement("button");
+ document.body.appendChild(elsewhere);
+ await act(async () => {
+ columnAt(mountPoint, 0)
+ .dispatchEvent(new Event("focusout", { bubbles: true }));
+ elsewhere.dispatchEvent(new Event("pointerdown", { bubbles: true }));
+ });
+ elsewhere.remove();
+
+ expect(isCollapsed(mountPoint, 0)).toBe(false);
+ });
+
+ it("keeps the collapsed column movable and stored as collapsed", async () => {
+ const { mountPoint } = await setup();
+
+ // The header is the drag handle whether or not the column is drawn as a strip.
+ expect(columnAt(mountPoint, 0).querySelector("h3")?.getAttribute("draggable"))
+ .toBe("true");
+ // Opening it by selection is not a change to the config, so nothing is written at all.
+ await select(mountPoint, 0);
+ expect(isCollapsed(mountPoint, 0)).toBe(false);
+ expect(saved).toEqual([]);
+ });
+
+ /**
+ * The menu is opened from the column, so that column is the open one. Storing the flag alone
+ * would change nothing on screen and leave the reader with no sign the entry did anything.
+ */
+ it("closes the column as soon as the menu entry collapses it", async () => {
+ const { mountPoint } = await setup();
+ const column = columnAt(mountPoint, 1);
+ expect(isCollapsed(mountPoint, 1)).toBe(false);
+
+ await select(mountPoint, 1);
+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
+ column.querySelector("h3")
+ ?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+
+ const entry = (show.mock.calls.at(-1)?.[0].items ?? []).find(item =>
+ item && "uiIcon" in item && item.uiIcon === "bx bx-collapse-horizontal");
+ if (!entry || !("handler" in entry)) throw new Error("expected a collapse entry");
+
+ await act(async () => {
+ entry.handler?.(entry, {} as never);
+ await flush();
+ });
+ show.mockRestore();
+
+ expect(isCollapsed(mountPoint, 1)).toBe(true);
+ expect(saved.at(-1)?.columns?.[1]).toEqual({ value: "Done", collapsed: true });
+ });
+
+ it("offers no icon picker or title editor while collapsed", async () => {
+ const { mountPoint } = await setup();
+ const collapsed = columnAt(mountPoint, 0);
+
+ expect(collapsed.querySelector(".column-icon button")).toBeNull();
+
+ startEditingTitle(collapsed);
+ await act(async () => { await flush(); });
+ expect(collapsed.querySelector("input")).toBeNull();
+
+ // Both come back with the column.
+ await select(mountPoint, 0);
+ expect(columnAt(mountPoint, 0).querySelector(".column-icon button")).not.toBeNull();
+ });
+});
+
describe("Board column creation", () => {
let container: HTMLElement | undefined;
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 468e0ded54..0c558d55ad 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -42,6 +42,11 @@ export interface BoardColumnData {
color?: string;
/** Whether the column is archived, absent while it is not. */
archived?: boolean;
+ /**
+ * Whether the column is drawn as a strip, with its cards left out. Selecting the column opens
+ * it again until another one is selected, which does not change this.
+ */
+ collapsed?: boolean;
/**
* Whether the inbox column also collects notes below the board's direct children. Has no
* meaning on any other column, which is defined by a grouping value instead.
@@ -66,6 +71,8 @@ interface CardDrag {
interface ColumnDrag {
column: string;
index: number;
+ /** What the column measures, so the gap held open for it is the size it will land in. */
+ size?: { width: number, height: number };
}
/**
@@ -85,6 +92,11 @@ interface BoardActions {
setBranchIdToEdit: Dispatch<StateUpdater<string | undefined>>;
setColumnNameToEdit: Dispatch<StateUpdater<string | undefined>>;
setColumnLimitToEdit: Dispatch<StateUpdater<string | undefined>>;
+ /**
+ * Names the column the reader is working in. A collapsed column is drawn open while it holds
+ * this, so selecting another one is the only thing that closes it again.
+ */
+ setActiveColumn: Dispatch<StateUpdater<string | undefined>>;
setDraggedCard: Dispatch<StateUpdater<CardDrag | null>>;
setDraggedColumn: (column: ColumnDrag | null) => void;
setDropPosition: (position: ColumnDrag | null) => void;
@@ -104,12 +116,13 @@ interface BoardDragState {
// Both defaults are the honest identity value rather than a stand-in, which is what lets consumers
// read these with a plain useContext(): no non-null assertion, and no guard for a provider that is
// structurally always there. Nothing is being dragged, and the setters have nothing to set.
-/* v8 ignore next 9 -- the board always provides these, so nothing but a consumer mounted outside
+/* v8 ignore next 10 -- the board always provides these, so nothing but a consumer mounted outside
it would ever call one; they exist so that consumers need no guard. */
export const BoardActionsContext = createContext<BoardActions>({
setBranchIdToEdit: () => undefined,
setColumnNameToEdit: () => undefined,
setColumnLimitToEdit: () => undefined,
+ setActiveColumn: () => undefined,
setDraggedCard: () => undefined,
setDraggedColumn: () => undefined,
setDropPosition: () => undefined,
@@ -184,12 +197,13 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
const [ draggedCard, setDraggedCard ] = useState<{ noteId: string, branchId: string, fromColumn: string, index: number } | null>(null);
const [ dropTarget, setDropTarget ] = useState<string | null>(null);
const [ dropPosition, setDropPosition ] = useState<{ column: string, index: number } | null>(null);
- const [ draggedColumn, setDraggedColumn ] = useState<{ column: string, index: number } | null>(null);
+ const [ draggedColumn, setDraggedColumn ] = useState<ColumnDrag | null>(null);
const [ columnDropPosition, setColumnDropPosition ] = useState<number | null>(null);
const [ columnHoverIndex, setColumnHoverIndex ] = useState<number | null>(null);
const [ branchIdToEdit, setBranchIdToEdit ] = useState<string>();
const [ columnNameToEdit, setColumnNameToEdit ] = useState<string>();
const [ columnLimitToEdit, setColumnLimitToEdit ] = useState<string>();
+ const [ activeColumn, setActiveColumn ] = useState<string>();
/** Bumped when the definition changes, since it is read off the note rather than held in state. */
const [ definitionRevision, setDefinitionRevision ] = useState(0);
// A ref rather than state: `api` is rebuilt on every refresh, and the map has to outlive those
@@ -238,13 +252,14 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
setBranchIdToEdit,
setColumnNameToEdit,
setColumnLimitToEdit,
+ setActiveColumn,
setDraggedCard,
setDraggedColumn,
setDropPosition,
setDropTarget
}), [
- setBranchIdToEdit, setColumnNameToEdit, setColumnLimitToEdit, setDraggedCard,
- setDraggedColumn, setDropPosition, setDropTarget
+ setBranchIdToEdit, setColumnNameToEdit, setColumnLimitToEdit, setActiveColumn,
+ setDraggedCard, setDraggedColumn, setDropPosition, setDropTarget
]);
// Read off the config rather than off `columns`, which the resolver hands back as names alone.
@@ -341,6 +356,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
const { onKeyDown: handleKeyDown, focusColumn, focusCard } = useBoardKeyboard({
containerRef,
+ setActiveColumn,
columns: shownColumns,
byColumn,
api,
@@ -381,6 +397,12 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
setColumnDropPosition(targetIndex);
}, [draggedColumn]);
+ // Measured rather than styled: a collapsed column is a strip, and the placeholder stands in
+ // for whichever column is being dragged.
+ const placeholderSize = draggedColumn?.size?.width
+ ? { width: `${draggedColumn.size.width}px`, height: `${draggedColumn.size.height}px` }
+ : undefined;
+
const handleContainerDrop = useCallback((e: DragEvent) => {
e.preventDefault();
if (draggedColumn && columnDropPosition !== null) {
@@ -405,7 +427,10 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
{shownColumns.map((column, index) => (
<>
{columnDropPosition === index && (
- <div className="column-drop-placeholder show" />
+ <div
+ className="column-drop-placeholder show"
+ style={placeholderSize}
+ />
)}
<Column
isInRelationMode={isInRelationMode}
@@ -415,6 +440,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
icon={storedColumns.get(column)?.icon}
color={storedColumns.get(column)?.color}
archived={storedColumns.get(column)?.archived}
+ collapsed={storedColumns.get(column)?.collapsed}
+ isActive={activeColumn === column}
nested={storedColumns.get(column)?.nested}
limit={storedColumns.get(column)?.limit}
columnIndex={index}
@@ -430,7 +457,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
</>
))}
{columnDropPosition === shownColumns.length && draggedColumn && (
- <div className="column-drop-placeholder show" />
+ <div className="column-drop-placeholder show" style={placeholderSize} />
)}
<AddNewColumn api={api} isInRelationMode={isInRelationMode} />
diff --git a/apps/client/src/widgets/collections/board/keyboard.spec.tsx b/apps/client/src/widgets/collections/board/keyboard.spec.tsx
index ea72394457..8cd5669c6c 100644
--- a/apps/client/src/widgets/collections/board/keyboard.spec.tsx
+++ b/apps/client/src/widgets/collections/board/keyboard.spec.tsx
@@ -285,7 +285,99 @@ describe("Board keyboard", () => {
});
});
+ describe("walking a board with a collapsed column", () => {
+ const columnAt = (board: HTMLElement, index: number) =>
+ [ ...board.querySelectorAll<HTMLElement>(".board-column") ][index];
+
+ /**
+ * A collapsed column draws neither cards nor the button under them, so the walk has only
+ * its header to land on. Landing nowhere would carry focus straight past the column.
+ */
+ it("lands on a collapsed column's header instead of passing it", async () => {
+ const board = await renderBoard("Doing");
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowRight");
+
+ expect(document.activeElement).toBe(columnAt(board, 1).querySelector("h3"));
+ // Landing on it is not opening it.
+ expect(columnAt(board, 1).classList.contains("collapsed")).toBe(true);
+ });
+
+ it("walks back out of a collapsed header the way it came", async () => {
+ const board = await renderBoard("Doing");
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowRight");
+ press(board, "ArrowLeft");
+
+ expect(focusedName(board)).toBe("First");
+ });
+
+ it("opens the column with Space and steps onto its first card", async () => {
+ const board = await renderBoard("Doing");
+ focusHeader(board, 1);
+
+ press(board, " ");
+ await act(async () => { await flush(); });
+
+ expect(columnAt(board, 1).classList.contains("collapsed")).toBe(false);
+ expect(focusedName(board)).toBe("Third");
+ });
+
+ /** Nothing to step onto, so the column opens and focus stays where it was. */
+ it("opens an empty column with Space and leaves focus on its header", async () => {
+ const board = await renderBoard("Done");
+ focusHeader(board, 2);
+
+ press(board, " ");
+ await act(async () => { await flush(); });
+
+ expect(columnAt(board, 2).classList.contains("collapsed")).toBe(false);
+ expect(document.activeElement).toBe(columnAt(board, 2).querySelector("h3"));
+ });
+
+ it("leaves Space alone on a column that is not collapsed", async () => {
+ const board = await renderBoard();
+ focusHeader(board, 1);
+
+ press(board, " ");
+
+ expect(document.activeElement).toBe(columnAt(board, 1).querySelector("h3"));
+ });
+ });
+
describe("moving what is focused", () => {
+ /**
+ * A collapsed column draws no cards, so the card carried into it would have nothing to be
+ * focused on. The column has to open as part of the move.
+ */
+ it("opens a collapsed column a card is carried into, and focuses the card there", async () => {
+ const board = await renderBoard("Doing");
+ const columnAt = (index: number) =>
+ [ ...board.querySelectorAll<HTMLElement>(".board-column") ][index];
+
+ expect(columnAt(1).classList.contains("collapsed")).toBe(true);
+
+ focusCard(board, 0, 0);
+ const moved = noteOf(board, "First");
+
+ press(board, "ArrowRight", { ctrlKey: true });
+ await redraw();
+
+ // Open from the moment the move is asked for, not once the write has landed.
+ expect(columnAt(1).classList.contains("collapsed")).toBe(false);
+
+ setStatus(moved, "Doing");
+ await redraw();
+
+ expect(columnAt(1).classList.contains("collapsed")).toBe(false);
+ expect(columnAt(1).querySelectorAll(".board-note")).toHaveLength(2);
+ // The card that moved is what focus rests on, as for any other cross-column move.
+ expect(columnOf(board, "First")).toBe(1);
+ expect(focusedName(board)).toBe("First");
+ });
+
it("moves a card up and down its own column", async () => {
const board = await renderBoard();
focusCard(board, 0, 1);
@@ -691,7 +783,7 @@ describe("Board keyboard", () => {
let boardNote: ReturnType<typeof buildNote>;
/** Two columns of cards, one empty column, and the button that adds another. */
- async function renderBoard() {
+ async function renderBoard(collapsed?: string) {
boardNote = buildNote({
title: "Board",
"#collection": "",
@@ -716,7 +808,10 @@ describe("Board keyboard", () => {
noteIds={[ ...boardNote.getChildNoteIds() ]}
highlightedTokens={null}
viewConfig={{
- columns: [ { value: "To Do" }, { value: "Doing" }, { value: "Done" } ]
+ columns: [ "To Do", "Doing", "Done" ].map(value => ({
+ value,
+ collapsed: value === collapsed ? true : undefined
+ }))
}}
saveConfig={(config) => saved.push(config)}
media="screen"
diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.ts
index 29256b8184..c7b92e0628 100644
--- a/apps/client/src/widgets/collections/board/keyboard.ts
+++ b/apps/client/src/widgets/collections/board/keyboard.ts
@@ -62,6 +62,12 @@ export interface BoardKeyboardOptions {
moveColumn: (fromIndex: number, toIndex: number) => void;
/** Puts a new column beside the given one and opens its title editor, as the menu does. */
insertColumn: (relativeTo: string, direction: "before" | "after") => void;
+ /**
+ * Names the column being worked in, which opens it while it is collapsed. A card carried into
+ * a collapsed column has to say so here: the column draws no cards, so there would be nothing
+ * for the focus to land on.
+ */
+ setActiveColumn: (column: string) => void;
}
/**
@@ -80,7 +86,7 @@ export interface BoardKeyboardOptions {
* focused on whichever column took its place.
*/
export function useBoardKeyboard({
- containerRef, columns, byColumn, api, moveColumn, insertColumn
+ containerRef, columns, byColumn, api, moveColumn, insertColumn, setActiveColumn
}: BoardKeyboardOptions) {
const pendingFocus = useRef<PendingFocus | null>(null);
@@ -180,7 +186,8 @@ export function useBoardKeyboard({
return;
}
- const moved = move(spot, e.key, { columns, byColumn, api }, e.shiftKey);
+ const moved = move(
+ spot, e.key, { columns, byColumn, api, setActiveColumn }, e.shiftKey);
if (moved) {
const pending: PendingFocus = { intent: moved.intent };
pendingFocus.current = pending;
@@ -206,6 +213,26 @@ export function useBoardKeyboard({
return;
}
+ if (e.key === " " && spot.kind === "header") {
+ const column = columns[spot.column];
+ const element = container.querySelector(`.board-column[data-column="${CSS.escape(column)}"]`);
+ if (!element?.classList.contains("collapsed")) return;
+
+ take(e);
+ setActiveColumn(column);
+
+ // The cards are drawn only once the column opens, so the first of them is asked for
+ // rather than focused here; the effect above puts focus on it as it appears. The
+ // header gives focus up for that, the effect leaving alone anything the reader is
+ // resting on. A column with no cards keeps it, there being nothing to step onto.
+ const first = byColumn?.get(column)?.[0];
+ if (first) {
+ pendingFocus.current = { intent: { noteId: first.note.noteId } };
+ (document.activeElement as HTMLElement | null)?.blur();
+ }
+ return;
+ }
+
if (e.key === " " && spot.kind === "item") {
const item = itemAt(columns, byColumn, spot);
if (item) {
@@ -256,7 +283,7 @@ export function useBoardKeyboard({
api.removeFromBoard(item.note.noteId);
}
}
- }, [ containerRef, columns, byColumn, api, moveColumn, insertColumn ]);
+ }, [ containerRef, columns, byColumn, api, moveColumn, insertColumn, setActiveColumn ]);
return { onKeyDown, focusColumn, focusCard };
}
@@ -337,7 +364,10 @@ function walk(container: HTMLElement, from: Spot, key: string) {
const next = destination(container, from, key);
if (!next) return false;
- elementAt(container, next)?.focus();
+ const element = elementAt(container, next);
+ if (!element) return false;
+
+ element.focus();
return true;
}
@@ -375,9 +405,16 @@ function destination(container: HTMLElement, from: Spot, key: string): Spot | nu
return { kind: "item", column: from.column, item: next - 1 };
}
-/** The first thing a column offers on the way in, which is never its header. */
+/** The first thing a column offers on the way in, which is its header only where it is collapsed. */
function entryOf(container: HTMLElement, column: number): Spot {
- return cardsOf(columnsOf(container)[column]).length
+ const element = columnsOf(container)[column];
+ // A collapsed column draws neither cards nor the button under them, so walking past it would
+ // otherwise find nothing to land on and skip the column entirely.
+ if (element?.classList.contains("collapsed")) {
+ return { kind: "header", column };
+ }
+
+ return cardsOf(element).length
? { kind: "item", column, item: 0 }
: { kind: "add-item", column };
}
@@ -390,7 +427,8 @@ function entryOf(container: HTMLElement, column: number): Spot {
function move(
spot: Spot,
key: string,
- { columns, byColumn, api }: Pick<BoardKeyboardOptions, "columns" | "byColumn" | "api">,
+ { columns, byColumn, api, setActiveColumn }:
+ Pick<BoardKeyboardOptions, "columns" | "byColumn" | "api" | "setActiveColumn">,
/** Whether the card goes the whole way rather than one place. */
toEnd = false
): { intent: FocusIntent; done: Promise<unknown> } | false {
@@ -409,6 +447,10 @@ function move(
// Only the whole way can ask for the column a card already stands in.
if (!target || target === column) return false;
+ // The card is drawn under the column it lands in, so a collapsed one has to open first for
+ // there to be anything to focus.
+ setActiveColumn(target);
+
return { intent: { noteId }, done: api.moveToColumnEnd(noteId, branchId, target) };
}