Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: make keyboard actions to operate over multi-selection

Adorian Dorancc80eaa9a099
diff --git a/apps/client/src/services/note_set.ts b/apps/client/src/services/note_set.ts
index 329e198586..f8316cf693 100644
--- a/apps/client/src/services/note_set.ts
+++ b/apps/client/src/services/note_set.ts
@@ -29,15 +29,14 @@ export function shared<T>(notes: FNote[], read: (note: FNote) => T): Shared<T> {
/**
* Sets a label to one value on every note.
*
- * Written note by note through `setLabelValues`, which reuses the labels already there and leaves
- * inherited ones alone. The bulk-action endpoint would be one request instead of several, but its
+ * Written through `setLabelValues`, which reuses the labels already there and leaves inherited ones
+ * alone. The bulk-action endpoint would be one request instead of several, but its
* `updateLabelValue` only touches labels a note already owns and `addLabel` always adds another,
- * so neither writes "hold this value" on a note that may or may not already hold it.
+ * so neither writes "hold this value" on a note that may or may not already hold it. The notes go
+ * together instead, so a set is not written one card at a time.
*/
export async function setLabelOnNotes(notes: FNote[], name: string, value: string) {
- for (const note of notes) {
- await setLabelValues(note, name, [ value ]);
- }
+ await Promise.all(notes.map((note) => setLabelValues(note, name, [ value ])));
}
/**
@@ -48,24 +47,18 @@ export async function setLabelOnNotes(notes: FNote[], name: string, value: strin
* holds and what `renderLabelValue` draws as nothing.
*/
export async function clearLabelOnNotes(notes: FNote[], name: string) {
- for (const note of notes) {
+ await Promise.all(notes.map((note) => {
const isInherited = note.getAttributes("label", name)
.some((attribute) => attribute.noteId !== note.noteId);
- await setLabelValues(note, name, isInherited ? [ "" ] : []);
- }
+ return setLabelValues(note, name, isInherited ? [ "" ] : []);
+ }));
}
/** Adds or removes `#archived` on every note, leaving the ones already in that state alone. */
export async function setArchivedOnNotes(notes: FNote[], archived: boolean) {
- for (const note of notes) {
- if (note.isArchived === archived) {
- continue;
- }
-
- if (archived) {
- await attributes.addLabel(note.noteId, "archived");
- } else {
- attributes.removeOwnedLabelByName(note, "archived");
- }
- }
+ await Promise.all(notes
+ .filter((note) => note.isArchived !== archived)
+ .map((note) => archived
+ ? attributes.addLabel(note.noteId, "archived")
+ : attributes.removeOwnedLabelByName(note, "archived")));
}
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index b938e2d96f..5c6d47b019 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -555,13 +555,21 @@ describe("BoardApi card operations", () => {
const [ first ] = items;
// The target column is empty, so there is nothing to place it against.
- await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 0, 1, "Done", "To Do");
+ await api.moveWithinBoard(
+ [ { noteId: first.note.noteId, branchId: first.branch.branchId } ], "To Do", 1);
expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
expect(branches.moveAfterBranch).not.toHaveBeenCalled();
- await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 0, 1, "To Do", "Done");
+ });
+
+ it("files a card arriving from another column before the one it was dropped on", async () => {
+ const { api, done, spare } = createBoardWithSpareCard();
+
+ await api.moveWithinBoard(
+ [ { noteId: spare.note.noteId, branchId: spare.branch.branchId } ], "Done", 1);
+
expect(branches.moveBeforeBranch)
- .toHaveBeenCalledWith([ first.branch.branchId ], items[1].branch.branchId);
+ .toHaveBeenCalledWith([ spare.branch.branchId ], done[1].branch.branchId);
});
/** A board whose "Done" column holds three cards, with a fourth waiting in "To Do". */
@@ -599,7 +607,8 @@ describe("BoardApi card operations", () => {
it("files a card dropped past the last card of another column after it", async () => {
const { api, done, spare } = createBoardWithSpareCard();
- await api.moveWithinBoard(spare.note.noteId, spare.branch.branchId, 0, 3, "To Do", "Done");
+ await api.moveWithinBoard(
+ [ { noteId: spare.note.noteId, branchId: spare.branch.branchId } ], "Done", 3);
expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
expect(branches.moveAfterBranch)
@@ -609,7 +618,8 @@ describe("BoardApi card operations", () => {
it("files a card dropped into a column a filter empties after the cards it hides", async () => {
const { api, done, spare } = createBoardWithSpareCard(() => []);
- await api.moveWithinBoard(spare.note.noteId, spare.branch.branchId, 0, 0, "To Do", "Done");
+ await api.moveWithinBoard(
+ [ { noteId: spare.note.noteId, branchId: spare.branch.branchId } ], "Done", 0);
expect(branches.moveAfterBranch)
.toHaveBeenCalledWith([ spare.branch.branchId ], done[2].branch.branchId);
@@ -618,7 +628,8 @@ describe("BoardApi card operations", () => {
it("files a card dropped past the last card shown after that one, not the hidden", async () => {
const { api, done, spare } = createBoardWithSpareCard((all) => [ all[0] ]);
- await api.moveWithinBoard(spare.note.noteId, spare.branch.branchId, 0, 1, "To Do", "Done");
+ await api.moveWithinBoard(
+ [ { noteId: spare.note.noteId, branchId: spare.branch.branchId } ], "Done", 1);
expect(branches.moveAfterBranch)
.toHaveBeenCalledWith([ spare.branch.branchId ], done[0].branch.branchId);
@@ -627,7 +638,8 @@ describe("BoardApi card operations", () => {
it("sends a card after the last one drawn in a column a filter narrows", async () => {
const { api, done, spare } = createBoardWithSpareCard((all) => [ all[0] ]);
- await api.moveToColumnEnd(spare.note.noteId, spare.branch.branchId, "Done");
+ await api.moveToColumnEnd(
+ [ { noteId: spare.note.noteId, branchId: spare.branch.branchId } ], "Done");
expect(branches.moveAfterBranch)
.toHaveBeenCalledWith([ spare.branch.branchId ], done[0].branch.branchId);
@@ -636,7 +648,8 @@ describe("BoardApi card operations", () => {
it("sends a card past the cards a filter hides when it draws none of them", async () => {
const { api, done, spare } = createBoardWithSpareCard(() => []);
- await api.moveToColumnEnd(spare.note.noteId, spare.branch.branchId, "Done");
+ await api.moveToColumnEnd(
+ [ { noteId: spare.note.noteId, branchId: spare.branch.branchId } ], "Done");
expect(branches.moveAfterBranch)
.toHaveBeenCalledWith([ spare.branch.branchId ], done[2].branch.branchId);
@@ -673,11 +686,13 @@ describe("BoardApi card operations", () => {
const { api, items } = createBoardWithCards();
const [ first, , third ] = items;
- await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 0, 2, "Done", "Done");
+ await api.moveWithinBoard(
+ [ { noteId: first.note.noteId, branchId: first.branch.branchId } ], "Done", 2);
expect(branches.moveBeforeBranch)
.toHaveBeenCalledWith([ first.branch.branchId ], third.branch.branchId);
- await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 0, 3, "Done", "Done");
+ await api.moveWithinBoard(
+ [ { noteId: first.note.noteId, branchId: first.branch.branchId } ], "Done", 3);
expect(branches.moveAfterBranch)
.toHaveBeenCalledWith([ first.branch.branchId ], third.branch.branchId);
});
@@ -690,10 +705,12 @@ describe("BoardApi card operations", () => {
const { api, items } = createBoardWithCards();
const [ first, second ] = items;
- await api.moveToColumnEnd(first.note.noteId, first.branch.branchId, "To Do");
+ await api.moveToColumnEnd(
+ [ { noteId: first.note.noteId, branchId: first.branch.branchId } ], "To Do");
expect(branches.moveAfterBranch).not.toHaveBeenCalled();
- await api.moveToColumnEnd(second.note.noteId, second.branch.branchId, "To Do");
+ await api.moveToColumnEnd(
+ [ { noteId: second.note.noteId, branchId: second.branch.branchId } ], "To Do");
expect(branches.moveAfterBranch)
.toHaveBeenLastCalledWith([ second.branch.branchId ], first.branch.branchId);
});
@@ -707,7 +724,8 @@ describe("BoardApi card operations", () => {
const { api, items } = createBoardWithCards();
const [ first, second, third ] = items;
- await api.moveToColumnEnd(first.note.noteId, first.branch.branchId, "To Do");
+ await api.moveToColumnEnd(
+ [ { noteId: first.note.noteId, branchId: first.branch.branchId } ], "To Do");
// The refresh that catches up, and with it a card that now stands last in that column.
api.update(
@@ -715,7 +733,8 @@ describe("BoardApi card operations", () => {
[ "To Do", "Done" ], first.note.getParentNotes()[0], "status", {}, () => {}, () => {});
// Behind what the board now shows last, not behind what this sent before it.
- await api.moveToColumnEnd(second.note.noteId, second.branch.branchId, "To Do");
+ await api.moveToColumnEnd(
+ [ { noteId: second.note.noteId, branchId: second.branch.branchId } ], "To Do");
expect(branches.moveAfterBranch)
.toHaveBeenLastCalledWith([ second.branch.branchId ], third.branch.branchId);
});
@@ -724,8 +743,10 @@ describe("BoardApi card operations", () => {
const { api, items } = createBoardWithCards();
const [ first ] = items;
- await api.moveWithinBoard(first.note.noteId, first.branch.branchId, 1, 1, "Done", "Done");
- await api.moveWithinBoard("missingNote", "missingBranch", 0, 2, "Done", "Done");
+ await api.moveWithinBoard(
+ [ { noteId: first.note.noteId, branchId: first.branch.branchId } ], "Done", 1);
+ await api.moveWithinBoard(
+ [ { noteId: "missingNote", branchId: "missingBranch" } ], "Done", 2);
expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
expect(branches.moveAfterBranch).not.toHaveBeenCalled();
@@ -735,11 +756,11 @@ describe("BoardApi card operations", () => {
const { api, items } = createBoardWithCards();
const removeLabel = vi.spyOn(attributes, "removeOwnedLabelByName").mockReturnValue(true);
- await api.removeFromBoard(items[0].note.noteId);
+ await api.removeFromBoard([ items[0].note.noteId ]);
expect(removeLabel).toHaveBeenCalledWith(items[0].note, "status");
// A note the cache has never heard of is left alone rather than throwing.
- await api.removeFromBoard("missingNote");
+ await api.removeFromBoard([ "missingNote" ]);
expect(removeLabel).toHaveBeenCalledTimes(1);
});
@@ -758,7 +779,7 @@ describe("BoardApi card operations", () => {
const removeLabel = vi.spyOn(attributes, "removeOwnedLabelByName").mockReturnValue(true);
const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined as never);
- await api.removeFromBoard(cardId);
+ await api.removeFromBoard([ cardId ]);
expect(setLabel).toHaveBeenCalledWith(cardId, "status", "");
expect(removeLabel).not.toHaveBeenCalled();
@@ -770,7 +791,7 @@ describe("BoardApi card operations", () => {
const removeRelation = vi.spyOn(attributes, "removeOwnedRelationByName")
.mockReturnValue(true);
- await api.removeFromBoard(board.getChildNoteIds()[0]);
+ await api.removeFromBoard([ board.getChildNoteIds()[0] ]);
expect(removeRelation).toHaveBeenCalledWith(expect.anything(), "status");
});
@@ -789,7 +810,7 @@ describe("BoardApi card operations", () => {
.mockReturnValue(true);
const message = vi.spyOn(toast, "showMessage").mockReturnValue(undefined);
- await api.removeFromBoard(board.getChildNoteIds()[0]);
+ await api.removeFromBoard([ board.getChildNoteIds()[0] ]);
expect(message).toHaveBeenCalledWith("board_view.inherited-column", 3000);
expect(removeRelation).not.toHaveBeenCalled();
@@ -1828,7 +1849,7 @@ describe("filing a card under the inbox", () => {
const removeRelation = vi.spyOn(attributes, "removeOwnedRelationByName")
.mockReturnValue(true);
- await api.removeFromBoard(board.getChildNoteIds()[0]);
+ await api.removeFromBoard([ board.getChildNoteIds()[0] ]);
expect(removeRelation).toHaveBeenCalled();
});
@@ -2130,7 +2151,8 @@ describe("moving a card into or inside a sorted column", () => {
it("writes the value alone when a card crosses into one", async () => {
const { api } = sortedApi([ "Done" ]);
- await api.moveWithinBoard("a2", "b_a2", 1, 0, "To Do", "Done");
+ await api.moveWithinBoard(
+ [ { noteId: "a2", branchId: "b_a2" } ], "Done", 0);
expect(setLabel).toHaveBeenCalledWith("a2", "status", "Done");
expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
@@ -2140,7 +2162,8 @@ describe("moving a card into or inside a sorted column", () => {
it("writes nothing at all for a move inside one", async () => {
const { api } = sortedApi([ "To Do" ]);
- await api.moveWithinBoard("a1", "b_a1", 0, 2, "To Do", "To Do");
+ await api.moveWithinBoard(
+ [ { noteId: "a1", branchId: "b_a1" } ], "To Do", 2);
expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
expect(branches.moveAfterBranch).not.toHaveBeenCalled();
@@ -2149,7 +2172,8 @@ describe("moving a card into or inside a sorted column", () => {
it("still places a card in a column left in the manual order", async () => {
const { api } = sortedApi([ "To Do" ]);
- await api.moveWithinBoard("a2", "b_a2", 1, 0, "To Do", "Done");
+ await api.moveWithinBoard(
+ [ { noteId: "a2", branchId: "b_a2" } ], "Done", 0);
expect(setLabel).toHaveBeenCalledWith("a2", "status", "Done");
expect(branches.moveBeforeBranch).toHaveBeenCalledWith([ "b_a2" ], "b_b1");
@@ -2158,7 +2182,7 @@ describe("moving a card into or inside a sorted column", () => {
it("sends a card across to a sorted column by value alone", async () => {
const { api } = sortedApi([ "Done" ]);
- await api.moveToColumnEnd("a1", "b_a1", "Done");
+ await api.moveToColumnEnd([ { noteId: "a1", branchId: "b_a1" } ], "Done");
expect(setLabel).toHaveBeenCalledWith("a1", "status", "Done");
expect(branches.moveAfterBranch).not.toHaveBeenCalled();
@@ -2248,7 +2272,7 @@ describe("a selection of cards", () => {
const { api, items } = createBoard();
const moved = [ items[3], items[0] ];
- await api.moveManyWithinBoard(
+ await api.moveWithinBoard(
moved.map((item) => ({ noteId: item.note.noteId, branchId: item.branch.branchId })),
"Done", 2);
@@ -2266,7 +2290,7 @@ describe("a selection of cards", () => {
const { api, items } = createBoard();
const moved = [ items[3] ];
- await api.moveManyWithinBoard(
+ await api.moveWithinBoard(
moved.map((item) => ({ noteId: item.note.noteId, branchId: item.branch.branchId })),
"Done", 3);
@@ -2281,7 +2305,7 @@ describe("a selection of cards", () => {
{ columns: [ { value: "Done", orderBy: "title" } ] });
const moved = [ items[3] ];
- await api.moveManyWithinBoard(
+ await api.moveWithinBoard(
moved.map((item) => ({ noteId: item.note.noteId, branchId: item.branch.branchId })),
"Done", 0);
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index c7f3bf51e7..40c27189fd 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -374,7 +374,7 @@ export default class BoardApi {
return;
}
- return this.removeFromBoard(noteId);
+ return this.removeCardFromBoard(noteId);
}
/**
@@ -1249,7 +1249,15 @@ export default class BoardApi {
.some(attribute => attribute.noteId !== note.noteId);
}
- removeFromBoard(noteId: string) {
+ /**
+ * Takes cards off the board, which leaves the notes where they are and only takes the grouping
+ * value away. Written together, so a set does not leave a card at a time.
+ */
+ async removeFromBoard(noteIds: string[]) {
+ await Promise.all(noteIds.map((noteId) => this.removeCardFromBoard(noteId)));
+ }
+
+ private removeCardFromBoard(noteId: string) {
const note = froca.getNoteFromCache(noteId);
if (!note) return;
if (this.isRelationMode) {
@@ -1278,28 +1286,40 @@ export default class BoardApi {
return !!this.getEffectiveColumnSort(column).orderBy;
}
- /** Moves a card to the end of another column, where a card sent by the keyboard belongs. */
- async moveToColumnEnd(noteId: string, branchId: string, targetColumn: string) {
- // Only the grouping value is written: `sortColumnMap` decides where the card is drawn.
- if (this.isColumnSorted(targetColumn)) {
- await this.changeColumn(noteId, targetColumn);
+ /**
+ * Sends cards to the end of another column, where the ones the keyboard sends belong, keeping
+ * the order they are given in.
+ *
+ * The grouping values go together rather than one after another, which is what keeps a set from
+ * arriving a card at a time: each is a request of its own, and one at a time makes the wait the
+ * sum of them. `moveAfterBranch` then places the whole set against one card, in order.
+ */
+ async moveToColumnEnd(cards: { noteId: string, branchId: string }[], targetColumn: string) {
+ const arrived = cards.at(-1);
+ if (!arrived) {
return;
}
// What is already at the end, as far as this instance can know: nothing waits for the board
// to redraw between two keystrokes, so the column map still shows the target as it was
- // before the card the last press sent. Anything sent since is remembered here instead, and
+ // before the cards the last press sent. Anything sent since is remembered here instead, and
// the memory lasts exactly as long as the map it stands in for, both being rebuilt by the
- // refresh that catches up.
- const last = this.sentToColumnEnd.get(targetColumn)
- ?? this.lastInColumn(targetColumn);
+ // refresh that catches up. Read before the writes below for the same reason.
+ const last = this.sentToColumnEnd.get(targetColumn) ?? this.lastInColumn(targetColumn);
+
+ await Promise.all(cards.map((card) => this.changeColumn(card.noteId, targetColumn)));
+
+ // Only the grouping value is written for a sorted column: `sortColumnMap` decides where
+ // its cards are drawn.
+ if (this.isColumnSorted(targetColumn)) {
+ return;
+ }
- await this.changeColumn(noteId, targetColumn);
- if (last && last !== branchId) {
- await branches.moveAfterBranch([ branchId ], last);
+ if (last && last !== arrived.branchId) {
+ await branches.moveAfterBranch(cards.map((card) => card.branchId), last);
}
- this.sentToColumnEnd.set(targetColumn, branchId);
+ this.sentToColumnEnd.set(targetColumn, arrived.branchId);
}
/**
@@ -1349,22 +1369,46 @@ export default class BoardApi {
* `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(
+ async moveWithinBoard(
cards: { noteId: string, branchId: string }[], targetColumn: string, targetIndex: number
) {
+ // A card the cache has never heard of is left out rather than written for.
+ const moving = cards.filter((card) => froca.getNoteFromCache(card.noteId));
+ if (!moving.length) {
+ return;
+ }
+
// 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));
+ const branchIds = moving.map((card) => card.branchId);
+ const moved = new Set(branchIds);
// 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];
+ const at = targetIndex - above;
+
+ // Nothing at all is written where the cards already stand where this would put them, which
+ // is what a card dropped back where it was picked up amounts to.
+ const standing = targetItems.map((item) => item.branch.branchId);
+ const landing = [
+ ...staying.slice(0, at).map((item) => item.branch.branchId),
+ ...branchIds,
+ ...staying.slice(at).map((item) => item.branch.branchId)
+ ];
+ if (landing.length === standing.length
+ && landing.every((branchId, place) => branchId === standing[place])) {
+ return;
+ }
- for (const card of cards) {
- await this.changeColumn(card.noteId, targetColumn);
+ // Only the cards arriving from elsewhere are written: one already under this column holds
+ // the value already, and writing it again is a change the board has to redraw for.
+ // Together rather than one after another, so a set does not arrive a card at a time.
+ const arriving = moving.filter((card) => !standing.includes(card.branchId));
+ if (arriving.length) {
+ await Promise.all(arriving.map((card) => this.changeColumn(card.noteId, targetColumn)));
}
// A sorted column places its own cards, so nothing is written against a card there.
@@ -1372,14 +1416,17 @@ export default class BoardApi {
return;
}
- const branchIds = cards.map((card) => card.branchId);
+ const before = staying[at];
if (before) {
await branches.moveBeforeBranch(branchIds, before.branch.branchId);
- } else {
- const last = staying.at(-1);
- if (last) {
- await branches.moveAfterBranch(branchIds, last.branch.branchId);
- }
+ return;
+ }
+
+ // What the cards are placed after: the last one staying, or `lastInColumn`'s answer where
+ // a filter draws none of them at all.
+ const after = staying.at(-1)?.branch.branchId ?? this.lastInColumn(targetColumn);
+ if (after && !moved.has(after)) {
+ await branches.moveAfterBranch(branchIds, after);
}
}
@@ -1422,55 +1469,7 @@ export default class BoardApi {
return;
}
- await this.moveWithinBoard(noteId, branchId, at, 0, column, column);
- }
-
- async moveWithinBoard(noteId: string, sourceBranchId: string, sourceIndex: number, targetIndex: number, sourceColumn: string, targetColumn: string) {
- const targetItems = this.byColumn?.get(targetColumn) ?? [];
- // Read before the writes below, since a redraw between them hands this instance the map
- // with the card already moved.
- const lastInTarget = this.lastInColumn(targetColumn);
-
- const note = froca.getNoteFromCache(noteId);
- if (!note) return;
-
- // A move into or inside a sorted column writes the grouping value and no branch
- // position. Clearing `orderBy` then restores the arrangement the user made.
- const isSortedTarget = this.isColumnSorted(targetColumn);
-
- if (sourceColumn !== targetColumn) {
- // Moving to a different column
- await this.changeColumn(noteId, targetColumn);
-
- if (isSortedTarget) {
- return;
- }
-
- if (targetIndex < targetItems.length) {
- const targetBranch = targetItems[targetIndex].branch;
- await branches.moveBeforeBranch([ sourceBranchId ], targetBranch.branchId);
- } else if (lastInTarget && lastInTarget !== sourceBranchId) {
- await branches.moveAfterBranch([ sourceBranchId ], lastInTarget);
- }
- } else if (!isSortedTarget && sourceIndex !== targetIndex) {
- // Reordering within the same column
- let targetBranchId: string | null = null;
-
- if (targetIndex < targetItems.length) {
- // Moving before an existing item
- const adjustedIndex = sourceIndex < targetIndex ? targetIndex : targetIndex;
- if (adjustedIndex < targetItems.length) {
- targetBranchId = targetItems[adjustedIndex].branch.branchId;
- if (targetBranchId) {
- await branches.moveBeforeBranch([ sourceBranchId ], targetBranchId);
- }
- }
- } else if (targetIndex > 0) {
- // Moving to the end - place after the last item
- const lastItem = targetItems[targetItems.length - 1];
- await branches.moveAfterBranch([ sourceBranchId ], lastItem.branch.branchId);
- }
- }
+ await this.moveWithinBoard([ { noteId, branchId } ], column, 0);
}
}
diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.ts
index 3effd30c06..5a1eb3c9f0 100644
--- a/apps/client/src/widgets/collections/board/context_menu.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.ts
@@ -451,13 +451,12 @@ function buildColumnItems(api: Api, target: NoteMenuTarget): MenuItem<CommandNam
badges: api.isColumnArchived(name)
? [ { title: t("board_view.archived-badge") } ]
: undefined,
- handler: async () => {
+ handler: () => {
// 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);
- }
+ return Promise.all(
+ target.notes.map((note) => api.changeColumn(note.noteId, name)));
}
}));
@@ -570,11 +569,7 @@ export function openNoteContextMenu(api: Api, event: ContextMenuEvent, target: N
title: t("board_view.remove-from-board"),
uiIcon: "bx bx-task-x",
shortcut: "Delete",
- handler: async () => {
- for (const selected of notes) {
- await api.removeFromBoard(selected.noteId);
- }
- }
+ handler: () => api.removeFromBoard(notes.map((selected) => selected.noteId))
},
{
title: t("board_view.delete-note"),
@@ -610,13 +605,9 @@ function CardsColorPicker({ notes }: { notes: FNote[] }) {
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");
- }
- }
+ await Promise.all(notes.map((note) => picked !== null
+ ? attributes.setLabel(note.noteId, "color", picked)
+ : attributes.removeOwnedLabelByName(note, "color")));
},
tooltips: {
clear: t("note-color.clear-color"),
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 0047ad0eca..ecf42b3387 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -836,16 +836,12 @@ export default function BoardView({
// 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))
+ api.moveWithinBoard(
+ carried.map((item) => ({
+ noteId: item.note.noteId,
+ branchId: item.branch.branchId
+ })),
+ position.column, position.index)
.finally(() => { movesInFlight.current--; });
}
setDraggedCard(null);
@@ -1034,6 +1030,47 @@ export default function BoardView({
setColumnDropPosition(null);
}, [ api, shownColumns ]);
+ /**
+ * Draws a move where it will leave the cards and holds the board there until the writes are in.
+ *
+ * A move is a write per card that changes column and one per branch being placed, and each
+ * lands a redraw of its own. Drawn as they arrive, the cards are seen to shuffle into place one
+ * after another: under their new column in the order their old branches give them, then each
+ * into the position the next write settles. The board is drawn where the move ends instead.
+ */
+ const holdMove = useCallback((
+ cards: { noteId: string, branchId: string }[],
+ targetColumn: string,
+ targetIndex: number,
+ done: Promise<unknown>
+ ) => {
+ if (allByColumn) {
+ setAllByColumn(applyCardMoves(
+ allByColumn, cards.map((card) => card.noteId), targetColumn, targetIndex));
+ }
+
+ movesInFlight.current++;
+ // Any refresh already on its way is about the board as it stood before the move, and would
+ // put the cards back where they came from as it resolves.
+ refreshSeqRef.current++;
+
+ return done.finally(() => { movesInFlight.current--; });
+ }, [ allByColumn ]);
+
+ /** Sends cards to the end of another column, which is where the keyboard puts them. */
+ const sendCardsToColumn = useCallback((
+ cards: { noteId: string, branchId: string }[], targetColumn: string
+ ) => holdMove(
+ cards, targetColumn, api.getColumnNoteIds(targetColumn).length,
+ api.moveToColumnEnd(cards, targetColumn)),
+ [ api, holdMove ]);
+
+ /** Moves cards to a place among the ones already in a column. */
+ const moveCardsWithin = useCallback((
+ cards: { noteId: string, branchId: string }[], column: string, index: number
+ ) => holdMove(cards, column, index, api.moveWithinBoard(cards, column, index)),
+ [ api, holdMove ]);
+
const clearSelectionOutsideCards = useCallback((e: MouseEvent) => {
if (!(e.target as HTMLElement | null)?.closest(".board-note")) {
selection.clear();
@@ -1048,6 +1085,8 @@ export default function BoardView({
api,
moveColumn: handleColumnDrop,
selection,
+ sendCardsToColumn,
+ moveCardsWithin,
insertColumn: useCallback(async (relativeTo: string, direction: "before" | "after") => {
setColumnNameToEdit(await api.insertColumn(relativeTo, direction));
}, [ api ])
diff --git a/apps/client/src/widgets/collections/board/keyboard.spec.tsx b/apps/client/src/widgets/collections/board/keyboard.spec.tsx
index e0fe97751e..11b2d96b29 100644
--- a/apps/client/src/widgets/collections/board/keyboard.spec.tsx
+++ b/apps/client/src/widgets/collections/board/keyboard.spec.tsx
@@ -317,6 +317,71 @@ describe("Board keyboard", () => {
expect(focusedName(board)).toBe("Second");
});
+ it("takes every picked-out card off the board, not only the focused one", async () => {
+ const board = await renderBoard();
+ const strip = vi.spyOn(attributes, "removeOwnedLabelByName").mockReturnValue(true);
+ const first = noteOf(board, "First");
+ const third = noteOf(board, "Third");
+ pick(board, 0, 0);
+ pick(board, 1, 0);
+ focusCard(board, 0, 0);
+
+ press(board, "Delete");
+ await settleWrites();
+
+ expect(strip)
+ .toHaveBeenCalledWith(expect.objectContaining({ noteId: first }), "status");
+ expect(strip)
+ .toHaveBeenCalledWith(expect.objectContaining({ noteId: third }), "status");
+ // The card that was never picked out stays where it is.
+ expect(strip).toHaveBeenCalledTimes(2);
+ });
+
+ it("deletes every picked-out card with Shift and Delete, in one call", async () => {
+ const board = await renderBoard();
+ pick(board, 0, 0);
+ pick(board, 0, 1);
+ focusCard(board, 0, 0);
+
+ press(board, "Delete", { shiftKey: true });
+
+ expect(branches.deleteNotes).toHaveBeenCalledWith(
+ [ branchOf(board, "First"), branchOf(board, "Second") ], false, false);
+ });
+
+ /**
+ * The card beside the focused one may be leaving with it, so focus walks past the cards on
+ * their way out rather than landing on one about to be drawn no more.
+ */
+ it("hands focus past the cards going with it", async () => {
+ const board = await renderBoard();
+ vi.spyOn(attributes, "removeOwnedLabelByName").mockReturnValue(true);
+ pick(board, 0, 0);
+ pick(board, 0, 1);
+ focusCard(board, 0, 0);
+
+ press(board, "Delete");
+
+ // Both cards of the column are going, so what is left to take focus is its button.
+ expect(document.activeElement?.classList.contains("board-new-item")).toBe(true);
+ });
+
+ /** A card the reader is standing on but has not picked out goes on its own. */
+ it("leaves a selection the focused card is no part of alone", async () => {
+ const board = await renderBoard();
+ const strip = vi.spyOn(attributes, "removeOwnedLabelByName").mockReturnValue(true);
+ const second = noteOf(board, "Second");
+ pick(board, 0, 1);
+ focusCard(board, 0, 0);
+
+ press(board, "Delete");
+ await settleWrites();
+
+ expect(strip).toHaveBeenCalledTimes(1);
+ expect(strip)
+ .not.toHaveBeenCalledWith(expect.objectContaining({ noteId: second }), "status");
+ });
+
it("takes the whole column off the board from its header, asking first", async () => {
const board = await renderBoard();
const strip = vi.spyOn(attributes, "removeOwnedLabelByName").mockReturnValue(true);
@@ -455,21 +520,214 @@ describe("Board keyboard", () => {
expect(focusedName(board)).toBe("First");
});
- it("moves a card up and down its own column", async () => {
+ it("sends every picked-out card to the next column, and leaves them picked out", async () => {
+ const board = await renderBoard();
+ const write = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ const first = noteOf(board, "First");
+ const second = noteOf(board, "Second");
+ pick(board, 0, 0);
+ pick(board, 0, 1);
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowRight", { ctrlKey: true });
+ await settleWrites();
+
+ expect(write).toHaveBeenCalledWith(first, "status", "Doing");
+ expect(write).toHaveBeenCalledWith(second, "status", "Doing");
+ // One placement for the set, against the card already at the end of that column.
+ expect(branches.moveAfterBranch).toHaveBeenCalledExactlyOnceWith(
+ [ branchOf(board, "First"), branchOf(board, "Second") ],
+ branchOf(board, "Third"));
+ expect(pickedNames(board)).toEqual([ "First", "Second" ]);
+ });
+
+ /**
+ * A move is two writes, the grouping value and the branch position, and each lands a redraw
+ * of its own. Drawn only by the first, the cards stand under their new column in the order
+ * their old branches give them, and are seen to reorder a moment later.
+ */
+ it("draws the cards where the move will leave them, before the writes land", async () => {
+ const board = await renderBoard();
+ // Never answered, so what the board shows is only what it has drawn for itself.
+ vi.spyOn(attributes, "setLabel").mockReturnValue(new Promise(() => {}));
+ pick(board, 0, 0);
+ pick(board, 0, 1);
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowRight", { ctrlKey: true });
+
+ // At the end of the column they join, after the card already standing there.
+ expect(namesIn(board, 1)).toEqual([ "Third", "First", "Second" ]);
+ expect(namesIn(board, 0)).toEqual([]);
+ });
+
+ /**
+ * The set lands at the end of the column it joins, so the last of them is what the board
+ * scrolls to: focus is what `reveal` follows, and the reader is left at the end of what
+ * they sent rather than above it.
+ */
+ it("leaves focus on the last card of the set it has sent", async () => {
+ const board = await renderBoard();
+ vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ const first = noteOf(board, "First");
+ const second = noteOf(board, "Second");
+ pick(board, 0, 0);
+ pick(board, 0, 1);
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowRight", { ctrlKey: true });
+ await settleWrites();
+
+ setStatus(first, "Doing");
+ setStatus(second, "Doing");
+ await redraw();
+
+ expect(focusedName(board)).toBe("Second");
+ });
+
+ /** Every card has a neighbour of its own, so there is no one column to send them all to. */
+ it("does nothing while the picked-out cards stand in several columns", async () => {
+ const board = await renderBoard();
+ const write = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ pick(board, 0, 0);
+ pick(board, 1, 0);
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowRight", { ctrlKey: true });
+ await settleWrites();
+
+ expect(write).not.toHaveBeenCalled();
+ expect(pickedNames(board)).toEqual([ "First", "Third" ]);
+ });
+
+ /**
+ * A move takes nothing away, so a selection the focused card is no part of is left where it
+ * stands rather than given up as deleting gives it up.
+ */
+ it("sends a card that is not picked out on its own", async () => {
+ const board = await renderBoard();
+ const write = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ pick(board, 0, 1);
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowRight", { ctrlKey: true });
+ await settleWrites();
+
+ expect(write).toHaveBeenCalledExactlyOnceWith(noteOf(board, "First"), "status", "Doing");
+ expect(pickedNames(board)).toEqual([ "Second" ]);
+ });
+
+ it("moves a card up its own column", async () => {
const board = await renderBoard();
focusCard(board, 0, 1);
press(board, "ArrowUp", { ctrlKey: true });
+
expect(branches.moveBeforeBranch)
.toHaveBeenCalledWith([ branchOf(board, "Second") ], branchOf(board, "First"));
+ });
+ /**
+ * A board of its own: the board draws a move as soon as it is asked for, so one press
+ * moves the cards the next press is counted against.
+ */
+ it("moves a card down its own column", async () => {
+ const board = await renderBoard();
focusCard(board, 0, 0);
+
press(board, "ArrowDown", { ctrlKey: true });
+
// Placed past the card below it, which is the last, so it goes after that one.
expect(branches.moveAfterBranch)
.toHaveBeenCalledWith([ branchOf(board, "First") ], branchOf(board, "Second"));
});
+ /** A column of four, so a run of two has cards both above and below it. */
+ const deepColumn = () => renderBoard(undefined, undefined, [ "To Do", "To Do" ]);
+
+ it("moves a run of picked-out cards up and down as one", async () => {
+ const board = await deepColumn();
+ pick(board, 0, 0);
+ pick(board, 0, 1);
+ focusCard(board, 0, 0);
+
+ // Already at the head, so there is nowhere above for the run to go.
+ press(board, "ArrowUp", { ctrlKey: true });
+ expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
+ expect(branches.moveAfterBranch).not.toHaveBeenCalled();
+
+ // The whole run passes the card below it, in one call and in its own order.
+ press(board, "ArrowDown", { ctrlKey: true });
+ expect(branches.moveBeforeBranch).toHaveBeenCalledExactlyOnceWith(
+ [ branchOf(board, "First"), branchOf(board, "Second") ],
+ branchOf(board, "Fifth"));
+ });
+
+ it("sends a run of picked-out cards to either end of its column", async () => {
+ const board = await deepColumn();
+ pick(board, 0, 1);
+ pick(board, 0, 2);
+ focusCard(board, 0, 1);
+
+ press(board, "End", { ctrlKey: true });
+ expect(branches.moveAfterBranch).toHaveBeenCalledExactlyOnceWith(
+ [ branchOf(board, "Second"), branchOf(board, "Fourth") ],
+ branchOf(board, "Fifth"));
+
+ press(board, "Home", { ctrlKey: true });
+ expect(branches.moveBeforeBranch).toHaveBeenCalledExactlyOnceWith(
+ [ branchOf(board, "Second"), branchOf(board, "Fourth") ],
+ branchOf(board, "First"));
+ });
+
+ /**
+ * A run is placed one branch at a time, each write landing a redraw of its own, so the
+ * cards would be seen shuffling into place one after another.
+ */
+ it("draws a run where the move leaves it, before the writes land", async () => {
+ const board = await deepColumn();
+ // Never answered, so what the board shows is only what it has drawn for itself.
+ vi.mocked(branches.moveBeforeBranch).mockReturnValue(new Promise(() => {}));
+ pick(board, 0, 0);
+ pick(board, 0, 1);
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowDown", { ctrlKey: true });
+
+ expect(namesIn(board, 0)).toEqual([ "Fourth", "First", "Second", "Fifth" ]);
+ });
+
+ /**
+ * Cards with others of their own column between them have no one place to be moved to, and
+ * a selection reaching into another column has no single order to keep.
+ */
+ it("moves nothing for picked-out cards that do not stand together", async () => {
+ const board = await deepColumn();
+ pick(board, 0, 0);
+ pick(board, 0, 2);
+ focusCard(board, 0, 0);
+
+ for (const key of [ "ArrowDown", "ArrowUp", "Home", "End" ]) {
+ press(board, key, { ctrlKey: true });
+ }
+
+ expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
+ expect(branches.moveAfterBranch).not.toHaveBeenCalled();
+ });
+
+ it("moves nothing up or down while the cards stand in several columns", async () => {
+ const board = await deepColumn();
+ pick(board, 0, 0);
+ pick(board, 1, 0);
+ focusCard(board, 0, 0);
+
+ press(board, "ArrowDown", { ctrlKey: true });
+ press(board, "End", { ctrlKey: true });
+
+ expect(branches.moveBeforeBranch).not.toHaveBeenCalled();
+ expect(branches.moveAfterBranch).not.toHaveBeenCalled();
+ });
+
/** A sorted column decides its own order, so there is nowhere for a card to be sent. */
it("does not move a card up or down inside a sorted column", async () => {
const board = await renderBoard(undefined, "title");
@@ -856,6 +1114,37 @@ describe("Board keyboard", () => {
.querySelectorAll<HTMLElement>(".board-note")[item].focus();
}
+ /**
+ * Lets a fan-out finish. The cards are written one after another, each awaiting the one before
+ * it, so a single turn of the microtask queue reaches only the first of them.
+ */
+ async function settleWrites() {
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+ }
+
+ /** Picks a card out the way Ctrl and a click do. */
+ function pick(board: HTMLElement, column: number, item: number) {
+ const card = board.querySelectorAll(".board-column")[column]
+ .querySelectorAll<HTMLElement>(".board-note")[item];
+ act(() => {
+ card.dispatchEvent(new MouseEvent(
+ "click", { bubbles: true, cancelable: true, detail: 1, ctrlKey: true }));
+ });
+ }
+
+ /** The cards of one column, by title, in the order the board draws them. */
+ function namesIn(board: HTMLElement, column: number) {
+ return [ ...board.querySelectorAll(".board-column")[column]
+ .querySelectorAll(".board-note") ]
+ .map((card) => card.querySelector(".title")?.textContent?.trim());
+ }
+
+ /** The cards picked out, by title, in the order the board draws them. */
+ function pickedNames(board: HTMLElement) {
+ return [ ...board.querySelectorAll(".board-note.selected") ]
+ .map((card) => card.querySelector(".title")?.textContent?.trim());
+ }
+
function focusButton(board: HTMLElement, column: number) {
board.querySelectorAll(".board-column")[column]
.querySelector<HTMLElement>(".board-new-item")?.focus();
@@ -874,8 +1163,13 @@ describe("Board keyboard", () => {
let boardNote: ReturnType<typeof buildNote>;
- /** Two columns of cards, one empty column, and the button that adds another. */
- async function renderBoard(collapsed?: string, orderBy?: string) {
+ /**
+ * Two columns of cards, one empty column, and the button that adds another.
+ *
+ * @param extra the cards to add beyond the three, each named by the column it stands in. Only
+ * the tests about moving a run of them need a column deep enough to hold one.
+ */
+ async function renderBoard(collapsed?: string, orderBy?: string, extra: string[] = []) {
boardNote = buildNote({
title: "Board",
"#collection": "",
@@ -883,7 +1177,9 @@ describe("Board keyboard", () => {
children: [
{ title: "First", "#status": "To Do" },
{ title: "Second", "#status": "To Do" },
- { title: "Third", "#status": "Doing" }
+ { title: "Third", "#status": "Doing" },
+ ...extra.map((status, at) => (
+ { title: [ "Fourth", "Fifth", "Sixth" ][at], "#status": status }))
]
});
diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.ts
index c30fd9f66f..4d2a3cca2c 100644
--- a/apps/client/src/widgets/collections/board/keyboard.ts
+++ b/apps/client/src/widgets/collections/board/keyboard.ts
@@ -6,7 +6,7 @@ import branches from "../../../services/branches";
import { FLIP_SETTLE_MS } from "../../react/flip";
import { SelectionStore } from "../../react/selection";
import BoardApi from "./api";
-import { ColumnMap } from "./data";
+import { ColumnItem, ColumnMap } from "./data";
/** Sideways, and with Ctrl, these carry the focused card the whole way rather than one column. */
const CARD_END_KEYS = [ "ArrowLeft", "ArrowRight" ];
@@ -73,6 +73,17 @@ export interface BoardKeyboardOptions {
setActiveColumn: (column: string) => void;
/** Which cards are picked out, which Ctrl+A fills with the focused column. */
selection: SelectionStore;
+ /**
+ * Sends cards to the end of another column, drawing them there while the writes are made. The
+ * board draws the outcome itself, so a move's two writes are not two redraws.
+ */
+ sendCardsToColumn: (
+ cards: { noteId: string, branchId: string }[], targetColumn: string
+ ) => Promise<unknown>;
+ /** As {@link sendCardsToColumn}, for a move to a place among the cards already in a column. */
+ moveCardsWithin: (
+ cards: { noteId: string, branchId: string }[], column: string, index: number
+ ) => Promise<unknown>;
}
/**
@@ -91,7 +102,8 @@ export interface BoardKeyboardOptions {
* would otherwise be left focused on nothing.
*/
export function useBoardKeyboard({
- containerRef, columns, byColumn, api, moveColumn, insertColumn, setActiveColumn, selection
+ containerRef, columns, byColumn, api, moveColumn, insertColumn, setActiveColumn, selection,
+ sendCardsToColumn, moveCardsWithin
}: BoardKeyboardOptions) {
const pendingFocus = useRef<PendingFocus | null>(null);
@@ -202,11 +214,25 @@ export function useBoardKeyboard({
}
const moved = move(
- spot, e.key, { columns, byColumn, api, setActiveColumn }, e.shiftKey);
+ spot,
+ e.key,
+ {
+ columns, byColumn, api, setActiveColumn, selection, sendCardsToColumn,
+ moveCardsWithin
+ },
+ e.shiftKey);
if (moved) {
const pending: PendingFocus = { intent: moved.intent };
pendingFocus.current = pending;
+ // Taken now rather than left to the redraw, which gives the intent up when focus
+ // rests anywhere but where it names: a set of cards is sent from one of its own
+ // members, and the card it names is another of them. Scrolling is left to
+ // `reveal`, which waits for the card to stop moving.
+ if ("noteId" in moved.intent) {
+ findCard(container, moved.intent.noteId)?.focus({ preventScroll: true });
+ }
+
// Nothing is going to arrive, so focus is not held for it any longer.
moved.done.catch(() => {
if (pendingFocus.current === pending) {
@@ -291,33 +317,53 @@ export function useBoardKeyboard({
if (!item) return;
take(e);
+ // The whole selection while the focused card belongs to it, and that card alone
+ // otherwise, which is the question the card's own menu answers the same way.
+ if (!selection.has(item.note.noteId)) {
+ selection.clear();
+ }
+ const selected = api.getCards(selection.keys);
+ const going = selected.length ? selected : [ item ];
+
// Straight away rather than through `pendingFocus`, which waits for a redraw: until the
// card goes, focus is still on it, and a redraw arriving first would read that as the
- // reader having chosen where to be and let the intent go.
- neighbourOf(container, columns, byColumn, spot)?.focus();
+ // reader having chosen where to be and let the intent go. The cards on their way out
+ // are passed over, since focus would land on one about to be drawn no more.
+ neighbourOf(container, columns, byColumn, spot,
+ new Set(going.map((card) => card.note.noteId)))?.focus();
if (e.shiftKey) {
- // The note itself, with the confirmation deleting one anywhere else asks for.
- branches.deleteNotes([ item.branch.branchId ], false, false);
+ // The notes themselves, with the confirmation deleting one anywhere else asks for.
+ branches.deleteNotes(going.map((card) => card.branch.branchId), false, false);
} else {
- api.removeFromBoard(item.note.noteId);
+ void api.removeFromBoard(going.map((card) => card.note.noteId));
}
}
- }, [ containerRef, columns, byColumn, api, moveColumn, insertColumn, setActiveColumn ]);
+ }, [
+ containerRef, columns, byColumn, api, moveColumn, insertColumn, setActiveColumn, selection
+ ]);
return { onKeyDown, focusColumn, focusCard };
}
-/** What to put focus on once a card goes: the one under it, the one over it, or the column. */
+/**
+ * What to put focus on once a card goes: the one under it, the one over it, or the column.
+ *
+ * @param going the cards leaving with it, which are passed over: a whole selection can be deleted
+ * at once, and the card beside the focused one may be on its way out too.
+ */
function neighbourOf(
container: HTMLElement,
columns: string[],
byColumn: ColumnMap | undefined,
- spot: Extract<Spot, { kind: "item" }>
+ spot: Extract<Spot, { kind: "item" }>,
+ going: ReadonlySet<string> = new Set()
) {
const column = columns[spot.column];
const items = byColumn?.get(column) ?? [];
- const next = items[spot.item + 1] ?? items[spot.item - 1];
+ const stays = (item: ColumnItem) => !going.has(item.note.noteId);
+ const next = items.slice(spot.item + 1).find(stays)
+ ?? items.slice(0, spot.item).findLast(stays);
return next
? findCard(container, next.note.noteId)
@@ -447,8 +493,10 @@ function entryOf(container: HTMLElement, column: number): Spot {
function move(
spot: Spot,
key: string,
- { columns, byColumn, api, setActiveColumn }:
- Pick<BoardKeyboardOptions, "columns" | "byColumn" | "api" | "setActiveColumn">,
+ { columns, byColumn, api, setActiveColumn, selection, sendCardsToColumn, moveCardsWithin }:
+ Pick<BoardKeyboardOptions,
+ "columns" | "byColumn" | "api" | "setActiveColumn" | "selection"
+ | "sendCardsToColumn" | "moveCardsWithin">,
/** Whether the card goes the whole way rather than one place. */
toEnd = false
): { intent: FocusIntent; done: Promise<unknown> } | false {
@@ -458,7 +506,16 @@ function move(
const column = columns[spot.column];
const items = byColumn?.get(column) ?? [];
const { noteId } = item.note;
- const { branchId } = item.branch;
+
+ // The whole selection while the focused card belongs to it, and that card alone otherwise.
+ // A move leaves a selection the card is no part of standing: nothing is lost by it, and a key
+ // that only reorders should not also undo what the reader has picked out.
+ const selected = api.getCards(selection.keys);
+ const moving = selection.has(noteId) && selected.length ? selected : [ item ];
+ const carried = moving.map((card) => ({
+ noteId: card.note.noteId,
+ branchId: card.branch.branchId
+ }));
if (key === "ArrowLeft" || key === "ArrowRight") {
const target = toEnd
@@ -467,26 +524,51 @@ function move(
// Only the whole way can ask for the column a card already stands in.
if (!target || target === column) return false;
- // The card is drawn under the column it lands in, so a collapsed one has to open first for
- // there to be anything to focus.
+ // A selection standing in several columns is left alone: each card has a neighbour of its
+ // own, and sending them all to one column is not what the key means anywhere else.
+ if (moving.some((card) => api.getCardColumn(card.note.noteId) !== column)) {
+ return false;
+ }
+
+ // The cards are drawn under the column they land in, so a collapsed one has to open first
+ // for there to be anything to focus.
setActiveColumn(target);
- return { intent: { noteId }, done: api.moveToColumnEnd(noteId, branchId, target) };
+ // The last of them, which is the one that lands furthest down the column it joins: focus
+ // is what the board scrolls to, so this is what makes the end of the set visible. For one
+ // card it is that card, as it has always been.
+ const arrived = moving.at(-1) ?? item;
+
+ return {
+ intent: { noteId: arrived.note.noteId },
+ done: sendCardsToColumn(carried, target)
+ };
+ }
+
+ // Where the cards stand in the column, which they can only be reordered as one if they stand
+ // together in it. A selection reaching into another column, or one with cards between its own,
+ // has no single place to be moved to and the key is answered with nothing.
+ const places = moving.map((card) =>
+ items.findIndex((candidate) => candidate.note.noteId === card.note.noteId));
+ const start = Math.min(...places);
+ const end = Math.max(...places);
+ if (places.some((place) => place < 0) || end - start !== places.length - 1) {
+ return false;
}
const last = items.length - 1;
- // A card is placed before a position too, so moving one down means passing the one below it.
- const to = key === "ArrowUp" && spot.item > 0 ? spot.item - 1
- : key === "ArrowDown" && spot.item < last ? spot.item + 2
- : key === "Home" && spot.item > 0 ? 0
- : key === "End" && spot.item < last ? items.length
+ // A card is placed before a position too, so moving down means passing the one below the run.
+ const to = key === "ArrowUp" && start > 0 ? start - 1
+ : key === "ArrowDown" && end < last ? end + 2
+ : key === "Home" && start > 0 ? 0
+ : key === "End" && end < last ? items.length
: null;
if (to === null) return false;
return {
intent: { noteId },
- done: api.moveWithinBoard(noteId, branchId, spot.item, to, column, column)
+ done: moveCardsWithin(carried, column, to)
};
}