Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: create a "Board properties" dialog, rework the template selection

Adorian Doran34de1ea00c6e
diff --git a/apps/client/src/services/dialog.spec.ts b/apps/client/src/services/dialog.spec.ts
index d129370950..502edf505e 100644
--- a/apps/client/src/services/dialog.spec.ts
+++ b/apps/client/src/services/dialog.spec.ts
@@ -145,7 +145,7 @@ describe("dialog service", () => {
});
});
- describe("lifting dialogs above a stacked popup", () => {
+ describe("lifting a dialog above what is already open", () => {
afterEach(() => {
document.body.className = "";
document.body.innerHTML = "";
@@ -202,8 +202,8 @@ describe("dialog service", () => {
expect(backdrop.style.zIndex).toBe("1109");
});
- it("does not lift when no popup is stacked", async () => {
- openStackedPopup("999"); // popup present but body lacks the -stacked class (non-stacked case)
+ it("does not lift over something it already stands above", async () => {
+ openStackedPopup("999"); // present, but below the layer a dialog stands on anyway
const $dialog = makeDialog().appendTo(document.body);
await openDialog($dialog, true);
@@ -211,6 +211,41 @@ describe("dialog service", () => {
expect($dialog[0].style.zIndex).toBe("");
});
+ /**
+ * A dialog opened from another dialog declares the same layer as the one it was opened
+ * from, which leaves the two tied: whichever stands later in the page wins, and that is
+ * not always the one just opened. Its backdrop follows it, so the dialog underneath cannot
+ * be pressed while this one is up.
+ */
+ it("lifts a dialog opened over another that declares the same layer", async () => {
+ const open = document.createElement("div");
+ open.className = "modal show";
+ open.style.zIndex = "2000";
+ document.body.appendChild(open);
+
+ const backdrop = document.createElement("div");
+ backdrop.className = "modal-backdrop";
+ document.body.appendChild(backdrop);
+
+ const $dialog = makeDialog().appendTo(document.body);
+ await openDialog($dialog, false, undefined, 2000);
+
+ expect($dialog[0].style.zIndex).toBe("2010");
+ expect(backdrop.style.zIndex).toBe("2009");
+ });
+
+ it("leaves a dialog that already declares a layer above what is open where it is", async () => {
+ const open = document.createElement("div");
+ open.className = "modal show";
+ open.style.zIndex = "1055";
+ document.body.appendChild(open);
+
+ const $dialog = makeDialog().appendTo(document.body);
+ await openDialog($dialog, false, undefined, 2000);
+
+ expect($dialog[0].style.zIndex).toBe("2000");
+ });
+
it("treats popups without a numeric z-index as layer 0 and excludes the dialog itself from the scan", async () => {
document.body.classList.add("tree-popup-stacked");
// No inline z-index -> getComputedStyle returns a non-numeric value -> parseInt NaN -> 0.
@@ -220,7 +255,9 @@ describe("dialog service", () => {
const $dialog = makeDialog().addClass("show").appendTo(document.body);
await openDialog($dialog, true);
- expect($dialog[0].style.zIndex).toBe("10"); // max(0) + 10
+ // Never below the layer a dialog stands on with nothing said about it: what is open
+ // has none of its own to clear, so the standard one is the floor.
+ expect($dialog[0].style.zIndex).toBe("1055");
});
it("never lifts a self-managed popup dialog, even while another popup is stacked", async () => {
diff --git a/apps/client/src/services/dialog.ts b/apps/client/src/services/dialog.ts
index 9eb6385ab0..769c0222ac 100644
--- a/apps/client/src/services/dialog.ts
+++ b/apps/client/src/services/dialog.ts
@@ -21,8 +21,8 @@ export async function openDialog($dialog: JQuery<HTMLElement>, closeActDialog =
saveFocusedElement();
- // Lift this dialog above a stacked quick-edit / tree popup if one is open (see raiseAboveStackedPopup).
- const bumpedZIndex = raiseAboveStackedPopup($dialog[0], declaredZIndex);
+ // Lift this dialog above whatever is already open, if anything is (see raiseAboveWhatIsOpen).
+ const bumpedZIndex = raiseAboveWhatIsOpen($dialog[0], declaredZIndex);
Modal.getOrCreateInstance($dialog[0], config).show();
@@ -149,37 +149,52 @@ export function closeActiveDialog() {
}
}
+/** The layer a dialog stands on with nothing said about it, which is Bootstrap's own. */
+const STANDARD_MODAL_LAYER = 1055;
+
/** Self-managing popups (quick-edit, tree popup) set their own z-index via CSS; never lift them. */
const SELF_MANAGED_POPUP_SELECTOR = ".popup-editor-dialog, .tree-popup-editor-dialog";
/**
- * When a quick-edit / tree popup is stacked on top of another modal it sits at z-index 1100 — above
- * the standard dialog layer (1055). A dialog opened from within it (delete/confirm/prompt/…) would
- * then render *behind* the popup. Detect that case and give the incoming dialog an inline z-index
- * just above the current top-most modal so it clears the popup.
+ * Puts a dialog opened over something else above it.
+ *
+ * Two cases, and one answer for both. A quick-edit / tree popup stacked on another modal sits at
+ * z-index 1100, above the standard dialog layer (1055), so a dialog opened from within it would
+ * render behind the popup. And a dialog opened from another dialog — a picker reached from a
+ * settings dialog, say — declares the same layer as the one it was opened from, which leaves the
+ * two tied: whichever stands later in the page wins, and that is not the one just opened.
+ *
+ * The incoming dialog is given an inline z-index just above the top-most modal, so it clears both.
+ * Its backdrop follows it (see the caller), which is what keeps the dialog underneath from being
+ * pressed while this one is up.
*
* The dialog's inline z-index is rewritten from scratch on every open, so a lift never outlives the
- * stacked context that warranted it. `declaredZIndex` is the layer the dialog defines for itself
- * (`Modal`'s `zIndex` prop, e.g. 1100 for the note type chooser or 2000 for confirm/prompt) and is
- * what it falls back to — clearing the property outright would strip that.
+ * context that warranted it. `declaredZIndex` is the layer the dialog defines for itself (`Modal`'s
+ * `zIndex` prop, e.g. 1100 for the note type chooser or 2000 for confirm/prompt) and is what it
+ * falls back to — clearing the property outright would strip that.
*
* Returns the assigned z-index (for the caller to match the backdrop), or `null` when no lift was
* applied.
*/
-function raiseAboveStackedPopup(dialogEl: HTMLElement, declaredZIndex?: number): number | null {
+function raiseAboveWhatIsOpen(dialogEl: HTMLElement, declaredZIndex?: number): number | null {
+ const others = Array.from(document.querySelectorAll<HTMLElement>(".modal.show"))
+ .filter((modal) => modal !== dialogEl);
+ const maxZIndex = others.reduce((max, modal) => Math.max(max, parseInt(getComputedStyle(modal).zIndex, 10) || 0), 0);
+
const hasStackedPopup = document.body.classList.contains("popup-editor-stacked")
|| document.body.classList.contains("tree-popup-stacked");
- if (!hasStackedPopup || dialogEl.matches(SELF_MANAGED_POPUP_SELECTOR)) {
+ // The layer this dialog would stand on of its own accord, which is what says whether anything
+ // already open would cover it.
+ const own = declaredZIndex ?? STANDARD_MODAL_LAYER;
+ const isCovered = hasStackedPopup || maxZIndex >= own;
+
+ if (!isCovered || dialogEl.matches(SELF_MANAGED_POPUP_SELECTOR)) {
dialogEl.style.zIndex = declaredZIndex ? String(declaredZIndex) : "";
return null;
}
- const others = Array.from(document.querySelectorAll<HTMLElement>(".modal.show"))
- .filter((modal) => modal !== dialogEl);
- const maxZIndex = others.reduce((max, modal) => Math.max(max, parseInt(getComputedStyle(modal).zIndex, 10) || 0), 0);
-
- // A dialog that already declares a layer above the popup keeps it; lifting only ever raises.
- const zIndex = Math.max(maxZIndex + 10, declaredZIndex ?? 0);
+ // A dialog that already declares a layer above everything open keeps it; lifting only raises.
+ const zIndex = Math.max(maxZIndex + 10, own);
dialogEl.style.zIndex = String(zIndex);
return zIndex;
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index aa57aa965b..a5cf9cbbd4 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2520,8 +2520,7 @@
"collections": "Collections",
"spreadsheet": "Spreadsheet",
"note-types": "Note types",
- "built-in-templates": "Built-in templates",
- "selector-save": "Save"
+ "built-in-templates": "Built-in templates"
},
"item_picker": {
"title": "Pick an item",
@@ -3434,11 +3433,16 @@
"expand-all-columns": "Expand all columns",
"show-inbox-column": "Show inbox column",
"show-archived-notes": "Show archived notes",
- "customize-templates": "Customize card templates",
+ "properties": "Board properties",
+ "properties-title": "Board properties",
+ "card-templates": "Card templates",
+ "card-templates-hint": "Choose what note types and note templates you would like to use when creating new board cards.",
+ "add-existing-template": "Add existing template",
+ "add-template-title": "Add a template to the board",
+ "create-template": "Create template",
+ "remove-template": "Remove from the board",
"more-templates": "More templates…",
"card-template": "Select a card template",
- "templates-title": "Templates offered on this board",
- "templates-hint": "Pick what a new card can be made from. At least one is needed.",
"collapse-hint": "Double click to collapse",
"set-limit": "Set limit...",
"set-limit-ok": "Set limit",
diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.ts
index 627fb88235..fef52527af 100644
--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts
@@ -717,10 +717,10 @@ describe("Board context menu", () => {
/**
* What the board itself offers, for a press on the ground the columns stand on. The last entry
- * opens the dialog naming what a card can be made from, which the pill inside the field a card
- * is named in opens as well.
+ * opens what the board is set up with, which the pill inside the field a card is named in
+ * opens as well.
*/
- it("offers what the board holds, and a way to what its cards are made from", () => {
+ it("offers what the board holds, and a way to how it is set up", () => {
const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
const board = {
inboxShown: true,
@@ -730,7 +730,7 @@ describe("Board context menu", () => {
onExpandAll: vi.fn(),
onShowInbox: vi.fn(),
onShowArchived: vi.fn(),
- onCustomizeTemplates: vi.fn()
+ onOpenProperties: vi.fn()
};
openBoardContextMenu({
@@ -741,17 +741,17 @@ describe("Board context menu", () => {
} as ContextMenuEvent, board);
const items = show.mock.calls.at(-1)?.[0].items ?? [];
- // A separator stands between what the board shows and what its cards are made from.
+ // A separator stands between what the board shows and how it is set up.
expect(items.map(item => item && "uiIcon" in item ? item.uiIcon : "---")).toEqual([
"bx bx-columns", "---",
"bx bx-collapse-alt", "bx bx-expand-alt", "---",
INBOX_COLUMN_ICON, "bx bx-archive", "---",
- "bx bx-list-ul"
+ "bx bx-cog"
]);
const entry = items.at(-1);
- if (!entry || !("handler" in entry)) throw new Error("expected an entry for the templates");
+ if (!entry || !("handler" in entry)) throw new Error("expected an entry for the properties");
entry.handler?.(entry, {} as never);
- expect(board.onCustomizeTemplates).toHaveBeenCalled();
+ expect(board.onOpenProperties).toHaveBeenCalled();
});
});
diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.ts
index a1a262fb00..838a36978e 100644
--- a/apps/client/src/widgets/collections/board/context_menu.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.ts
@@ -180,8 +180,8 @@ interface BoardMenuTarget {
onExpandAll: () => void;
onShowInbox: (shown: boolean) => void;
onShowArchived: (shown: boolean) => void;
- /** Opens the dialog naming what a new card can be made from. */
- onCustomizeTemplates: () => void;
+ /** Opens the dialog holding what the board is set up with, its card templates among them. */
+ onOpenProperties: () => void;
}
/** What the board itself offers, for a press on the ground the columns stand on. */
@@ -224,9 +224,9 @@ export function openBoardContextMenu(event: ContextMenuEvent, board: BoardMenuTa
},
{ kind: "separator" },
{
- title: t("board_view.customize-templates"),
- uiIcon: "bx bx-list-ul",
- handler: board.onCustomizeTemplates
+ title: t("board_view.properties"),
+ uiIcon: "bx bx-cog",
+ handler: board.onOpenProperties
}
],
selectMenuItemHandler() {}
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index 071bc6a5df..0c7dc19828 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -8,6 +8,8 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Modal as BootstrapModal } from "bootstrap";
+
import Component from "../../../components/component";
import contextMenu from "../../../menus/context_menu";
import dialog from "../../../services/dialog";
@@ -511,7 +513,7 @@ describe("Collapsed board columns", () => {
: []);
expect(entries.map(entry => entry.icon)).toEqual([
"bx bx-columns", "bx bx-collapse-alt", "bx bx-expand-alt",
- INBOX_COLUMN_ICON, "bx bx-archive", "bx bx-list-ul"
+ INBOX_COLUMN_ICON, "bx bx-archive", "bx bx-cog"
]);
const entry = (icon: string) => entries.find(item => item.icon === icon)?.handler;
@@ -1753,6 +1755,25 @@ describe("Board column rename", () => {
return field;
}
+ /**
+ * Takes a dialog down as Bootstrap would.
+ *
+ * Its own teardown waits on a transition that happy-dom never runs, so a dialog left open keeps
+ * the focus trap Bootstrap put on the page: every editor the tests after it open would lose the
+ * focus the moment it was given.
+ */
+ async function dismiss(dialog?: HTMLElement) {
+ await act(async () => {
+ dialog?.dispatchEvent(new Event("hidden.bs.modal", { bubbles: true }));
+ await flush();
+ });
+
+ BootstrapModal.getInstance(dialog as HTMLElement)?.dispose();
+ dialog?.remove();
+ document.querySelector(".modal-backdrop")?.remove();
+ document.body.classList.remove("modal-open");
+ }
+
/** The element standing for a note, which a move draws afresh. */
function drawn(container: HTMLElement, noteId: string) {
const element = [ ...container.querySelectorAll<HTMLElement>(".board-note") ]
@@ -2459,11 +2480,9 @@ describe("Board column rename", () => {
}
});
- /** The pill's last entry opens the dialog that decides what the board offers. */
- it("opens the templates dialog from the pill, and stores what is ticked", async () => {
+ /** The pill's last entry leads where the board's own menu does: how the board is set up. */
+ it("opens the board's properties from the pill, listing what it offers in order", async () => {
const { container } = await setup();
- const stored = vi.spyOn(BoardApi.prototype, "setCardTemplateIds")
- .mockResolvedValue(undefined);
const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]
.querySelector<HTMLElement>(".board-new-item");
@@ -2490,52 +2509,19 @@ describe("Board column rename", () => {
await flush();
});
- // The last of them: a dialog portalled to the page outlives the board that drew it here,
- // so every board this file has rendered has left one behind.
- const dialog = [ ...document.querySelectorAll<HTMLElement>(".note-type-selector-dialog") ]
+ // The last of them: a dialog portalled to the page outlives the board that drew it here.
+ const dialog = [ ...document.querySelectorAll<HTMLElement>(".board-properties-dialog") ]
.at(-1);
expect(dialog).toBeTruthy();
- const boxes = [ ...(dialog?.querySelectorAll<HTMLInputElement>("input[type=checkbox]") ?? []) ];
- // The name carries a suffix of its own, which is what ties the box to its label.
- const named = boxes.map(box => box.getAttribute("name")?.replace(/-[^-]{10}$/, ""));
- // Everything the app can make is listed, with what the board offers already ticked.
- expect(named).toEqual([
- "type:text:text/html",
- "type:code:text/x-markdown",
- "type:canvas:application/json",
- "type:spreadsheet:application/json",
- "type:mermaid:text/mermaid"
- ]);
- expect(boxes.filter(box => box.checked).length).toBe(4);
-
- // Nothing ticked is nothing a card could be made from, so it cannot be saved.
- await act(async () => {
- for (const box of boxes.filter(box => box.checked)) {
- box.checked = false;
- box.dispatchEvent(new Event("change", { bubbles: true }));
- }
- await flush();
- });
- const save = [ ...(dialog?.querySelectorAll<HTMLButtonElement>("button") ?? []) ]
- .find(button => button.textContent?.includes("selector-save"));
- expect(save?.disabled).toBe(true);
-
- await act(async () => {
- boxes[4].checked = true;
- boxes[4].dispatchEvent(new Event("change", { bubbles: true }));
- await flush();
- });
- expect(save?.disabled).toBe(false);
-
- await act(async () => {
- dialog?.querySelector("form")?.dispatchEvent(
- new Event("submit", { bubbles: true, cancelable: true }));
- await flush();
- });
- expect(stored).toHaveBeenCalledWith([ "type:mermaid:text/mermaid" ]);
+ // What the board offers, in the order it stores them, each carried by a grip of its own.
+ const named = [ ...(dialog?.querySelectorAll(".board-template-name") ?? []) ]
+ .map(element => element.textContent);
+ expect(named).toEqual([ "Text", "Markdown", "Canvas", "Spreadsheet" ]);
+ expect(dialog?.querySelectorAll(".tn-sortable-grip").length).toBe(4);
+ expect(dialog?.querySelectorAll(".tn-sortable-adder").length).toBe(2);
- stored.mockRestore();
+ await dismiss(dialog);
});
/**
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index d84e1d9c69..0c1079db5d 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -29,7 +29,6 @@ import {
} from "../../react/hooks";
import Icon from "../../react/Icon";
import NoteAutocomplete from "../../react/NoteAutocomplete";
-import NoteTypeSelectorDialog from "../../react/NoteTypeSelectorDialog";
import ShortcutHintButton from "../../shortcut_hints/shortcut_hint_button";
import { onWheelHorizontalScroll } from "../../widget_utils";
import ActionButton from "../../react/ActionButton";
@@ -45,6 +44,7 @@ import { DEFAULT_COLUMN_ICON, DEFAULT_GROUP_BY, getStatusDefinition, INBOX_COLUM
import Column from "./column";
import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";
import ColumnLimitDialog from "./column_limit";
+import BoardProperties from "./properties";
import { openBoardContextMenu, openCreateColumnMenu } from "./context_menu";
import { applyCardMove, ColumnMap, getBoardData } from "./data";
import { useBoardKeyboard } from "./keyboard";
@@ -269,7 +269,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
const [ isCreatingColumn, setIsCreatingColumn ] = useState(false);
/** Everything a card could be made from, read once: the note types and every template. */
const [ availableTemplates, setAvailableTemplates ] = useState<NoteTypeOption[]>([]);
- const [ isPickingTemplates, setIsPickingTemplates ] = useState(false);
+ const [ isEditingProperties, setIsEditingProperties ] = useState(false);
/** How many reads of the templates were asked for, and the newest one answered. */
const readsAsked = useRef(0);
@@ -390,7 +390,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
onAddColumn: () => setIsCreatingColumn(true),
onShowInbox: (shown) => api.setInboxEnabled(shown),
onShowArchived: (shown) => api.setArchivedShown(shown),
- onCustomizeTemplates: () => setIsPickingTemplates(true),
+ onOpenProperties: () => setIsEditingProperties(true),
onCollapseAll: () => {
// The open column is closed with the rest: it holds the peek that would otherwise
// keep it open against what is being written for it.
@@ -419,7 +419,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
offered: offeredTemplates,
current: currentCardTemplate(offeredTemplates, api.getLastCardTemplateId()),
onSelect: (template: NoteTypeOption) => api.setLastCardTemplateId(template.id),
- onMore: () => setIsPickingTemplates(true)
+ onMore: () => setIsEditingProperties(true)
}), [ api, viewConfig, offeredTemplates ]);
const boardActions = useMemo<BoardActions>(() => ({
@@ -821,14 +821,11 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
column={columnLimitToEdit}
onClose={() => setColumnLimitToEdit(undefined)}
/>
- <NoteTypeSelectorDialog
+ <BoardProperties
+ api={api}
available={availableTemplates}
- selected={api.getCardTemplateIds()}
- shown={isPickingTemplates}
- title={t("board_view.templates-title")}
- hint={t("board_view.templates-hint")}
- onSave={(ids) => api.setCardTemplateIds(ids)}
- onClose={() => setIsPickingTemplates(false)}
+ shown={isEditingProperties}
+ onClose={() => setIsEditingProperties(false)}
/>
</>,
document.body
diff --git a/apps/client/src/widgets/collections/board/properties.css b/apps/client/src/widgets/collections/board/properties.css
new file mode 100644
index 0000000000..0ee3daa19d
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/properties.css
@@ -0,0 +1,13 @@
+.modal.board-properties-dialog {
+ /* The name takes what room there is, so the way to remove an entry stands at its trailing edge. */
+ .board-template-name {
+ flex-grow: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .board-template-remove {
+ flex-shrink: 0;
+ }
+}
diff --git a/apps/client/src/widgets/collections/board/properties.spec.tsx b/apps/client/src/widgets/collections/board/properties.spec.tsx
new file mode 100644
index 0000000000..4547be2657
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/properties.spec.tsx
@@ -0,0 +1,202 @@
+import { Modal as BootstrapModal } from "bootstrap";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import dialog from "../../../services/dialog";
+import { type NoteTypeOption } from "../../../services/note_types";
+import BoardApi from "./api";
+import BoardProperties from "./properties";
+
+// i18next is never initialised under test, so every label would read as undefined.
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string) => key
+}));
+
+/** Everything the app could make, as `getNoteTypeOptions` answers with it. */
+const AVAILABLE = [
+ [ "type:text:text/html", "Text", "type" ],
+ [ "type:code:text/x-markdown", "Markdown", "type" ],
+ [ "type:canvas:application/json", "Canvas", "type" ],
+ [ "template:shipped", "Shipped template", "builtin" ],
+ [ "template:mine", "My template", "user" ]
+].map(([ id, title, group ]) => ({
+ id, title, group, icon: "bx bx-note", options: { type: "text" }
+}) as NoteTypeOption);
+
+describe("Board properties", () => {
+ let container: HTMLElement;
+ let stored: string[][];
+ let offered: string[];
+
+ beforeEach(() => {
+ stored = [];
+ offered = [ "type:text:text/html", "type:code:text/x-markdown" ];
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ // Taken down before Bootstrap is: what is left of a dialog it still believes is shown holds
+ // the focus of everything after it, its teardown waiting on a transition happy-dom never
+ // runs.
+ render(null, container);
+ container.remove();
+
+ const modal = document.querySelector<HTMLElement>(".board-properties-dialog");
+ if (modal) {
+ BootstrapModal.getInstance(modal)?.dispose();
+ modal.remove();
+ }
+
+ document.querySelector(".modal-backdrop")?.remove();
+ document.body.classList.remove("modal-open");
+ });
+
+ it("lists what the board offers, in the order it stores them", () => {
+ draw();
+
+ expect(captions()).toEqual([ "Text", "Markdown" ]);
+ expect(dialog_()?.querySelector(".tn-card-heading")?.textContent)
+ .toContain("board_view.card-templates");
+ expect(dialog_()?.querySelector(".tn-card-description")?.textContent)
+ .toBe("board_view.card-templates-hint");
+ });
+
+ /** The grip leads, so the trailing edge is left to what each entry carries there. */
+ it("carries the grip at the start of an entry and the way to remove it at the end", () => {
+ draw();
+ const [ first ] = segments();
+
+ expect(first.firstElementChild?.className).toContain("tn-sortable-grip");
+ // Inside what the card draws for an entry, which is the rest of the segment.
+ expect(first.querySelector(".tn-sortable-content")?.lastElementChild?.className)
+ .toContain("board-template-remove");
+ });
+
+ it("stores the order the reader puts them in", () => {
+ draw();
+
+ press(segments()[0], "ArrowDown", { ctrlKey: true });
+
+ expect(stored).toEqual([ [ "type:code:text/x-markdown", "type:text:text/html" ] ]);
+ });
+
+ it("takes an entry away, and leaves the last one alone", () => {
+ draw();
+
+ act(() => { segments()[0].querySelector<HTMLElement>(".board-template-remove")?.click(); });
+
+ expect(stored).toEqual([ [ "type:code:text/x-markdown" ] ]);
+ // And gone from the card, which is drawn from the list this dialog holds rather than from
+ // the board it wrote to.
+ expect(captions()).toEqual([ "Markdown" ]);
+
+ // Nothing to make a card from is nothing the board could make one with, so the way to
+ // take the last one away is not offered at all.
+ offered = [ "type:text:text/html" ];
+ draw();
+ expect(segments()[0].querySelector(".board-template-remove")).toBeNull();
+ });
+
+ describe("adding one", () => {
+ it("offers the note types and the reader's own templates, and not the app's", async () => {
+ const picking = vi.spyOn(dialog, "pickSingleItem").mockResolvedValue(null);
+ draw();
+
+ await add("board_view.add-existing-template");
+
+ const groups = picking.mock.calls.at(-1)?.[0].items as {
+ key: string, items: { key: string }[]
+ }[];
+ expect(groups.map((group) => group.key)).toEqual([ "type", "user" ]);
+ // What the board already offers is left out, as is everything the app ships.
+ expect(groups.flatMap((group) => group.items.map((item) => item.key)))
+ .toEqual([ "type:canvas:application/json", "template:mine" ]);
+ });
+
+ it("adds what was picked to the end of the list", async () => {
+ vi.spyOn(dialog, "pickSingleItem")
+ .mockResolvedValue({ key: "template:mine", caption: "My template" });
+ draw();
+
+ await add("board_view.add-existing-template");
+
+ expect(stored.at(-1))
+ .toEqual([ "type:text:text/html", "type:code:text/x-markdown", "template:mine" ]);
+ expect(captions()).toEqual([ "Text", "Markdown", "My template" ]);
+ });
+
+ it("adds nothing where the reader backed out of the picker", async () => {
+ vi.spyOn(dialog, "pickSingleItem").mockResolvedValue(null);
+ draw();
+
+ await add("board_view.add-existing-template");
+
+ expect(stored).toEqual([]);
+ expect(captions()).toEqual([ "Text", "Markdown" ]);
+ });
+
+ /** The second way in is drawn, and does nothing yet. */
+ it("offers a way to make one, which makes nothing for now", async () => {
+ draw();
+
+ expect(adders().map((button) => button.textContent)).toEqual([
+ "board_view.add-existing-template", "board_view.create-template"
+ ]);
+
+ await add("board_view.create-template");
+ expect(stored).toEqual([]);
+ });
+ });
+
+ // #region The dialog, and what the test does to it
+
+ function draw() {
+ const api = {
+ getCardTemplateIds: () => offered,
+ setCardTemplateIds: async (ids: string[]) => { stored.push(ids); }
+ } as unknown as BoardApi;
+
+ act(() => {
+ render(
+ <BoardProperties api={api} available={AVAILABLE} shown onClose={() => {}} />,
+ container);
+ });
+ }
+
+ function dialog_() {
+ return document.querySelector<HTMLElement>(".board-properties-dialog");
+ }
+
+ function segments() {
+ return [ ...(dialog_()?.querySelectorAll<HTMLElement>(".tn-sortable-segment") ?? []) ];
+ }
+
+ function captions() {
+ return segments().map((element) =>
+ element.querySelector(".board-template-name")?.textContent);
+ }
+
+ function adders() {
+ return [ ...(dialog_()?.querySelectorAll<HTMLElement>(".tn-sortable-adder") ?? []) ];
+ }
+
+ async function add(label: string) {
+ const button = adders().find((element) => element.textContent === label);
+ await act(async () => {
+ button?.click();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ }
+
+ function press(target: Element, key: string, options: KeyboardEventInit = {}) {
+ act(() => {
+ target.dispatchEvent(
+ new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...options }));
+ });
+ }
+
+ // #endregion
+});
diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsx
new file mode 100644
index 0000000000..813390b451
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/properties.tsx
@@ -0,0 +1,169 @@
+import "./properties.css";
+
+import { useCallback, useEffect, useMemo, useState } from "preact/hooks";
+
+import dialog from "../../../services/dialog";
+import { t } from "../../../services/i18n";
+import { type NoteTypeOption, noteTypeOptionGroupTitle, resolveNoteTypeOptions } from "../../../services/note_types";
+import ActionButton from "../../react/ActionButton";
+import Icon from "../../react/Icon";
+import { type PickerItem, type PickerItemGroup } from "../../dialogs/item_picker";
+import Modal from "../../react/Modal";
+import { type SortableItem, SortableCard } from "../../react/SortableCard";
+import BoardApi from "./api";
+
+/**
+ * What the board is set up with, apart from the columns and the cards themselves.
+ *
+ * One card for now, the templates a new card is made from; the dialog is the place the rest of the
+ * board's own settings will be put as they arrive.
+ */
+export default function BoardProperties({ api, available, shown, onClose }: {
+ api: BoardApi,
+ /** Everything a card could be made from, as the board read them. */
+ available: NoteTypeOption[],
+ shown: boolean,
+ onClose: () => void
+}) {
+ return (
+ <Modal
+ className="board-properties-dialog"
+ title={t("board_view.properties-title")}
+ size="lg"
+ scrollable
+ zIndex={2000}
+ show={shown}
+ onHidden={onClose}
+ >
+ <CardTemplates api={api} available={available} shown={shown} />
+ </Modal>
+ );
+}
+
+/**
+ * The templates a new card can be made from, in the order the board stores them.
+ *
+ * The order is the reader's to change, since the first of them is what a card is made from until
+ * another is picked, and what the pill in a card's editor leads with.
+ */
+function CardTemplates({ api, available, shown }: {
+ api: BoardApi,
+ available: NoteTypeOption[],
+ shown: boolean
+}) {
+ /**
+ * The list as it stands here, which is what the card is drawn from.
+ *
+ * Held rather than read from the board on every draw: a change made here is written straight
+ * through, and the board has nothing to draw this dialog again for, so what is shown would
+ * otherwise be the list as it was when the dialog opened.
+ */
+ const [ ids, setIds ] = useState(() => api.getCardTemplateIds());
+
+ // Read afresh each time the dialog opens, the board having been changed elsewhere meanwhile.
+ useEffect(() => {
+ if (shown) {
+ setIds(api.getCardTemplateIds());
+ }
+ }, [ api, shown ]);
+
+ const offered = useMemo(
+ () => resolveNoteTypeOptions(ids, available), [ available, ids ]);
+ const items = useMemo(() => offered.map((option) => ({
+ key: option.id,
+ caption: option.title,
+ icon: option.icon
+ })), [ offered ]);
+
+ const store = useCallback((order: SortableItem[]) => {
+ const next = order.map((item) => item.key);
+ setIds(next);
+ api.setCardTemplateIds(next);
+ }, [ api ]);
+
+ /** Asks which of the ones not already offered to add, and answers with it as an entry. */
+ const addExisting = useCallback(async () => {
+ const taken = new Set(offered.map((option) => option.id));
+ const picked = await dialog.pickSingleItem({
+ title: t("board_view.add-template-title"),
+ items: pickable(available, taken)
+ });
+
+ return picked
+ ? { key: picked.key, caption: picked.caption, icon: picked.icon }
+ : undefined;
+ }, [ available, offered ]);
+
+ return (
+ <SortableCard
+ heading={t("board_view.card-templates")}
+ description={t("board_view.card-templates-hint")}
+ items={items}
+ onChange={store}
+ // The grip leads, so the trailing edge is left to what each entry carries there.
+ gripPlacement="start"
+ renderItem={(item, index) => (
+ <>
+ {item.icon && <Icon icon={item.icon} />}
+ <span className="board-template-name">{item.caption}</span>
+
+ {/* The last one left is not removable: a board with nothing to make a card
+ from could make none, so the write behind this refuses it anyway. */}
+ {items.length > 1 && (
+ <ActionButton
+ className="board-template-remove"
+ icon="bx bx-x"
+ text={t("board_view.remove-template")}
+ onClick={(event) => {
+ event.stopPropagation();
+ store(items.filter((unused, at) => at !== index));
+ }}
+ />
+ )}
+ </>
+ )}
+ itemCreationButtons={[
+ {
+ label: t("board_view.add-existing-template"),
+ icon: "bx bx-list-plus",
+ onCreateItem: addExisting
+ },
+ {
+ label: t("board_view.create-template"),
+ icon: "bx bx-plus",
+ onCreateItem: () => undefined
+ }
+ ]}
+ />
+ );
+}
+
+/**
+ * What can still be added, as groups for the picker.
+ *
+ * The templates the app ships are left out: they are a starting point for a note of one's own
+ * rather than something a board is set up to make its cards from.
+ */
+function pickable(available: NoteTypeOption[], taken: Set<string>): PickerItemGroup[] {
+ const groups = new Map<string, PickerItemGroup>();
+
+ for (const option of available) {
+ if (option.group === "builtin" || taken.has(option.id)) {
+ continue;
+ }
+
+ const group = groups.get(option.group) ?? {
+ key: option.group,
+ groupHeader: noteTypeOptionGroupTitle(option.group),
+ items: []
+ };
+
+ const entry: PickerItem = {
+ key: option.id, caption: option.title, icon: option.icon
+ };
+ group.items.push(entry);
+ groups.set(option.group, group);
+ }
+
+ return [ ...groups.values() ];
+}
diff --git a/apps/client/src/widgets/react/NoteTypeSelectorDialog.css b/apps/client/src/widgets/react/NoteTypeSelectorDialog.css
deleted file mode 100644
index c4e9293cb4..0000000000
--- a/apps/client/src/widgets/react/NoteTypeSelectorDialog.css
+++ /dev/null
@@ -1,21 +0,0 @@
-:where(:root) {
- --note-type-selector-group-gap: 1.2em;
-}
-
-.modal.note-type-selector-dialog {
- .note-type-selector-hint {
- margin-bottom: var(--note-type-selector-group-gap);
- color: var(--muted-text-color);
- }
-
- section + section {
- margin-top: var(--note-type-selector-group-gap);
- }
-
- h5 {
- margin-bottom: 0.4em;
- font-size: 1em;
- font-weight: 600;
- color: var(--muted-text-color);
- }
-}
diff --git a/apps/client/src/widgets/react/NoteTypeSelectorDialog.tsx b/apps/client/src/widgets/react/NoteTypeSelectorDialog.tsx
deleted file mode 100644
index 3dfea8df5f..0000000000
--- a/apps/client/src/widgets/react/NoteTypeSelectorDialog.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import "./NoteTypeSelectorDialog.css";
-
-import { useEffect, useMemo, useState } from "preact/hooks";
-
-import { t } from "../../services/i18n";
-import {
- type NoteTypeOption, type NoteTypeOptionGroup, noteTypeOptionGroupTitle
-} from "../../services/note_types";
-import Button from "./Button";
-import FormCheckbox from "./FormCheckbox";
-import Icon from "./Icon";
-import Modal from "./Modal";
-
-/**
- * Which of the things a note can be made from a feature offers, ticked off a list of all of them.
- *
- * Written for anything that lets the reader narrow the choice down to what they actually use: a
- * board's card templates are the first, and the dialog knows nothing of boards. Saving an empty
- * selection is refused, since a feature that offers nothing can make nothing.
- */
-export default function NoteTypeSelectorDialog({
- available, selected, shown, title, hint, onSave, onClose
-}: {
- /** Everything that could be offered, usually `getNoteTypeOptions()`. */
- available: NoteTypeOption[],
- /** What is offered now, which is what the dialog opens on. */
- selected: string[],
- shown: boolean,
- title: string,
- /** A line above the list saying what the choice is for. */
- hint?: string,
- onSave: (ids: string[]) => void,
- onClose: () => void
-}) {
- const [ picked, setPicked ] = useState<string[]>(selected);
-
- // Opened on what is offered now rather than on what was offered when it was first drawn: the
- // dialog is kept mounted and shown by a flag.
- useEffect(() => {
- if (shown) {
- setPicked(selected);
- }
- }, [ shown, selected ]);
-
- const groups = useMemo(() => {
- const byGroup = new Map<NoteTypeOptionGroup, NoteTypeOption[]>();
- for (const option of available) {
- byGroup.set(option.group, [ ...(byGroup.get(option.group) ?? []), option ]);
- }
-
- return [ ...byGroup.entries() ];
- }, [ available ]);
-
- return (
- <Modal
- className="note-type-selector-dialog"
- title={title}
- size="lg"
- scrollable
- // Raised the way every dialog opened from a menu is: the menu's own backdrop stands
- // above the stock modal layer, and would otherwise cover this.
- zIndex={2000}
- show={shown}
- onSubmit={() => {
- onSave(picked);
- onClose();
- }}
- onHidden={onClose}
- footer={<>
- <Button text={t("modal.cancel")} onClick={onClose} />
- <Button
- text={t("note_types.selector-save")}
- keyboardShortcut="Enter"
- kind="primary"
- disabled={!picked.length}
- />
- </>}
- >
- {hint && <p className="note-type-selector-hint">{hint}</p>}
-
- {groups.map(([ group, options ]) => (
- <section key={group}>
- <h5>{noteTypeOptionGroupTitle(group)}</h5>
- {options.map((option) => (
- <FormCheckbox
- key={option.id}
- name={option.id}
- label={<><Icon icon={option.icon} /> {option.title}</>}
- currentValue={picked.includes(option.id)}
- onChange={(checked) => setPicked((was) => checked
- ? [ ...was, option.id ]
- : was.filter((id) => id !== option.id))}
- />
- ))}
- </section>
- ))}
- </Modal>
- );
-}