Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: tweak newly created cards

Adorian Doran49c2a98c3368
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index 9b029ec138..5f28850896 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -20,9 +20,11 @@ function Card({
index,
statusAttribute,
isNew,
+ focusOnArrival,
isDragging,
isEditing,
- onFocusCard
+ onFocusCard,
+ onCreated
}: {
api: BoardApi,
note: FNote,
@@ -34,8 +36,10 @@ function Card({
* one identity for the life of the board, which a `memo` comparison cannot see through.
*/
statusAttribute: string,
- /** Whether this is the card the new-item editor has just made, which is revealed on arrival. */
+ /** Whether this is the card just made, which is revealed on arrival. */
isNew: boolean,
+ /** Whether the card just made is also left focused, which an insert's is and the footer's is not. */
+ focusOnArrival: boolean,
isDragging: boolean,
/**
* Passed down rather than derived here from the drag state's `branchIdToEdit`, so that a card
@@ -43,7 +47,9 @@ function Card({
*/
isEditing: boolean,
/** Puts focus back on this card once a change of column has drawn it under another one. */
- onFocusCard: (noteId: string) => void
+ onFocusCard: (noteId: string) => void,
+ /** Names the card inserted next to this one, which the column reveals as it draws it. */
+ onCreated: (noteId: string | undefined) => void
}) {
const { setBranchIdToEdit } = useContext(BoardActionsContext);
const colorClass = note.getColorClass() || '';
@@ -64,8 +70,8 @@ function Card({
});
const handleContextMenu = useCallback((e: ContextMenuEvent) => {
- openNoteContextMenu(api, e, note, branch.branchId, column, onFocusCard);
- }, [ api, note, branch, column, onFocusCard ]);
+ openNoteContextMenu(api, e, note, branch.branchId, column, onFocusCard, onCreated);
+ }, [ api, note, branch, column, onFocusCard, onCreated ]);
const handleOpen = useCallback((e: MouseEvent) => {
// A double click is one gesture, and its second click would open the note over itself: the
@@ -85,30 +91,46 @@ function Card({
// 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.
e.preventDefault();
- api.insertRowAtPosition(column, branch.branchId, e.shiftKey ? "before" : "after");
+ api.insertRowAtPosition(column, branch.branchId, e.shiftKey ? "before" : "after")
+ .then(created => onCreated(created?.noteId));
} else if (e.key === "F2") {
setBranchIdToEdit(branch.branchId);
}
- }, [ api, column, branch, setBranchIdToEdit ]);
+ }, [ api, column, branch, setBranchIdToEdit, onCreated ]);
useEffect(() => {
editorRef.current?.focus();
}, [ isEditing ]);
+ // An insert opens the new card's title editor, which holds focus while a title is typed. The
+ // card takes it from there, so that the arrow keys carry on from where the reader is.
+ useEffect(() => {
+ if (focusOnArrival && !isEditing) {
+ cardRef.current?.focus();
+ }
+ }, [ focusOnArrival, isEditing ]);
+
useEffect(() => {
setTitle(note.title);
}, [ note ]);
- // A card is added at the end of its column, which on a full column is below the fold. The
- // column is taken to its end rather than the card into view, so the card lands clear of the
- // fade the scrolling body draws over its bottom edge.
+ // A new card can be below the fold on a full column. One at the end takes the column to its
+ // end, so it lands clear of the fade the scrolling body draws over its bottom edge; one
+ // inserted between others is only brought into view.
useLayoutEffect(() => {
if (!isNew) {
return;
}
- const content = cardRef.current?.closest(".board-column-content");
- if (content) {
+ const card = cardRef.current;
+ const content = card?.closest(".board-column-content");
+ if (!card || !content) {
+ return;
+ }
+
+ if (card.nextElementSibling) {
+ card.scrollIntoView?.({ block: "nearest" });
+ } else {
content.scrollTop = content.scrollHeight;
}
}, [ isNew ]);
@@ -138,6 +160,7 @@ function Card({
</>
) : (
<TitleEditor
+ returnFocusTo={cardRef}
currentValue={note.title}
save={newTitle => {
api.renameCard(note.noteId, newTitle);
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index d2685f14f8..beace88e6c 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -76,7 +76,13 @@ export default function Column({
onFocusCard: (noteId: string) => void
} & DragContext) {
const [ isCreatingNewItem, setIsCreatingNewItem ] = useState(false);
- const [ createdNoteId, setCreatedNoteId ] = useState<string>();
+ const [ created, setCreated ] = useState<{ noteId?: string, takesFocus: boolean }>();
+ // A card inserted next to another one is where the reader is working, so it is left focused; one
+ // made in the footer is not, or every card would take focus from the editor still being typed in.
+ const cardInserted = useCallback(
+ (noteId: string | undefined) => setCreated({ noteId, takesFocus: true }), []);
+ const cardAdded = useCallback(
+ (noteId: string | undefined) => setCreated({ noteId, takesFocus: false }), []);
const { setColumnNameToEdit, setColumnLimitToEdit, setActiveColumn } =
useContext(BoardActionsContext);
const { branchIdToEdit, columnNameToEdit, dropTarget, draggedCard, dropPosition } = useContext(BoardDragStateContext);
@@ -305,10 +311,14 @@ export default function Column({
column={column}
index={index}
statusAttribute={api.statusAttribute}
- isNew={note.noteId === createdNoteId}
+ isNew={note.noteId === created?.noteId}
+ focusOnArrival={
+ note.noteId === created?.noteId && created.takesFocus
+ }
isDragging={draggedCard?.noteId === note.noteId}
isEditing={branch.branchId === branchIdToEdit}
onFocusCard={onFocusCard}
+ onCreated={cardInserted}
/>
</Fragment>
);
@@ -323,7 +333,7 @@ export default function Column({
column={column}
isCreating={isCreatingNewItem}
setIsCreating={setIsCreatingNewItem}
- onCreated={setCreatedNoteId}
+ onCreated={cardAdded}
/>}
</div>
);
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 045a57abf9..e2147c72c4 100644
--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts
@@ -452,7 +452,7 @@ describe("Board item context menu", () => {
{ getStatusLabel: () => "Status", getColumnTitle: (name: string) => name }, api);
openNoteContextMenu(
withDefaults, event, buildNote({ title: "Card" }) as FNote, "branchId", column,
- focusCard);
+ focusCard, () => {});
return show.mock.calls.at(-1)?.[0].items ?? [];
}
diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.ts
index fc909ec016..a2d402f771 100644
--- a/apps/client/src/widgets/collections/board/context_menu.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.ts
@@ -251,7 +251,9 @@ function buildColumnItems(
export function openNoteContextMenu(
api: Api, event: ContextMenuEvent, note: FNote, branchId: string, column: string,
/** Puts focus back on the card once a change of column has drawn it under another one. */
- onFocusCard: (noteId: string) => void
+ onFocusCard: (noteId: string) => void,
+ /** Names the card an insert makes, which the column reveals once the board has drawn it. */
+ onCreated: (noteId: string | undefined) => void
) {
event.preventDefault();
event.stopPropagation();
@@ -267,12 +269,14 @@ export function openNoteContextMenu(
uiIcon: "bx bx-list-plus",
shortcut: "Shift+Enter",
handler: () => api.insertRowAtPosition(column, branchId, "before")
+ .then(created => onCreated(created?.noteId))
},
{
title: t("board_view.insert-below"),
uiIcon: "bx bx-empty",
shortcut: "Enter",
handler: () => api.insertRowAtPosition(column, branchId, "after")
+ .then(created => onCreated(created?.noteId))
},
{ kind: "header", title: api.getStatusLabel() },
...buildColumnItems(api, note, column, onFocusCard),
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index ed54ff2b47..640974bc49 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -1209,6 +1209,121 @@ describe("Board column rename", () => {
expect(others.some(other => other.classList.contains("appearing"))).toBe(false);
});
+ it("reveals a card inserted next to another one, without leaving its place", async () => {
+ const { note, container } = await setup();
+
+ // A second card in the same column, so the one standing in for the insert has a card after
+ // it and the column is brought to it rather than run to its end.
+ addCard(note, "Doing");
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={new Component()}>
+ <Harness
+ note={note}
+ noteIds={[ ...note.getChildNoteIds() ]}
+ initialConfig={DEFAULT_CONFIG}
+ />
+ </ParentComponent.Provider>,
+ container
+ );
+ await flush();
+ });
+ await act(async () => { await flush(); });
+
+ const column = container.querySelectorAll<HTMLElement>(".board-column")[1];
+ const [ first, second ] = column.querySelectorAll<HTMLElement>(".board-note");
+ const noteId = first?.getAttribute("data-note-id");
+ if (!first || !second || !noteId) throw new Error("expected a column of two cards");
+
+ const scrolled = vi.fn();
+ Object.defineProperty(first, "scrollIntoView",
+ { value: scrolled, configurable: true, writable: true });
+ const content = column.querySelector<HTMLElement>(".board-column-content");
+ Object.defineProperty(content, "scrollHeight",
+ { value: 500, configurable: true, writable: true });
+ vi.spyOn(BoardApi.prototype, "insertRowAtPosition")
+ .mockResolvedValue({ noteId } as never);
+
+ await act(async () => {
+ second.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ await flush();
+ });
+
+ expect(first.classList.contains("appearing")).toBe(true);
+ expect(scrolled).toHaveBeenCalled();
+ expect(content?.scrollTop).toBe(0);
+ });
+
+ /**
+ * The editor an insert opens holds focus while the title is typed; the card takes it once that
+ * editor is done, so the arrow keys carry on from the card just made.
+ */
+ it("leaves an inserted card focused, and a card added in the footer unfocused", async () => {
+ const { container } = await setup();
+ const column = container.querySelectorAll<HTMLElement>(".board-column")[1];
+ const card = column.querySelector<HTMLElement>(".board-note");
+ const noteId = card?.getAttribute("data-note-id");
+ if (!card || !noteId) throw new Error("expected a card in the column");
+
+ vi.spyOn(BoardApi.prototype, "insertRowAtPosition")
+ .mockResolvedValue({ noteId } as never);
+ await act(async () => {
+ card.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ await flush();
+ });
+
+ expect(document.activeElement).toBe(card);
+
+ // The footer's own editor keeps focus instead, so a run of cards can be typed into it.
+ vi.spyOn(BoardApi.prototype, "createNewItem").mockResolvedValue(noteId);
+ const slot = column.querySelector<HTMLElement>(".board-new-item");
+ await act(async () => {
+ slot?.click();
+ await flush();
+ });
+
+ const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");
+ if (!editor) throw new Error("expected the new-item editor to be open");
+ editor.value = "Another";
+ await act(async () => {
+ editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ await flush();
+ });
+
+ expect(document.activeElement).toBe(editor);
+ });
+
+ /**
+ * The editor used to hand focus back to whatever held it before it opened, which for a card
+ * whose editor was opened for it is a different card: that one lit up on the way past.
+ */
+ it("closes a card editor onto its own card, not the one focus came from", async () => {
+ const { container } = await setup();
+ const columns = container.querySelectorAll<HTMLElement>(".board-column");
+ const from = columns[0].querySelector<HTMLElement>(".board-note");
+ const edited = columns[1].querySelector<HTMLElement>(".board-note");
+ if (!from || !edited) throw new Error("expected a card in each of two columns");
+
+ from.focus();
+ const cameFrom = vi.spyOn(from, "focus");
+
+ await act(async () => {
+ edited.dispatchEvent(new KeyboardEvent("keydown", { key: "F2", bubbles: true }));
+ await flush();
+ });
+
+ const editor = edited.querySelector<HTMLTextAreaElement>("textarea");
+ if (!editor) throw new Error("expected the card editor to be open");
+
+ await act(async () => {
+ editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+ await flush();
+ });
+
+ expect(document.activeElement).toBe(edited);
+ expect(cameFrom).not.toHaveBeenCalled();
+ });
+
it("starts the new item off with the character typed on its button", async () => {
const { container } = await setup();
const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 67db75ad99..5dab73aea5 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -3,7 +3,7 @@ import "./index.css";
import clsx from "clsx";
import { createContext, Fragment, TargetedKeyboardEvent } from "preact";
-import { createPortal } from "preact/compat";
+import { createPortal, RefObject } from "preact/compat";
import {
Dispatch, StateUpdater, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState
} from "preact/hooks";
@@ -715,7 +715,7 @@ function AddNewColumn({ api, isInRelationMode }: { api: BoardApi, isInRelationMo
export function TitleEditor({
currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true,
- saveAndContinue = false
+ saveAndContinue = false, returnFocusTo
}: {
currentValue?: string;
placeholder?: string;
@@ -728,6 +728,12 @@ export function TitleEditor({
* be typed one after another. Escape and clicking away still close it.
*/
saveAndContinue?: boolean;
+ /**
+ * Where focus goes when the editor closes, instead of back to whatever held it before. A card
+ * whose editor was opened for it rather than by it names itself, so that closing does not light
+ * up the card the reader came from on the way.
+ */
+ returnFocusTo?: RefObject<HTMLElement>;
/**
* Whether opening the editor selects what is already in it, which is what a rename wants. An
* editor opened part-typed puts the caret after the text instead, so the next key carries on
@@ -781,9 +787,10 @@ export function TitleEditor({
if (e.key === "Enter" || e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
- if (focusElRef.current instanceof HTMLElement) {
+ const target = returnFocusTo?.current ?? focusElRef.current;
+ if (target instanceof HTMLElement) {
shouldDismiss.current = (e.key === "Escape");
- focusElRef.current.focus();
+ target.focus();
} else {
dismiss();
}