Skip to content

Build your personal knowledge base with Trilium Notes

client/ui/sortable card: add support for multiple item creation buttons

Adorian Doran3e2fcdf21d0e
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index a4478e0f24..b1b05a25b3 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2524,7 +2524,6 @@
"selector-save": "Save"
},
"sortable_card": {
- "add": "Add item",
"reorder": "Drag to reorder"
},
"protect_note": {
diff --git a/apps/client/src/widgets/react/SortableCard.css b/apps/client/src/widgets/react/SortableCard.css
index 6b1fbf3a45..5f4e0daa59 100644
--- a/apps/client/src/widgets/react/SortableCard.css
+++ b/apps/client/src/widgets/react/SortableCard.css
@@ -87,11 +87,29 @@
}
}
- .tn-sortable-add {
+ /* The row itself is painted with nothing: the gaps between the buttons are the card's parent
+ showing through, and each button carries what a segment is painted with. */
+ .tn-sortable-adders {
display: flex;
+ gap: var(--card-section-gap);
+ border: none;
+ padding: 0;
+ background: transparent;
+ }
+
+ /* All of one width, however many there are. */
+ .tn-sortable-adder {
+ display: flex;
+ flex: 1 1 0;
+ justify-content: center;
align-items: center;
gap: 0.3em;
+ min-width: 0;
+ border: 1px solid var(--card-border-color, var(--main-border-color));
+ padding: var(--card-padding-block) var(--card-padding-inline);
+ background: var(--card-background-color);
color: var(--muted-text-color);
+ font: inherit;
cursor: pointer;
&:hover {
@@ -100,6 +118,23 @@
}
}
+ /* The card's own corners are the row's to keep, and it is the buttons that are painted. */
+ .tn-sortable-adders:first-of-type .tn-sortable-adder:first-child {
+ border-start-start-radius: var(--card-border-radius);
+ }
+
+ .tn-sortable-adders:first-of-type .tn-sortable-adder:last-child {
+ border-start-end-radius: var(--card-border-radius);
+ }
+
+ .tn-sortable-adders:last-of-type .tn-sortable-adder:first-child {
+ border-end-start-radius: var(--card-border-radius);
+ }
+
+ .tn-sortable-adders:last-of-type .tn-sortable-adder:last-child {
+ border-end-end-radius: var(--card-border-radius);
+ }
+
.tn-sortable-appearing {
animation: tn-sortable-appear 400ms ease-out;
}
diff --git a/apps/client/src/widgets/react/SortableCard.spec.tsx b/apps/client/src/widgets/react/SortableCard.spec.tsx
index 2c3f6d9803..753c150927 100644
--- a/apps/client/src/widgets/react/SortableCard.spec.tsx
+++ b/apps/client/src/widgets/react/SortableCard.spec.tsx
@@ -285,18 +285,16 @@ describe("SortableCard", () => {
describe("adding an entry", () => {
it("draws no segment for adding unless it is given one", () => {
draw();
- expect(container.querySelector(".tn-sortable-add")).toBeNull();
+ expect(container.querySelector(".tn-sortable-adders")).toBeNull();
- draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
- expect(adder()?.textContent).toContain("sortable_card.add");
+ draw({ itemCreationButtons: [ makes("d", "Delta") ] });
+ expect(adder()?.textContent).toContain("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" });
+ draw({ itemCreationButtons: [ makes("d", "Delta", "Add a preference") ] });
- expect(container.querySelector(".tn-sortable-add")?.textContent)
- .toContain("Add a preference");
+ expect(adder()?.textContent).toContain("Add a preference");
await click(adder());
@@ -316,7 +314,7 @@ describe("SortableCard", () => {
it("adds nothing where the caller answers with nothing, a picker being backed out of",
async () => {
- draw({ onAdd: () => undefined });
+ draw({ itemCreationButtons: [ { label: "Add", onCreateItem: () => undefined } ] });
await click(adder());
@@ -326,7 +324,8 @@ describe("SortableCard", () => {
it("waits for a caller that asks the reader first", async () => {
let answer: (item: SortableItem | undefined) => void = () => {};
- draw({ onAdd: () => new Promise((resolve) => { answer = resolve; }) });
+ draw({ itemCreationButtons: [ { label: "Add", onCreateItem: () => new Promise(
+ (resolve) => { answer = resolve; }) } ] });
await click(adder());
expect(changed).toEqual([]);
@@ -335,23 +334,42 @@ describe("SortableCard", () => {
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" }) });
+ it("offers a button for each way of making one, each the width of the others", async () => {
+ draw({ itemCreationButtons: [
+ makes("d", "Delta", "Add a note"),
+ makes("e", "Epsilon", "Add a link"),
+ makes("f", "Zeta", "Add a folder")
+ ] });
- press(adder(), "Enter");
- await act(async () => {});
- expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "d" ]);
+ expect(adders().map((button) => button.textContent))
+ .toEqual([ "Add a note", "Add a link", "Add a folder" ]);
+ // Of one width, however many there are, which the row shares out between them.
+ expect(adders().every((button) => button.style.flex === "")).toBe(true);
- press(adder(), " ");
- await act(async () => {});
- expect(changed).toHaveLength(2);
+ await click(adders()[1]);
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "e" ]);
+
+ await click(adders()[2]);
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "e", "f" ]);
+ });
+
+ /** Three is as many as the foot of a card can read; a fourth is the caller's mistake. */
+ it("refuses more than three ways of making an entry", () => {
+ const buttons = [ makes("d", "D"), makes("e", "E"), makes("f", "F"), makes("g", "G") ];
+
+ expect(() => draw({ itemCreationButtons: buttons }))
+ .toThrow("Up to three item creation buttons are supported");
+ expect(() => draw({ itemCreationButtons: buttons.slice(0, 3) })).not.toThrow();
});
/** 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}` }) });
+ draw({ itemCreationButtons: [ {
+ label: "Add",
+ onCreateItem: () => ({ key: `d${++made}`, caption: `Delta ${made}` })
+ } ] });
press(segmentOf("a"), "Enter");
await act(async () => {});
@@ -365,7 +383,7 @@ describe("SortableCard", () => {
});
it("leaves the reader standing on what it made, which is shown arriving", async () => {
- draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
+ draw({ itemCreationButtons: [ makes("d", "Delta") ] });
press(segmentOf("b"), "Enter");
await act(async () => {});
@@ -385,7 +403,7 @@ describe("SortableCard", () => {
});
it("makes nothing beside an entry where the caller answers with nothing", async () => {
- draw({ onAdd: () => undefined });
+ draw({ itemCreationButtons: [ { label: "Add", onCreateItem: () => undefined } ] });
press(segmentOf("a"), "Enter");
await act(async () => {});
@@ -399,7 +417,7 @@ describe("SortableCard", () => {
* 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" }) });
+ draw({ itemCreationButtons: [ makes("d", "Delta") ] });
expect(adder()?.tabIndex).toBe(0);
@@ -418,14 +436,14 @@ describe("SortableCard", () => {
/** 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" }) });
+ draw({ itemCreationButtons: [ makes("d", "Delta") ] });
focus(adder());
press(adder(), "ArrowDown");
expect(document.activeElement).toBe(adder());
items = [];
- draw({ onAdd: () => ({ key: "d", caption: "Delta" }) });
+ draw({ itemCreationButtons: [ makes("d", "Delta") ] });
focus(adder());
press(adder(), "ArrowUp");
expect(document.activeElement).toBe(adder());
@@ -433,7 +451,7 @@ describe("SortableCard", () => {
/** 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" }) });
+ draw({ itemCreationButtons: [ makes("d", "Delta") ] });
expect(adder()?.querySelector(".tn-sortable-grip")).toBeNull();
expect(adder()?.getAttribute("role")).not.toBe("listitem");
@@ -525,7 +543,7 @@ describe("SortableCard", () => {
configurable: true
});
- for (const segment of [ ...segments(), adder() ]) {
+ for (const segment of [ ...segments(), row() ]) {
if (!segment) {
continue;
}
@@ -547,8 +565,22 @@ describe("SortableCard", () => {
return container.querySelector<HTMLElement>(".tn-sortable-list");
}
+ function row() {
+ return container.querySelector<HTMLElement>(".tn-sortable-adders");
+ }
+
+ /** The first of the buttons at the foot of the card, there being at least one in these. */
function adder() {
- return container.querySelector<HTMLElement>(".tn-sortable-add");
+ return container.querySelector<HTMLElement>(".tn-sortable-adder");
+ }
+
+ function adders() {
+ return [ ...container.querySelectorAll<HTMLElement>(".tn-sortable-adder") ];
+ }
+
+ /** A way of making one entry, named so a test can tell which button made what. */
+ function makes(key: string, caption: string, label = "Add") {
+ return { label, onCreateItem: () => ({ key, caption }) };
}
function segments() {
diff --git a/apps/client/src/widgets/react/SortableCard.tsx b/apps/client/src/widgets/react/SortableCard.tsx
index d99eb52477..30b08e754d 100644
--- a/apps/client/src/widgets/react/SortableCard.tsx
+++ b/apps/client/src/widgets/react/SortableCard.tsx
@@ -10,6 +10,9 @@ import { Card, type CardProps } from "./Card";
import { useFlip } from "./flip";
import Icon from "./Icon";
+/** How many buttons the foot of a card holds before they are too narrow to read. */
+const MAX_CREATION_BUTTONS = 3;
+
/** One entry of a {@link SortableCard}, named by a key that outlives the order it stands in. */
export interface SortableItem {
key: string;
@@ -19,6 +22,19 @@ export interface SortableItem {
icon?: string;
}
+/**
+ * One way of making an entry, drawn as a button at the foot of the card.
+ *
+ * What an entry is is the caller's: the button can ask with a dialog or a picker of its own, and
+ * answering with nothing makes none.
+ */
+export interface ItemCreationButton<T extends SortableItem> {
+ label: string;
+ /** An icon class, `bx` prefix included. */
+ icon?: string;
+ onCreateItem: () => T | undefined | Promise<T | undefined>;
+}
+
export interface SortableCardProps<T extends SortableItem> extends CardProps {
/** The entries, in the order they stand. */
items: T[];
@@ -30,14 +46,12 @@ export interface SortableCardProps<T extends SortableItem> extends CardProps {
*/
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 ways an entry can be made, drawn as a row of buttons at the foot of the card and left out
+ * where there are none. Up to three, past which they are too narrow to read.
*
- * 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.
+ * The first of them is what Enter beside an entry makes, that being the one a card leads with.
*/
- onAdd?: () => T | undefined | Promise<T | undefined>;
- /** What the entry at the foot of the card reads. */
- addLabel?: string;
+ itemCreationButtons?: ItemCreationButton<T>[];
/** The entry the reader is on, for a card whose selection the caller keeps. */
selectedKey?: string;
onSelect?: (key: string) => void;
@@ -55,8 +69,12 @@ export interface SortableCardProps<T extends SortableItem> extends CardProps {
* 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
+ items, onChange, renderItem, itemCreationButtons, selectedKey, onSelect, className, ...card
}: SortableCardProps<T>) {
+ if ((itemCreationButtons?.length ?? 0) > MAX_CREATION_BUTTONS) {
+ throw new Error("Up to three item creation buttons are supported");
+ }
+
const listRef = useRef<HTMLDivElement>(null);
const adderRef = useRef<HTMLElement>(null);
const dragRef = useRef<Drag<T>>();
@@ -217,14 +235,10 @@ export function SortableCard<T extends SortableItem>({
* 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.
+ * for it; one made at the foot leaves them on the button that made it, so another can follow.
*/
- const add = useCallback(async (at?: number) => {
- if (!onAdd) {
- return;
- }
-
- const created = await onAdd();
+ const add = useCallback(async (create: ItemCreationButton<T>["onCreateItem"], at?: number) => {
+ const created = await create();
if (!created) {
return;
}
@@ -238,7 +252,7 @@ export function SortableCard<T extends SortableItem>({
}
onChange(order);
- }, [ onAdd, onChange, shown ]);
+ }, [ onChange, shown ]);
const onSegmentKeyDown = useCallback((event: KeyboardEvent, index: number) => {
if (event.key === "Escape" && dragRef.current) {
@@ -248,11 +262,12 @@ export function SortableCard<T extends SortableItem>({
}
// 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) {
+ // row: below it, or above it with Shift. Made the way the card leads with, there being no
+ // button under the reader's hand to say which of them was meant.
+ const leading = itemCreationButtons?.[0];
+ if (event.key === "Enter" && leading && !event.ctrlKey && !event.metaKey) {
event.preventDefault();
- add(event.shiftKey ? index : index + 1);
+ add(leading.onCreateItem, event.shiftKey ? index : index + 1);
return;
}
@@ -263,9 +278,9 @@ export function SortableCard<T extends SortableItem>({
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) {
+ if (!control && event.key === "ArrowDown" && index === last) {
event.preventDefault();
- adderRef.current?.focus();
+ adderRef.current?.querySelector<HTMLElement>(".tn-sortable-adder")?.focus();
}
return;
@@ -277,15 +292,9 @@ export function SortableCard<T extends SortableItem>({
} else {
focusEntry(to);
}
- }, [ add, endDrag, focusEntry, moveItem, onAdd, shown ]);
+ }, [ add, endDrag, focusEntry, itemCreationButtons, moveItem, 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;
@@ -296,7 +305,7 @@ export function SortableCard<T extends SortableItem>({
event.preventDefault();
focusEntry(to);
- }, [ add, focusEntry, shown ]);
+ }, [ focusEntry, shown ]);
return (
<Card className={clsx("tn-sortable-card", className)} {...card}>
@@ -352,16 +361,26 @@ export function SortableCard<T extends SortableItem>({
</section>
))}
- {onAdd && (
+ {/* Painted with nothing of its own: the gaps between the buttons are the card's
+ parent showing through, and each button carries what a segment is painted
+ with. */}
+ {!!itemCreationButtons?.length && (
<section
ref={adderRef}
- className="tn-card-section tn-sortable-add"
- tabIndex={0}
- onClick={() => add()}
+ className="tn-card-section tn-sortable-adders"
onKeyDown={onAddKeyDown}
>
- <Icon icon="bx bx-plus" />
- <span>{addLabel ?? t("sortable_card.add")}</span>
+ {itemCreationButtons.map((button) => (
+ <button
+ key={button.label}
+ type="button"
+ className="tn-sortable-adder"
+ onClick={() => add(button.onCreateItem)}
+ >
+ {button.icon && <Icon icon={button.icon} />}
+ <span>{button.label}</span>
+ </button>
+ ))}
</section>
)}
</div>
diff --git a/packages/commons/src/lib/script_api_preact.ts b/packages/commons/src/lib/script_api_preact.ts
index 37b7ef0420..c3aef26312 100644
--- a/packages/commons/src/lib/script_api_preact.ts
+++ b/packages/commons/src/lib/script_api_preact.ts
@@ -402,20 +402,25 @@ export declare const Slider: FunctionComponent<SliderProps>;
* 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.
+ * for a card that shows more than a name, and `itemCreationButtons` puts a row of buttons at the
+ * foot of the card that make another entry, answering with nothing where the reader backs out.
*/
interface SortableItem {
key: string;
caption?: ComponentChildren;
icon?: string;
}
+interface ItemCreationButton<T extends SortableItem> {
+ label: string;
+ icon?: string;
+ onCreateItem: () => T | undefined | Promise<T | undefined>;
+}
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;
+ /** Up to three, drawn as a row of buttons at the foot of the card. */
+ itemCreationButtons?: ItemCreationButton<T>[];
selectedKey?: string;
onSelect?: (key: string) => void;
heading?: string;