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: implement an "Add existing note" / "Create note" button to new card / column input field
Adorian Doran8a7c2742ba9a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex c7348a0b7a..205c89f22d 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3394,7 +3394,10 @@"add-existing-item": "Add existing note...","add-existing-item-title": "Add an existing note to the board","add-existing-item-ok": "Add to column",+ "add-existing-column": "Add existing column","add-new-column": "Add new column",+ "create-new-note": "Create note",+ "create-new-column": "Create column","add-column-before": "Before","add-column-after": "After","new-column": "New column",diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex af4e756b0e..352a51ae2e 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -10,6 +10,7 @@ import FBranch from "../../../entities/fbranch";import FNote from "../../../entities/fnote";import { ContextMenuEvent } from "../../../menus/context_menu";import branches from "../../../services/branches";+import dialog from "../../../services/dialog";import { getHue, parseColor } from "../../../services/css_class_manager";import froca from "../../../services/froca";import { t } from "../../../services/i18n";@@ -404,6 +405,18 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreatsetIsCreating(true);}, [ setIsCreating ]);+ /** Puts a note that already exists into this column, for a field with nothing typed into it. */+ const addExistingItem = useCallback(async () => {+ const noteId = await dialog.chooseNote({+ title: t("board_view.add-existing-item-title"),+ okLabel: t("board_view.add-existing-item-ok")+ });++ if (noteId) {+ await api.addExistingItem(column, noteId);+ }+ }, [ api, column ]);+const handleKeyDown = useCallback((e: KeyboardEvent) => {if (isCreating) return;@@ -446,6 +459,11 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreatselectOnFocus={false}saveAndContinueabandon={setInitialTitle}+ whenEmpty={{+ title: t("board_view.add-existing-item"),+ onClick: addExistingItem+ }}+ submitTitle={t("board_view.create-new-note")}/>)}</div>diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex bd40168ce6..d74ec5661c 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -507,6 +507,40 @@ body.mobile .board-view-container .board-add-column {resize: none;}+/* The field and the button that submits it, which stands over the field's own end. */+.board-view-container .title-editor-with-submit {+ display: flex;+ flex-grow: 1;+ position: relative;+ align-items: center;+}++/*+ * Held near the field's foot, where it stays as the field grows a line at a time, except where+ * centring it would put it there anyway: `min()` takes the smaller of the two, which on a field of+ * one line is the centred offset and on a taller one is the foot.+ *+ * Sized through the icon button's own variables rather than by overriding its box, and in `rem`+ * rather than `em`: a custom property is worked out where it is used, and this button's font is+ * itself derived from the size below.+ */+.board-view-container .title-editor-with-submit .title-editor-submit {+ --icon-button-size: 1.6rem;+ --icon-button-icon-ratio: 0.72;++ position: absolute;+ inset-inline-end: 0.3rem;+ inset-block-end: min(calc((100% - var(--icon-button-size)) / 2), 0.4rem);+ color: var(--muted-text-color);+}++/* Room for the button, so a long title runs up to it rather than under it. Stated after the rule+ above, whose shorthand padding would otherwise take this back. */+.board-view-container .title-editor-with-submit textarea.form-control,+.board-view-container .title-editor-with-submit input.form-control {+ padding-inline-end: 2.2em;+}+/* A card or column lands where the reader may not be looking, so it announces itself. */@keyframes board-item-appear {from { opacity: 0; }diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex a86034aeec..48b98d36ad 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import Component from "../../../components/component";import contextMenu from "../../../menus/context_menu";+import dialog from "../../../services/dialog";import server from "../../../services/server";import toast from "../../../services/toast";import FBranch from "../../../entities/fbranch";@@ -55,6 +56,14 @@ async function flush() {await new Promise((resolve) => setTimeout(resolve));}+/** Fills a field the way typing does, so that what watches the field hears about it. */+async function type(field: HTMLInputElement | HTMLTextAreaElement, value: string) {+ await act(async () => {+ field.value = value;+ field.dispatchEvent(new Event("input", { bubbles: true }));+ });+}+const saved: BoardViewData[] = [];/**@@ -1501,6 +1510,72 @@ describe("Board column rename", () => {expect(slot?.classList.contains("editing")).toBe(false);});+ /**+ * The same as Enter, for a reader who would rather press something: pressing it must not take+ * focus out of the field first, since losing focus is what closes the editor.+ */+ it("makes a card from the button inside the new-item editor, and clears it", async () => {+ const { container } = await setup();+ const created = vi.spyOn(BoardApi.prototype, "createNewItem")+ .mockResolvedValue(undefined);+ created.mockClear();+ 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");+ const submit = slot?.querySelector<HTMLElement>(".title-editor-submit");+ if (!editor || !submit) throw new Error("expected the editor and its button");++ await type(editor, "From the button");+ await act(async () => {+ submit.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ await flush();+ });++ expect(created).toHaveBeenCalledWith("Doing", "From the button");+ expect(editor.value).toBe("");+ expect(slot?.querySelector("textarea")).toBe(editor);+ expect(document.activeElement).toBe(editor);+ });++ /**+ * With nothing typed there is nothing to save, so the button reaches for a note that exists+ * already instead, and goes back to making one as soon as the field holds anything.+ */+ it("offers an existing note from the new-item button while the field is empty", async () => {+ const { container } = await setup();+ const chosen = vi.spyOn(dialog, "chooseNote").mockResolvedValue("existing");+ const added = vi.spyOn(BoardApi.prototype, "addExistingItem").mockResolvedValue(true);+ 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");+ const button = () => slot?.querySelector<HTMLElement>(".title-editor-submit");+ if (!editor) throw new Error("expected the editor");+ expect(button()?.className).toContain("bx-folder-open");++ await act(async () => {+ slot?.querySelector<HTMLElement>(".title-editor-submit")+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ await flush();+ });+ expect(chosen).toHaveBeenCalled();+ expect(added).toHaveBeenCalledWith("Doing", "existing");++ await type(editor, "Typed");+ expect(button()?.className).toContain("bx-plus-circle");+ });+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.tsxindex da6451a862..a1877d522f 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -26,6 +26,7 @@ import Icon from "../../react/Icon";import NoteAutocomplete from "../../react/NoteAutocomplete";import ShortcutHintButton from "../../shortcut_hints/shortcut_hint_button";import { onWheelHorizontalScroll } from "../../widget_utils";+import ActionButton from "../../react/ActionButton";import { useDragPan } from "../../react/drag_pan";import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";import { ViewModeProps } from "../interface";@@ -787,6 +788,8 @@ function AddNewColumn({ api, isInRelationMode, columnCount, onCreated }: {// standing with an empty field. A column named by a note answers for// itself, since picking one is what closes that editor.saveAndContinue={!isInRelationMode}+ whenEmpty={{ title: t("board_view.add-existing-column") }}+ submitTitle={t("board_view.create-new-column")}mode={isInRelationMode ? "relation" : "normal"}/>)}@@ -796,7 +799,7 @@ function AddNewColumn({ api, isInRelationMode, columnCount, onCreated }: {export function TitleEditor({currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true,- saveAndContinue = false, returnFocusTo, abandon+ saveAndContinue = false, returnFocusTo, abandon, whenEmpty, submitTitle}: {currentValue?: string;placeholder?: string;@@ -814,6 +817,14 @@ export function TitleEditor({saveAndContinue?: boolean;/** What was typed and not saved, handed over so that reopening the editor can carry it back. */abandon?: (typed: string) => void;+ /**+ * What the button stands for while there is nothing to save. The icon is the same wherever it+ * is offered; an editor whose caller has nothing to do yet keeps the button, which then does+ * nothing rather than coming and going as the field is typed into and emptied again.+ */+ whenEmpty?: { title: string, onClick?: () => void };+ /** What the button beside the field makes, for the reader hovering over it. */+ submitTitle?: string;/*** 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@@ -828,6 +839,8 @@ export function TitleEditor({selectOnFocus?: boolean;}) {const inputRef = useRef<any>(null);+ /** Whether the field holds anything, which is what the button beside it offers to do. */+ const [ isEmpty, setIsEmpty ] = useState(!currentValue?.trim());const focusElRef = useRef<Element>(null);const dismissOnNextRefreshRef = useRef(false);const shouldDismiss = useRef(false);@@ -863,12 +876,7 @@ export function TitleEditor({if (e.key === "Enter" && saveAndContinue) {e.preventDefault();e.stopPropagation();-- const input = inputRef.current;- if (input?.value.trim()) {- commit(input.value);- input.value = "";- }+ submit();return;}@@ -894,6 +902,18 @@ export function TitleEditor({}};+ /** Saves what is in the editor and empties it, leaving it open for whatever comes next. */+ function submit() {+ const input = inputRef.current;+ if (input?.value.trim()) {+ commit(input.value);+ input.value = "";+ }++ input?.focus();+ setIsEmpty(true);+ }+const onBlur = (newValue: string) => {if (saveAndContinue) {abandon?.(newValue);@@ -921,8 +941,7 @@ export function TitleEditor({if (mode !== "relation") {const Element = mode === "multiline" ? FormTextArea : FormTextBox;-- return (+ const field = (<ElementinputRef={inputRef}currentValue={currentValue ?? ""}@@ -931,8 +950,37 @@ export function TitleEditor({rows={mode === "multiline" ? 4 : undefined}onKeyDown={onKeyDown}onBlur={onBlur}+ onInput={(e) => setIsEmpty(!e.currentTarget.value.trim())}/>);++ if (!saveAndContinue) {+ return field;+ }++ const offered = isEmpty && whenEmpty+ ? { icon: "bx bx-folder-open", ...whenEmpty }+ : {+ icon: "bx bx-plus-circle",+ title: submitTitle ?? t("board_view.add-new-item"),+ onClick: submit+ };++ return (+ <div className="title-editor-with-submit">+ {field}+ {/* The press must not take focus out of the field first: losing it is what closes+ the editor, and it would be gone before the click arrived. */}+ <span onMouseDown={(e) => e.preventDefault()}>+ <ActionButton+ className="title-editor-submit"+ icon={offered.icon}+ text={offered.title}+ onClick={offered.onClick}+ />+ </span>+ </div>+ );}return (<NoteAutocomplete