Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/collections/board: keep the new card input field fixed at the bottom of the column, so scrolling to reach it won't be needed anymore
Adorian Doran4bce3626c858
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 03df7e6808..0387af3626 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -156,12 +156,14 @@ export default class BoardApi {async createNewItem(column: string, title: string) {try {- await note_create.createNote(this.parentNote.noteId, {+ const { note } = await note_create.createNote(this.parentNote.noteId, {activate: false,title,isProtected: this.parentNote.isProtected,attributes: this.groupingFor(column)});++ return note?.noteId;} catch (error) {console.error("Failed to create new item:", error);}diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsxindex da3881b590..9b029ec138 100644--- a/apps/client/src/widgets/collections/board/card.tsx+++ b/apps/client/src/widgets/collections/board/card.tsx@@ -1,5 +1,7 @@import { memo } from "preact/compat";-import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";+import {+ useCallback, useContext, useEffect, useLayoutEffect, useRef, useState+} from "preact/hooks";import FBranch from "../../../entities/fbranch";import FNote from "../../../entities/fnote";import BoardApi from "./api";@@ -17,6 +19,7 @@ function Card({column,index,statusAttribute,+ isNew,isDragging,isEditing,onFocusCard@@ -31,6 +34,8 @@ 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. */+ isNew: boolean,isDragging: boolean,/*** Passed down rather than derived here from the drag state's `branchIdToEdit`, so that a card@@ -43,6 +48,7 @@ function Card({const { setBranchIdToEdit } = useContext(BoardActionsContext);const colorClass = note.getColorClass() || '';const editorRef = useRef<HTMLInputElement>(null);+ const cardRef = useRef<HTMLDivElement>(null);const [ isArchived ] = useNoteLabelBoolean(note, "archived");const [ title, setTitle ] = useState(note.title);// Tracks the `iconClass` label, which an attribute change carries and the note row never does.@@ -93,9 +99,24 @@ function Card({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.+ useLayoutEffect(() => {+ if (!isNew) {+ return;+ }++ const content = cardRef.current?.closest(".board-column-content");+ if (content) {+ content.scrollTop = content.scrollHeight;+ }+ }, [ isNew ]);+return (<div- className={`board-note ${colorClass} ${isDragging ? 'dragging' : ''} ${isEditing ? "editing" : ""} ${isArchived ? "archived" : ""}`}+ ref={cardRef}+ className={`board-note ${colorClass} ${isDragging ? 'dragging' : ''} ${isEditing ? "editing" : ""} ${isArchived ? "archived" : ""} ${isNew ? "appearing" : ""}`}data-note-id={note.noteId}onContextMenu={handleContextMenu}onClick={!isEditing ? handleOpen : undefined}diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 43b1c87b3f..d2685f14f8 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -1,7 +1,7 @@import clsx from "clsx";import { Fragment } from "preact";import {- useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState+ useCallback, useContext, useEffect, useMemo, useRef, useState} from "preact/hooks";import { JSX } from "preact/jsx-runtime";@@ -76,6 +76,7 @@ export default function Column({onFocusCard: (noteId: string) => void} & DragContext) {const [ isCreatingNewItem, setIsCreatingNewItem ] = useState(false);+ const [ createdNoteId, setCreatedNoteId ] = useState<string>();const { setColumnNameToEdit, setColumnLimitToEdit, setActiveColumn } =useContext(BoardActionsContext);const { branchIdToEdit, columnNameToEdit, dropTarget, draggedCard, dropPosition } = useContext(BoardDragStateContext);@@ -304,6 +305,7 @@ export default function Column({column={column}index={index}statusAttribute={api.statusAttribute}+ isNew={note.noteId === createdNoteId}isDragging={draggedCard?.noteId === note.noteId}isEditing={branch.branchId === branchIdToEdit}onFocusCard={onFocusCard}@@ -314,15 +316,15 @@ export default function Column({{dropPosition?.column === column && dropPosition.index === (columnItems?.length ?? 0) && (<div className="board-drop-placeholder show" style={gapStyle} />)}-- <AddNewItem- api={api}- column={column}- itemCount={columnItems?.length ?? 0}- isCreating={isCreatingNewItem}- setIsCreating={setIsCreatingNewItem}- /></div>}++ {!isCollapsed && <AddNewItem+ api={api}+ column={column}+ isCreating={isCreatingNewItem}+ setIsCreating={setIsCreatingNewItem}+ onCreated={setCreatedNoteId}+ />}</div>);}@@ -331,34 +333,15 @@ 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, itemCount, isCreating, setIsCreating }: {+function AddNewItem({ column, api, isCreating, setIsCreating, onCreated }: {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+ setIsCreating: (isCreating: boolean) => void,+ /** Names the card just made, which the column reveals once the board has drawn it. */+ onCreated: (noteId: string | undefined) => void}) {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);@@ -384,11 +367,9 @@ function AddNewItem({ column, api, itemCount, isCreating, setIsCreating }: {return (<div- ref={slotRef}className={`board-new-item ${isCreating ? "editing" : ""}`}onClick={() => open("")}onKeyDown={handleKeyDown}- onFocus={scrollToEnd}tabIndex={300}>{!isCreating ? (@@ -400,10 +381,11 @@ function AddNewItem({ column, api, itemCount, isCreating, setIsCreating }: {<TitleEditorcurrentValue={initialTitle}placeholder={t("board_view.new-item-placeholder")}- save={(title) => api.createNewItem(column, title)}+ save={async (title) => onCreated(await api.createNewItem(column, title))}dismiss={() => setIsCreating(false)}mode="multiline" isNewItemselectOnFocus={false}+ saveAndContinue/>)}</div>diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex 4a9b318b8d..ac51f2fd80 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -230,11 +230,20 @@ body.mobile .board-view-container .board-add-column {.board-view-container .board-column > .board-column-content {flex-grow: 1;+ /* Without this the cards set the floor for the column's height and push the footer past it. */+ min-height: 0;overflow-x: hidden;overflow-y: auto;padding: 0.5em;}+.board-view-container .board-column > .board-new-item {+ flex-shrink: 0;+ /* Matches the padding of the scrolling body above, so the footer lines up with the cards. */+ margin-inline: 0.5em;+ margin-block-end: 0.5em;+}+.board-view-container .board-note:hover .edit-icon {opacity: 1;}@@ -243,7 +252,7 @@ body.mobile .board-view-container .board-add-column {.board-view-container .board-note,.board-view-container .board-new-item.editing {box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.1);- margin: 0.65em 0;+ margin-block: 0.65em;padding: var(--card-padding);border-radius: 5px;position: relative;@@ -472,6 +481,22 @@ body.mobile .board-view-container .board-add-column {resize: none;}+/* A card lands at the end of a column the reader may not be looking at, so it announces itself. */+@keyframes board-card-appear {+ from { opacity: 0; }+ to { opacity: 1; }+}++.board-view-container .board-note.appearing {+ animation: board-card-appear 500ms ease-out;+}++@media (prefers-reduced-motion: reduce) {+ .board-view-container .board-note.appearing {+ animation: none;+ }+}+.board-drop-placeholder {height: 40px;margin: 0.65em 0;@@ -503,7 +528,6 @@ body.mobile .board-view-container .board-add-column {}.board-new-item {- margin-top: 0.5em;padding: 0.25em 0.5em;border-radius: 5px;color: var(--muted-text-color);diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex b7161bfe8d..ed54ff2b47 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -19,7 +19,7 @@ import { buildNote } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";import BoardView, { BoardViewData } from ".";import { collectShortcutHints } from "../../../services/shortcut_hints";-import { getPendingWrites } from "./api";+import BoardApi, { getPendingWrites } from "./api";import { DEFAULT_COLUMN_ICON } from "./columns";// Stands in for the server: by the time the bulk action resolves, the notes carry the new value,@@ -1115,44 +1115,98 @@ 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();+ it("keeps the new-item slot out of the column's scrolling body", async () => {+ const { 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");+ const slot = column.querySelector<HTMLElement>(".board-new-item");++ expect(slot).toBeTruthy();+ expect(slot?.closest(".board-column-content")).toBeNull();+ expect(slot?.parentElement).toBe(column);+ });++ /**+ * Cards are added in runs, so the editor stays where it is with an empty field rather than+ * closing and having to be opened again for the next one.+ */+ it("clears the new-item editor on Enter and leaves it open", async () => {+ const { container } = await setup();+ const created = vi.spyOn(BoardApi.prototype, "createNewItem")+ .mockResolvedValue(undefined);+ const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]+ .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 = "First";+ await act(async () => {+ editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await flush();+ });++ expect(created).toHaveBeenCalledWith("Doing", "First");+ expect(slot?.querySelector("textarea")).toBe(editor);+ expect(editor.value).toBe("");+ expect(document.activeElement).toBe(editor);++ // The one already saved is not written a second time by the one that follows it.+ editor.value = "Second";+ await act(async () => {+ editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await flush();+ });++ expect(created).toHaveBeenCalledTimes(2);+ expect(created).toHaveBeenLastCalledWith("Doing", "Second");+ });++ /**+ * A card is added at the end of its column, which on a full column is out of sight, so it is+ * scrolled to and faded in rather than appearing wherever the reader is not looking.+ */+ it("reveals the card the editor just made", async () => {+ const { container } = await setup();+ const card = container.querySelector<HTMLElement>(".board-note");+ const noteId = card?.getAttribute("data-note-id");+ const column = card?.closest<HTMLElement>(".board-column");+ if (!card || !noteId || !column) throw new Error("expected a card to stand in for the new one");// happy-dom lays nothing out, so the scrollable height has to be stood in for.- Object.defineProperty(content, "scrollHeight", { value: 500, configurable: true });+ const content = column.querySelector<HTMLElement>(".board-column-content");+ if (!content) throw new Error("expected a scrollable column body");+ Object.defineProperty(content, "scrollHeight",+ { value: 500, configurable: true, writable: true });expect(content.scrollTop).toBe(0);+ vi.spyOn(BoardApi.prototype, "createNewItem").mockResolvedValue(noteId);++ const slot = column.querySelector<HTMLElement>(".board-new-item");await act(async () => {- column.querySelector<HTMLElement>(".board-new-item")?.focus();+ slot?.click();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");+ const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");+ if (!editor) throw new Error("expected the new-item editor to be open");+ editor.value = "Fresh";await act(async () => {- render(- <ParentComponent.Provider value={new Component()}>- <Harness- note={note}- noteIds={[ ...note.getChildNoteIds() ]}- initialConfig={DEFAULT_CONFIG}- />- </ParentComponent.Provider>,- container- );+ editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));await flush();});- await act(async () => { await flush(); });- expect(columnTitles(container)).toEqual([ "To Do", "Doing", "Done" ]);- expect(content.scrollTop).toBe(900);+ expect(card.classList.contains("appearing")).toBe(true);+ expect(content.scrollTop).toBe(500);++ // The cards that were already there are left alone.+ const others = [ ...container.querySelectorAll(".board-note") ]+ .filter(other => other !== card);+ expect(others.some(other => other.classList.contains("appearing"))).toBe(false);});it("starts the new item off with the character typed on its button", async () => {diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex b4e584e8bc..67db75ad99 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -714,7 +714,8 @@ function AddNewColumn({ api, isInRelationMode }: { api: BoardApi, isInRelationMo}export function TitleEditor({- currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true+ currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true,+ saveAndContinue = false}: {currentValue?: string;placeholder?: string;@@ -722,6 +723,11 @@ export function TitleEditor({dismiss: () => void;isNewItem?: boolean;mode?: "normal" | "multiline" | "relation";+ /**+ * Whether Enter saves and clears the editor rather than closing it, so that a run of cards can+ * be typed one after another. Escape and clicking away still close it.+ */+ saveAndContinue?: boolean;/*** 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@@ -760,6 +766,18 @@ export function TitleEditor({return;}+ if (e.key === "Enter" && saveAndContinue) {+ e.preventDefault();+ e.stopPropagation();++ const input = inputRef.current;+ if (input?.value.trim()) {+ commit(input.value);+ input.value = "";+ }+ return;+ }+if (e.key === "Enter" || e.key === "Escape") {e.preventDefault();e.stopPropagation();@@ -774,19 +792,23 @@ export function TitleEditor({const onBlur = (newValue: string) => {if (!shouldDismiss.current && newValue.trim() && (newValue !== currentValue || isNewItem)) {- // The editor is closing either way, and what a save writes has already been put back by- // whatever could not write it; all that is left is to say so rather than to reject- // unhandled, which is what a save reaching nobody used to do.- Promise.resolve(save(newValue)).catch((e) => {- console.error("Failed to save what the board editor was given:", e);- toast.showError(t("board_view.save-error"));- });+ commit(newValue);dismissOnNextRefreshRef.current = true;} else {dismiss();}};+ // The editor is closing either way, and what a save writes has already been put back by+ // whatever could not write it; all that is left is to say so rather than to reject unhandled,+ // which is what a save reaching nobody used to do.+ function commit(newValue: string) {+ Promise.resolve(save(newValue)).catch((e) => {+ console.error("Failed to save what the board editor was given:", e);+ toast.showError(t("board_view.save-error"));+ });+ }+if (mode !== "relation") {const Element = mode === "multiline" ? FormTextArea : FormTextBox;