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: add template selector for the cards created from context menu as well
Adorian Dorand005e86a0c31
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex cc86971df5..bd6e69a222 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -644,28 +644,62 @@ describe("BoardApi card operations", () => {"notes/" + items[0].note.noteId + "/title", { title: "Fresh title" });});- it("inserts a card beside another and opens its title for editing", async () => {- const { api, editing, items } = createBoardWithCards();+ it("inserts a card beside another, named and iconed as it was typed", async () => {+ const { api, items } = createBoardWithCards();const created = buildNote({ title: "Created" });vi.spyOn(server, "put").mockResolvedValue(undefined);vi.mocked(note_create.createNote).mockResolvedValue({note: created, branch: { branchId: "createdBranch" }} as never);- const note = await api.insertRowAtPosition("Done", items[0].branch.branchId, "after");+ const result = await api.insertRowAtPosition(+ "Done", items[0].branch.branchId, "after", "Typed", "bx bx-star");- expect(note).toBe(created);+ expect(result).toEqual({ note: created, branch: { branchId: "createdBranch" } });expect(note_create.createNote).toHaveBeenCalledWith(expect.any(String),- expect.objectContaining({ targetBranchId: items[0].branch.branchId, target: "after" }));- expect(editing).toEqual([ "createdBranch" ]);+ expect.objectContaining({+ targetBranchId: items[0].branch.branchId,+ target: "after",+ title: "Typed",+ attributes: expect.arrayContaining([+ expect.objectContaining({ name: "iconClass", value: "bx bx-star" })+ ])+ }));+ });++ /**+ * What a field standing among a column's cards makes: the card goes above the one the field+ * stands over, and a field standing below the last card makes one at the end of the column.+ */+ it("creates a card above the one a field stands over", async () => {+ const { api, items } = createBoardWithCards();+ const created = buildNote({ title: "Created" });+ vi.spyOn(server, "put").mockResolvedValue(undefined);+ vi.mocked(note_create.createNote).mockResolvedValue({+ note: created, branch: { branchId: "createdBranch" }+ } as never);++ expect(await api.createNewItemBefore("Done", items[0].branch.branchId, "First"))+ .toBe(created.noteId);+ expect(note_create.createNote).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({+ targetBranchId: items[0].branch.branchId, target: "before", title: "First"+ }));++ // Below the last card there is nothing to go above, so the card is made at the end.+ expect(await api.createNewItemBefore("Done", undefined, "Last")).toBe(created.noteId);+ const last = vi.mocked(note_create.createNote).mock.calls.at(-1)?.[1];+ expect(last).toEqual(expect.objectContaining({ title: "Last" }));+ expect(last).not.toHaveProperty("target");});it("reports a card it could not create rather than filing nothing", async () => {const { api, items } = createBoardWithCards();vi.mocked(note_create.createNote).mockResolvedValue({ note: null, branch: null } as never);- await expect(api.insertRowAtPosition("Done", items[0].branch.branchId, "after"))+ await expect(api.insertRowAtPosition("Done", items[0].branch.branchId, "after", "Typed")).rejects.toThrow("Failed to create note");});@@ -782,12 +816,12 @@ describe("BoardApi card operations", () => {} as never);// Nothing has been used yet, so the first the board offers stands.- await api.insertRowAtPosition("Done", "branchId", "after");+ await api.insertRowAtPosition("Done", "branchId", "after", "Typed");expect(note_create.createNote).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ type: "text" }));await api.setLastCardTemplateId("type:canvas:application/json");- await api.insertRowAtPosition("Done", "branchId", "after");+ await api.insertRowAtPosition("Done", "branchId", "after", "Typed");expect(note_create.createNote).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ type: "canvas" }));@@ -828,7 +862,7 @@ describe("BoardApi card operations", () => {expect.objectContaining({ type: "canvas", mime: "application/json" }));// And the same for a card inserted beside another one.- await api.insertRowAtPosition("Done", "branchId", "after", {+ await api.insertRowAtPosition("Done", "branchId", "after", "Typed", undefined, {id: "note:mine",title: "My template",icon: "bx bx-star",diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex f0e5a074df..550deb632b 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -186,17 +186,7 @@ export default class BoardApi {title,isProtected: this.parentNote.isProtected,...(template?.options ?? {}),- attributes: [- ...this.groupingFor(column),- ...(icon- ? [ {- type: "label" as const,- name: "iconClass",- value: icon,- isInheritable: false- } ]- : [])- ],+ attributes: this.attributesFor(column, icon),...(first ? { target: "before", targetBranchId: first } : {})});@@ -206,6 +196,40 @@ export default class BoardApi {}}+ /**+ * Creates a card above another one, for a field standing among a column's cards.+ *+ * Without a card to go above, which is where the field stands below the last one, the card is+ * made at the end of the column.+ */+ async createNewItemBefore(+ column: string, beforeBranchId: string | undefined, title: string, icon?: string,+ template: NoteTypeOption | undefined = this.getCurrentCardTemplate()+ ) {+ if (!beforeBranchId) {+ return this.createNewItem(column, title, "bottom", icon, template);+ }++ const { note } = await this.insertRowAtPosition(+ column, beforeBranchId, "before", title, icon, template);+ return note.noteId;+ }++ /** What a new card carries besides its title: the column it lands in, and its icon. */+ private attributesFor(column: string, icon?: string) {+ return [+ ...this.groupingFor(column),+ ...(icon+ ? [ {+ type: "label" as const,+ name: "iconClass",+ value: icon,+ isInheritable: false+ } ]+ : [])+ ];+ }+/*** What a new card carries so that it lands in the column it was added to.*@@ -237,7 +261,7 @@ export default class BoardApi {** @returns whether the note was added, `false` when the user backed out.*/- async addExistingItem(column: string, noteId: string) {+ async addExistingItem(column: string, noteId: string, beforeBranchId?: string) {const note = await froca.getNote(noteId, true);if (!note) return false;@@ -258,9 +282,33 @@ export default class BoardApi {}await this.changeColumn(noteId, column);++ if (beforeBranchId) {+ await this.moveIntoPlace(noteId, beforeBranchId);+ }+return true;}+ /**+ * Puts a card that was just added above another one, which is where a field standing among a+ * column's cards adds it, rather than leaving it at the end of the column.+ *+ * The wait is what makes the move possible: a note cloned onto the board is given its branch by+ * the server, and that branch has to be in froca before it can be moved.+ */+ private async moveIntoPlace(noteId: string, beforeBranchId: string) {+ await ws.waitForMaxKnownEntityChangeId();++ const note = await froca.getNote(noteId);+ const branchId = note?.getParentBranches()+ .find(branch => branch.parentNoteId === this.parentNote.noteId)?.branchId;++ if (branchId && branchId !== beforeBranchId) {+ await branches.moveBeforeBranch([ branchId ], beforeBranchId);+ }+ }+async changeColumn(noteId: string, newColumn: string) {if (newColumn === INBOX_COLUMN) {return this.moveToInbox(noteId);@@ -940,27 +988,29 @@ export default class BoardApi {);}+ /** Creates a card beside another one, which is what a field between two cards makes. */async insertRowAtPosition(column: string,relativeToBranchId: string,direction: "before" | "after",+ title: string,+ icon?: string,template: NoteTypeOption | undefined = this.getCurrentCardTemplate()) {const { note, branch } = await note_create.createNote(this.parentNote.noteId, {activate: false,targetBranchId: relativeToBranchId,target: direction,- title: t("board_view.new-item"),+ title,+ isProtected: this.parentNote.isProtected,...(template?.options ?? {}),- attributes: this.groupingFor(column)+ attributes: this.attributesFor(column, icon)});if (!note || !branch) {throw new Error("Failed to create note");}- this.startEditing(branch.branchId);-- return note;+ return { note, branch };}openNote(noteId: string) {diff --git a/apps/client/src/widgets/collections/board/card.spec.tsx b/apps/client/src/widgets/collections/board/card.spec.tsxindex 9b76b859fe..2a7d826069 100644--- a/apps/client/src/widgets/collections/board/card.spec.tsx+++ b/apps/client/src/widgets/collections/board/card.spec.tsx@@ -122,22 +122,35 @@ describe("Board card", () => {.toHaveBeenCalledWith("openInPopup", { noteIdOrPath: first });});- /** Enter adds a card where a spreadsheet would add a row, and Shift puts it above instead. */- it("adds a card under the focused one for Enter, and over it for Shift and Enter", async () => {- const insert = vi.spyOn(BoardApi.prototype, "insertRowAtPosition")- .mockResolvedValue(undefined as never);- const openInPopup = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);- const { first } = await renderBoard();+ /**+ * Enter opens the field a card is named in where a spreadsheet would add a row, and Shift puts+ * it above instead. The card itself is made by that field, once it has been given a title.+ */+ it("opens the field under the focused card for Enter, and over it for Shift and Enter",+ async () => {+ const openInPopup = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);+ const { first } = await renderBoard();- await act(async () => { press(card(first), "Enter"); });- expect(insert).toHaveBeenLastCalledWith("To Do", expect.any(String), "after");+ await act(async () => { press(card(first), "Enter"); });+ expect(fieldBeside(first)).toBe("after");- await act(async () => { press(card(first), "Enter", { shiftKey: true }); });- expect(insert).toHaveBeenLastCalledWith("To Do", expect.any(String), "before");+ await act(async () => { press(card(first), "Enter", { shiftKey: true }); });+ expect(fieldBeside(first)).toBe("before");- // The card it was pressed on stays where it is; Space is what opens one.- expect(openInPopup).not.toHaveBeenCalled();- });+ // The card it was pressed on stays where it is; Space is what opens one.+ expect(openInPopup).not.toHaveBeenCalled();+ });++ /** Which side of a card the field for a new one stands on, or that none is open. */+ function fieldBeside(noteId: string) {+ const field = container?.querySelector(".board-new-item.inserting");+ if (!field) return "none";++ const element = card(noteId);+ if (field.previousElementSibling === element) return "after";+ if (field.nextElementSibling === element) return "before";+ return "elsewhere";+ }it("opens the note once for a double click, not once per click of it", async () => {const { first } = await renderBoard();diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsxindex aceb979d60..91c5aff4a6 100644--- a/apps/client/src/widgets/collections/board/card.tsx+++ b/apps/client/src/widgets/collections/board/card.tsx@@ -27,7 +27,7 @@ function Card({isDragging,isEditing,onFocusCard,- onCreated+ onInsert}: {api: BoardApi,note: FNote,@@ -41,7 +41,7 @@ function Card({statusAttribute: string,/** 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. */+ /** Whether the card just made is also left focused, which one made among the others is. */focusOnArrival: boolean,isDragging: boolean,/**@@ -51,8 +51,11 @@ 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,- /** Names the card inserted next to this one, which the column reveals as it draws it. */- onCreated: (noteId: string | undefined) => void+ /**+ * Opens the field a new card is named in at a place in the column, which is what makes the+ * card. The index is where the field stands among the cards.+ */+ onInsert: (index: number) => void}) {const { setBranchIdToEdit } = useContext(BoardActionsContext);// Tracks the `color` label, which the board does not redraw a card for.@@ -78,8 +81,8 @@ function Card({});const handleContextMenu = useCallback((e: ContextMenuEvent) => {- openNoteContextMenu(api, e, note, branch.branchId, column, onFocusCard, onCreated);- }, [ api, note, branch, column, onFocusCard, onCreated ]);+ openNoteContextMenu(api, e, note, branch.branchId, column, index, onFocusCard, onInsert);+ }, [ api, note, branch, column, index, onFocusCard, onInsert ]);const handleOpen = useCallback((e: MouseEvent) => {// A double click is one gesture, and its second click would open the note over itself: the@@ -99,19 +102,18 @@ 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")- .then(created => onCreated(created?.noteId));+ onInsert(e.shiftKey ? index : index + 1);} else if (e.key === "F2") {setBranchIdToEdit(branch.branchId);}- }, [ api, column, branch, setBranchIdToEdit, onCreated ]);+ }, [ branch, index, setBranchIdToEdit, onInsert ]);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.+ // The field a card is named in closes as the card is made, so the card takes focus as it is+ // drawn and the arrow keys carry on from there.useEffect(() => {if (focusOnArrival && !isEditing) {cardRef.current?.focus();diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex deababe892..a2d03ac0b0 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -19,13 +19,11 @@ import ActionButton from "../../react/ActionButton";import Icon from "../../react/Icon";import { IconPickerButton } from "../../react/IconPicker";import { useStaticTooltip } from "../../react/hooks";-import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";+import { useFlip } from "../../react/flip";import { useScrollFade } from "../../react/scroll_fade";-/**- * How long `footerQuietUntil` holds for a card `AddNewItem` is making, if the write never answers.- */-const FOOTER_QUIET_MS = 5000;+/** How long a field waits for the card it made, after which it is taken down regardless. */+const HAND_OVER_MS = 2000;/** How long an open takes. Matches `--board-expand-duration` in the board's own rules. */const EXPAND_MS = 200;@@ -101,40 +99,43 @@ export default function Column({onFocusCard: (noteId: string) => void} & DragContext) {const [ isCreatingNewItem, setIsCreatingNewItem ] = useState(false);- const [ created, setCreated ] = useState<{ noteId?: string, takesFocus: boolean }>();/**- * Every card this column has drawn, which is what tells one just made from one coming back.+ * The card a field standing among the cards makes its own above, absent while no such field is+ * open and empty for one standing below the last card.*- * `created` names a card until another is made, and the card itself is marked in no way, so a- * card carried off the column and back would arrive under that name again. Every arrival is- * recorded, whatever became of it: the card can be drawn before the write answers with its id,- * and the footer's own card is never opened out at all.+ * The card below the field rather than the one above it, so the field keeps its place as it+ * makes cards: each one is drawn above the field, and a run of them stands in the order it was+ * typed. Named by the card above instead, the field would be carried down past every card it+ * made, and moving the element it is typed in takes focus out of it.*/- const arrived = useRef(new Set<string>());- // `isNew` stays true until another column is added, so the reveal is recorded here rather than- // replayed on every redraw of the board.- const [ isRevealed, setIsRevealed ] = useState(false);+ const [ insertBefore, setInsertBefore ] = useState<{ branchId?: string }>();/**- * Until when a card from `AddNewItem` can still arrive, during which `useFlip` does not grow- * it.- *- * Testing the id is not enough: `createNewItem()` answers with it after the refresh that draws- * the card can already have run, so `created` is set too late. `onCreating` sets this before- * the write instead.+ * The cards as last drawn, for the callback that opens a field among them. Read through a ref+ * so that callback keeps one identity: rebuilt per refresh, it would be a new prop on every+ * card and no card could be left undrawn.*/- const footerQuietUntil = useRef(0);- // An inserted card is left focused, since that is where the work is; a card from the footer is- // not, or it would take focus from the editor being typed in.- const cardInserted = useCallback(- (noteId: string | undefined) => setCreated({ noteId, takesFocus: true }), []);- const addingFromFooter = useCallback(() => {- // Long enough for a write that never answers; `cardAdded` shortens it when one does.- footerQuietUntil.current = Date.now() + FOOTER_QUIET_MS;+ const itemsRef = useRef(columnItems);+ itemsRef.current = columnItems;+ /** Opens the field at a place among the cards, which is the index the card it makes takes. */+ const beginInsert = useCallback((index: number) => {+ setInsertBefore({ branchId: itemsRef.current?.[index]?.branch.branchId });}, []);- const cardAdded = useCallback((noteId: string | undefined) => {- footerQuietUntil.current = Date.now() + FLIP_SETTLE_MS;- setCreated({ noteId, takesFocus: false });+ /** The card the footer just made, which is revealed and scrolled to as it is drawn. */+ const [ createdNoteId, setCreatedNoteId ] = useState<string>();+ /**+ * The card a field standing among the others just made, which takes the field's place.+ *+ * The field stands where the card goes until the board has drawn it, so the card fades in+ * where the field was rather than opening out of a gap the column has to make for it.+ */+ const [ insertedNoteId, setInsertedNoteId ] = useState<string>();+ const cardInserted = useCallback((noteId: string | undefined) => {+ setInsertedNoteId(noteId);+ setCreatedNoteId(noteId);}, []);+ // `isNew` stays true until another column is added, so the reveal is recorded here rather than+ // replayed on every redraw of the board.+ const [ isRevealed, setIsRevealed ] = useState(false);const { setColumnNameToEdit, setColumnLimitToEdit, setActiveColumn } =useContext(BoardActionsContext);const { branchIdToEdit, columnNameToEdit, dropTarget, draggedCard, dropPosition } = useContext(BoardDragStateContext);@@ -143,25 +144,10 @@ export default function Column({const headerRef = useRef<HTMLHeadingElement>(null);const contentRef = useRef<HTMLDivElement>(null);const scrollFade = useScrollFade(contentRef);- // Cards slide to follow the drop gap opening and closing. Only the card named by `created`- // opens out of nothing: a card moved here from another column mounts as a new element too, and- // would collapse and reopen after the drop. The footer's own card is excluded as well, by- // `footerQuietUntil`: the scroll to the end and the fade already show it.- useFlip(contentRef, {- selector: ".board-note",- grow: (card) => {- const noteId = card.getAttribute("data-note-id");- if (!noteId) {- return false;- }-- const isFirstArrival = !arrived.current.has(noteId);- arrived.current.add(noteId);-- return isFirstArrival && noteId === created?.noteId- && Date.now() > footerQuietUntil.current;- }- });+ // Cards slide to follow the drop gap opening and closing. No card opens out of nothing: one+ // made in the footer is shown by the scroll to the end and by its fade, and one made among the+ // others takes the place its field was standing in.+ useFlip(contentRef, { selector: ".board-note" });const { handleDragOver, handleDragLeave, handleDrop } = useDragging({column, columnIndex, columnItems, isEditing, api, parentNote});@@ -334,6 +320,44 @@ export default function Column({editorRef.current?.focus();}, [ isEditing ]);+ // The field is taken down only once the card it made stands in its place, so the column does+ // not close the gap the field held and open it again for the card.+ useEffect(() => {+ if (!insertedNoteId) {+ return;+ }++ const close = () => {+ setInsertBefore(undefined);+ setInsertedNoteId(undefined);+ };++ if (columnItems?.some(({ note }) => note.noteId === insertedNoteId)) {+ close();+ return;+ }++ // A card can be drawn in another column, which one made from a template carrying a value+ // of its own is, so the field is not left standing for a card that never arrives here.+ const timer = window.setTimeout(close, HAND_OVER_MS);+ return () => window.clearTimeout(timer);+ }, [ insertedNoteId, columnItems ]);++ // The field a card is inserted in, drawn where the reader asked for the card. The same field+ // as the one below the column, so a card is made the same way wherever it goes.+ const insertField = insertBefore && (+ <AddNewItem+ api={api}+ cardTemplates={cardTemplates}+ column={column}+ insert={{+ before: insertBefore.branchId,+ close: () => setInsertBefore(undefined)+ }}+ onCreated={cardInserted}+ />+ );+return (<divdata-column={column}@@ -474,6 +498,7 @@ export default function Column({{showIndicatorBefore && (<div className="board-drop-placeholder show" style={gapStyle} />)}+ {insertBefore?.branchId === branch.branchId && insertField}<Cardapi={api}note={note}@@ -481,18 +506,17 @@ export default function Column({column={column}index={index}statusAttribute={api.statusAttribute}- isNew={note.noteId === created?.noteId}- focusOnArrival={- note.noteId === created?.noteId && created.takesFocus- }+ isNew={note.noteId === createdNoteId}+ focusOnArrival={note.noteId === insertedNoteId}isDragging={draggedCard?.noteId === note.noteId}isEditing={branch.branchId === branchIdToEdit}onFocusCard={onFocusCard}- onCreated={cardInserted}+ onInsert={beginInsert}/></Fragment>);})}+ {insertBefore && !insertBefore.branchId && insertField}{dropPosition?.column === column && dropPosition.index === (columnItems?.length ?? 0) && (<div className="board-drop-placeholder show" style={gapStyle} />)}@@ -504,30 +528,41 @@ export default function Column({column={column}isCreating={isCreatingNewItem}setIsCreating={setIsCreatingNewItem}- onCreated={cardAdded}- onCreating={addingFromFooter}+ onCreated={setCreatedNoteId}/>}</div>);}/**- * 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.+ * The editor a new card is named in, standing below the column or between two of its cards.+ *+ * Below the column it is opened by the button it replaces or by the column's menu, so that state+ * is the column's rather than this component's: the menu is raised from the header. Between two+ * cards it is opened by a card's own menu, and `insert` says where it stands.*/function AddNewItem({- column, api, cardTemplates, isCreating, setIsCreating, onCreated, onCreating+ column, api, cardTemplates, isCreating, setIsCreating, onCreated, insert}: {column: string,api: BoardApi,cardTemplates: CardTemplates,- isCreating: boolean,- setIsCreating: (isCreating: boolean) => void,- /** Names the card just made, which the column reveals once the board has drawn it. */+ isCreating?: boolean,+ setIsCreating?: (isCreating: boolean) => void,+ /** Names the card just made, which the column shows once the board has drawn it. */onCreated: (noteId: string | undefined) => void,- /** Said before the write, which the card can be drawn by the board ahead of. */- onCreating: () => void+ /**+ * Where a field standing among the cards puts what it makes: above the card it is given, or+ * at the end of the column where it is given none. Absent for the field below the column.+ */+ insert?: { before?: string, close: () => void }}) {+ // A field standing among the cards is nothing else: there is no button for it to replace, and+ // it is taken down rather than closed.+ const isEditing = !!insert || !!isCreating;+ const close = useCallback(+ () => insert ? insert.close() : setIsCreating?.(false),+ [ insert, setIsCreating ]);// What the editor opens with: empty to begin with, then whatever was typed into it and left// unsaved, so that reaching for something else and coming back does not cost the title.const [ initialTitle, setInitialTitle ] = useState("");@@ -536,7 +571,7 @@ function AddNewItem({const open = useCallback((title: string) => {setInitialTitle(title);- setIsCreating(true);+ setIsCreating?.(true);}, [ setIsCreating ]);/** Puts a note that already exists into this column, for a field with nothing typed into it. */@@ -547,15 +582,15 @@ function AddNewItem({});if (noteId) {- await api.addExistingItem(column, noteId);+ await api.addExistingItem(column, noteId, insert?.before);}- }, [ api, column ]);+ }, [ api, column, insert ]);const handleKeyDown = useCallback((e: KeyboardEvent) => {if (isCreating) return;if (e.key === "Enter" && !e.ctrlKey) {- setIsCreating(true);+ setIsCreating?.(true);return;}@@ -568,14 +603,34 @@ function AddNewItem({}}, [ isCreating, open, setIsCreating ]);+ /** Makes the card, where the field stands or at the end of the column. */+ const create = useCallback(async (title: string, atStart?: boolean) => {+ const cardIcon = icon !== DEFAULT_CARD_ICON ? icon : undefined;++ if (insert) {+ // Left standing until the column has drawn the card, which takes the field's place.+ const noteId = await api.createNewItemBefore(+ column, insert.before, title, cardIcon, cardTemplates.current);+ if (noteId) {+ onCreated(noteId);+ } else {+ insert.close();+ }+ return;+ }++ onCreated(await api.createNewItem(+ column, title, atStart ? "top" : "bottom", cardIcon, cardTemplates.current));+ }, [ api, cardTemplates, column, icon, insert, onCreated ]);+return (<div- className={`board-new-item ${isCreating ? "editing" : ""}`}- onClick={() => flushSync(() => setIsCreating(true))}- onKeyDown={handleKeyDown}- tabIndex={300}+ className={clsx("board-new-item", { editing: isEditing, inserting: !!insert })}+ onClick={!insert ? () => flushSync(() => setIsCreating?.(true)) : undefined}+ onKeyDown={!insert ? handleKeyDown : undefined}+ tabIndex={!insert ? 300 : undefined}>- {!isCreating ? (+ {!isEditing ? (<><Icon icon="bx bx-plus" />{" "}{t("board_view.new-item")}@@ -584,24 +639,21 @@ function AddNewItem({<TitleEditorcurrentValue={initialTitle}placeholder={t("board_view.new-item-placeholder")}- save={async (title, atStart) => {- onCreating();- onCreated(await api.createNewItem(- column, title, atStart ? "top" : "bottom",- icon !== DEFAULT_CARD_ICON ? icon : undefined,- cardTemplates.current));- }}- dismiss={() => setIsCreating(false)}+ save={create}+ dismiss={close}mode="multiline" isNewItemselectOnFocus={false}saveAndContinue+ handsOver={!!insert}abandon={setInitialTitle}whenEmpty={{title: t("board_view.add-existing-item"),onClick: addExistingItem}}submitTitle={t("board_view.create-new-note")}- openPlacements={openCreateCardMenu}+ // Only the field below the column offers both ends. One standing among the+ // cards is already at the end the reader asked for.+ openPlacements={!insert ? openCreateCardMenu : undefined}footer={(hold) => <CardTemplatePill {...cardTemplates} {...hold} />}icon={{current: icon,diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.tsindex f671b1ca33..69ff99a12b 100644--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts@@ -413,15 +413,16 @@ describe("Board item context menu", () => {expect(api.startEditing).toHaveBeenCalledWith("branchId");});- it("inserts a card on either side of the one it was opened on", () => {+ /** The card is named in a field opened where it goes, so the menu only says where that is. */+ it("opens the field for a card on either side of the one it was opened on", () => {const api = {columns: [],isColumnArchived: () => false,getColumnIcon: () => DEFAULT_COLUMN_ICON,- getColumnColorClass: () => "",- insertRowAtPosition: vi.fn(async () => {})+ getColumnColorClass: () => ""} as unknown as BoardApi;- const items = openItemMenu(api);+ const insert = vi.fn();+ const items = openItemMenu(api, "To Do", vi.fn(), insert, 2);for (const icon of [ "bx bx-list-plus", "bx bx-empty" ]) {const entry = items.find(item => item && "uiIcon" in item && item.uiIcon === icon);@@ -429,8 +430,8 @@ describe("Board item context menu", () => {entry.handler?.(entry, {} as never);}- expect(vi.mocked(api.insertRowAtPosition).mock.calls.map(call => call[2]))- .toEqual([ "before", "after" ]);+ // The field stands where the card it makes goes: in this card's place, or after it.+ expect(insert.mock.calls.map(call => call[0])).toEqual([ 2, 3 ]);});/** Where Ctrl+Home sends it, for a reader who reached the card with the mouse. */@@ -557,7 +558,8 @@ describe("Board item context menu", () => {}/** Opens the menu a card offers, and hands back what it was given to show. */- function openItemMenu(api: BoardApi, column = "To Do", focusCard = vi.fn()) {+ function openItemMenu(+ api: BoardApi, column = "To Do", focusCard = vi.fn(), insert = vi.fn(), index = 2) {const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});const event = {preventDefault: () => {},@@ -576,8 +578,8 @@ describe("Board item context menu", () => {},api);openNoteContextMenu(- withDefaults, event, buildNote({ title: "Card" }) as FNote, "branchId", column,- focusCard, () => {});+ withDefaults, event, buildNote({ title: "Card" }) as FNote, "branchId", column, index,+ focusCard, insert);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.tsindex 7d341c3574..a22fbec23e 100644--- a/apps/client/src/widgets/collections/board/context_menu.ts+++ b/apps/client/src/widgets/collections/board/context_menu.ts@@ -400,10 +400,12 @@ function buildColumnItems(export function openNoteContextMenu(api: Api, event: ContextMenuEvent, note: FNote, branchId: string, column: string,+ /** Where this card stands among its column's cards, which is what an insert is placed by. */+ index: number,/** Puts focus back on the card once a change of column has drawn it under another one. */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+ /** Opens the field a new card is named in at a place in the column, above or below this one. */+ onInsert: (index: number) => void) {event.preventDefault();event.stopPropagation();@@ -424,15 +426,13 @@ export function openNoteContextMenu(title: t("board_view.insert-above"),uiIcon: "bx bx-list-plus",shortcut: "Shift+Enter",- handler: () => api.insertRowAtPosition(column, branchId, "before")- .then(created => onCreated(created?.noteId))+ handler: () => onInsert(index)},{title: t("board_view.insert-below"),uiIcon: "bx bx-empty",shortcut: "Enter",- handler: () => api.insertRowAtPosition(column, branchId, "after")- .then(created => onCreated(created?.noteId))+ handler: () => onInsert(index + 1)},// Left out for the card already at the head, which has nowhere to go....(api.isFirstInColumn(branchId, column) ? [] : [ {diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex 191356b67d..90be6daa27 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -259,6 +259,11 @@ body.mobile .board-view-container .board-add-column {padding: 0.5em 0.5em 0;}+/* A field standing among the cards is spaced as one of them, which is what it stands for. */+.board-view-container .board-column-content > .board-new-item {+ margin-block: 0 0.65em;+}+.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. */diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex b927e73688..2d4fab7851 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -22,7 +22,6 @@ import { buildNote } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";import BoardView, { BoardViewData } from ".";import { collectShortcutHints } from "../../../services/shortcut_hints";-import { FLIP_SETTLE_MS } from "../../react/flip";import BoardApi, { getPendingWrites } from "./api";import { DEFAULT_COLUMN_ICON, INBOX_COLUMN_ICON } from "./columns";@@ -1648,140 +1647,76 @@ describe("Board column rename", () => {});/**- * The column names the card it just made until it makes another, so what opens out is counted- * as well: a card dragged out of the column and back is a card coming back, not one just made.+ * The field a card is named in stands where the card goes and holds what it is called, so the+ * card is drawn into the place the field was keeping for it: it fades in there rather than+ * opening out of a gap the column makes after closing the one the field left.*/- it("opens out the card it just made once, and not when it comes back", async () => {+ it("keeps the field standing until the card it made takes its place", async () => {const { note, container } = await setup();- withBoxes();-- try {- const card = buildNote({ title: "Made", "#status": "Doing" });- vi.spyOn(BoardApi.prototype, "insertRowAtPosition")- .mockResolvedValue({ noteId: card.noteId } as never);-- // Made here, and drawn only by the refresh that follows.- const standIn = container.querySelectorAll<HTMLElement>(".board-column")[1]- .querySelector<HTMLElement>(".board-note");- await act(async () => {- standIn?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));- await flush();- });+ const made = buildNote({ title: "Made", "#status": "Doing" });+ let answer: (noteId: string) => void = () => {};+ vi.spyOn(BoardApi.prototype, "createNewItemBefore")+ .mockReturnValue(new Promise((resolve) => { answer = resolve; }));- fileCard(note, card);- await redraw(note, container);- expect(drawn(container, card.noteId).style.height).toBe("0px");-- // Carried off the column and dropped back on it, which draws it afresh both times.- unfileCard(note, card);- await redraw(note, container);- fileCard(note, card);- await redraw(note, container);-- expect(drawn(container, card.noteId).style.height).toBe("");- } finally {- dropBoxes();- }- });-- /**- * The footer's own card never opens out, the scroll to the end and the fade standing for it, so- * its arrival is recorded rather than its growth: otherwise it is the one card the column has- * made that opens out when it comes back.- */- it("leaves a card the footer made alone when it comes back", async () => {- const { note, container } = await setup();- withBoxes();-- try {- const card = buildNote({ title: "Footed", "#status": "Doing" });- vi.spyOn(BoardApi.prototype, "createNewItem").mockResolvedValue(card.noteId);+ const column = container.querySelectorAll<HTMLElement>(".board-column")[1];+ const standIn = column.querySelector<HTMLElement>(".board-note");+ if (!standIn) throw new Error("expected a card in the column");- const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]- .querySelector<HTMLElement>(".board-new-item");- await act(async () => {- slot?.click();- await flush();- });+ await act(async () => {+ standIn.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await flush();+ });- const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");- if (!editor) throw new Error("expected the new-item editor to be open");- editor.value = "Footed";- await act(async () => {- editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));- await flush();- });+ const field = column+ .querySelector<HTMLTextAreaElement>(".board-new-item.inserting textarea");+ if (!field) throw new Error("expected the field for a new card to be open");+ field.value = "Made";+ await act(async () => {+ field.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await flush();+ });- fileCard(note, card);- await redraw(note, container);- expect(drawn(container, card.noteId).style.height).toBe("");+ // The write is still in flight, so the field stands, and holds what it is about to become.+ await act(async () => {+ answer(made.noteId);+ await flush();+ });+ expect(column.querySelector(".board-new-item.inserting")).toBeTruthy();+ expect(field.value).toBe("Made");- // Once the quiet window the footer opened has passed, and back on the column.- await act(async () => {- await new Promise((resolve) => setTimeout(resolve, FLIP_SETTLE_MS + 100));- });- unfileCard(note, card);- await redraw(note, container);- fileCard(note, card);- await redraw(note, container);+ fileCard(note, made);+ await redraw(note, container);- expect(drawn(container, card.noteId).style.height).toBe("");- } finally {- dropBoxes();- }+ expect(column.querySelector(".board-new-item.inserting")).toBeNull();+ // Faded in where the field stood, and not opened out of nothing.+ const card = drawn(container, made.noteId);+ expect(card.classList.contains("appearing")).toBe(true);+ expect(card.style.height).toBe("");});/**- * The write answers with the card's id, and the refresh that draws the card can land first, so- * the column draws it before it knows what it made. That arrival counts all the same, or the- * card is the one the column would open out when it comes back.+ * Names a card in the field a press of Enter opens below the given one, which is what makes it.+ *+ * Answers with the field, which is taken down as the card is made.*/- it("leaves a card drawn before the write answered alone when it comes back", async () => {- const { note, container } = await setup();- withBoxes();-- try {- const card = buildNote({ title: "Early", "#status": "Doing" });- let answer: (noteId: string) => void = () => {};- vi.spyOn(BoardApi.prototype, "createNewItem")- .mockReturnValue(new Promise((resolve) => { answer = resolve; }));-- 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 = "Early";- await act(async () => {- editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));- await flush();- });+ async function nameCardBeside(card: HTMLElement, title: string) {+ await act(async () => {+ card.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await flush();+ });- // Drawn while the write is still in flight, and only then answered.- fileCard(note, card);- await redraw(note, container);- await act(async () => {- answer(card.noteId);- await flush();- });+ const field = card.parentElement+ ?.querySelector<HTMLTextAreaElement>(".board-new-item.inserting textarea");+ if (!field) throw new Error("expected the field for a new card to be open");- await act(async () => {- await new Promise((resolve) => setTimeout(resolve, FLIP_SETTLE_MS + 100));- });- unfileCard(note, card);- await redraw(note, container);- fileCard(note, card);- await redraw(note, container);+ field.value = title;+ await act(async () => {+ field.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await flush();+ });- expect(drawn(container, card.noteId).style.height).toBe("");- } finally {- dropBoxes();- }- });+ return field;+ }/** The element standing for a note, which a move draws afresh. */function drawn(container: HTMLElement, noteId: string) {@@ -1793,10 +1728,10 @@ describe("Board column rename", () => {/*** A card that arrives from somewhere else, a move between columns above all, mounts as a new- * element in the column that draws it. Only the card the column itself made opens out of- * nothing; the rest are already where they were put.+ * element in the column that draws it. Only a card the column itself made is shown: the rest+ * are already where they were put.*/- it("opens out only the card the column made, not one that merely arrived", async () => {+ it("shows only the card the column made, not one that merely arrived", async () => {const { note, container } = await setup();withBoxes();@@ -1807,6 +1742,7 @@ describe("Board column rename", () => {const arrived = [ ...container.querySelectorAll<HTMLElement>(".board-note") ].find(card => card.textContent?.includes("Added"));if (!arrived) throw new Error("expected the card that arrived to be drawn");+ expect(arrived.classList.contains("appearing")).toBe(false);expect(arrived.style.height).toBe("");expect(arrived.style.overflow).toBe("");} finally {@@ -1885,13 +1821,9 @@ describe("Board column rename", () => {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);+ vi.spyOn(BoardApi.prototype, "createNewItemBefore").mockResolvedValue(noteId);- await act(async () => {- last.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));- await flush();- });+ await nameCardBeside(last, "Typed");expect(middle.classList.contains("appearing")).toBe(true);expect(scrolled).toHaveBeenCalled();@@ -1899,23 +1831,50 @@ describe("Board column rename", () => {});/**- * 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.+ * The same field wherever it stands, so a card inserted between two others is named, iconed and+ * made from a template the way a card added below the column is.*/- it("leaves an inserted card focused, and a card added in the footer unfocused", async () => {+ it("inserts with the field the column's own footer uses", 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");+ if (!card) 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();});+ const field = column.querySelector<HTMLElement>(".board-new-item.inserting");+ expect(field?.querySelector(".title-editor-icon button")).toBeTruthy();+ expect(field?.querySelector(".card-template-pill button")?.textContent).toContain("Text");+ expect(field?.querySelector("textarea")?.placeholder).toBeTruthy();++ // Escape takes it down again, having made nothing.+ const editor = field?.querySelector<HTMLTextAreaElement>("textarea");+ await act(async () => {+ editor?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ await flush();+ });+ expect(column.querySelector(".board-new-item.inserting")).toBeNull();+ });++ /**+ * The field a card is named in among the others stands for the card being made, so it is taken+ * down as the card lands and the card is left focused: the arrow keys carry on from there.+ */+ it("leaves the card it made 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");++ // The stand-in for the card just made, which is what the board draws and focuses.+ vi.spyOn(BoardApi.prototype, "createNewItemBefore").mockResolvedValue(noteId);+ await nameCardBeside(card, "Typed");++ expect(column.querySelector(".board-new-item.inserting")).toBeNull();expect(document.activeElement).toBe(card);// The footer's own editor keeps focus instead, so a run of cards can be typed into it.@@ -2714,7 +2673,8 @@ describe("Board column rename", () => {await flush();});expect(chosen).toHaveBeenCalled();- expect(added).toHaveBeenCalledWith("Doing", "existing");+ // No place given: the field below a column adds the note at the end of it.+ expect(added).toHaveBeenCalledWith("Doing", "existing", undefined);await type(editor, "Typed");expect(button()?.className).toContain("bx-plus-circle");diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 3d2a4fe51e..1cd0470254 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -962,8 +962,8 @@ function AddNewColumn({export function TitleEditor({currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true,- saveAndContinue = false, returnFocusTo, abandon, whenEmpty, submitTitle, openPlacements, icon,- footer+ saveAndContinue = false, handsOver = false, returnFocusTo, abandon, whenEmpty, submitTitle,+ openPlacements, icon, footer}: {currentValue?: string;placeholder?: string;@@ -978,6 +978,13 @@ export function TitleEditor({* away from often enough that saving on the way out would create cards nobody asked for.*/saveAndContinue?: boolean;+ /**+ * Whether the field keeps what was typed once it has saved, and saves only once.+ *+ * For an editor the caller takes down as what it made takes its place: emptied instead, the+ * field would stand where the new thing is about to be drawn without holding what it says.+ */+ handsOver?: boolean;/** Reports what was typed and not saved, so reopening the editor can restore it. */abandon?: (typed: string) => void;/**@@ -1043,6 +1050,8 @@ export function TitleEditor({inputRef.current?.focus();}}), []);+ /** Whether the field has already saved, for one that keeps what it saved standing. */+ const hasHandedOver = useRef(false);const held = useRef<number>();/** Where on the screen the finger went down, against which a scroll is told from a hold. */const heldFrom = useRef<{ x: number, y: number }>();@@ -1117,8 +1126,20 @@ export function TitleEditor({function submit(atStart?: boolean, typed?: string) {const input = inputRef.current;const value = typed ?? input?.value ?? "";+if (value.trim()) {+ if (hasHandedOver.current) {+ return;+ }+commit(value, atStart);++ if (handsOver) {+ hasHandedOver.current = true;+ input?.focus();+ return;+ }+if (input) {input.value = "";}