Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: typing on the focused "New item" button will enter in new item editing mode

Adorian Doranbd7c66c6545c
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index 3bfef2e7ee..17df0e95a8 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -1,6 +1,8 @@
import clsx from "clsx";
import { Fragment } from "preact";
-import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";
+import {
+ useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState
+} from "preact/hooks";
import { JSX } from "preact/jsx-runtime";
import FBranch from "../../../entities/fbranch";
@@ -214,6 +216,7 @@ export default function Column({
<AddNewItem
api={api}
column={column}
+ itemCount={columnItems?.length ?? 0}
isCreating={isCreatingNewItem}
setIsCreating={setIsCreatingNewItem}
/>
@@ -226,24 +229,64 @@ export default function Column({
* The editor a new card is named in, opened by the button below the column or by its menu. The
* state is the column's rather than this component's, since the menu is raised from the header.
*/
-function AddNewItem({ column, api, isCreating, setIsCreating }: {
+function AddNewItem({ column, api, itemCount, isCreating, setIsCreating }: {
column: string,
api: BoardApi,
+ /** How many cards stand above it, which is what moves it out of view as they come and go. */
+ itemCount: number,
isCreating: boolean,
setIsCreating: (isCreating: boolean) => void
}) {
- const addItemCallback = useCallback(() => setIsCreating(true), [ setIsCreating ]);
+ const [ initialTitle, setInitialTitle ] = useState("");
+ const slotRef = useRef<HTMLDivElement>(null);
+
+ // Reaching the button means reaching the end of the column, so what is under it comes into view
+ // with it. The browser scrolls only far enough to show the button itself.
+ const scrollToEnd = useCallback(() => {
+ const content = slotRef.current?.closest(".board-column-content");
+ if (content) {
+ content.scrollTop = content.scrollHeight;
+ }
+ }, []);
+
+ // A card added lands above the button and pushes it out of sight, and the editor stands taller
+ // than the button it replaces. Neither raises a focus event, so whatever is focused in here has
+ // to be followed back into view.
+ useLayoutEffect(() => {
+ if (slotRef.current?.contains(document.activeElement)) {
+ scrollToEnd();
+ }
+ }, [ itemCount, isCreating, scrollToEnd ]);
+
+ const open = useCallback((title: string) => {
+ setInitialTitle(title);
+ setIsCreating(true);
+ }, [ setIsCreating ]);
+
const handleKeyDown = useCallback((e: KeyboardEvent) => {
- if (!isCreating && e.key === "Enter") {
- setIsCreating(true);
+ if (isCreating) return;
+
+ if (e.key === "Enter") {
+ open("");
+ return;
+ }
+
+ // Typing on the button starts the note off with what was typed, rather than asking for it
+ // twice. A printable key is one whose name is the character itself, which no modified press
+ // and none of the named keys are.
+ if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
+ e.preventDefault();
+ open(e.key);
}
- }, [ isCreating, setIsCreating ]);
+ }, [ isCreating, open ]);
return (
<div
+ ref={slotRef}
className={`board-new-item ${isCreating ? "editing" : ""}`}
- onClick={addItemCallback}
+ onClick={() => open("")}
onKeyDown={handleKeyDown}
+ onFocus={scrollToEnd}
tabIndex={300}
>
{!isCreating ? (
@@ -253,10 +296,12 @@ function AddNewItem({ column, api, isCreating, setIsCreating }: {
</>
) : (
<TitleEditor
+ currentValue={initialTitle}
placeholder={t("board_view.new-item-placeholder")}
save={(title) => api.createNewItem(column, title)}
dismiss={() => setIsCreating(false)}
mode="multiline" isNewItem
+ selectOnFocus={false}
/>
)}
</div>
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index dfe8c1d319..51bd8f63f5 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -9,6 +9,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import Component from "../../../components/component";
import contextMenu from "../../../menus/context_menu";
+import FBranch from "../../../entities/fbranch";
import froca from "../../../services/froca";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
@@ -73,6 +74,21 @@ function Harness({ note, noteIds, initialConfig }: { note: ReturnType<typeof bui
);
}
+/** Files a fresh note under the board, the way an import or another client's write reaches it. */
+function addCard(board: ReturnType<typeof buildNote>, status: string) {
+ const card = buildNote({ title: "Added", "#status": status });
+ const branchId = `${board.noteId}_${card.noteId}`;
+
+ froca.branches[branchId] = new FBranch(froca, {
+ branchId,
+ notePosition: 100,
+ fromSearchNote: false,
+ noteId: card.noteId,
+ parentNoteId: board.noteId
+ });
+ board.addChild(card.noteId, branchId, false);
+}
+
/** Opens the title editor the way the keyboard does, the menu entry needing a rendered menu. */
function startEditingTitle(column: HTMLElement) {
column.querySelector("h3")
@@ -204,7 +220,11 @@ describe("Board column rename", () => {
await act(async () => {
render(
<ParentComponent.Provider value={new Component()}>
- <Harness note={note} noteIds={note.getChildNoteIds()} initialConfig={config} />
+ <Harness
+ note={note}
+ noteIds={[ ...note.getChildNoteIds() ]}
+ initialConfig={config}
+ />
</ParentComponent.Provider>,
mountPoint
);
@@ -271,7 +291,7 @@ describe("Board column rename", () => {
<ParentComponent.Provider value={new Component()}>
<Harness
note={other}
- noteIds={other.getChildNoteIds()}
+ noteIds={[ ...other.getChildNoteIds() ]}
initialConfig={{ columns: [ { value: "Doing" }, { value: "Shipped" } ] }}
/>
</ParentComponent.Provider>,
@@ -375,6 +395,82 @@ describe("Board column rename", () => {
show.mockRestore();
});
+ it("scrolls the column to its end when the new-item button takes focus", async () => {
+ const { note, container } = await setup();
+ const column = container.querySelectorAll<HTMLElement>(".board-column")[1];
+ const content = column.querySelector<HTMLElement>(".board-column-content");
+ if (!content) throw new Error("expected a scrollable column body");
+
+ // happy-dom lays nothing out, so the scrollable height has to be stood in for.
+ Object.defineProperty(content, "scrollHeight", { value: 500, configurable: true });
+ expect(content.scrollTop).toBe(0);
+
+ await act(async () => {
+ column.querySelector<HTMLElement>(".board-new-item")?.focus();
+ await flush();
+ });
+
+ expect(content.scrollTop).toBe(500);
+
+ // The card just made lands above the button, pushing it out of sight again. Nothing is
+ // focused afresh by that, so only the effect watching the count brings it back.
+ Object.defineProperty(content, "scrollHeight", { value: 900, configurable: true });
+ 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(); });
+
+ expect(columnTitles(container)).toEqual([ "To Do", "Doing", "Done" ]);
+ expect(content.scrollTop).toBe(900);
+ });
+
+ 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]
+ .querySelector<HTMLElement>(".board-new-item");
+
+ await act(async () => {
+ slot?.dispatchEvent(new KeyboardEvent("keydown", { key: "R", bubbles: true }));
+ await flush();
+ });
+
+ const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");
+ expect(editor?.value).toBe("R");
+ // After the character rather than over it, so the next key carries on.
+ expect([ editor?.selectionStart, editor?.selectionEnd ]).toEqual([ 1, 1 ]);
+ });
+
+ it("opens the new item empty for Enter, and ignores keys that are not characters", async () => {
+ const { container } = await setup();
+ const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]
+ .querySelector<HTMLElement>(".board-new-item");
+
+ for (const key of [ "Tab", "ArrowRight", "F2" ]) {
+ await act(async () => {
+ slot?.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));
+ await flush();
+ });
+ }
+ expect(slot?.querySelector("textarea")).toBeNull();
+
+ await act(async () => {
+ slot?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ await flush();
+ });
+ expect(slot?.querySelector<HTMLTextAreaElement>("textarea")?.value).toBe("");
+ });
+
it("keeps the cards of the renamed column under it", async () => {
const { container } = await setup();
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index d9b13a266d..2f73543531 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -391,13 +391,21 @@ function AddNewColumn({ api, isInRelationMode }: { api: BoardApi, isInRelationMo
);
}
-export function TitleEditor({ currentValue, placeholder, save, dismiss, mode, isNewItem }: {
+export function TitleEditor({
+ currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true
+}: {
currentValue?: string;
placeholder?: string;
save: (newValue: string) => void | Promise<void>;
dismiss: () => void;
isNewItem?: boolean;
mode?: "normal" | "multiline" | "relation";
+ /**
+ * 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
+ * rather than replacing it.
+ */
+ selectOnFocus?: boolean;
}) {
const inputRef = useRef<any>(null);
const focusElRef = useRef<Element>(null);
@@ -407,7 +415,13 @@ export function TitleEditor({ currentValue, placeholder, save, dismiss, mode, is
useEffect(() => {
focusElRef.current = document.activeElement !== document.body ? document.activeElement : null;
inputRef.current?.focus();
- inputRef.current?.select();
+
+ if (selectOnFocus) {
+ inputRef.current?.select();
+ } else {
+ const end = inputRef.current?.value.length ?? 0;
+ inputRef.current?.setSelectionRange(end, end);
+ }
}, [ inputRef ]);
useEffect(() => {