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 support for multi-selection
Adorian Doran3f24ff288d64
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 771a9e25cc..b938e2d96f 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -2179,3 +2179,116 @@ describe("moving a card into or inside a sorted column", () => {expect(api.isColumnSorted("To Do")).toBe(false);});});++describe("a selection of cards", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.spyOn(server, "put").mockResolvedValue(undefined);+ vi.mocked(branches.moveBeforeBranch).mockClear();+ vi.mocked(branches.moveAfterBranch).mockClear();+ });++ /** A board of four cards, three under "Done" and one under "To Do". */+ function createBoard(sorts?: BoardViewData) {+ const board = buildNote({+ title: "Board",+ children: [+ { title: "First", "#status": "Done" },+ { title: "Second", "#status": "Done" },+ { title: "Third", "#status": "Done" },+ { title: "Spare", "#status": "To Do" }+ ]+ });++ const items = board.getChildBranches().flatMap(branch => {+ const note = froca.getNoteFromCache(branch.noteId);+ return note ? [ { branch, note } ] : [];+ });+ const byColumn: ColumnMap = new Map([+ [ "To Do", [ items[3] ] ],+ [ "Done", items.slice(0, 3) ]+ ]);++ return {+ ...createApi(sorts ?? {}, [ "To Do", "Done" ], board, "status", byColumn),+ items+ };+ }++ const ids = (items: ColumnItem[]) => items.map((item) => item.note.noteId);+ const branchIds = (items: ColumnItem[]) => items.map((item) => item.branch.branchId);++ it("names the cards a column draws, in the order it draws them", () => {+ const { api, items } = createBoard();++ expect(api.getColumnNoteIds("Done")).toEqual(ids(items.slice(0, 3)));+ expect(api.getColumnNoteIds("Nowhere")).toEqual([]);+ });++ it("says which column a card stands in, and nothing for one it is not drawing", () => {+ const { api, items } = createBoard();++ expect(api.getCardColumn(items[0].note.noteId)).toBe("Done");+ expect(api.getCardColumn(items[3].note.noteId)).toBe("To Do");+ expect(api.getCardColumn("elsewhere")).toBeUndefined();+ });++ /**+ * A selection kept from before a refresh can name a card the board has stopped drawing, which+ * is left out rather than making a command act on something that is no longer there.+ */+ it("resolves a selection in board order, leaving out what it no longer holds", () => {+ const { api, items } = createBoard();+ const asked = new Set([ items[2].note.noteId, items[3].note.noteId, "gone" ]);++ expect(ids(api.getCards(asked))).toEqual([ items[3].note.noteId, items[2].note.noteId ]);+ });++ it("files every card under the column and places them before the card dropped on", async () => {+ const { api, items } = createBoard();+ const moved = [ items[3], items[0] ];++ await api.moveManyWithinBoard(+ moved.map((item) => ({ noteId: item.note.noteId, branchId: item.branch.branchId })),+ "Done", 2);++ // Each card's grouping value is written, then one placement carries the whole set.+ expect(server.put).toHaveBeenCalledWith(+ `notes/${items[3].note.noteId}/set-attribute`,+ { type: "label", name: "status", value: "Done", isInheritable: false }, undefined);+ // Counted among the cards as drawn: `First` is moving and stands above the place, so the+ // set lands before `Third` rather than before `Second`.+ expect(branches.moveBeforeBranch)+ .toHaveBeenCalledWith(branchIds(moved), items[2].branch.branchId);+ });++ it("places a set dropped past the last card after the one staying at the end", async () => {+ const { api, items } = createBoard();+ const moved = [ items[3] ];++ await api.moveManyWithinBoard(+ moved.map((item) => ({ noteId: item.note.noteId, branchId: item.branch.branchId })),+ "Done", 3);++ expect(branches.moveBeforeBranch).not.toHaveBeenCalled();+ expect(branches.moveAfterBranch)+ .toHaveBeenCalledWith(branchIds(moved), items[2].branch.branchId);+ });++ /** A sorted column decides where its own cards go, so nothing is written against one. */+ it("writes no placement into a column that sorts itself", async () => {+ const { api, items } = createBoard(+ { columns: [ { value: "Done", orderBy: "title" } ] });+ const moved = [ items[3] ];++ await api.moveManyWithinBoard(+ moved.map((item) => ({ noteId: item.note.noteId, branchId: item.branch.branchId })),+ "Done", 0);++ expect(server.put).toHaveBeenCalledWith(+ `notes/${items[3].note.noteId}/set-attribute`,+ { type: "label", name: "status", value: "Done", isInheritable: false }, undefined);+ expect(branches.moveBeforeBranch).not.toHaveBeenCalled();+ expect(branches.moveAfterBranch).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 81c09fc3ea..c7f3bf51e7 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -28,7 +28,7 @@ import {DEFAULT_GROUP_BY, INBOX_COLUMN, INBOX_COLUMN_ICON} from "./columns";import { readColumns, writeColumns } from "./column_storage";-import { ColumnMap } from "./data";+import { ColumnItem, ColumnMap } from "./data";import { SORT_DESCENDING_LABEL, SORT_LABEL } from "./sort";/** Which end of a column a new card is made at. */@@ -1302,6 +1302,87 @@ export default class BoardApi {this.sentToColumnEnd.set(targetColumn, branchId);}+ /**+ * The notes a column draws, in the order it draws them.+ *+ * What a range selection is measured against, so a range covers only the cards the reader can+ * see and never reaches into another column.+ */+ getColumnNoteIds(column: string) {+ return (this.byColumn?.get(column) ?? []).map((item) => item.note.noteId);+ }++ /**+ * The cards named by `noteIds`, in the order the board draws them.+ *+ * A note the board is not drawing is left out, so a selection that has fallen behind a refresh+ * cannot make a command act on a card that is no longer there.+ */+ getCards(noteIds: ReadonlySet<string>) {+ const cards: ColumnItem[] = [];+ for (const items of this.byColumn?.values() ?? []) {+ for (const item of items) {+ if (noteIds.has(item.note.noteId)) {+ cards.push(item);+ }+ }+ }++ return cards;+ }++ /** Which column a card stands in, or nothing where the board is not drawing the card. */+ getCardColumn(noteId: string) {+ for (const [ column, items ] of this.byColumn ?? []) {+ if (items.some((item) => item.note.noteId === noteId)) {+ return column;+ }+ }++ return undefined;+ }++ /**+ * Moves several cards into a column at one place, keeping the order they were drawn in.+ *+ * The grouping value is written for each card, then the branches are placed in one call:+ * `moveBeforeBranch` and `moveAfterBranch` both take the whole set and keep its order, so the+ * cards land together rather than each being placed against the one before it.+ */+ async moveManyWithinBoard(+ cards: { noteId: string, branchId: string }[], targetColumn: string, targetIndex: number+ ) {+ // Read before the writes below: a redraw between them hands this instance the map with the+ // cards already moved.+ const targetItems = this.byColumn?.get(targetColumn) ?? [];+ const moved = new Set(cards.map((card) => card.branchId));+ // The place is counted among the cards as they are drawn, which includes the ones being+ // moved. Each of those standing above it names one place that is about to close up.+ const above = targetItems.slice(0, targetIndex)+ .filter((item) => moved.has(item.branch.branchId)).length;+ const staying = targetItems.filter((item) => !moved.has(item.branch.branchId));+ const before = staying[targetIndex - above];++ for (const card of cards) {+ await this.changeColumn(card.noteId, targetColumn);+ }++ // A sorted column places its own cards, so nothing is written against a card there.+ if (this.isColumnSorted(targetColumn)) {+ return;+ }++ const branchIds = cards.map((card) => card.branchId);+ if (before) {+ await branches.moveBeforeBranch(branchIds, before.branch.branchId);+ } else {+ const last = staying.at(-1);+ if (last) {+ await branches.moveAfterBranch(branchIds, last.branch.branchId);+ }+ }+ }+/** Whether a card stands at the head of its column, with nowhere left to be moved up to. */isFirstInColumn(branchId: string, column: string) {return this.byColumn?.get(column)?.[0]?.branch.branchId === branchId;diff --git a/apps/client/src/widgets/collections/board/board_drag.spec.tsx b/apps/client/src/widgets/collections/board/board_drag.spec.tsxindex 9b9c63c1a6..0bbd67dd8f 100644--- a/apps/client/src/widgets/collections/board/board_drag.spec.tsx+++ b/apps/client/src/widgets/collections/board/board_drag.spec.tsx@@ -3,13 +3,15 @@ import { useRef } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { type BoardDragCallbacks, type DropPosition, useBoardDrag } from "./board_drag";+import {+ type BoardDragCallbacks, type DraggedCard, type DropPosition, useBoardDrag+} from "./board_drag";describe("useBoardDrag, carrying a card", () => {let container: HTMLElement | undefined;let board: HTMLElement;let calls: {- start: unknown[],+ start: DraggedCard[],move: { position: unknown | null, inside: boolean }[],end: { card: unknown, position: unknown }[],columnStart: { column: string, index: number, size: unknown }[],@@ -45,7 +47,23 @@ describe("useBoardDrag, carrying a card", () => {move(70, 60);expect(calls.start)- .toEqual([ { noteId: "n1", fromColumn: "To Do", index: 0, height: 50 } ]);+ .toEqual([+ { noteId: "n1", noteIds: [ "n1" ], fromColumn: "To Do", index: 0, height: 50 }+ ]);+ });++ it("carries a selection as one card naming how many are on the move", () => {+ setup({ carried: [ "n1", "n2", "n3" ] });++ press(card("n1"), 50, 60);+ move(90, 90);++ expect(calls.start[0]?.noteIds).toEqual([ "n1", "n2", "n3" ]);+ // A blank card holding the count, rather than a copy of the one under the pointer.+ const copy = preview();+ expect(copy?.classList.contains("board-drag-count")).toBe(true);+ expect(copy?.textContent).toBe("3");+ expect(copy?.querySelector(".title")).toBeNull();});it("carries a copy under the pointer without redrawing the board", () => {@@ -255,7 +273,7 @@ describe("useBoardDrag, carrying a card", () => {release(320, 200);expect(calls.end).toEqual([ {- card: { noteId: "n1", fromColumn: "To Do", index: 0, height: 50 },+ card: { noteId: "n1", noteIds: [ "n1" ], fromColumn: "To Do", index: 0, height: 50 },position: { column: "Doing", index: 1 }} ]);});@@ -458,7 +476,7 @@ describe("useBoardDrag, carrying a card", () => {});expect(calls.end).toEqual([ {- card: { noteId: "n1", fromColumn: "To Do", index: 0, height: 50 },+ card: { noteId: "n1", noteIds: [ "n1" ], fromColumn: "To Do", index: 0, height: 50 },position: null} ]);expect(element.style.transform).toBe("");@@ -593,12 +611,17 @@ describe("useBoardDrag, carrying a card", () => {* Two 100px columns, 200 apart, each card 50 tall. The first holds two cards, the second one.* happy-dom lays nothing out, so every box is declared.*/- function setup({ disabled = false } = {}) {+ function setup({ disabled = false, carried }: {+ disabled?: boolean,+ /** The cards a press answers with, for the tests about carrying a selection. */+ carried?: string[]+ } = {}) {const mountPoint = document.createElement("div");container = mountPoint;document.body.appendChild(mountPoint);const callbacks: BoardDragCallbacks = {+ carriedWith: (noteId) => carried ?? [ noteId ],onCardStart: (card) => calls.start.push(card),onCardMove: (position, inside) => calls.move.push({ position, inside }),onCardEnd: (card, position) => calls.end.push({ card, position }),diff --git a/apps/client/src/widgets/collections/board/board_drag.ts b/apps/client/src/widgets/collections/board/board_drag.tsindex 25bc5bb081..09b625e506 100644--- a/apps/client/src/widgets/collections/board/board_drag.ts+++ b/apps/client/src/widgets/collections/board/board_drag.ts@@ -32,6 +32,11 @@ const COMPATIBILITY_WINDOW_MS = 700;/** Which card is being carried, named the way the board's own moves are. */export interface DraggedCard {noteId: string;+ /**+ * Every card on the move, in the order the board draws them, this one among them. Holds one+ * entry unless the card was taken hold of as part of a selection.+ */+ noteIds: string[];fromColumn: string;index: number;/** How tall it stands, so the gap held open for it is the size it will fill. */@@ -45,6 +50,13 @@ export interface DropPosition {}export interface BoardDragCallbacks {+ /**+ * Which cards travel with the one being pressed, in the order the board draws them.+ *+ * Asked as the press lands rather than when the drag opens, so the answer is the selection as+ * it stood when the reader took hold. Answers with the card alone where it is not selected.+ */+ carriedWith(noteId: string): string[];/** A card has been taken hold of, and is now being carried. */onCardStart(card: DraggedCard): void;/**@@ -269,7 +281,8 @@ export function useBoardDrag(// Anything the card or the heading offers in its own right keeps its press.if (!target || target.closest("input, textarea, button, a")) return;- const started = startCard(target) ?? startColumn(target, container);+ const started = startCard(target, latest.current.carriedWith)+ ?? startColumn(target, container);if (!started) return;gesture.current = {@@ -505,7 +518,9 @@ function askForMenu(element: HTMLElement, clientX: number, clientY: number) {}/** What a press on a card starts, or nothing where the press was not on one. */-function startCard(target: HTMLElement): CardSubject | null {+function startCard(+ target: HTMLElement, carriedWith: (noteId: string) => string[]+): CardSubject | null {const element = target.closest<HTMLElement>(".board-note");const columnElement = element?.closest<HTMLElement>(".board-column");const noteId = element?.dataset.noteId;@@ -518,6 +533,7 @@ function startCard(target: HTMLElement): CardSubject | null {menuTarget: element,card: {noteId,+ noteIds: carriedWith(noteId),fromColumn: columnElement.dataset.column ?? "",index: cards.indexOf(element),height: element.getBoundingClientRect().height@@ -558,7 +574,13 @@ function startColumn(target: HTMLElement, container: HTMLElement): ColumnSubject*/function lift(held: Gesture, container: HTMLElement) {const rect = held.element.getBoundingClientRect();- const preview = held.element.cloneNode(true) as HTMLElement;+ // A selection is carried as one blank card saying how many are on the move. The cards+ // themselves stay where they are drawn, and a stack of copies would hide the board they are+ // being placed on without saying any more than the count does.+ const carried = held.kind === "card" ? held.card.noteIds.length : 1;+ const preview = carried > 1+ ? countPreview(carried)+ : held.element.cloneNode(true) as HTMLElement;preview.classList.add("board-drag-preview");preview.removeAttribute("data-note-id");@@ -605,6 +627,14 @@ function lift(held: Gesture, container: HTMLElement) {};}+/** A card-shaped copy standing for the cards being carried, with their number in the middle. */+function countPreview(count: number) {+ const preview = document.createElement("div");+ preview.className = "board-note board-drag-count";+ preview.textContent = String(count);+ return preview;+}+interface CardSubject {kind: "card";element: HTMLElement;diff --git a/apps/client/src/widgets/collections/board/card.spec.tsx b/apps/client/src/widgets/collections/board/card.spec.tsxindex e456ed3df1..965c6632e5 100644--- a/apps/client/src/widgets/collections/board/card.spec.tsx+++ b/apps/client/src/widgets/collections/board/card.spec.tsx@@ -256,6 +256,108 @@ describe("Board card", () => {expect(openInPopup).not.toHaveBeenCalled();});+ describe("picking several cards out", () => {+ it("marks a card on Ctrl and click, and lets go of it on the next one", async () => {+ const { first, second } = await renderBoard();+ const openInPopup = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);++ await click(first, { ctrlKey: true });+ expect(cardClasses(first)).toContain("selected");+ expect(cardClasses(second)).not.toContain("selected");+ // Picking a card out is not opening it.+ expect(openInPopup).not.toHaveBeenCalled();++ await click(second, { ctrlKey: true });+ expect(cardClasses(first)).toContain("selected");+ expect(cardClasses(second)).toContain("selected");++ await click(first, { ctrlKey: true });+ expect(cardClasses(first)).not.toContain("selected");+ expect(cardClasses(second)).toContain("selected");+ });++ it("takes everything between the two cards on Shift and click", async () => {+ const { first, second, extra } = await renderBoard([ "To Do", "To Do" ]);++ await click(first, { ctrlKey: true });+ await click(extra[1], { shiftKey: true });++ expect(selectedCards()).toEqual([ "First", "Second", "Extra 1", "Extra 2" ]);+ });++ /**+ * A range is measured against one column, so an anchor left in another is not in the list+ * the press is counted against and the card it landed on is taken on its own.+ */+ it("keeps a range inside one column", async () => {+ const { first, extra } = await renderBoard([ "Done", "Done" ]);++ await click(first, { ctrlKey: true });+ await click(extra[1], { shiftKey: true });++ expect(selectedCards()).toEqual([ "Extra 2" ]);+ });++ it("gives the whole selection up on a plain click, which opens the note", async () => {+ const { first, second } = await renderBoard();+ const openInPopup = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);++ await click(first, { ctrlKey: true });+ await click(second, { ctrlKey: true });+ await click(first, {});++ expect(selectedCards()).toEqual([]);+ expect(openInPopup).toHaveBeenCalledTimes(1);+ });++ it("opens the menu on the whole selection when it is opened from within it", async () => {+ const { first, second } = await renderBoard();+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});++ await click(first, { ctrlKey: true });+ await click(second, { ctrlKey: true });+ await act(async () => {+ card(second).dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));+ });++ // The entries that only make sense for one card are gone.+ expect(menuTitles(show)).not.toContain("board_view.edit-title");+ expect(menuTitles(show)).toContain("board_view.remove-from-board");+ });++ it("acts on a card alone when the menu is opened outside the selection", async () => {+ const { first, second } = await renderBoard();+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});++ await click(first, { ctrlKey: true });+ await act(async () => {+ card(second).dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));+ });++ expect(menuTitles(show)).toContain("board_view.edit-title");+ expect(selectedCards()).toEqual([]);+ });++ /** The titles of the cards picked out, in the order the board draws them. */+ function selectedCards() {+ return [ ...(container?.querySelectorAll(".board-note.selected") ?? []) ]+ .map((element) => element.querySelector(".title")?.textContent);+ }++ function menuTitles(show: { mock: { calls: unknown[][] } }) {+ const items = (show.mock.calls.at(-1)?.[0] as+ { items: { title?: string }[] } | undefined)?.items ?? [];+ return items.map((item) => item.title);+ }++ async function click(noteId: string, modifiers: MouseEventInit) {+ await act(async () => {+ card(noteId).dispatchEvent(new MouseEvent(+ "click", { bubbles: true, cancelable: true, detail: 1, ...modifiers }));+ });+ }+ });+it("offers the card menu on a right click", async () => {const { first } = await renderBoard();const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});@@ -284,16 +386,25 @@ describe("Board card", () => {}/** Renders a board of two cards and hands back the component their subscriptions register on. */- async function renderBoard() {+ /**+ * Draws a board of two cards under "To Do".+ *+ * @param extra the cards to add beyond those two, each named by the column it stands in. Only+ * the tests about picking several cards out need them.+ */+ async function renderBoard(extra: string[] = []) {const first = `card${idSeed++}`;const second = `card${idSeed++}`;+ const rest = extra.map((status, at) => (+ { id: `card${idSeed++}`, title: `Extra ${at + 1}`, "#status": status }));const note = buildNote({title: "Board","#collection": "","#viewType": "board",children: [{ id: first, title: "First", "#status": "To Do" },- { id: second, title: "Second", "#status": "To Do" }+ { id: second, title: "Second", "#status": "To Do" },+ ...rest]});@@ -308,7 +419,7 @@ describe("Board card", () => {<BoardViewnote={note}notePath={`root/${note.noteId}`}- noteIds={[ first, second ]}+ noteIds={[ first, second, ...rest.map((card) => card.id) ]}highlightedTokens={null}viewConfig={{ columns: [ { value: "To Do" } ] }}saveConfig={() => {}}@@ -321,7 +432,7 @@ describe("Board card", () => {});await settle();- return { note, component, first, second };+ return { note, component, first, second, extra: rest.map((card) => card.id) };}/** Moves a card to another column the way an edit made anywhere else reaches the board. */diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsxindex 8326f0d08c..9b217b2357 100644--- a/apps/client/src/widgets/collections/board/card.tsx+++ b/apps/client/src/widgets/collections/board/card.tsx@@ -1,3 +1,4 @@+import clsx from "clsx";import { memo } from "preact/compat";import {useCallback, useContext, useEffect, useLayoutEffect, useRef, useState@@ -22,6 +23,7 @@ import {} from "../../react/hooks";import { TooltipIcon } from "../../react/Icon";import { HighlightedText } from "../../react/RawHtml";+import { useIsSelected, useSelection } from "../../react/selection";function Card({api,@@ -84,6 +86,11 @@ function Card({const [ title, setTitle ] = useState(note.title);// Tracks the `iconClass` label, which an attribute change carries and the note row never does.const icon = useNoteIcon(note);+ // Read from the store rather than through the board's state, so picking one card redraws that+ // card and no other. The store keeps one identity for the life of the board, so holding it+ // here leaves the memo below intact.+ const selection = useSelection();+ const isSelected = useIsSelected(note.noteId);// A card owns its own title: the board does not redraw for a note-row change. Setting the value// already held is a no-op, so a save that left the title alone re-renders nothing.@@ -95,17 +102,36 @@ function Card({});const handleContextMenu = useCallback((e: ContextMenuEvent) => {- openNoteContextMenu(- api, e, note, branch.branchId, column, index, onFocusCard, onInsert, onNewItem);- }, [ api, note, branch, column, index, onFocusCard, onInsert, onNewItem ]);+ // A card outside the selection is acted on alone, and the selection it was not part of is+ // dropped, so the menu never writes to cards the reader has stopped looking at.+ if (!selection.has(note.noteId)) {+ selection.clear();+ }++ const cards = api.getCards(selection.keys);+ openNoteContextMenu(api, e, {+ note,+ branchId: branch.branchId,+ column,+ index,+ notes: cards.length ? cards.map((card) => card.note) : [ note ],+ branchIds: cards.length+ ? cards.map((card) => card.branch.branchId)+ : [ branch.branchId ],+ onFocusCard,+ onInsert,+ onNewItem+ });+ }, [ api, note, branch, column, index, selection, onFocusCard, onInsert, onNewItem ]);- const handleOpen = useCallback((e: MouseEvent) => {+ const handleClick = useCallback((e: MouseEvent) => {// A double click is one gesture, and its second click would open the note over itself: the// popup already standing is taken as the one to stack on, and closing that leaves neither.if (e.detail > 1) return;// A link to a note, such as a relation's target, opens in the popup. Cancelled here so that// `goToLink` does not open a tab for it as well; a link naming no note is left alone.+ // Checked before the modifiers below, so Ctrl on a link still means what it means anywhere.const link = (e.target as HTMLElement | null)?.closest<HTMLAnchorElement>("a[href]");if (link) {const { notePath } = parseNavigationStateFromUrl(link.getAttribute("href") ?? undefined);@@ -119,8 +145,23 @@ function Card({return;}+ // Ctrl picks this card out on its own, keeping whatever else is picked. Neither modifier+ // opens the note.+ if (e.ctrlKey || e.metaKey) {+ selection.toggle(note.noteId);+ return;+ }++ // Shift takes everything between the card the selection started from and this one. Only+ // this column is offered, so a range never reaches into another.+ if (e.shiftKey) {+ selection.selectRange(api.getColumnNoteIds(column), note.noteId);+ return;+ }++ selection.clear();api.openNote(note.noteId);- }, [ api, note ]);+ }, [ api, note, column, selection ]);const handleEdit = useCallback((e: MouseEvent) => {e.stopPropagation(); // don't also open the note@@ -189,7 +230,13 @@ function Card({return (<divref={cardRef}- className={`board-note ${colorClass} ${isDragging ? 'dragging' : ''} ${isEditing ? "editing" : ""} ${isArchived ? "archived" : ""} ${isNew && !isRevealed ? "appearing" : ""}`}+ className={clsx("board-note", colorClass, {+ dragging: isDragging,+ editing: isEditing,+ archived: isArchived,+ selected: isSelected,+ appearing: isNew && !isRevealed+ })}onAnimationEnd={(e) => {if (e.animationName === "board-item-appear") {setIsRevealed(true);@@ -197,7 +244,7 @@ function Card({}}data-note-id={note.noteId}onContextMenu={handleContextMenu}- onClick={!isEditing ? handleOpen : undefined}+ onClick={!isEditing ? handleClick : undefined}onKeyDown={handleKeyDown}tabIndex={300}>diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex a04501180a..89e589e7d8 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -190,6 +190,11 @@ export default function Column({useContext(BoardActionsContext);const { branchIdToEdit, columnNameToEdit, draggedCard, draggedColumn } =useContext(BoardDragStateContext);+ // Every card on the move. The one under the pointer is taken out of the flow by the gesture+ // itself; the rest of a carried selection stay where they are drawn and are dimmed instead.+ const carriedNoteIds = draggedCard+ ? new Set(draggedCard.noteIds ?? [ draggedCard.noteId ])+ : null;// Asked about this column alone: where the gap stands changes on every step of a drag, and a// column that the answer does not concern is left as it is rather than drawn again.const standingDropIndex = useDropIndex(column);@@ -672,7 +677,7 @@ export default function Column({isNew={note.noteId === createdNoteId|| note.noteId === landedNoteId}focusOnArrival={note.noteId === insertedNoteId}- isDragging={draggedCard?.noteId === note.noteId}+ isDragging={!!carriedNoteIds?.has(note.noteId)}isEditing={branch.branchId === branchIdToEdit}onFocusCard={onFocusCard}onInsert={beginInsert}diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.tsindex e8c51c3206..d25977ef81 100644--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts@@ -726,10 +726,15 @@ describe("Board item context menu", () => {return `<span class="tn-menu-name">${name}</span>`;}- /** Opens the menu a card offers, and hands back what it was given to show. */+ /**+ * Opens the menu a card offers, and hands back what it was given to show.+ *+ * @param notes the selection the menu writes to, the card the menu was opened on standing+ * first. One note unless a test is about what a selection changes.+ */function openItemMenu(api: BoardApi, column = "To Do", focusCard = vi.fn(), insert = vi.fn(), index = 2,- newItem = vi.fn()) {+ newItem = vi.fn(), notes?: FNote[]) {const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});const event = {preventDefault: () => {},@@ -747,12 +752,22 @@ describe("Board item context menu", () => {getColumnTitle: (name: string) => name,getPromotedAttributes: () => [],isFirstInColumn: () => false,- isColumnSorted: () => false+ isColumnSorted: () => false,+ getCardColumn: () => column},api);- openNoteContextMenu(- withDefaults, event, buildNote({ title: "Card" }) as FNote, "branchId", column, index,- focusCard, insert, newItem);+ const selected = notes ?? [ buildNote({ title: "Card" }) as FNote ];+ openNoteContextMenu(withDefaults, event, {+ note: selected[0],+ branchId: "branchId",+ column,+ index,+ notes: selected,+ branchIds: selected.map((_, at) => `branchId${at || ""}`),+ onFocusCard: focusCard,+ onInsert: insert,+ onNewItem: newItem+ });return show.mock.calls.at(-1)?.[0].items ?? [];}@@ -916,6 +931,110 @@ describe("Board item context menu", () => {.map(item => !!(item && "badges" in item && item.badges?.length))).toEqual([ false, true ]);});++ describe("opened on a selection", () => {+ const columnApi = {+ columns: [ "To Do", "Done" ],+ isColumnArchived: () => false,+ getColumnIcon: () => DEFAULT_COLUMN_ICON,+ getColumnColorClass: () => ""+ } as unknown as BoardApi;++ it("leaves out the entries about one card, and leads with the columns", () => {+ const items = openSelectionMenu(columnApi, [+ buildNote({ title: "One" }), buildNote({ title: "Two" })+ ]);++ // No entries of its own above them, and no divider left standing where they were.+ expect(items[0]).toEqual({ kind: "header", title: "Status" });+ expect(titlesOf(items)).not.toContain("board_view.edit-title");+ expect(titlesOf(items)).not.toContain("board_view.duplicate-item");+ expect(titlesOf(items)).not.toContain("board_view.insert-above");+ });++ it("ticks a column only while every card stands in it", () => {+ const notes = [ buildNote({ title: "One" }), buildNote({ title: "Two" }) ];+ const together = {+ ...columnApi, getCardColumn: () => "Done"+ } as unknown as BoardApi;+ const apart = {+ ...columnApi,+ getCardColumn: (noteId: string) => noteId === notes[0].noteId ? "To Do" : "Done"+ } as unknown as BoardApi;++ expect(marksOf(openSelectionMenu(together, notes)))+ .toEqual([ undefined, "bx bx-check" ]);+ expect(marksOf(openSelectionMenu(apart, notes))).toEqual([ undefined, undefined ]);+ });++ it("files every card under the column picked", async () => {+ const changeColumn = vi.fn();+ const notes = [ buildNote({ title: "One" }), buildNote({ title: "Two" }) ];+ const api = { ...columnApi, changeColumn } as unknown as BoardApi;++ const entry = openSelectionMenu(api, notes)+ .find(item => item && "title" in item && item.title === boxed("Done"));+ if (!entry || !("handler" in entry)) throw new Error("expected the Done entry");+ await entry.handler?.(entry, {} as never);++ expect(changeColumn).toHaveBeenCalledWith(notes[0].noteId, "Done");+ expect(changeColumn).toHaveBeenCalledWith(notes[1].noteId, "Done");+ });++ it("deletes every branch the selection names in one call", () => {+ const deleteNotes = vi.spyOn(branches, "deleteNotes").mockResolvedValue(false);+ const notes = [ buildNote({ title: "One" }), buildNote({ title: "Two" }) ];++ const entry = openSelectionMenu(columnApi, notes)+ .find(item => item && "uiIcon" in item && item.uiIcon === "bx bx-trash");+ if (!entry || !("handler" in entry)) throw new Error("expected the delete entry");+ entry.handler?.(entry, {} as never);++ expect(deleteNotes).toHaveBeenCalledWith([ "branchId", "branchId1" ], false, false);+ });++ /**+ * One entry cannot say what picking it would do while the cards are in different states,+ * and both entries at once would read as two states the same cards are in.+ */+ it("offers archiving only while the cards agree on what they are", () => {+ const plain = buildNote({ title: "One" });+ const archived = buildNote({ title: "Two", "#archived": "" });++ expect(titlesOf(openSelectionMenu(columnApi, [ plain, plain ])))+ .toContain("board_view.archive-note");+ expect(titlesOf(openSelectionMenu(columnApi, [ archived, archived ])))+ .toContain("board_view.unarchive-note");++ const mixed = titlesOf(openSelectionMenu(columnApi, [ plain, archived ]));+ expect(mixed).not.toContain("board_view.archive-note");+ expect(mixed).not.toContain("board_view.unarchive-note");+ });++ /** The menu a selection opens, which is the card menu given more than one note. */+ function openSelectionMenu(api: BoardApi, notes: FNote[]) {+ return openItemMenu(api, "To Do", vi.fn(), vi.fn(), 2, vi.fn(), notes);+ }++ /** The column entries alone, which stand between the Status header and the separator. */+ function columnEntries(items: MenuItem<unknown>[]) {+ const header = items.findIndex(item =>+ item && "kind" in item && item.kind === "header" && item.title === "Status");+ const rest = items.slice(header + 1);+ const end = rest.findIndex(item => item && "kind" in item && item.kind === "separator");+ return rest.slice(0, end < 0 ? rest.length : end);+ }++ function marksOf(items: MenuItem<unknown>[]) {+ return columnEntries(items)+ .map(item => item && "trailingIcon" in item ? item.trailingIcon : undefined);+ }++ function titlesOf(items: MenuItem<unknown>[]) {+ return items.flatMap(item =>+ item && "title" in item && item.title ? [ item.title ] : []);+ }+ });});describe("Board context menu", () => {diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.tsindex db62ef7bb3..3effd30c06 100644--- a/apps/client/src/widgets/collections/board/context_menu.ts+++ b/apps/client/src/widgets/collections/board/context_menu.ts@@ -1,14 +1,16 @@import { useState } from "preact/hooks";-import FNote from "../../../entities/fnote";-import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker";import type { CommandNames } from "../../../components/app_context";+import FNote from "../../../entities/fnote";import contextMenu, { ContextMenuEvent, MenuItem } from "../../../menus/context_menu";+import { getArchiveMenuItems, menuName } from "../../../menus/context_menu_utils";+import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker";import link_context_menu from "../../../menus/link_context_menu";+import attributes from "../../../services/attributes";import branches from "../../../services/branches";import dialog from "../../../services/dialog";-import { getArchiveMenuItem, menuName } from "../../../menus/context_menu_utils";import { t } from "../../../services/i18n";+import { shared } from "../../../services/note_set";import ColorPicker from "../../react/ColorPicker";import { buildAttributeMenuItems } from "../attribute_menu";import { buildSortMenuItems, type SortMenuOptions } from "../sort_menu";@@ -401,33 +403,61 @@ function ColumnColorPicker({ api, value, color }: { api: Api, value: string, col});}+/** What a card's menu acts on: the card it was opened from, and the notes it writes to. */+export interface NoteMenuTarget {+ /** The card the menu was opened on. */+ note: FNote;+ branchId: string;+ column: string;+ /** This card's index in its column, which an insert is placed against. */+ index: number;+ /**+ * Every note the menu writes to: this card alone, or the whole selection it belongs to. Always+ * holds the card the menu was opened on.+ */+ notes: FNote[];+ /** The branches those notes have on this board, in the order `notes` lists them. */+ branchIds: string[];+ /** Refocuses the card after a column change has redrawn it elsewhere. */+ onFocusCard: (noteId: string) => void;+ /** Opens the new-card editor at an index in the column, above or below this card. */+ onInsert: (index: number) => void;+ /** Opens the editor at the foot of the column, which a sorted column offers instead. */+ onNewItem: () => void;+}+/**- * The columns a card can be moved to, listed in the menu rather than in a submenu, which would put- * every column a step further away. Past `LISTED_COLUMNS`, the rest move into one submenu entry,- * and the card's current column is always listed.+ * The columns the cards can be moved to, listed in the menu rather than in a submenu, which would+ * put every column a step further away. Past `LISTED_COLUMNS`, the rest move into one submenu+ * entry, and the column the cards are in is always listed.*- * An archived column is offered like any other, with a badge, since the card then leaves the+ * An archived column is offered like any other, with a badge, since the cards then leave the* board's default view.*/-function buildColumnItems(- api: Api, note: FNote, column: string, onFocusCard: (noteId: string) => void-): MenuItem<CommandNames>[] {+function buildColumnItems(api: Api, target: NoteMenuTarget): MenuItem<CommandNames>[] {+ // Marked only while every card stands in the same column: one check on a selection spanning+ // several would name one column as the state of all of them.+ const standing = shared(target.notes, (note) => api.getCardColumn(note.noteId));+ const current = standing.agreed ? standing.value : undefined;+const items: MenuItem<CommandNames>[] = api.columns.map((name) => ({title: menuName(api.getColumnTitle(name)),uiIcon: api.getColumnIcon(name),iconColorClass: api.getColumnColorClass(name),- // The one it is already under is shown rather than hidden, so the list reads as the whole- // set of columns and says which of them this card belongs to.- trailingIcon: name === column ? "bx bx-check" : undefined,- className: name === column ? "board-current-column" : undefined,+ // The one they are already under is shown rather than hidden, so the list reads as the+ // whole set of columns and says which of them the cards belong to.+ trailingIcon: name === current ? "bx bx-check" : undefined,+ className: name === current ? "board-current-column" : undefined,badges: api.isColumnArchived(name)? [ { title: t("board_view.archived-badge") } ]: undefined,- handler: () => {- // Asked for before the write: the card is drawn afresh under the column- // it lands in, so the element the menu was opened from will be gone.- onFocusCard(note.noteId);- api.changeColumn(note.noteId, name);+ handler: async () => {+ // Asked for before the write: the cards are drawn afresh under the column they land+ // in, so the element the menu was opened from will be gone.+ target.onFocusCard(target.note.noteId);+ for (const note of target.notes) {+ await api.changeColumn(note.noteId, name);+ }}}));@@ -438,11 +468,11 @@ function buildColumnItems(const listed = items.slice(0, LISTED_COLUMNS);const rest = items.slice(LISTED_COLUMNS);- // The card's own column is listed even where it falls outside: the check beside it is what- // says which column the card is in, and behind an entry it says nothing.- const current = api.columns.indexOf(column);- if (current >= LISTED_COLUMNS) {- listed.push(...rest.splice(current - LISTED_COLUMNS, 1));+ // The cards' own column is listed even where it falls outside: the check beside it is what+ // says which column they are in, and behind an entry it says nothing.+ const at = current === undefined ? -1 : api.columns.indexOf(current);+ if (at >= LISTED_COLUMNS) {+ listed.push(...rest.splice(at - LISTED_COLUMNS, 1));}return [@@ -455,42 +485,37 @@ function buildColumnItems(];}-export function openNoteContextMenu(- api: Api, event: ContextMenuEvent, note: FNote, branchId: string, column: string,- /** This card's index in its column, which an insert is placed against. */- index: number,- /** Refocuses the card after a column change has redrawn it elsewhere. */- onFocusCard: (noteId: string) => void,- /** Opens the new-card editor at an index in the column, above or below this card. */- onInsert: (index: number) => void,- /** Opens the editor at the foot of the column, which a sorted column offers instead. */- onNewItem: () => void-) {+export function openNoteContextMenu(api: Api, event: ContextMenuEvent, target: NoteMenuTarget) {+ const { note, branchId, column, index, notes, branchIds } = target;+event.preventDefault();event.stopPropagation();// A sorted column decides where its cards go, so the entries naming a place are left out.const isSorted = api.isColumnSorted(column);+ // What only makes sense for one card: a place to insert at, a title to edit, a note to open.+ // Everything below writes to every selected note instead.+ const isSingle = notes.length === 1;// What the card is placed beside, and the copy made below it.- const placement: MenuItem<CommandNames>[] = [+ const placement: MenuItem<CommandNames>[] = !isSingle ? [] : [// A sorted column takes its new cards at the foot, where its own button makes them....(isSorted ? [ {title: t("board_view.insert-new"),uiIcon: "bx bx-plus",- handler: onNewItem+ handler: target.onNewItem} ] : [{title: t("board_view.insert-above"),uiIcon: "bx bx-list-plus",shortcut: "Shift+Enter",- handler: () => onInsert(index)+ handler: () => target.onInsert(index)},{title: t("board_view.insert-below"),uiIcon: "bx bx-empty",shortcut: "Enter",- handler: () => onInsert(index + 1)+ handler: () => target.onInsert(index + 1)}]),{@@ -506,54 +531,97 @@ export function openNoteContextMenu(handler: () => {// Asked for before the write: the card is blurred as it is moved in the page, and// the reveal that follows the focus is what shows where it went.- onFocusCard(note.noteId);+ target.onFocusCard(note.noteId);api.moveToColumnStart(note.noteId, branchId, column);}} ])];+ // What is done to the card itself, which a selection has none of: the menu it opens leads with+ // the columns instead.+ const identity: MenuItem<CommandNames>[] = !isSingle ? [] : [+ // Space opens the same popup for the card the cursor stands on.+ { ...link_context_menu.getQuickEditItem(), shortcut: "Space" },+ {+ title: t("board_view.edit-title"),+ uiIcon: "bx bx-rename",+ shortcut: "F2",+ handler: () => api.startEditing(branchId)+ },+ link_context_menu.getOpenNoteItem(event),+ { kind: "separator" }+ ];+contextMenu.show({x: event.pageX,y: event.pageY,items: [- // Space opens the same popup for the card the cursor stands on.- { ...link_context_menu.getQuickEditItem(), shortcut: "Space" },- {- title: t("board_view.edit-title"),- uiIcon: "bx bx-rename",- shortcut: "F2",- handler: () => api.startEditing(branchId)- },- link_context_menu.getOpenNoteItem(event),- { kind: "separator" },+ ...identity,...placement,{ kind: "header", title: api.getStatusLabel() },- ...buildColumnItems(api, note, column, onFocusCard),+ ...buildColumnItems(api, target),...buildAttributeMenuItems<CommandNames>({- note,+ notes,attributes: api.getPromotedAttributes()}),{ kind: "separator" },- getArchiveMenuItem(note),+ ...getArchiveMenuItems<CommandNames>(notes),{title: t("board_view.remove-from-board"),uiIcon: "bx bx-task-x",shortcut: "Delete",- handler: () => api.removeFromBoard(note.noteId)+ handler: async () => {+ for (const selected of notes) {+ await api.removeFromBoard(selected.noteId);+ }+ }},{title: t("board_view.delete-note"),uiIcon: "bx bx-trash",shortcut: "Shift+Delete",- handler: () => branches.deleteNotes([ branchId ], false, false)+ handler: () => branches.deleteNotes(branchIds, false, false)},{ kind: "separator" },{kind: "custom",- componentFn: () => NoteColorPicker({note})+ componentFn: () => isSingle+ ? NoteColorPicker({ note })+ : CardsColorPicker({ notes })}],selectMenuItemHandler: ({ command }) => link_context_menu.handleLinkContextMenuItem(command, event, note.noteId),});}+/**+ * The colour of several cards at once, shown as their colour only while they agree on one.+ *+ * `NoteColorPicker` reads and writes one note, so a selection is painted through the plain picker,+ * as a column's colour is. Keeps the picked value rather than re-reading it: the menu renders once,+ * and a redraw underneath never reaches it.+ */+function CardsColorPicker({ notes }: { notes: FNote[] }) {+ const agreed = shared(notes, (note) => note.getLabelValue("color") ?? null);+ const [ currentColor, setCurrentColor ] = useState(agreed.agreed ? agreed.value : null);++ return ColorPicker({+ className: "note-color-picker",+ currentValue: currentColor,+ onChange: async (picked) => {+ setCurrentColor(picked);+ for (const note of notes) {+ if (picked !== null) {+ await attributes.setLabel(note.noteId, "color", picked);+ } else {+ attributes.removeOwnedLabelByName(note, "color");+ }+ }+ },+ tooltips: {+ clear: t("note-color.clear-color"),+ set: t("note-color.set-color"),+ setCustom: t("note-color.set-custom-color")+ }+ });+}diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.tsindex df746fdde2..b0206a8d8c 100644--- a/apps/client/src/widgets/collections/board/data.spec.ts+++ b/apps/client/src/widgets/collections/board/data.spec.ts@@ -9,11 +9,11 @@ import type { PromotedAttribute } from "../promoted_attributes";import type { SortContext, SortKey } from "../sorting";import { INBOX_COLUMN } from "./columns";import {- affectsSortOrder, applyCardMove, type ColumnMap, type ColumnSort, filterColumnMap,+ affectsSortOrder, applyCardMoves, type ColumnMap, type ColumnSort, filterColumnMap,getBoardData, resolveColumnSorts, resolveSortWatch, sortColumnMap, unfilteredCardIndex} from "./data";-describe("applyCardMove", () => {+describe("applyCardMoves", () => {/** Cards named by their note id, which is all this reads them for. */function board(columns: Record<string, string[]>): ColumnMap {return new Map(Object.entries(columns).map(([ column, ids ]) => [@@ -26,23 +26,23 @@ describe("applyCardMove", () => {(map.get(column) ?? []).map((item) => item.note.noteId);it("takes a card out of one column and puts it in another", () => {- const next = applyCardMove(board({ A: [ "a1", "a2", "a3" ], B: [ "b1", "b2" ] }),- "a2", "A", "B", 1);+ const next = applyCardMoves(board({ A: [ "a1", "a2", "a3" ], B: [ "b1", "b2" ] }),+ [ "a2" ], "B", 1);expect(names(next, "A")).toEqual([ "a1", "a3" ]);expect(names(next, "B")).toEqual([ "b1", "a2", "b2" ]);});it("puts it at either end of the column it lands in", () => {- const start = applyCardMove(board({ A: [ "a1" ], B: [ "b1", "b2" ] }), "a1", "A", "B", 0);+ const start = applyCardMoves(board({ A: [ "a1" ], B: [ "b1", "b2" ] }), [ "a1" ], "B", 0);expect(names(start, "B")).toEqual([ "a1", "b1", "b2" ]);- const end = applyCardMove(board({ A: [ "a1" ], B: [ "b1", "b2" ] }), "a1", "A", "B", 2);+ const end = applyCardMoves(board({ A: [ "a1" ], B: [ "b1", "b2" ] }), [ "a1" ], "B", 2);expect(names(end, "B")).toEqual([ "b1", "b2", "a1" ]);});it("puts it in a column holding none", () => {- const next = applyCardMove(board({ A: [ "a1" ], B: [] }), "a1", "A", "B", 0);+ const next = applyCardMoves(board({ A: [ "a1" ], B: [] }), [ "a1" ], "B", 0);expect(names(next, "A")).toEqual([]);expect(names(next, "B")).toEqual([ "a1" ]);@@ -55,16 +55,35 @@ describe("applyCardMove", () => {it("counts a move down its own column against the list it came from", () => {const start = board({ A: [ "a1", "a2", "a3" ] });- expect(names(applyCardMove(start, "a1", "A", "A", 3), "A")).toEqual([ "a2", "a3", "a1" ]);- expect(names(applyCardMove(start, "a1", "A", "A", 2), "A")).toEqual([ "a2", "a1", "a3" ]);- expect(names(applyCardMove(start, "a3", "A", "A", 0), "A")).toEqual([ "a3", "a1", "a2" ]);- expect(names(applyCardMove(start, "a3", "A", "A", 1), "A")).toEqual([ "a1", "a3", "a2" ]);+ expect(names(applyCardMoves(start, [ "a1" ], "A", 3), "A")).toEqual([ "a2", "a3", "a1" ]);+ expect(names(applyCardMoves(start, [ "a1" ], "A", 2), "A")).toEqual([ "a2", "a1", "a3" ]);+ expect(names(applyCardMoves(start, [ "a3" ], "A", 0), "A")).toEqual([ "a3", "a1", "a2" ]);+ expect(names(applyCardMoves(start, [ "a3" ], "A", 1), "A")).toEqual([ "a1", "a3", "a2" ]);+ });++ it("moves several cards from several columns, keeping the order they are given in", () => {+ const next = applyCardMoves(+ board({ A: [ "a1", "a2", "a3" ], B: [ "b1", "b2" ], C: [] }),+ [ "a1", "b2", "a3" ], "C", 0);++ expect(names(next, "A")).toEqual([ "a2" ]);+ expect(names(next, "B")).toEqual([ "b1" ]);+ expect(names(next, "C")).toEqual([ "a1", "b2", "a3" ]);+ });++ it("counts a move of several down their own column against the cards staying put", () => {+ const start = board({ A: [ "a1", "a2", "a3", "a4" ] });++ expect(names(applyCardMoves(start, [ "a1", "a2" ], "A", 4), "A"))+ .toEqual([ "a3", "a4", "a1", "a2" ]);+ expect(names(applyCardMoves(start, [ "a1", "a4" ], "A", 2), "A"))+ .toEqual([ "a2", "a1", "a4", "a3" ]);});it("leaves the board alone for a card it does not hold", () => {const start = board({ A: [ "a1" ], B: [] });- expect(applyCardMove(start, "nope", "A", "B", 0)).toBe(start);+ expect(applyCardMoves(start, [ "nope" ], "B", 0)).toBe(start);});describe("filterColumnMap", () => {diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex 410808b931..a184c55056 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -18,32 +18,50 @@ export interface ColumnItem {export type ColumnMap = Map<string, ColumnItem[]>;/**- * The columns as they stand once a card has moved, for drawing the outcome before the writes land.+ * The columns as they stand once cards have moved, for drawing the outcome before the writes land.** A card crossing columns is written twice, the value first and the branch after, and each lands a* redraw of its own. The first shows the card in its new column at whatever place its old branch* gives it, which is above every card already there.*- * @param index where the card goes, counting the target column as it stands at the moment of the- * drop, the card itself included where it does not leave its column.+ * The cards keep the order `noteIds` lists them in, wherever they came from, and land together.+ * A card the board does not hold is left out; where that is all of them, the map is handed back as+ * it stands.+ *+ * @param index where the cards go, counting the target column as it stands at the moment of the+ * drop, the cards being moved included where they do not leave that column.*/-export function applyCardMove(- byColumn: ColumnMap, noteId: string, from: string, to: string, index: number+export function applyCardMoves(+ byColumn: ColumnMap, noteIds: string[], to: string, index: number): ColumnMap {- const source = [ ...(byColumn.get(from) ?? []) ];- const at = source.findIndex((item) => item.note.noteId === noteId);- if (at < 0) {- return byColumn;+ const moving = new Set(noteIds);+ const next: ColumnMap = new Map();+ const picked = new Map<string, ColumnItem>();++ for (const [ column, items ] of byColumn) {+ const kept: ColumnItem[] = [];+ for (const item of items) {+ if (moving.has(item.note.noteId)) {+ picked.set(item.note.noteId, item);+ } else {+ kept.push(item);+ }+ }++ next.set(column, kept);}- const [ moved ] = source.splice(at, 1);- const next = new Map(byColumn);- next.set(from, source);+ if (!picked.size) {+ return byColumn;+ }- const target = from === to ? source : [ ...(byColumn.get(to) ?? []) ];- // Taking the card out shifts everything after it up one, so a place beyond where it stood- // names one card earlier in the list left behind.- target.splice(from === to && index > at ? index - 1 : index, 0, moved);+ // Taking the cards out shifts everything below them up, so a place counted with them still in+ // the column names one card earlier for each of them standing above it.+ const above = (byColumn.get(to) ?? []).slice(0, index)+ .filter((item) => moving.has(item.note.noteId)).length;+ const target = next.get(to) ?? [];+ target.splice(index - above, 0,+ ...noteIds.flatMap((noteId) => picked.get(noteId) ?? []));next.set(to, target);return next;diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex e4a3b404fa..d51138a8db 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -22,6 +22,12 @@--board-collapse-duration-quick: 0.3s;--board-expand-duration: 0.2s;+ /* The lift a card takes under the pointer, named so that a picked-out card can carry its ring+ and this shadow together. */+ --board-item-hover-shadow: 2px 4px 8px rgba(0, 0, 0, 0.1);+ /* The ring a picked-out card carries. */+ --board-selected-ring-color: var(--link-color);+--board-focus-outline-saturation: 55%;--board-focus-outline-lightness: 45%;/* Follows the theme of its own accord, so neither theme has to name it again. */@@ -440,7 +446,34 @@ body.mobile .board-view-container .board-add-column {}.board-view-container .board-note:hover {- box-shadow: 2px 4px 8px rgba(0, 0, 0, 0.1);+ box-shadow: var(--board-item-hover-shadow);+}++/* A picked-out card. An inset ring rather than an outline, since focus is drawn as an outline and+ a card can be both picked out and focused. */+.board-view-container .board-note.selected {+ box-shadow: inset 0 0 0 2px var(--board-selected-ring-color);+}++.board-view-container .board-note.selected:hover {+ box-shadow:+ inset 0 0 0 2px var(--board-selected-ring-color),+ var(--board-item-hover-shadow);+}++/* A card travelling with the one under the pointer. That one is taken out of the flow by the+ gesture; the rest stay where they are drawn. */+.board-view-container .board-note.dragging {+ opacity: 0.4;+}++/* What a carried selection is drawn as: one card-shaped block holding how many are on the move. */+.board-view-container .board-note.board-drag-count {+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 1.6em;+ font-weight: 600;}.board-view-container .board-note:hover > .edit-icon {diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 47803820b4..f7de8c7f83 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -40,6 +40,7 @@ import ActionButton from "../../react/ActionButton";import { IconPickerButton } from "../../react/IconPicker";import { useDragPan } from "../../react/drag_pan";import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";+import { SelectionContext, SelectionStore } from "../../react/selection";import { CollectionFilterInput, useCollectionFilter } from "../collection_filter";import { ViewModeProps } from "../interface";import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api";@@ -58,7 +59,7 @@ import BoardProperties from "./properties";import { openBoardContextMenu, openCreateColumnMenu } from "./context_menu";import { useBoardSort } from "./sort";import {- affectsSortOrder, applyCardMove, ColumnMap, filterColumnMap, getBoardData, resolveColumnSorts,+ affectsSortOrder, applyCardMoves, ColumnMap, filterColumnMap, getBoardData, resolveColumnSorts,resolveSortWatch, sortColumnMap, unfilteredCardIndex} from "./data";import { useBoardKeyboard } from "./keyboard";@@ -140,6 +141,11 @@ export interface BoardColumnData {interface CardDrag {noteId: string;+ /**+ * Every card on the move, this one among them. One entry unless the card was taken hold of as+ * part of a selection; absent for a drag from the note tree, which carries no card.+ */+ noteIds?: string[];branchId: string;fromColumn: string;index: number;@@ -342,6 +348,11 @@ export default function BoardView({* the gap is not near.*/const dropState = useMemo(() => new DropStateStore(), []);+ /**+ * Which cards are picked out, kept out of the board's state for the same reason: selecting one+ * card must wake that card and no other.+ */+ const selection = useMemo(() => new SelectionStore(), []);const setDropPosition = useCallback((position: ColumnDrag | null) => {dropState.set({ ...dropState.get(), position });}, [ dropState ]);@@ -461,6 +472,16 @@ export default function BoardView({() => resolveSortWatch(allByColumn, columnSorts, sortContext.definitions),[ allByColumn, columnSorts, sortContext ]);+ // A card the board has stopped drawing, because it was deleted, archived out of view or moved+ // off the board, leaves the selection with it. A command would otherwise write to a note the+ // reader can no longer see.+ useEffect(() => {+ if (byColumn) {+ selection.retain(new Set([ ...byColumn.values() ]+ .flatMap((items) => items.map((item) => item.note.noteId))));+ }+ }, [ byColumn, selection ]);+if (!apiRef.current || apiRef.current.board !== boardIdentity) {apiRef.current = {board: boardIdentity,@@ -731,12 +752,21 @@ export default function BoardView({// The gesture drives the same state a drag from the note tree does, so the placeholders and the// card's own dimming are drawn from one place whichever brought the card here.const { isDragging: isDraggingItem, remeasure } = useBoardDrag(containerRef, {+ carriedWith: (noteId) => (selection.has(noteId)+ ? api.getCards(selection.keys).map((card) => card.note.noteId)+ : [ noteId ]),onCardStart: (card) => {// The card leaves the flow and the gap opens in its place, which eased would read as// the column closing up and sliding back open.holdStill();+ // A card taken hold of from outside the selection travels alone, and what was picked+ // out is given up: those cards stay where they are, and would still read as selected.+ if (!selection.has(card.noteId)) {+ selection.clear();+ }setDraggedCard({noteId: card.noteId,+ noteIds: card.noteIds,branchId: byColumn?.get(card.fromColumn)?.[card.index]?.branch.branchId ?? "",fromColumn: card.fromColumn,index: card.index,@@ -761,23 +791,29 @@ export default function BoardView({// card, hide the gap and close the room it took, and if those reach the screen in// separate frames the reader sees a gap open where nothing is being carried any more.closeGaps(containerRef.current);- const branchId = byColumn?.get(card.fromColumn)?.[card.index]?.branch.branchId;+ // Every card on the move, in the order the board draws them, with the branches they+ // are moved by. One entry unless the card was carried as part of a selection.+ const carried = api.getCards(new Set(card.noteIds));const isSortedTarget = !!position && columnSorts.has(position.column);- // A drop inside a sorted column changes nothing: `sortColumnMap` already placed it.- if (isSortedTarget && position?.column === card.fromColumn) {+ // A drop inside a sorted column changes nothing: `sortColumnMap` already placed the+ // cards. Only while every card carried is already there; one from another column still+ // has to be filed under this one.+ const allInTarget = !!position && carried.every((item) =>+ api.getCardColumn(item.note.noteId) === position.column);+ if (isSortedTarget && allInTarget) {setDraggedCard(null);dropState.set({ position: null, target: null });focusCard(card.noteId);return;}- if (position && branchId && byColumn && allByColumn) {+ if (position && carried.length && byColumn && allByColumn) {// Drawn at once, into `allByColumn` since that is what `byColumn` derives from, at// the index `unfilteredCardIndex` translates rather than the visible drop index.// The index does not matter for a sorted column: `sortColumnMap` reorders the// map afterwards.- setAllByColumn(applyCardMove(- allByColumn, card.noteId, card.fromColumn, position.column,+ setAllByColumn(applyCardMoves(+ allByColumn, carried.map((item) => item.note.noteId), position.column,unfilteredCardIndex(byColumn.get(position.column) ?? [],allByColumn.get(position.column) ?? [],@@ -789,13 +825,20 @@ export default function BoardView({// Any refresh already on its way is about the board as it stood before the drop,// and would put the card back where it came from as it resolves.refreshSeqRef.current++;- api.moveWithinBoard(- card.noteId, branchId, card.index, position.index,- card.fromColumn, position.column)- // Nothing is asked for once the writes are in: `froca` learns of the branch- // move from the server a moment later, so a refresh here reads the new column- // with the old order and puts the card at the top of it. The change reaches the- // board as an entity reload, which settles it once there is something to read.+ // Nothing is asked for once the writes are in: `froca` learns of the branch move+ // from the server a moment later, so a refresh here reads the new column with the+ // old order and puts the card at the top of it. The change reaches the board as an+ // entity reload, which settles it once there is something to read.+ (carried.length === 1+ ? api.moveWithinBoard(+ card.noteId, carried[0].branch.branchId, card.index, position.index,+ card.fromColumn, position.column)+ : api.moveManyWithinBoard(+ carried.map((item) => ({+ noteId: item.note.noteId,+ branchId: item.branch.branchId+ })),+ position.column, position.index)).finally(() => { movesInFlight.current--; });}setDraggedCard(null);@@ -984,7 +1027,13 @@ export default function BoardView({setColumnDropPosition(null);}, [ api, shownColumns ]);- const { onKeyDown: handleKeyDown, focusColumn, focusCard } = useBoardKeyboard({+ const clearSelectionOutsideCards = useCallback((e: MouseEvent) => {+ if (!(e.target as HTMLElement | null)?.closest(".board-note")) {+ selection.clear();+ }+ }, [ selection ]);++ const { onKeyDown: handleBoardKeys, focusColumn, focusCard } = useBoardKeyboard({containerRef,setActiveColumn,columns: shownColumns,@@ -996,6 +1045,19 @@ export default function BoardView({}, [ api ])});+ // Escape gives the selection up, before the board's own keys are offered the press: nothing+ // else on the board answers for Escape, and a reader who has picked cards out expects it to+ // undo that first.+ const handleKeyDown = useCallback((e: KeyboardEvent) => {+ if (e.key === "Escape" && selection.size) {+ e.stopPropagation();+ selection.clear();+ return;+ }++ handleBoardKeys(e);+ }, [ selection, handleBoardKeys ]);+useTriliumEvent("entitiesReloaded", ({ loadResults }) => {// The column list is read off the definition, which may be edited from the attribute panel,// another split, or a synced instance. Re-reading it re-runs the refresh through the effect.@@ -1046,6 +1108,7 @@ export default function BoardView({<BoardKeptCardsContext.Provider value={filter.keptNoteIds}><BoardDropStateContext.Provider value={dropState}><BoardDragStateContext.Provider value={boardDragState}>+ <SelectionContext.Provider value={selection}>{byColumn && columns && <divref={containerRef}className={clsx("board-view-container", {@@ -1053,6 +1116,7 @@ export default function BoardView({panning: isPanning})}onKeyDown={handleKeyDown}+ onClick={clearSelectionOutsideCards}onContextMenu={openBoardMenu}onWheel={onWheelHorizontalScroll}>@@ -1154,6 +1218,7 @@ export default function BoardView({/>)}</div>}+ </SelectionContext.Provider></BoardDragStateContext.Provider></BoardDropStateContext.Provider></BoardKeptCardsContext.Provider>