Skip to content

Build your personal knowledge base with Trilium Notes

client/ui: implement a card with sortable items

Adorian Doran551445c4bd4c
diff --git a/apps/client/src/services/frontend_script_api_preact.ts b/apps/client/src/services/frontend_script_api_preact.ts
index de0f711251..03d3e6d05d 100644
--- a/apps/client/src/services/frontend_script_api_preact.ts
+++ b/apps/client/src/services/frontend_script_api_preact.ts
@@ -30,6 +30,7 @@ import NoteAutocomplete from "../widgets/react/NoteAutocomplete";
import NoteLink from "../widgets/react/NoteLink";
import RawHtml from "../widgets/react/RawHtml";
import Slider from "../widgets/react/Slider";
+import { SortableCard } from "../widgets/react/SortableCard";
import RightPanelWidget from "../widgets/sidebar/RightPanelWidget";
export interface WidgetDefinition {
@@ -100,6 +101,7 @@ export const preactAPI = Object.freeze({
NoteLink,
RawHtml,
Slider,
+ SortableCard,
Table,
// Specialized widgets
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index ed956caa6a..a4478e0f24 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2523,6 +2523,10 @@
"built-in-templates": "Built-in templates",
"selector-save": "Save"
},
+ "sortable_card": {
+ "add": "Add item",
+ "reorder": "Drag to reorder"
+ },
"protect_note": {
"toggle-on": "Protect the note",
"toggle-off": "Unprotect the note",
diff --git a/apps/client/src/widgets/react/SortableCard.css b/apps/client/src/widgets/react/SortableCard.css
new file mode 100644
index 0000000000..1980ff591d
--- /dev/null
+++ b/apps/client/src/widgets/react/SortableCard.css
@@ -0,0 +1,119 @@
+:where(:root) {
+ --sortable-grip-color: var(--muted-text-color);
+ --sortable-grip-hover-color: var(--main-text-color);
+ --sortable-selected-color: var(--main-text-color);
+ --sortable-dragging-shadow: 2px 4px 8px rgba(0, 0, 0, 0.2);
+ /* Enough to read as held rather than filed, without losing what it says. */
+ --sortable-dragging-opacity: 0.85;
+}
+
+.tn-card.tn-sortable-card {
+ .tn-sortable-list {
+ display: flex;
+ /* The carried segment is placed against this, so it must be what `offsetTop` is read from. */
+ position: relative;
+ flex-direction: column;
+ gap: var(--card-section-gap);
+ }
+
+ .tn-sortable-segment {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ /* What `useFlip` turns into a slide: it puts a segment back where it was for one frame and
+ lets this carry it to where it now stands. 200ms matches FLIP_DURATION_MS. */
+ transition: transform 200ms ease;
+ }
+
+ .tn-sortable-segment:focus-visible {
+ outline: 2px solid var(--sortable-selected-color);
+ outline-offset: -2px;
+ }
+
+ /* Painted inside the segment's own box, so a selected segment takes no more room than the rest. */
+ .tn-sortable-selected {
+ box-shadow: inset 0 0 0 1px var(--sortable-selected-color);
+ }
+
+ .tn-sortable-content {
+ display: flex;
+ flex-grow: 1;
+ align-items: center;
+ gap: 0.5em;
+ min-width: 0;
+ }
+
+ .tn-sortable-caption {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .tn-sortable-grip {
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ padding: 0.2em 0.1em;
+ color: var(--sortable-grip-color);
+ cursor: grab;
+ /* The gesture is this element's own: without it a finger scrolls the page instead. */
+ touch-action: none;
+
+ & svg {
+ width: 1.1em;
+ height: 1.1em;
+ stroke: currentColor;
+ stroke-width: 1.5;
+ stroke-linecap: round;
+ }
+
+ &:hover {
+ color: var(--sortable-grip-hover-color);
+ }
+ }
+
+ /* Under the pointer rather than in the flow: it follows the finger, and the transition the other
+ segments slide by would drag it a frame behind. */
+ .tn-sortable-dragging {
+ z-index: 1;
+ box-shadow: var(--sortable-dragging-shadow);
+ opacity: var(--sortable-dragging-opacity);
+ transition: none;
+
+ & .tn-sortable-grip {
+ cursor: grabbing;
+ }
+ }
+
+ .tn-sortable-add {
+ display: flex;
+ align-items: center;
+ gap: 0.3em;
+ color: var(--muted-text-color);
+ cursor: pointer;
+
+ &:hover {
+ background-color: var(--card-background-hover-color);
+ color: var(--main-text-color);
+ }
+ }
+
+ .tn-sortable-appearing {
+ animation: tn-sortable-appear 400ms ease-out;
+ }
+}
+
+@keyframes tn-sortable-appear {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .tn-card.tn-sortable-card .tn-sortable-segment {
+ transition: none;
+ }
+
+ .tn-card.tn-sortable-card .tn-sortable-appearing {
+ animation: none;
+ }
+}
diff --git a/apps/client/src/widgets/react/SortableCard.spec.tsx b/apps/client/src/widgets/react/SortableCard.spec.tsx
new file mode 100644
index 0000000000..2c3f6d9803
--- /dev/null
+++ b/apps/client/src/widgets/react/SortableCard.spec.tsx
@@ -0,0 +1,636 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { SortableCard, type SortableItem } from "./SortableCard";
+
+// i18next is never initialised under test, so a stock label would be undefined and the segment it
+// stands in would read nothing at all.
+vi.mock("../../services/i18n", () => ({
+ t: (key: string) => key
+}));
+
+/** How tall every segment stands, and the gap between two of them, as the card is laid out. */
+const SEGMENT_HEIGHT = 40;
+const SEGMENT_GAP = 4;
+
+describe("SortableCard", () => {
+ let container: HTMLElement;
+ let items: SortableItem[];
+ let changed: SortableItem[][];
+
+ beforeEach(() => {
+ items = [
+ { key: "a", caption: "Alpha" },
+ { key: "b", caption: "Beta" },
+ { key: "c", caption: "Gamma" }
+ ];
+ changed = [];
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ it("reads its entries in order, with the card's own heading and sentence", () => {
+ draw();
+
+ expect(container.querySelector(".tn-card-heading")?.textContent).toContain("Order");
+ expect(container.querySelector(".tn-card-description")?.textContent)
+ .toBe("Put them as you like.");
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
+ // Every segment answers for itself, so any of them can be reached and moved by keyboard.
+ expect(segments().every((segment) => segment.tabIndex === 0)).toBe(true);
+ });
+
+ /** The slot, for a card that shows more of an entry than its name. */
+ it("draws each entry with what the caller gives it", () => {
+ draw({ renderItem: (item, index) => <b>{`${index}:${item.key}`}</b> });
+
+ expect(segments().map((segment) => segment.querySelector("b")?.textContent))
+ .toEqual([ "0:a", "1:b", "2:c" ]);
+ });
+
+ describe("moving with the keyboard", () => {
+ it("moves an entry one place, and reports the whole list in its new order", () => {
+ draw();
+
+ press(segments()[0], "ArrowDown", { ctrlKey: true });
+
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "b", "a", "c" ]);
+ expect(captions()).toEqual([ "Beta", "Alpha", "Gamma" ]);
+ // The reader is left standing on the entry they moved, not on the place it left.
+ expect(document.activeElement).toBe(segmentOf("a"));
+ });
+
+ it("sends an entry to either end", () => {
+ draw();
+
+ press(segments()[2], "Home", { ctrlKey: true });
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "c", "a", "b" ]);
+
+ press(segmentOf("c"), "End", { ctrlKey: true });
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c" ]);
+ });
+
+ /** There is nowhere past the ends, and a key that changes nothing is left to the page. */
+ it("leaves an entry at the end where it is", () => {
+ draw();
+ const atTop = segments()[0];
+
+ press(atTop, "ArrowUp", { ctrlKey: true });
+ press(atTop, "Home", { ctrlKey: true });
+ press(segments()[2], "End", { ctrlKey: true });
+ press(segments()[2], "ArrowDown", { ctrlKey: true });
+
+ expect(changed).toEqual([]);
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
+ });
+
+ it("steps between entries without Control, moving nothing", () => {
+ draw();
+
+ // Nothing stands below the last entry on a card that cannot be added to.
+ focus(segments()[2]);
+ press(segments()[2], "ArrowDown");
+ expect(document.activeElement).toBe(segmentOf("c"));
+
+ press(segments()[0], "ArrowDown");
+ expect(document.activeElement).toBe(segmentOf("b"));
+
+ press(segmentOf("b"), "End");
+ expect(document.activeElement).toBe(segmentOf("c"));
+
+ press(segmentOf("c"), "Home");
+ expect(document.activeElement).toBe(segmentOf("a"));
+
+ expect(changed).toEqual([]);
+ });
+ });
+
+ describe("selection", () => {
+ it("selects the entry the reader reaches, and says which it is", () => {
+ const onSelect = vi.fn();
+ draw({ onSelect });
+
+ focus(segmentOf("b"));
+
+ expect(onSelect).toHaveBeenLastCalledWith("b");
+ expect(segmentOf("b")?.className).toContain("tn-sortable-selected");
+ expect(segmentOf("b")?.getAttribute("aria-current")).toBe("true");
+ expect(segmentOf("a")?.className).not.toContain("tn-sortable-selected");
+ });
+
+ it("follows the selection the caller keeps", () => {
+ draw({ selectedKey: "c" });
+
+ expect(segmentOf("c")?.className).toContain("tn-sortable-selected");
+
+ // What the reader does is reported; what is drawn stays the caller's to decide.
+ focus(segmentOf("a"));
+ expect(segmentOf("c")?.className).toContain("tn-sortable-selected");
+ expect(segmentOf("a")?.className).not.toContain("tn-sortable-selected");
+ });
+ });
+
+ describe("carrying a segment", () => {
+ it("is carried by its grip alone, which says so while it is held", () => {
+ draw();
+
+ grab(segmentOf("a"));
+
+ expect(segmentOf("a")?.className).toContain("tn-sortable-dragging");
+ expect(captured).toEqual([ 1 ]);
+
+ drop();
+ expect(segmentOf("a")?.className).not.toContain("tn-sortable-dragging");
+ });
+
+ it("puts the entry where it was carried, and reports it once", () => {
+ draw();
+
+ grab(segmentOf("a"));
+ // Past the middle of the second segment, which is what it changes places with.
+ moveTo(SEGMENT_HEIGHT + SEGMENT_GAP + 1);
+
+ expect(captions()).toEqual([ "Beta", "Alpha", "Gamma" ]);
+ // Nothing is reported until it lands: a carry across the card is one change, not one
+ // for every segment it passes.
+ expect(changed).toEqual([]);
+
+ drop();
+ expect(changed.map((order) => order.map((item) => item.key)))
+ .toEqual([ [ "b", "a", "c" ] ]);
+ });
+
+ /**
+ * A segment gives way as the carried one's foot passes its middle, which is what puts the
+ * last place within reach: the carried segment can be held no lower than that place, so
+ * middle against middle it would have to reach a place it cannot be carried to.
+ */
+ it("takes the last place as its foot passes the middle of the last segment", () => {
+ draw();
+ const last = SEGMENT_HEIGHT * 2 + SEGMENT_GAP * 2;
+
+ grab(segmentOf("a"));
+ // Short of the last place by half a segment, and just past the middle of the one
+ // standing in it.
+ moveTo(last - SEGMENT_HEIGHT / 2 + 1);
+
+ expect(captions()).toEqual([ "Beta", "Gamma", "Alpha" ]);
+ });
+
+ /** And the other way about: the head passing a middle is what sends a segment above it. */
+ it("takes the first place as its head passes the middle of the first segment", () => {
+ draw();
+
+ grab(segmentOf("c"));
+ moveTo(SEGMENT_HEIGHT / 2 - 1);
+
+ expect(captions()).toEqual([ "Gamma", "Alpha", "Beta" ]);
+ });
+
+ it("carries an entry the whole way down, and back", () => {
+ draw();
+
+ grab(segmentOf("a"));
+ moveTo(500);
+ expect(captions()).toEqual([ "Beta", "Gamma", "Alpha" ]);
+
+ moveTo(-500);
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
+
+ drop();
+ // Back where it started, so there is nothing to report.
+ expect(changed).toEqual([]);
+ });
+
+ /** The segment is held inside the card, whatever the pointer does past its ends. */
+ it("carries it no further than the ends of the card", () => {
+ draw();
+ const carried = segmentOf("c");
+
+ grab(carried);
+ moveTo(-500);
+ expect(shift(carried)).toBe(0);
+
+ const [ first ] = segments();
+ grab(first, 0);
+ moveTo(500);
+ // The last place a segment can stand in: the room the list has, less its own height.
+ expect(shift(first)).toBe(listHeight() - SEGMENT_HEIGHT);
+ drop();
+ });
+
+ it("puts the order back when the carry is abandoned", () => {
+ draw();
+
+ grab(segmentOf("a"));
+ moveTo(500);
+ expect(captions()).toEqual([ "Beta", "Gamma", "Alpha" ]);
+
+ press(segmentOf("a"), "Escape");
+
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
+ expect(changed).toEqual([]);
+ expect(segmentOf("a")?.className).not.toContain("tn-sortable-dragging");
+ });
+
+ it("puts it back when the pointer is taken away from it", () => {
+ draw();
+
+ grab(segmentOf("a"));
+ moveTo(500);
+ act(() => { list()?.dispatchEvent(pointerEvent("pointercancel", 0)); });
+
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
+ expect(changed).toEqual([]);
+ });
+
+ /** A finger carries it the same way a mouse does, the grip answering for the gesture. */
+ it("is carried by a finger as well as by a pointer", () => {
+ draw();
+
+ grab(segmentOf("a"), 0, { pointerType: "touch", button: -1 });
+ moveTo(SEGMENT_HEIGHT + SEGMENT_GAP + 1, { pointerType: "touch" });
+
+ expect(captions()).toEqual([ "Beta", "Alpha", "Gamma" ]);
+ drop();
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "b", "a", "c" ]);
+ });
+
+ it("carries a card of one entry nowhere, and says nothing about it", () => {
+ items = [ { key: "a", caption: "Alpha" } ];
+ draw();
+
+ grab(segmentOf("a"));
+ moveTo(500);
+ drop();
+
+ expect(captions()).toEqual([ "Alpha" ]);
+ expect(changed).toEqual([]);
+ });
+
+ /** A press that is not the primary button is somebody else's: a menu, most likely. */
+ it("is not carried by a right click", () => {
+ draw();
+
+ grab(segmentOf("a"), 0, { button: 2 });
+
+ expect(segmentOf("a")?.className).not.toContain("tn-sortable-dragging");
+ });
+ });
+
+ describe("adding an entry", () => {
+ it("draws no segment for adding unless it is given one", () => {
+ draw();
+ expect(container.querySelector(".tn-sortable-add")).toBeNull();
+
+ draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
+ expect(adder()?.textContent).toContain("sortable_card.add");
+ });
+
+ it("appends what the caller made, and shows it arriving", async () => {
+ const onAdd = vi.fn(() => ({ key: "d", caption: "Delta" }));
+ draw({ onAdd, addLabel: "Add a preference" });
+
+ expect(container.querySelector(".tn-sortable-add")?.textContent)
+ .toContain("Add a preference");
+
+ await click(adder());
+
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "d" ]);
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma", "Delta" ]);
+ expect(segmentOf("d")?.className).toContain("tn-sortable-appearing");
+ // The reader is left on the segment that adds, so another entry can follow.
+ expect(document.activeElement).not.toBe(segmentOf("d"));
+
+ // Shown once: the entry stays the one just made, and a redraw must not play it again.
+ act(() => {
+ segmentOf("d")?.dispatchEvent(
+ new AnimationEvent("animationend", { bubbles: true }));
+ });
+ expect(segmentOf("d")?.className).not.toContain("tn-sortable-appearing");
+ });
+
+ it("adds nothing where the caller answers with nothing, a picker being backed out of",
+ async () => {
+ draw({ onAdd: () => undefined });
+
+ await click(adder());
+
+ expect(changed).toEqual([]);
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
+ });
+
+ it("waits for a caller that asks the reader first", async () => {
+ let answer: (item: SortableItem | undefined) => void = () => {};
+ draw({ onAdd: () => new Promise((resolve) => { answer = resolve; }) });
+
+ await click(adder());
+ expect(changed).toEqual([]);
+
+ await act(async () => { answer({ key: "d", caption: "Delta" }); });
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "d" ]);
+ });
+
+ it("adds from the keyboard as well as from a press", async () => {
+ draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
+
+ press(adder(), "Enter");
+ await act(async () => {});
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "d" ]);
+
+ press(adder(), " ");
+ await act(async () => {});
+ expect(changed).toHaveLength(2);
+ });
+
+ /** Beside the entry the reader stands on, the way a spreadsheet adds a row. */
+ it("makes an entry below the focused one for Enter, and above it for Shift and Enter",
+ async () => {
+ let made = 0;
+ draw({ onAdd: () => ({ key: `d${++made}`, caption: `Delta ${made}` }) });
+
+ press(segmentOf("a"), "Enter");
+ await act(async () => {});
+ expect(captions()).toEqual([ "Alpha", "Delta 1", "Beta", "Gamma" ]);
+ expect(changed.at(-1)?.map((item) => item.key))
+ .toEqual([ "a", "d1", "b", "c" ]);
+
+ press(segmentOf("c"), "Enter", { shiftKey: true });
+ await act(async () => {});
+ expect(captions()).toEqual([ "Alpha", "Delta 1", "Beta", "Delta 2", "Gamma" ]);
+ });
+
+ it("leaves the reader standing on what it made, which is shown arriving", async () => {
+ draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
+
+ press(segmentOf("b"), "Enter");
+ await act(async () => {});
+
+ expect(document.activeElement).toBe(segmentOf("d"));
+ expect(segmentOf("d")?.className).toContain("tn-sortable-appearing");
+ });
+
+ it("makes nothing beside an entry where the card cannot be added to", async () => {
+ draw();
+
+ press(segmentOf("a"), "Enter");
+ await act(async () => {});
+
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
+ expect(changed).toEqual([]);
+ });
+
+ it("makes nothing beside an entry where the caller answers with nothing", async () => {
+ draw({ onAdd: () => undefined });
+
+ press(segmentOf("a"), "Enter");
+ await act(async () => {});
+
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
+ expect(changed).toEqual([]);
+ });
+
+ /**
+ * It is one of the places the reader stands, even though it holds no entry: stepping down
+ * from the last entry reaches it, and the keys that name an entry lead back into them.
+ */
+ it("is stepped onto and off again, like the entries above it", () => {
+ draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
+
+ expect(adder()?.tabIndex).toBe(0);
+
+ press(segmentOf("c"), "ArrowDown");
+ expect(document.activeElement).toBe(adder());
+
+ press(adder(), "ArrowUp");
+ expect(document.activeElement).toBe(segmentOf("c"));
+
+ press(adder(), "Home");
+ expect(document.activeElement).toBe(segmentOf("a"));
+
+ press(adder(), "End");
+ expect(document.activeElement).toBe(segmentOf("c"));
+ });
+
+ /** Nothing stands below it, and a card of no entries has nowhere to lead back to. */
+ it("goes nowhere from the segment that adds", () => {
+ draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
+
+ focus(adder());
+ press(adder(), "ArrowDown");
+ expect(document.activeElement).toBe(adder());
+
+ items = [];
+ draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
+ focus(adder());
+ press(adder(), "ArrowUp");
+ expect(document.activeElement).toBe(adder());
+ });
+
+ /** It stands at the foot of the card to be pressed, not to be put in order with the rest. */
+ it("leaves the segment for adding where it is", () => {
+ draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
+ expect(adder()?.querySelector(".tn-sortable-grip")).toBeNull();
+ expect(adder()?.getAttribute("role")).not.toBe("listitem");
+
+ press(adder(), "ArrowUp", { ctrlKey: true });
+ expect(changed).toEqual([]);
+ // Nor does a key meant for the entries carry the reader off it while Control is held.
+ expect(document.activeElement).not.toBe(segmentOf("c"));
+ });
+ });
+
+ it("carries the grip on the trailing edge of each segment, after what it reads", () => {
+ draw();
+ const [ first ] = segments();
+
+ expect(first.lastElementChild?.className).toContain("tn-sortable-grip");
+ expect(first.querySelector(".tn-sortable-grip svg line")).not.toBeNull();
+ // The keyboard answers for what the grip does, so it is not read out a second time.
+ expect(first.querySelector(".tn-sortable-grip")?.getAttribute("aria-hidden")).toBe("true");
+ });
+
+ /**
+ * The order is the caller's: what it hands back is what the card draws, so a caller that keeps
+ * the order elsewhere, or refuses a move, is drawn as it decides rather than as the card left
+ * things.
+ */
+ it("draws the order the caller answers with", () => {
+ draw();
+
+ press(segments()[0], "ArrowDown", { ctrlKey: true });
+ expect(captions()).toEqual([ "Beta", "Alpha", "Gamma" ]);
+
+ // The caller keeps the order it had, which is what the card is drawn from again.
+ redraw([ ...items ]);
+ expect(captions()).toEqual([ "Alpha", "Beta", "Gamma" ]);
+ });
+
+ // #region The card, and what the test does to it
+
+ let captured: number[];
+
+ function draw(props: Partial<Parameters<typeof SortableCard>[0]> = {}) {
+ if (container) {
+ render(null, container);
+ container.remove();
+ }
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ captured = [];
+
+ redraw(items, props);
+ }
+
+ function redraw(
+ order: SortableItem[], props: Partial<Parameters<typeof SortableCard>[0]> = {}
+ ) {
+ act(() => {
+ render(
+ <SortableCard
+ heading="Order"
+ description="Put them as you like."
+ items={order}
+ onChange={(next) => changed.push(next)}
+ {...props}
+ />,
+ container);
+ });
+
+ lay();
+ }
+
+ /**
+ * Tells the segments where they stand, which happy-dom lays nothing out to work out for itself.
+ *
+ * Answered from where a segment stands among its siblings at the moment it is asked, rather
+ * than from a number written once: the card reads these back the instant it has put a segment
+ * elsewhere, and a browser would have laid the list out again by then.
+ */
+ function lay() {
+ const element = list();
+ if (!element) {
+ return;
+ }
+
+ element.setPointerCapture = (pointerId: number) => { captured.push(pointerId); };
+ element.releasePointerCapture = () => {};
+ Object.defineProperty(element, "clientHeight", {
+ get: () => segments().length * (SEGMENT_HEIGHT + SEGMENT_GAP) - SEGMENT_GAP,
+ configurable: true
+ });
+
+ for (const segment of [ ...segments(), adder() ]) {
+ if (!segment) {
+ continue;
+ }
+
+ Object.defineProperty(segment, "offsetTop", {
+ get() {
+ const place = [ ...(this.parentElement?.children ?? []) ].indexOf(this);
+ return place * (SEGMENT_HEIGHT + SEGMENT_GAP);
+ },
+ configurable: true
+ });
+ Object.defineProperty(segment, "offsetHeight", {
+ get: () => SEGMENT_HEIGHT, configurable: true
+ });
+ }
+ }
+
+ function list() {
+ return container.querySelector<HTMLElement>(".tn-sortable-list");
+ }
+
+ function adder() {
+ return container.querySelector<HTMLElement>(".tn-sortable-add");
+ }
+
+ function segments() {
+ return [ ...container.querySelectorAll<HTMLElement>(".tn-sortable-segment") ];
+ }
+
+ function segmentOf(key: string) {
+ return container.querySelector<HTMLElement>(`.tn-sortable-segment[data-key="${key}"]`);
+ }
+
+ function captions() {
+ return segments().map((segment) => segment.textContent?.trim());
+ }
+
+ function listHeight() {
+ return list()?.clientHeight ?? 0;
+ }
+
+ /** How far a carried segment stands from where the list would otherwise have put it. */
+ function shift(segment: HTMLElement | null) {
+ const by = Number(/translateY\((-?[\d.]+)px\)/.exec(segment?.style.transform ?? "")?.[1]);
+ return (segment?.offsetTop ?? 0) + (Number.isNaN(by) ? 0 : by);
+ }
+
+ function grab(segment: HTMLElement | null, at = 0, options: Record<string, unknown> = {}) {
+ grabbedAt = at;
+ grabbedFrom = segment?.offsetTop ?? 0;
+ act(() => {
+ segment?.querySelector(".tn-sortable-grip")
+ ?.dispatchEvent(pointerEvent("pointerdown", at, options));
+ });
+ lay();
+ }
+
+ /** Carries the held segment until its head stands at `top`, wherever it was taken from. */
+ function moveTo(top: number, options: Record<string, unknown> = {}) {
+ act(() => {
+ list()?.dispatchEvent(
+ pointerEvent("pointermove", grabbedAt + (top - grabbedFrom), options));
+ });
+ lay();
+ }
+
+ function drop() {
+ act(() => { list()?.dispatchEvent(pointerEvent("pointerup", 0)); });
+ lay();
+ }
+
+ let grabbedAt = 0;
+ let grabbedFrom = 0;
+
+ function pointerEvent(type: string, clientY: number, options: Record<string, unknown> = {}) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ for (const [ name, value ] of Object.entries({
+ clientY, clientX: 0, pointerId: 1, button: 0, pointerType: "mouse", ...options
+ })) {
+ Object.defineProperty(event, name, { value, configurable: true });
+ }
+ return event;
+ }
+
+ function press(target: Element | null, key: string, options: KeyboardEventInit = {}) {
+ act(() => {
+ target?.dispatchEvent(
+ new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...options }));
+ });
+ lay();
+ }
+
+ function focus(target: HTMLElement | null) {
+ act(() => {
+ target?.focus();
+ target?.dispatchEvent(new FocusEvent("focus", { bubbles: false }));
+ });
+ }
+
+ async function click(target: HTMLElement | null) {
+ await act(async () => {
+ target?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ lay();
+ }
+
+ // #endregion
+});
diff --git a/apps/client/src/widgets/react/SortableCard.tsx b/apps/client/src/widgets/react/SortableCard.tsx
new file mode 100644
index 0000000000..d99eb52477
--- /dev/null
+++ b/apps/client/src/widgets/react/SortableCard.tsx
@@ -0,0 +1,465 @@
+import "./SortableCard.css";
+
+import clsx from "clsx";
+import { ComponentChildren } from "preact";
+import { flushSync } from "preact/compat";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
+
+import { t } from "../../services/i18n";
+import { Card, type CardProps } from "./Card";
+import { useFlip } from "./flip";
+import Icon from "./Icon";
+
+/** One entry of a {@link SortableCard}, named by a key that outlives the order it stands in. */
+export interface SortableItem {
+ key: string;
+ /** What the segment reads, for a card that draws its entries itself. */
+ caption?: ComponentChildren;
+ /** An icon class, `bx` prefix included, drawn before the caption. */
+ icon?: string;
+}
+
+export interface SortableCardProps<T extends SortableItem> extends CardProps {
+ /** The entries, in the order they stand. */
+ items: T[];
+ /** Said with the whole list in its new order, whenever the reader changes it. */
+ onChange: (items: T[]) => void;
+ /**
+ * Draws what stands inside a segment, for a card that shows more than a name. Without it the
+ * segment reads the item's own caption and icon.
+ */
+ renderItem?: (item: T, index: number) => ComponentChildren;
+ /**
+ * Makes the entry a segment at the foot of the card adds, which is drawn only when given.
+ *
+ * The caller decides what a new entry is, so it can ask with a dialog or a picker of its own;
+ * answering with nothing adds none. The entry is appended and opens out where it lands.
+ */
+ onAdd?: () => T | undefined | Promise<T | undefined>;
+ /** What the entry at the foot of the card reads. */
+ addLabel?: string;
+ /** The entry the reader is on, for a card whose selection the caller keeps. */
+ selectedKey?: string;
+ onSelect?: (key: string) => void;
+}
+
+/**
+ * A card whose segments the reader can put in any order.
+ *
+ * Each entry is one segment, carried by the grip on its trailing edge or moved with the keyboard,
+ * and the segments slide out of each other's way as it goes. A segment travels up and down only,
+ * and no further than the ends of the card it stands in.
+ *
+ * The order is the caller's: every change is reported through `onChange`, and the card draws
+ * whatever it is handed back. It knows nothing of what the entries mean, so the same card sorts a
+ * list of preferences, of columns, or of anything else named by a key.
+ */
+export function SortableCard<T extends SortableItem>({
+ items, onChange, renderItem, onAdd, addLabel, selectedKey, onSelect, className, ...card
+}: SortableCardProps<T>) {
+ const listRef = useRef<HTMLDivElement>(null);
+ const adderRef = useRef<HTMLElement>(null);
+ const dragRef = useRef<Drag<T>>();
+ /**
+ * The order while a segment is being carried, which the caller is told of once it lands.
+ *
+ * Kept until the caller answers with an order of its own, so the segments stay where they were
+ * put rather than springing back for the frames in between.
+ */
+ const [ draft, setDraft ] = useState<T[] | null>(null);
+ const [ draggedKey, setDraggedKey ] = useState<string>();
+ const [ ownSelection, setOwnSelection ] = useState<string>();
+ /** The entry just added, which opens out and fades in where it lands. */
+ const [ addedKey, setAddedKey ] = useState<string>();
+ /** Which segment takes focus once the card has been drawn again, a move having moved it. */
+ const pendingFocus = useRef<string>();
+
+ const shown = draft ?? items;
+ const selected = selectedKey ?? ownSelection;
+
+ useEffect(() => {
+ // The caller has answered, so the draft has served its purpose. Not while a segment is
+ // being carried: that order is still being decided.
+ if (!dragRef.current) {
+ setDraft(null);
+ }
+ }, [ items ]);
+
+ const segmentOf = useCallback(
+ (key: string) => listRef.current?.querySelector<HTMLElement>(`[data-key="${key}"]`), []);
+
+ // The carried segment is left out: it stands where the pointer holds it, and would otherwise be
+ // slid back to the place the list has made for it.
+ useFlip(listRef, {
+ selector: ".tn-sortable-segment:not(.tn-sortable-dragging)",
+ grow: (segment) => segment.dataset.key === addedKey
+ });
+
+ useLayoutEffect(() => {
+ const key = pendingFocus.current;
+ if (!key) {
+ return;
+ }
+
+ pendingFocus.current = undefined;
+ segmentOf(key)?.focus();
+ });
+
+ const select = useCallback((key: string) => {
+ setOwnSelection(key);
+ onSelect?.(key);
+ }, [ onSelect ]);
+
+ /** Stands the reader on an entry, wherever they were before it. */
+ const focusEntry = useCallback((index: number) => {
+ const key = shown[index]?.key;
+ if (!key) {
+ return;
+ }
+
+ pendingFocus.current = key;
+ select(key);
+ segmentOf(key)?.focus();
+ }, [ segmentOf, select, shown ]);
+
+ /** Puts the entry at `from` where `to` is, and leaves the reader standing on it. */
+ const moveItem = useCallback((from: number, to: number) => {
+ const order = moved(shown, from, to);
+ if (!order) {
+ return;
+ }
+
+ pendingFocus.current = shown[from].key;
+ setDraft(order);
+ onChange(order);
+ }, [ onChange, shown ]);
+
+ /** Ends the carry, keeping where the segment was put or putting the order back as it was. */
+ const endDrag = useCallback((keep: boolean) => {
+ const drag = dragRef.current;
+ if (!drag) {
+ return;
+ }
+
+ dragRef.current = undefined;
+ const segment = segmentOf(drag.key);
+ if (segment) {
+ segment.style.transform = "";
+ }
+
+ listRef.current?.releasePointerCapture?.(drag.pointerId);
+ setDraggedKey(undefined);
+ pendingFocus.current = drag.key;
+
+ if (!keep) {
+ setDraft(null);
+ return;
+ }
+
+ setDraft(drag.order);
+ if (drag.order.some((item, index) => item.key !== drag.was[index].key)) {
+ onChange(drag.order);
+ }
+ }, [ onChange, segmentOf ]);
+
+ const beginDrag = useCallback((event: PointerEvent, key: string) => {
+ const list = listRef.current;
+ const segment = segmentOf(key);
+ if (!list || !segment || (event.pointerType === "mouse" && event.button !== 0)) {
+ return;
+ }
+
+ // The gesture is the grip's alone: it must not also scroll the page under a finger, nor
+ // start a selection under a mouse.
+ event.preventDefault();
+ list.setPointerCapture?.(event.pointerId);
+
+ dragRef.current = {
+ key,
+ pointerId: event.pointerId,
+ grabbedAt: event.clientY,
+ from: segment.offsetTop,
+ height: segment.offsetHeight,
+ order: shown,
+ was: shown
+ };
+
+ setDraggedKey(key);
+ select(key);
+ segment.focus();
+ }, [ segmentOf, select, shown ]);
+
+ const dragTo = useCallback((clientY: number) => {
+ const drag = dragRef.current;
+ const list = listRef.current;
+ const segment = drag && segmentOf(drag.key);
+ if (!drag || !list || !segment) {
+ return;
+ }
+
+ // Held inside the card: the segment goes no higher than the first place and no lower than
+ // the last, whatever the pointer does past them.
+ const room = Math.max(0, list.clientHeight - drag.height);
+ const top = Math.min(Math.max(drag.from + (clientY - drag.grabbedAt), 0), room);
+
+ const order = orderFor(drag, segment, top, segmentOf);
+ if (order) {
+ drag.order = order;
+ // Drawn before the segment is placed, so it is placed against the room the list has
+ // just made for it rather than against the place it is leaving.
+ flushSync(() => setDraft(order));
+ }
+
+ segment.style.transform = `translateY(${top - segment.offsetTop}px)`;
+ }, [ segmentOf ]);
+
+ /**
+ * Makes an entry and puts it at `at`, or at the foot of the card where it is given no place.
+ *
+ * The reader is left standing on an entry made among the others, that being where they asked
+ * for it; one made at the foot leaves them on the segment that adds, so another can follow.
+ */
+ const add = useCallback(async (at?: number) => {
+ if (!onAdd) {
+ return;
+ }
+
+ const created = await onAdd();
+ if (!created) {
+ return;
+ }
+
+ const order = [ ...shown ];
+ order.splice(at ?? order.length, 0, created);
+ setAddedKey(created.key);
+ setDraft(order);
+ if (at !== undefined) {
+ pendingFocus.current = created.key;
+ }
+
+ onChange(order);
+ }, [ onAdd, onChange, shown ]);
+
+ const onSegmentKeyDown = useCallback((event: KeyboardEvent, index: number) => {
+ if (event.key === "Escape" && dragRef.current) {
+ event.preventDefault();
+ endDrag(false);
+ return;
+ }
+
+ // An entry is made beside the one the reader is standing on, the way a spreadsheet adds a
+ // row: below it, or above it with Shift. Only where the caller can make one at all.
+
+ if (event.key === "Enter" && onAdd && !event.ctrlKey && !event.metaKey) {
+ event.preventDefault();
+ add(event.shiftKey ? index : index + 1);
+ return;
+ }
+
+ const control = event.ctrlKey || event.metaKey;
+ const last = shown.length - 1;
+ const to = placeFor(event, index, last);
+
+ if (to === undefined) {
+ // Below the last entry stands the segment that adds another, which the reader steps
+ // onto rather than past. It holds no entry, so there is nothing to move onto it.
+ if (!control && event.key === "ArrowDown" && index === last && onAdd) {
+ event.preventDefault();
+ adderRef.current?.focus();
+ }
+
+ return;
+ }
+
+ event.preventDefault();
+ if (control) {
+ moveItem(index, to);
+ } else {
+ focusEntry(to);
+ }
+ }, [ add, endDrag, focusEntry, moveItem, onAdd, shown ]);
+
+ const onAddKeyDown = useCallback((event: KeyboardEvent) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ add();
+ return;
+ }
+
+ // Back up into the entries. Home and End name the first and last of them here as they do
+ // on an entry itself, this segment being one the reader stands on rather than one of them.
+ const control = event.ctrlKey || event.metaKey;
+ const to = control || !shown.length ? undefined : lastPlaceFor(event, shown.length - 1);
+ if (to === undefined) {
+ return;
+ }
+
+ event.preventDefault();
+ focusEntry(to);
+ }, [ add, focusEntry, shown ]);
+
+ return (
+ <Card className={clsx("tn-sortable-card", className)} {...card}>
+ <div
+ ref={listRef}
+ className="tn-sortable-list"
+ role="list"
+ onPointerMove={(event) => {
+ if (dragRef.current?.pointerId === event.pointerId) {
+ event.preventDefault();
+ dragTo(event.clientY);
+ }
+ }}
+ onPointerUp={() => endDrag(true)}
+ onPointerCancel={() => endDrag(false)}
+ >
+ {shown.map((item, index) => (
+ <section
+ key={item.key}
+ data-key={item.key}
+ role="listitem"
+ tabIndex={0}
+ aria-current={item.key === selected ? "true" : undefined}
+ className={clsx("tn-card-section tn-sortable-segment", {
+ "tn-sortable-dragging": item.key === draggedKey,
+ "tn-sortable-selected": item.key === selected,
+ "tn-sortable-appearing": item.key === addedKey
+ })}
+ onFocus={() => select(item.key)}
+ onKeyDown={(event) => onSegmentKeyDown(event, index)}
+ onAnimationEnd={() => setAddedKey(undefined)}
+ >
+ <span className="tn-sortable-content">
+ {renderItem
+ ? renderItem(item, index)
+ : <>
+ {item.icon && <Icon icon={item.icon} />}
+ <span className="tn-sortable-caption">{item.caption}</span>
+ </>}
+ </span>
+
+ <span
+ className="tn-sortable-grip"
+ title={t("sortable_card.reorder")}
+ aria-hidden="true"
+ onPointerDown={(event) => beginDrag(event, item.key)}
+ >
+ <svg viewBox="0 0 16 16">
+ <line x1="3" y1="6" x2="13" y2="6" />
+ <line x1="3" y1="10" x2="13" y2="10" />
+ </svg>
+ </span>
+ </section>
+ ))}
+
+ {onAdd && (
+ <section
+ ref={adderRef}
+ className="tn-card-section tn-sortable-add"
+ tabIndex={0}
+ onClick={() => add()}
+ onKeyDown={onAddKeyDown}
+ >
+ <Icon icon="bx bx-plus" />
+ <span>{addLabel ?? t("sortable_card.add")}</span>
+ </section>
+ )}
+ </div>
+ </Card>
+ );
+}
+
+/** A segment being carried: where it was taken from, and the order it has reached. */
+interface Drag<T extends SortableItem> {
+ key: string;
+ pointerId: number;
+ /** Where the pointer went down, against which everything after it is measured. */
+ grabbedAt: number;
+ /** Where the segment stood in the list when it was taken. */
+ from: number;
+ height: number;
+ /** The order as it now stands, which is what the caller is told of. */
+ order: T[];
+ /** The order it was taken from, against which a carry that changed nothing is told. */
+ was: T[];
+}
+
+/**
+ * Where the carried segment now belongs: after every segment it has covered the middle of.
+ *
+ * The others are measured where the list has them now rather than where they started, a segment
+ * sliding out of the way already being reported at the place it is sliding to.
+ *
+ * A segment gives way as the carried one's near edge passes its middle: the foot of the carried
+ * segment for one below, its head for one above. Measured by the middles alone, the carried
+ * segment would have to reach the very middle of the last place to take it, which is the one place
+ * it cannot be carried past, and the last place could not be reached at all.
+ */
+function orderFor<T extends SortableItem>(
+ drag: Drag<T>, carried: HTMLElement, top: number,
+ segmentOf: (key: string) => HTMLElement | null | undefined
+) {
+ const from = drag.order.findIndex((item) => item.key === drag.key);
+ let to = 0;
+
+ for (const item of drag.order) {
+ const segment = item.key !== drag.key && segmentOf(item.key);
+ if (!segment) {
+ continue;
+ }
+
+ const middle = segment.offsetTop + segment.offsetHeight / 2;
+ const isBelow = segment.offsetTop > carried.offsetTop;
+ if (isBelow ? middle < top + drag.height : middle <= top) {
+ to++;
+ }
+ }
+
+ return from === to ? undefined : moved(drag.order, from, to);
+}
+
+/** The list with one entry put elsewhere, or nothing where that would leave it as it stands. */
+function moved<T>(items: T[], from: number, to: number) {
+ const place = Math.min(Math.max(to, 0), items.length - 1);
+ if (from < 0 || from >= items.length || place === from) {
+ return undefined;
+ }
+
+ const order = [ ...items ];
+ order.splice(place, 0, ...order.splice(from, 1));
+ return order;
+}
+
+/** Which entry a key asks for from the segment standing below them all. */
+function lastPlaceFor(event: KeyboardEvent, last: number) {
+ switch (event.key) {
+ case "ArrowUp":
+ case "End":
+ return last;
+ case "Home":
+ return 0;
+ default:
+ return undefined;
+ }
+}
+
+/**
+ * Which place a key asks for, or nothing for a key the card leaves alone.
+ *
+ * The same keys move a segment and step between them, the difference being Control: the board's
+ * cards are moved this way too, so a reader who knows one knows the other.
+ */
+function placeFor(event: KeyboardEvent, index: number, last: number) {
+ switch (event.key) {
+ case "ArrowUp":
+ return index - 1 < 0 ? undefined : index - 1;
+ case "ArrowDown":
+ return index + 1 > last ? undefined : index + 1;
+ case "Home":
+ return index === 0 ? undefined : 0;
+ case "End":
+ return index === last ? undefined : last;
+ default:
+ return undefined;
+ }
+}
diff --git a/packages/commons/src/lib/script_api_preact.ts b/packages/commons/src/lib/script_api_preact.ts
index 584896b20e..37b7ef0420 100644
--- a/packages/commons/src/lib/script_api_preact.ts
+++ b/packages/commons/src/lib/script_api_preact.ts
@@ -396,6 +396,37 @@ interface SliderProps {
}
export declare const Slider: FunctionComponent<SliderProps>;
+/**
+ * A card whose segments the reader can put in any order, by carrying the grip on a segment or with
+ * the keyboard. The order is the caller's: every change is reported through `onChange`, and the
+ * card draws whatever it is handed back.
+ *
+ * `items` are named by a `key` that outlives the order they stand in; `renderItem` draws a segment
+ * for a card that shows more than a name, and `onAdd` puts a segment at the foot of the card that
+ * makes another entry, answering with nothing where the reader backs out.
+ */
+interface SortableItem {
+ key: string;
+ caption?: ComponentChildren;
+ icon?: string;
+}
+interface SortableCardProps<T extends SortableItem> {
+ items: T[];
+ onChange: (items: T[]) => void;
+ renderItem?: (item: T, index: number) => ComponentChildren;
+ onAdd?: () => T | undefined | Promise<T | undefined>;
+ addLabel?: string;
+ selectedKey?: string;
+ onSelect?: (key: string) => void;
+ heading?: string;
+ description?: ComponentChildren;
+ actions?: ComponentChildren;
+ className?: string;
+}
+// Generic, as the component itself is: the entries are the caller's own, so what `onChange` and
+// `renderItem` are handed is the caller's type and not what this card asks of it.
+export declare const SortableCard: <T extends SortableItem>(props: SortableCardProps<T>) => VNode;
+
/**
* Generic Tabulator-based data grid. The full Tabulator `Options` surface is loosened here (any option
* may be passed through); `data` is the row array, `columns` the column definitions, `modules` the