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: implement a reusable multi-note selection utility
Adorian Doranee4d11e0e460
diff --git a/apps/client/src/menus/context_menu_utils.ts b/apps/client/src/menus/context_menu_utils.tsindex 68c09bacc7..9a8043888e 100644--- a/apps/client/src/menus/context_menu_utils.ts+++ b/apps/client/src/menus/context_menu_utils.ts@@ -1,24 +1,32 @@+import type FNote from "../entities/fnote"+import type { MenuItem } from "./context_menu"import { t } from "../services/i18n"-import attributes from "../services/attributes"-import FNote from "../entities/fnote"+import { setArchivedOnNotes, shared } from "../services/note_set"import { escapeHtml } from "../services/utils"-export function getArchiveMenuItem(note: FNote) {- if (!note.isArchived) {- return {- title: t("board_view.archive-note"),- uiIcon: "bx bx-archive",- handler: () => attributes.addLabel(note.noteId, "archived")- }- } else {- return {+/**+ * The entry that archives the notes, or unarchives them when they are all archived already.+ *+ * Returns nothing where the notes disagree: one entry cannot say what picking it would do, and+ * both entries at once would read as two states the same notes are in.+ */+export function getArchiveMenuItems<T>(notes: FNote[]): MenuItem<T>[] {+ const state = shared(notes, (note) => note.isArchived)+ if (!state.agreed) {+ return []+ }++ return [ state.value+ ? {title: t("board_view.unarchive-note"),uiIcon: "bx bx-archive-out",- handler: async () => {- attributes.removeOwnedLabelByName(note, "archived")- }+ handler: () => { void setArchivedOnNotes(notes, false) }}- }+ : {+ title: t("board_view.archive-note"),+ uiIcon: "bx bx-archive",+ handler: () => { void setArchivedOnNotes(notes, true) }+ } ]}/**diff --git a/apps/client/src/services/note_set.spec.ts b/apps/client/src/services/note_set.spec.tsnew file mode 100644index 0000000000..482c119d01--- /dev/null+++ b/apps/client/src/services/note_set.spec.ts@@ -0,0 +1,124 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import { buildNote } from "../test/easy-froca";+import froca from "./froca";+import {+ clearLabelOnNotes, setArchivedOnNotes, setLabelOnNotes, shared+} from "./note_set";++// The writes alone, so the rest of the service reads a note the way the application does. Both+// shapes are replaced: `note_set` calls one of these by name and the others off the default export.+const writes = vi.hoisted(() => ({+ setLabelValues: vi.fn(),+ addLabel: vi.fn(),+ removeOwnedLabelByName: vi.fn()+}));+vi.mock("./attributes", async (importOriginal) => {+ const original = await importOriginal<{ default: object }>();+ return { ...original, ...writes, default: { ...original.default, ...writes } };+});++beforeEach(() => vi.clearAllMocks());++describe("shared", () => {+ it("answers with the value every note holds", () => {+ const notes = [+ buildNote({ title: "One", "#state": "Doing" }),+ buildNote({ title: "Two", "#state": "Doing" })+ ];++ expect(shared(notes, (note) => note.getLabelValue("state")))+ .toEqual({ agreed: true, value: "Doing" });+ });++ it("answers with nothing where the notes disagree", () => {+ const notes = [+ buildNote({ title: "One", "#state": "Doing" }),+ buildNote({ title: "Two", "#state": "Done" })+ ];++ expect(shared(notes, (note) => note.getLabelValue("state"))).toEqual({ agreed: false });+ });++ /**+ * Every note being unset is something they agree on, which a menu marks, and is not the same+ * answer as notes holding different values.+ */+ it("counts every note holding none as an agreement", () => {+ const notes = [ buildNote({ title: "One" }), buildNote({ title: "Two" }) ];++ expect(shared(notes, (note) => note.getLabelValue("state")))+ .toEqual({ agreed: true, value: null });+ });++ it("answers with nothing for no notes at all", () => {+ expect(shared([], (note) => note.title)).toEqual({ agreed: false });+ });++ it("reads whatever the caller asks for, not only labels", () => {+ const notes = [+ buildNote({ title: "One", "#archived": "" }),+ buildNote({ title: "Two", "#archived": "" })+ ];++ expect(shared(notes, (note) => note.isArchived)).toEqual({ agreed: true, value: true });+ });+});++describe("writing to a set of notes", () => {+ it("sets the label on every one of them", async () => {+ const first = buildNote({ title: "One" });+ const second = buildNote({ title: "Two", "#state": "Done" });++ await setLabelOnNotes([ first, second ], "state", "Doing");++ expect(writes.setLabelValues).toHaveBeenCalledWith(first, "state", [ "Doing" ]);+ expect(writes.setLabelValues).toHaveBeenCalledWith(second, "state", [ "Doing" ]);+ });++ it("takes the label off every one of them", async () => {+ const first = buildNote({ title: "One", "#state": "Doing" });+ const second = buildNote({ title: "Two", "#state": "Done" });++ await clearLabelOnNotes([ first, second ], "state");++ expect(writes.setLabelValues).toHaveBeenCalledWith(first, "state", []);+ expect(writes.setLabelValues).toHaveBeenCalledWith(second, "state", []);+ });++ /**+ * Only the labels a note owns are removed, so a note with nothing of its own would keep what it+ * inherits. An empty label of its own overrides it.+ */+ it("shadows an inherited value rather than removing nothing", async () => {+ const parent = buildNote({+ title: "Parent",+ "#state(inheritable)": "Doing",+ children: [ { title: "Card" } ]+ });+ const child = froca.notes[parent.getChildNoteIds()[0]];+ if (!child) throw new Error("expected the card to be built");++ await clearLabelOnNotes([ child ], "state");++ expect(writes.setLabelValues).toHaveBeenCalledWith(child, "state", [ "" ]);+ });++ it("archives the notes that are not archived already", async () => {+ const plain = buildNote({ title: "One" });+ const archived = buildNote({ title: "Two", "#archived": "" });++ await setArchivedOnNotes([ plain, archived ], true);++ expect(writes.addLabel).toHaveBeenCalledExactlyOnceWith(plain.noteId, "archived");+ });++ it("unarchives the notes that are archived", async () => {+ const plain = buildNote({ title: "One" });+ const archived = buildNote({ title: "Two", "#archived": "" });++ await setArchivedOnNotes([ plain, archived ], false);++ expect(writes.removeOwnedLabelByName).toHaveBeenCalledExactlyOnceWith(archived, "archived");+ });+});diff --git a/apps/client/src/services/note_set.ts b/apps/client/src/services/note_set.tsnew file mode 100644index 0000000000..329e198586--- /dev/null+++ b/apps/client/src/services/note_set.ts@@ -0,0 +1,71 @@+import type FNote from "../entities/fnote";+import attributes, { setLabelValues } from "./attributes";++/**+ * What a set of notes holds in common: one value they all agree on, or nothing.+ *+ * Kept apart from a plain `T | undefined` because the two answers are different: every note being+ * unset is an agreement, and a menu marks it, while notes that disagree mark nothing at all.+ */+export type Shared<T> = { agreed: true, value: T } | { agreed: false };++/**+ * Reads one thing off every note and reports what they agree on.+ *+ * Takes a reader rather than a property name, so the same function answers for a label, a flag or+ * anything else an `FNote` can be asked. An empty set agrees on nothing.+ */+export function shared<T>(notes: FNote[], read: (note: FNote) => T): Shared<T> {+ if (!notes.length) {+ return { agreed: false };+ }++ const value = read(notes[0]);+ return notes.every((note) => read(note) === value)+ ? { agreed: true, value }+ : { agreed: false };+}++/**+ * 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+ * `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.+ */+export async function setLabelOnNotes(notes: FNote[], name: string, value: string) {+ for (const note of notes) {+ await setLabelValues(note, name, [ value ]);+ }+}++/**+ * Takes a label off every note.+ *+ * `setLabelValues` removes only the labels a note owns, so an inherited value would still apply.+ * Such a note is given an empty label of its own instead, which is what an unset promoted field+ * holds and what `renderLabelValue` draws as nothing.+ */+export async function clearLabelOnNotes(notes: FNote[], name: string) {+ for (const note of notes) {+ const isInherited = note.getAttributes("label", name)+ .some((attribute) => attribute.noteId !== note.noteId);+ await 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");+ }+ }+}diff --git a/apps/client/src/widgets/collections/attribute_menu.spec.ts b/apps/client/src/widgets/collections/attribute_menu.spec.tsindex 94d75d11fb..7083b4358d 100644--- a/apps/client/src/widgets/collections/attribute_menu.spec.ts+++ b/apps/client/src/widgets/collections/attribute_menu.spec.ts@@ -62,7 +62,7 @@ describe("buildAttributeMenuItems", () => {it("is marked while the item carries it, and turned off when picked", () => {const note = buildNote({ title: "Card", "#done": "true" });- const items = buildAttributeMenuItems<string>({ note, attributes: flag });+ const items = buildAttributeMenuItems<string>({ notes: [ note ], attributes: flag });expect(items[1]).toMatchObject({ trailingIcon: "bx bx-check" });pick(items[1]);@@ -71,19 +71,43 @@ describe("buildAttributeMenuItems", () => {it("is unmarked while the item does not, and turned on when picked", () => {const note = buildNote({ title: "Card" });- const items = buildAttributeMenuItems<string>({ note, attributes: flag });+ const items = buildAttributeMenuItems<string>({ notes: [ note ], attributes: flag });expect(items[1]).toMatchObject({ trailingIcon: undefined });pick(items[1]);expect(writes.setLabelValues).toHaveBeenCalledWith(note, "done", [ "true" ]);});+ it("is marked only while every selected item carries it", () => {+ const set = buildNote({ title: "One", "#done": "true" });+ const unset = buildNote({ title: "Two" });++ expect(buildAttributeMenuItems<string>({ notes: [ set, unset ], attributes: flag })[1])+ .toMatchObject({ trailingIcon: undefined });+ expect(buildAttributeMenuItems<string>({+ notes: [ set, buildNote({ title: "Three", "#done": "true" }) ], attributes: flag+ })[1]).toMatchObject({ trailingIcon: "bx bx-check" });+ });++ it("writes the value to every selected item, settling a disagreement", async () => {+ const set = buildNote({ title: "One", "#done": "true" });+ const unset = buildNote({ title: "Two" });++ await pick(+ buildAttributeMenuItems<string>({ notes: [ set, unset ], attributes: flag })[1]);++ expect(writes.setLabelValues).toHaveBeenCalledWith(set, "done", [ "true" ]);+ expect(writes.setLabelValues).toHaveBeenCalledWith(unset, "done", [ "true" ]);+ });+// The stored values are the checkbox's own, so the entry says what the item draws: a box// the user unchecked holds "false", and anything else was never set through the field.it("counts every value but true as unset", () => {for (const value of [ "false", "", "yes" ]) {const note = buildNote({ title: "Card", "#done": value });- const items = buildAttributeMenuItems<string>({ note, attributes: flag });+ const items = buildAttributeMenuItems<string>({+ notes: [ note ], attributes: flag+ });expect(items[1]).toMatchObject({ trailingIcon: undefined });}@@ -99,8 +123,8 @@ describe("buildAttributeMenuItems", () => {}) ];/** The entries a state's submenu offers, the caller having none of its own to add. */- function options(note: FNote) {- const items = buildAttributeMenuItems<string>({ note, attributes: state });+ function options(...notes: FNote[]) {+ const items = buildAttributeMenuItems<string>({ notes, attributes: state });const entry = items[1];if (!entry || !("items" in entry)) throw new Error("expected a submenu");return entry.items ?? [];@@ -144,6 +168,35 @@ describe("buildAttributeMenuItems", () => {expect(writes.setLabelValues).toHaveBeenCalledWith(note, "state", []);});+ it("marks the option only while every selected item holds it", () => {+ const doing = buildNote({ title: "One", "#state": "Doing" });++ expect(marked(options(doing, buildNote({ title: "Two", "#state": "Doing" }))))+ .toEqual([ `<span class="tn-menu-name">Doing</span>` ]);+ expect(marked(options(doing, buildNote({ title: "Two", "#state": "Done" }))))+ .toEqual([]);+ expect(marked(options(doing, buildNote({ title: "Two" })))).toEqual([]);+ });++ it("marks Not set only while every selected item holds none", () => {+ const unset = buildNote({ title: "One" });++ expect(marked(options(unset, buildNote({ title: "Two" }))))+ .toEqual([ `<span class="tn-menu-name">attribute_menu.not-set</span>` ]);+ expect(marked(options(unset, buildNote({ title: "Two", "#state": "Doing" }))))+ .toEqual([]);+ });++ it("writes the option picked to every selected item", async () => {+ const first = buildNote({ title: "One" });+ const second = buildNote({ title: "Two", "#state": "Done" });++ await pick(options(first, second)[2]);++ expect(writes.setLabelValues).toHaveBeenCalledWith(first, "state", [ "Doing" ]);+ expect(writes.setLabelValues).toHaveBeenCalledWith(second, "state", [ "Doing" ]);+ });+/*** Only the labels a note owns are removed, so a note with nothing of its own would keep the* value it inherits. An empty label of its own overrides it.@@ -182,7 +235,7 @@ function build(attributes: PromotedAttribute[],title?: string) {- return buildAttributeMenuItems<string>({ note: buildNote(note), attributes, title });+ return buildAttributeMenuItems<string>({ notes: [ buildNote(note) ], attributes, title });}function attribute(fields: Partial<PromotedAttribute> & { name: string }): PromotedAttribute {@@ -206,7 +259,8 @@ const marked = (items: MenuItem<string>[]) => items.filter(item => "trailingIcon" in item && item.trailingIcon).map(item => ("title" in item ? item.title : ""));+/** Runs an entry's handler and hands back what it returns, so a caller can wait for its writes. */function pick(item: MenuItem<string> | undefined) {if (!item || !("handler" in item)) throw new Error("expected a menu entry");- item.handler?.(item as MenuCommandItem<string>, {} as never);+ return item.handler?.(item as MenuCommandItem<string>, {} as never);}diff --git a/apps/client/src/widgets/collections/attribute_menu.ts b/apps/client/src/widgets/collections/attribute_menu.tsindex 38bbdea0ad..1159338757 100644--- a/apps/client/src/widgets/collections/attribute_menu.ts+++ b/apps/client/src/widgets/collections/attribute_menu.ts@@ -1,8 +1,8 @@import type FNote from "../../entities/fnote";import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";import { menuName } from "../../menus/context_menu_utils";-import { setLabelValues } from "../../services/attributes";import { t } from "../../services/i18n";+import { clearLabelOnNotes, setLabelOnNotes, shared } from "../../services/note_set";import { promotedAttributeIcon } from "../attribute_widgets/attribute_types";import type { PromotedAttribute } from "./promoted_attributes";@@ -14,8 +14,12 @@ const TRUE = "true";const FALSE = "false";export interface AttributeMenuOptions {- /** The item whose values the entries read and write. */- note: FNote;+ /**+ * The items whose values the entries read and write. One note for a menu opened on a single+ * item, every selected note for a menu opened on a selection: an entry is marked only where+ * they all hold the same value, and picking one writes it to each of them.+ */+ notes: FNote[];/** The attributes the collection shows on its items, in the order it shows them. */attributes: PromotedAttribute[];/** What the section is called. "Attributes" unless the caller names it. */@@ -34,7 +38,7 @@ export interface AttributeMenuOptions {* checking for an empty section.*/export function buildAttributeMenuItems<T>({- note, attributes, title+ notes, attributes, title}: AttributeMenuOptions): MenuItem<T>[] {const items = attributes.flatMap<MenuItem<T>>((attribute) => {if (attribute.hidden || attribute.type !== "label") {@@ -42,12 +46,12 @@ export function buildAttributeMenuItems<T>({}if (attribute.labelType === "boolean") {- return [ buildBooleanItem<T>(note, attribute) ];+ return [ buildBooleanItem<T>(notes, attribute) ];}// A select without options is skipped: its submenu would hold "Not set" alone.if (attribute.labelType === "select" && attribute.selectOptions?.length) {- return [ buildSelectItem<T>(note, attribute, attribute.selectOptions) ];+ return [ buildSelectItem<T>(notes, attribute, attribute.selectOptions) ];}return [];@@ -66,27 +70,32 @@ export function buildAttributeMenuItems<T>({* Read and written as `"true"` and `"false"`, the values the field's own checkbox stores, so the* entry says what the item draws. A value stored any other way counts as unset, as it does on the* item.+ *+ * Notes that disagree leave the entry unmarked, and picking it sets them all, which is the only+ * move that ends with them agreeing.*/-function buildBooleanItem<T>(note: FNote, attribute: PromotedAttribute): MenuCommandItem<T> {- const isSet = note.getLabelValue(attribute.name) === TRUE;+function buildBooleanItem<T>(notes: FNote[], attribute: PromotedAttribute): MenuCommandItem<T> {+ const state = shared(notes, (note) => note.getLabelValue(attribute.name) === TRUE);+ const isSet = state.agreed && state.value;return {...attributeEntry<T>(attribute),trailingIcon: isSet ? CHECK : undefined,handler: () => {- void setLabelValues(note, attribute.name, [ isSet ? FALSE : TRUE ]);+ void setLabelOnNotes(notes, attribute.name, isSet ? FALSE : TRUE);}};}/*** A `select`, its options in a submenu in the order the definition lists them, with the value the- * item holds marked. A value the definition no longer lists marks nothing.+ * item holds marked. A value the definition no longer lists marks nothing, and so do notes holding+ * different values.*/function buildSelectItem<T>(- note: FNote, attribute: PromotedAttribute, options: string[]+ notes: FNote[], attribute: PromotedAttribute, options: string[]): MenuCommandItem<T> {- const current = note.getLabelValue(attribute.name);+ const current = shared(notes, (note) => note.getLabelValue(attribute.name));return {...attributeEntry<T>(attribute),@@ -97,32 +106,18 @@ function buildSelectItem<T>(// Boxed like the options: a menu row is a flex line, so a bare title keeps the// space that separates it from the icon and renders as indented.title: menuName(t("attribute_menu.not-set")),- trailingIcon: current ? undefined : CHECK,- handler: () => { void clearValue(note, attribute.name); }+ trailingIcon: current.agreed && !current.value ? CHECK : undefined,+ handler: () => { void clearLabelOnNotes(notes, attribute.name); }},...options.map<MenuItem<T>>((option) => ({title: menuName(option),- trailingIcon: option === current ? CHECK : undefined,- handler: () => { void setLabelValues(note, attribute.name, [ option ]); }+ trailingIcon: current.agreed && current.value === option ? CHECK : undefined,+ handler: () => { void setLabelOnNotes(notes, attribute.name, option); }}))]};}-/**- * Takes the value off the note.- *- * `setLabelValues` removes only the labels the note owns, so an inherited value would still apply.- * The note is given an empty label of its own instead, which is what an unset promoted field holds- * and what `renderLabelValue` draws as nothing.- */-function clearValue(note: FNote, name: string) {- const isInherited = note.getAttributes("label", name)- .some((attribute) => attribute.noteId !== note.noteId);-- return setLabelValues(note, name, isInherited ? [ "" ] : []);-}-/** What every entry carries: the attribute's display name, under the icon of its type. */function attributeEntry<T>(attribute: PromotedAttribute): MenuCommandItem<T> {return {diff --git a/apps/client/src/widgets/collections/calendar/context_menu.ts b/apps/client/src/widgets/collections/calendar/context_menu.tsindex 8c3511c363..a2d43036ab 100644--- a/apps/client/src/widgets/collections/calendar/context_menu.ts+++ b/apps/client/src/widgets/collections/calendar/context_menu.ts@@ -1,6 +1,7 @@+import type { CommandNames } from "../../../components/app_context";import FNote from "../../../entities/fnote";import contextMenu, { ContextMenuEvent } from "../../../menus/context_menu";-import { getArchiveMenuItem } from "../../../menus/context_menu_utils";+import { getArchiveMenuItems } from "../../../menus/context_menu_utils";import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker";import link_context_menu from "../../../menus/link_context_menu";import branches from "../../../services/branches";@@ -16,7 +17,7 @@ export function openCalendarContextMenu(e: ContextMenuEvent, note: FNote, parentitems: [...link_context_menu.getItems(e),{ kind: "separator" },- getArchiveMenuItem(note),+ ...getArchiveMenuItems<CommandNames>([ note ]),{title: t("calendar_view.delete_note"),uiIcon: "bx bx-trash",diff --git a/apps/client/src/widgets/react/selection.spec.tsx b/apps/client/src/widgets/react/selection.spec.tsxnew file mode 100644index 0000000000..c40092cd76--- /dev/null+++ b/apps/client/src/widgets/react/selection.spec.tsx@@ -0,0 +1,198 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { SelectionContext, SelectionStore, useIsSelected, useSelectionCount } from "./selection";++const ITEMS = [ "a", "b", "c", "d", "e" ];++describe("SelectionStore", () => {+ let store: SelectionStore;++ beforeEach(() => {+ store = new SelectionStore();+ });++ const selected = () => [ ...store.keys ];++ it("starts holding nothing", () => {+ expect(selected()).toEqual([]);+ expect(store.size).toBe(0);+ expect(store.anchor).toBeNull();+ expect(store.has("a")).toBe(false);+ });++ it("adds and removes one item at a time, keeping the rest", () => {+ store.toggle("b");+ store.toggle("d");+ expect(selected()).toEqual([ "b", "d" ]);++ store.toggle("b");+ expect(selected()).toEqual([ "d" ]);+ expect(store.has("b")).toBe(false);+ });++ it("takes one item on its own, dropping what was picked before", () => {+ store.toggle("b");+ store.toggle("d");+ store.selectOnly("a");++ expect(selected()).toEqual([ "a" ]);+ expect(store.anchor).toBe("a");+ });++ it("gives up everything at once", () => {+ store.toggle("b");+ store.clear();++ expect(selected()).toEqual([]);+ expect(store.anchor).toBeNull();+ });++ describe("a range", () => {+ it("covers everything between the anchor and the item picked, either way round", () => {+ store.toggle("b");+ store.selectRange(ITEMS, "d");+ expect(selected()).toEqual([ "b", "c", "d" ]);++ store.selectRange(ITEMS, "a");+ expect(selected()).toEqual([ "a", "b" ]);+ });++ it("replaces what was picked rather than adding to it", () => {+ store.toggle("a");+ store.toggle("e");+ // The anchor moved to `e` with the second pick, so the range runs from there.+ store.selectRange(ITEMS, "c");++ expect(selected()).toEqual([ "c", "d", "e" ]);+ });++ it("leaves the anchor where it stands, so a second range moves one end", () => {+ store.toggle("b");+ store.selectRange(ITEMS, "e");+ store.selectRange(ITEMS, "c");++ expect(store.anchor).toBe("b");+ expect(selected()).toEqual([ "b", "c" ]);+ });++ it("takes the item alone where there is no anchor to measure from", () => {+ store.selectRange(ITEMS, "c");++ expect(selected()).toEqual([ "c" ]);+ expect(store.anchor).toBe("c");+ });++ /**+ * The caller decides what a range can cover, which is one column of a board. An anchor set+ * in another column is not in the list, and the press takes the item it landed on alone.+ */+ it("takes the item alone where the anchor stands outside the list", () => {+ store.toggle("elsewhere");+ store.selectRange(ITEMS, "c");++ expect(selected()).toEqual([ "c" ]);+ expect(store.anchor).toBe("c");+ });++ it("does nothing at all for an item the list does not hold", () => {+ store.toggle("b");+ store.selectRange(ITEMS, "gone");++ expect(selected()).toEqual([ "b" ]);+ });+ });++ describe("pruning", () => {+ it("drops what the collection no longer holds and keeps the rest", () => {+ store.toggle("a");+ store.toggle("b");+ store.toggle("c");++ store.retain(new Set([ "a", "c", "z" ]));+ expect(selected()).toEqual([ "a", "c" ]);+ });++ it("gives the anchor up with the item it named", () => {+ store.toggle("a");+ store.toggle("b");++ store.retain(new Set([ "a" ]));+ expect(store.anchor).toBeNull();++ store.toggle("a");+ store.retain(new Set([ "a" ]));+ expect(store.anchor).toBe("a");+ });+ });+});++describe("what a change wakes", () => {+ let container: HTMLElement;+ let store: SelectionStore;+ let renders: Record<string, number>;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ store = new SelectionStore();+ renders = {};+ act(() => {+ render(+ <SelectionContext.Provider value={store}>+ {ITEMS.map((key) => <Watcher key={key} item={key} />)}+ <Counter />+ </SelectionContext.Provider>,+ container);+ });+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ it("answers each item about itself alone", () => {+ act(() => store.toggle("b"));++ expect(read("a")).toBe("-");+ expect(read("b")).toBe("selected");+ expect(count()).toBe("1");+ });++ it("wakes the item picked and the one dropped, and no others", () => {+ act(() => store.toggle("b"));+ const afterFirst = { ...renders };++ act(() => store.selectOnly("e"));+ expect(drawnSince(afterFirst)).toEqual([ "b", "e" ]);++ // Picking what is already picked changes nothing, so nothing is drawn again.+ const afterSecond = { ...renders };+ act(() => store.selectOnly("e"));+ expect(drawnSince(afterSecond)).toEqual([]);+ });++ function read(item: string) {+ return container.querySelector(`[data-item="${item}"]`)?.textContent;+ }++ function count() {+ return container.querySelector("[data-count]")?.textContent;+ }++ function drawnSince(before: Record<string, number>) {+ return ITEMS.filter((item) => renders[item] !== before[item]);+ }++ function Watcher({ item }: { item: string }) {+ renders[item] = (renders[item] ?? 0) + 1;+ const isSelected = useIsSelected(item);+ return <div data-item={item}>{isSelected ? "selected" : "-"}</div>;+ }++ function Counter() {+ return <div data-count>{useSelectionCount()}</div>;+ }+});diff --git a/apps/client/src/widgets/react/selection.ts b/apps/client/src/widgets/react/selection.tsnew file mode 100644index 0000000000..9af79f62b4--- /dev/null+++ b/apps/client/src/widgets/react/selection.ts@@ -0,0 +1,150 @@+import { createContext } from "preact";+import { useSyncExternalStore } from "preact/compat";+import { useCallback, useContext } from "preact/hooks";++/**+ * Which items a collection has selected, held outside component state.+ *+ * Kept in a store rather than in state so that a change wakes only the items whose own answer+ * changed. A board holds hundreds of cards, and selecting one must not redraw the rest.+ *+ * The keys are opaque strings the collection chooses. A board selects by `noteId`; another+ * collection can select by whatever identifies one of its rows.+ */+export class SelectionStore {+ private selected: ReadonlySet<string> = new Set();+ private anchorKey: string | null = null;+ private listeners = new Set<() => void>();++ /** The selected keys, which keep one identity until the selection changes. */+ get keys() {+ return this.selected;+ }++ /** Where a range starts, which is the item last picked without Shift. */+ get anchor() {+ return this.anchorKey;+ }++ get size() {+ return this.selected.size;+ }++ has(key: string) {+ return this.selected.has(key);+ }++ /** Selects one item on its own, dropping whatever else was selected. */+ selectOnly(key: string) {+ this.anchorKey = key;+ this.replace(new Set([ key ]));+ }++ /** Adds or removes one item, keeping the rest. Ctrl+Click does this. */+ toggle(key: string) {+ const next = new Set(this.selected);+ if (!next.delete(key)) {+ next.add(key);+ }++ this.anchorKey = key;+ this.replace(next);+ }++ /**+ * Selects everything between the anchor and `to`, dropping whatever else was selected.+ *+ * The anchor stays where it was, so a second Shift+Click grows or shrinks the same range+ * rather than starting a new one.+ *+ * @param ordered the items a range can cover, in the order they are drawn. The caller decides+ * what that list holds, so a board passes one column and a range never crosses into another.+ * @param to the item that was clicked.+ */+ selectRange(ordered: string[], to: string) {+ const end = ordered.indexOf(to);+ if (end < 0) {+ return;+ }++ // No anchor yet, or one standing outside `ordered`, such as a card in another column.+ const start = this.anchorKey === null ? -1 : ordered.indexOf(this.anchorKey);+ if (start < 0) {+ this.selectOnly(to);+ return;+ }++ this.replace(new Set(ordered.slice(Math.min(start, end), Math.max(start, end) + 1)));+ }++ clear() {+ this.anchorKey = null;+ this.replace(new Set());+ }++ /**+ * Drops the keys `present` does not list, for items that have left the collection.+ *+ * Called when the collection redraws: a note deleted, archived out of view or moved off the+ * board must leave the selection, or a later command acts on an item that is no longer there.+ */+ retain(present: ReadonlySet<string>) {+ if ([ ...this.selected ].every((key) => present.has(key))) {+ return;+ }++ const kept = new Set([ ...this.selected ].filter((key) => present.has(key)));+ if (this.anchorKey !== null && !kept.has(this.anchorKey)) {+ this.anchorKey = null;+ }++ this.replace(kept);+ }++ subscribe(listener: () => void) {+ this.listeners.add(listener);+ return () => { this.listeners.delete(listener); };+ }++ /** Announces the new set, and only when it differs, so an unchanged pick redraws nothing. */+ private replace(next: ReadonlySet<string>) {+ if (next.size === this.selected.size+ && [ ...next ].every((key) => this.selected.has(key))) {+ return;+ }++ this.selected = next;+ for (const listener of [ ...this.listeners ]) {+ listener();+ }+ }+}++/* v8 ignore next -- a collection always provides its own; this is what lets a consumer read it+ with a plain useContext(), with no guard for a provider that is structurally always there. */+export const SelectionContext = createContext(new SelectionStore());++/** The store itself, for the handlers that change the selection. */+export function useSelection() {+ return useContext(SelectionContext);+}++/** Whether one item is selected. Redraws that item alone when its own answer changes. */+export function useIsSelected(key: string) {+ const store = useSelection();++ return useSyncExternalStore(+ useCallback((listener: () => void) => store.subscribe(listener), [ store ]),+ useCallback(() => store.has(key), [ store, key ])+ );+}++/** How many items are selected, for the components that report the size of a selection. */+export function useSelectionCount() {+ const store = useSelection();++ return useSyncExternalStore(+ useCallback((listener: () => void) => store.subscribe(listener), [ store ]),+ useCallback(() => store.size, [ store ])+ );+}