Skip to content

Build your personal knowledge base with Trilium Notes

refactor(client): share the board's template pill with other collections

Elian Doran8e8ac77efee6
diff --git a/apps/client/src/services/note_types.spec.ts b/apps/client/src/services/note_types.spec.ts
index 31614730a4..713f421645 100644
--- a/apps/client/src/services/note_types.spec.ts
+++ b/apps/client/src/services/note_types.spec.ts
@@ -19,7 +19,10 @@ vi.mock("./experimental_features.js", () => ({
}));
import { isExperimentalFeatureEnabled } from "./experimental_features.js";
-import noteTypesService, { isCurrentNoteType, selectableNoteTypes } from "./note_types";
+import noteTypesService, {
+ currentNoteTypeOption, isCurrentNoteType, type NoteTypeOption, noteTypeOptionIcon,
+ selectableNoteTypes
+} from "./note_types";
const llmFlag = vi.mocked(isExperimentalFeatureEnabled);
@@ -668,3 +671,34 @@ describe("selectableNoteTypes", () => {
}
});
});
+
+describe("currentNoteTypeOption and noteTypeOptionIcon", () => {
+ function option(id: string, title: string): NoteTypeOption {
+ return { id, title, icon: "bx bx-note", group: "type", options: { type: "text" } };
+ }
+
+ /**
+ * The stored option can be gone: removed from the list, or its template note deleted. A note
+ * is made from the first option offered rather than from nothing.
+ */
+ it("falls back to the first offered option", () => {
+ const offered = [ option("type:text:text/html", "Text"), option("note:mine", "Mine") ];
+
+ expect(currentNoteTypeOption(offered, "note:mine")?.title).toBe("Mine");
+ expect(currentNoteTypeOption(offered, "type:canvas:application/json")?.title).toBe("Text");
+ expect(currentNoteTypeOption(offered, undefined)?.title).toBe("Text");
+ expect(currentNoteTypeOption([], "type:text:text/html")).toBeUndefined();
+ });
+
+ /**
+ * A note type carries a bare icon class, while a template note's comes from `FNote.getIcon()`
+ * with `tn-icon` in front. The picker writes neither prefix, so both have to read alike.
+ */
+ it("gives an option's icon as the icon picker would write it", () => {
+ const template = { ...option("note:mine", "Mine"), icon: "tn-icon bx bx-user" };
+
+ expect(noteTypeOptionIcon(template)).toBe("bx bx-user");
+ expect(noteTypeOptionIcon(option("type:text:text/html", "Text"))).toBe("bx bx-note");
+ expect(noteTypeOptionIcon(undefined)).toBeUndefined();
+ });
+});
diff --git a/apps/client/src/services/note_types.ts b/apps/client/src/services/note_types.ts
index f18207d4b4..81715f278c 100644
--- a/apps/client/src/services/note_types.ts
+++ b/apps/client/src/services/note_types.ts
@@ -159,6 +159,25 @@ export function resolveNoteTypeOptions(ids: NoteTypeId[], available: NoteTypeOpt
});
}
+/**
+ * The option a new note is made from: the stored one if it is still offered, otherwise the first.
+ *
+ * A stored option can have been removed from the list, or its template note deleted.
+ */
+export function currentNoteTypeOption(offered: NoteTypeOption[], stored: string | undefined) {
+ return offered.find((option) => option.id === stored) ?? offered[0];
+}
+
+/**
+ * The icon a note made from `option` carries, in the form `IconPicker` writes.
+ *
+ * `FNote.getIcon()` prefixes its result with `tn-icon` and an `#iconClass` label does not, so a
+ * template note's icon needs that prefix removed to compare with a picked one.
+ */
+export function noteTypeOptionIcon(option: NoteTypeOption | undefined) {
+ return option?.icon.replace(/^tn-icon\s+/, "");
+}
+
/** The name of the group an option stands in, for a list the reader picks from. */
export function noteTypeOptionGroupTitle(group: NoteTypeOptionGroup) {
switch (group) {
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index 4627b7c7e4..d938ac2371 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -19,8 +19,9 @@ import { buildNote } from "../../../test/easy-froca";
import { BoardViewData } from ".";
import BoardApi, { getPendingWrites, PendingColumnWrites } from "./api";
import { ColumnItem, ColumnMap } from "./data";
-import { BOARD_TEMPLATE_ID, DEFAULT_COLUMN_ICON, getStatusDefinition, INBOX_COLUMN } from "./columns";
-import { DEFAULT_CARD_TEMPLATES } from "./card_templates";
+import {
+ BOARD_TEMPLATE_ID, DEFAULT_CARD_TEMPLATES, DEFAULT_COLUMN_ICON, getStatusDefinition, INBOX_COLUMN
+} from "./columns";
import { COLUMN_ID_LENGTH } from "./reference";
vi.mock("../../../services/bulk_action", () => ({
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index 46039e9ede..e297ae49d4 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -10,10 +10,13 @@ import dialog from "../../../services/dialog";
import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
import note_create from "../../../services/note_create";
-import { type NoteTypeOption, resolveNoteTypeOptions } from "../../../services/note_types";
+import {
+ currentNoteTypeOption, type NoteTypeOption, resolveNoteTypeOptions
+} from "../../../services/note_types";
import server from "../../../services/server";
import ws from "../../../services/ws";
import toast from "../../../services/toast";
+import { offeredTemplateIds } from "../../react/TemplatePill";
import {
type PromotedAttribute, resolvePromotedAttributes, storedPromotedAttributes,
visiblePromotedAttributeNames
@@ -22,11 +25,10 @@ import {
DEFAULT_SORT, MANUAL_SORT, parseSortKey, parseStoredSortKey, type SortKey, type StoredSortKey
} from "../sorting";
import { BoardColumnData, BoardViewData } from ".";
-import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";
import {
type BoardStatusDefinition, canStoreColumnsInDefinition, COLUMN_WIDTH_LABEL, type ColumnWidth,
- DEFAULT_COLUMN_ICON, DEFAULT_COLUMN_WIDTH, DEFAULT_GROUP_BY, INBOX_COLUMN, INBOX_COLUMN_ICON,
- parseColumnWidth
+ DEFAULT_CARD_TEMPLATES, DEFAULT_COLUMN_ICON, DEFAULT_COLUMN_WIDTH, DEFAULT_GROUP_BY, INBOX_COLUMN,
+ INBOX_COLUMN_ICON, parseColumnWidth
} from "./columns";
import { readColumns, writeColumns } from "./column_storage";
import { cardNotes, ColumnItem, ColumnMap } from "./data";
@@ -959,15 +961,14 @@ export default class BoardApi {
/** What a card is made from now: the one last used, or the first the board offers. */
getCurrentCardTemplate() {
- return currentCardTemplate(
+ return currentNoteTypeOption(
resolveNoteTypeOptions(this.getCardTemplateIds(), this.availableTemplates),
this.getLastCardTemplateId());
}
/** The templates the board offers, or the stock set until the reader has picked for it. */
getCardTemplateIds() {
- const stored = this.viewConfig?.templates;
- return stored?.length ? stored : DEFAULT_CARD_TEMPLATES;
+ return offeredTemplateIds(this.viewConfig, DEFAULT_CARD_TEMPLATES);
}
/** Which of them a new card is made from, until another is picked. */
diff --git a/apps/client/src/widgets/collections/board/card_template_pill.tsx b/apps/client/src/widgets/collections/board/card_template_pill.tsx
deleted file mode 100644
index ae07a7f84b..0000000000
--- a/apps/client/src/widgets/collections/board/card_template_pill.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { useMemo, useState } from "preact/hooks";
-
-import { t } from "../../../services/i18n";
-import { type NoteTypeOption } from "../../../services/note_types";
-import Dropdown from "../../react/Dropdown";
-import { FormListItem } from "../../react/FormList";
-import Icon from "../../react/Icon";
-
-/**
- * What a new card will be made from, standing inside the editor it is named in.
- *
- * The pill is a dropdown of what the board offers, and a way to the dialog that decides what that
- * is. It reports a pick rather than storing one: the board writes what it last used, so that the
- * editor opens on it again.
- */
-export default function CardTemplatePill({ offered, current, onSelect, onMore, onOpened, onClosed }: {
- offered: NoteTypeOption[];
- /** The one a card would be made from now, absent while the board is still reading them. */
- current?: NoteTypeOption;
- onSelect: (template: NoteTypeOption) => void;
- /** Opens the dialog that decides which templates the board offers. */
- onMore: () => void;
- /**
- * Said as the dropdown opens and closes. The editor closes on losing focus, and the menu takes
- * focus with it, so it has to be held open for as long as the reader is in it.
- */
- onOpened?: () => void;
- onClosed?: () => void;
-}) {
- const [ isShown, setIsShown ] = useState(false);
-
- // Rebuilt only as the list changes, since a dropdown is torn down and put back up with it.
- const items = useMemo(() => offered.map((template) => (
- <FormListItem
- key={template.id}
- icon={template.icon}
- onClick={() => onSelect(template)}
- >
- {template.title}
- {/* Ticked rather than highlighted: a highlighted row reads as the one under the
- pointer. The icon each template carries stays where it is. */}
- {template.id === current?.id && (
- <Icon className="card-template-current" icon="bx bx-check" />
- )}
- </FormListItem>
- )), [ offered, current, onSelect ]);
-
- // The name alone stands in the pill: the field already carries the icon the card itself will
- // wear, and a second icon beside it reads as a second thing to pick.
- return (
- <Dropdown
- className="card-template-pill"
- buttonClassName="card-template-pill-button"
- text={<span className="card-template-name">{current?.title ?? ""}</span>}
- title={t("board_view.card-template")}
- noSelectButtonStyle
- onShown={() => {
- setIsShown(true);
- onOpened?.();
- }}
- onHidden={() => {
- setIsShown(false);
- onClosed?.();
- }}
- >
- {isShown && <>
- {items}
- <li><hr className="dropdown-divider" /></li>
- <FormListItem icon="bx bx-list-ul" onClick={onMore}>
- {t("board_view.more-templates")}
- </FormListItem>
- </>}
- </Dropdown>
- );
-}
diff --git a/apps/client/src/widgets/collections/board/card_templates.spec.ts b/apps/client/src/widgets/collections/board/card_templates.spec.ts
deleted file mode 100644
index 7b1e3012b1..0000000000
--- a/apps/client/src/widgets/collections/board/card_templates.spec.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { type NoteTypeOption } from "../../../services/note_types";
-import { cardTemplateIcon, currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";
-
-/** An option as `getNoteTypeOptions` builds one, cut down to what the board reads. */
-function option(id: string, title: string): NoteTypeOption {
- return { id, title, icon: "bx bx-note", group: "type", options: { type: "text" } };
-}
-
-describe("what a board makes its cards from", () => {
- it("offers text, Markdown, canvas and a spreadsheet until the reader says otherwise", () => {
- expect(DEFAULT_CARD_TEMPLATES).toEqual([
- "type:text:text/html",
- "type:code:text/x-markdown",
- "type:canvas:application/json",
- "type:spreadsheet:application/json"
- ]);
- });
-
- /**
- * What the board stored can be gone: switched off in the dialog, or a template note deleted.
- * A card is made from the first thing offered rather than from nothing.
- */
- it("falls back to the first offered template", () => {
- const offered = [ option("type:text:text/html", "Text"), option("note:mine", "Mine") ];
-
- expect(currentCardTemplate(offered, "note:mine")?.title).toBe("Mine");
- expect(currentCardTemplate(offered, "type:canvas:application/json")?.title).toBe("Text");
- expect(currentCardTemplate(offered, undefined)?.title).toBe("Text");
- expect(currentCardTemplate([], "type:text:text/html")).toBeUndefined();
- });
-
- /**
- * A note type carries a bare icon class, while a template note's comes from `FNote.getIcon()`
- * with `tn-icon` in front. The picker writes neither prefix, so both have to read alike.
- */
- it("gives a template's icon as the picker would write it", () => {
- const template = { ...option("note:mine", "Mine"), icon: "tn-icon bx bx-user" };
-
- expect(cardTemplateIcon(template)).toBe("bx bx-user");
- expect(cardTemplateIcon(option("type:text:text/html", "Text"))).toBe("bx bx-note");
- expect(cardTemplateIcon(undefined)).toBeUndefined();
- });
-});
diff --git a/apps/client/src/widgets/collections/board/card_templates.ts b/apps/client/src/widgets/collections/board/card_templates.ts
deleted file mode 100644
index fc554bd3c4..0000000000
--- a/apps/client/src/widgets/collections/board/card_templates.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { buildNoteTypeId } from "@triliumnext/commons";
-
-import { type NoteTypeOption } from "../../../services/note_types";
-
-/**
- * What a board makes its cards from.
- *
- * A card template is a {@link NoteTypeOption} like any other: the list, the ids and the dialog that
- * narrows them down are the app's, and what the board adds is which of them it offers, which it
- * last used, and that a new card is made from that one.
- */
-export interface CardTemplates {
- /** What the board offers, in the order it stores them. */
- offered: NoteTypeOption[];
- /** The one a card would be made from now. */
- current?: NoteTypeOption;
- onSelect: (template: NoteTypeOption) => void;
- /** Opens the dialog that decides what the board offers. */
- onMore: () => void;
-}
-
-/** What a board offers until the reader says otherwise. */
-export const DEFAULT_CARD_TEMPLATES = [
- buildNoteTypeId("text", "text/html"),
- buildNoteTypeId("code", "text/x-markdown"),
- buildNoteTypeId("canvas", "application/json"),
- buildNoteTypeId("spreadsheet", "application/json")
-];
-
-/**
- * The template a new card is made from: the one the board last used, or the first it offers.
- *
- * A board whose stored template is no longer offered falls back rather than making nothing: the
- * template may have been switched off, or the note behind it deleted.
- */
-export function currentCardTemplate(offered: NoteTypeOption[], stored: string | undefined) {
- return offered.find((template) => template.id === stored) ?? offered[0];
-}
-
-/**
- * The icon a card made from `template` carries, in the form `IconPicker` writes.
- *
- * `FNote.getIcon()` prefixes its result with `tn-icon` and an `#iconClass` label does not, so a
- * template note's icon needs that prefix removed to compare with a picked one.
- */
-export function cardTemplateIcon(template: NoteTypeOption | undefined) {
- return template?.icon.replace(/^tn-icon\s+/, "");
-}
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index a8f00d03e7..a7d564621a 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -13,6 +13,7 @@ import dialog from "../../../services/dialog";
import { getHue, parseColor } from "../../../services/css_class_manager";
import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
+import { noteTypeOptionIcon } from "../../../services/note_types";
import { isMobile } from "../../../services/utils";
import ActionButton from "../../react/ActionButton";
import Icon from "../../react/Icon";
@@ -39,14 +40,13 @@ const MIN_CARD_HEIGHT = 32;
/** How long an open takes. Matches `--board-expand-duration` in the board's own rules. */
export const EXPAND_MS = 200;
import NoteLink from "../../react/NoteLink";
+import TemplatePill, { type TemplateChoice } from "../../react/TemplatePill";
import {
BoardActionsContext, BoardDragStateContext, BoardEditingContext, BoardOverlayHostContext,
BoardSelectionModeContext
} from ".";
import BoardApi from "./api";
import Card from "./card";
-import CardTemplatePill from "./card_template_pill";
-import { cardTemplateIcon, type CardTemplates } from "./card_templates";
import { DEFAULT_CARD_ICON, DEFAULT_COLUMN_ICON, INBOX_COLUMN } from "./columns";
import { ColumnToolbar, RAIL_EXIT_MS } from "./card_toolbar";
import { openColumnContextMenu, openColumnSortMenu, openCreateCardMenu } from "./context_menu";
@@ -133,7 +133,7 @@ export default function Column({
*/
standsAside?: number,
/** What a new card is made from, and how the reader picks something else. */
- cardTemplates: CardTemplates,
+ cardTemplates: TemplateChoice,
/** Whether the inbox also collects notes deeper than the board's direct children. */
nested?: boolean,
/** The note limit, absent if disabled. */
@@ -1020,7 +1020,7 @@ function AddNewItem({
}: {
column: string,
api: BoardApi,
- cardTemplates: CardTemplates,
+ cardTemplates: TemplateChoice,
/** Whether the column orders its own cards, which leaves the reader no end to pick. */
isSorted?: boolean,
isCreating?: boolean,
@@ -1044,7 +1044,7 @@ function AddNewItem({
// unsaved, so that reaching for something else and coming back does not cost the title.
const [ initialTitle, setInitialTitle ] = useState("");
// The icon a card made from the current template would carry.
- const templateIcon = cardTemplateIcon(cardTemplates.current) ?? DEFAULT_CARD_ICON;
+ const templateIcon = noteTypeOptionIcon(cardTemplates.current) ?? DEFAULT_CARD_ICON;
// Kept between cards, unlike the title: a run of cards is often a run of the same kind of card.
const [ icon, setIcon ] = useState(templateIcon);
/** The template icon `icon` was last set from, telling a picked icon from a followed one. */
@@ -1147,7 +1147,14 @@ function AddNewItem({
// cards is already at the end the reader asked for, and a sorted column places
// the card itself.
openPlacements={!insert && !isSorted ? openCreateCardMenu : undefined}
- footer={(hold) => <CardTemplatePill {...cardTemplates} {...hold} />}
+ footer={(hold) => (
+ <TemplatePill
+ {...cardTemplates}
+ {...hold}
+ title={t("board_view.card-template")}
+ moreText={t("board_view.more-templates")}
+ />
+ )}
icon={{
current: icon,
onSelect: setIcon,
diff --git a/apps/client/src/widgets/collections/board/columns.spec.ts b/apps/client/src/widgets/collections/board/columns.spec.ts
index e35699c6fa..4fe713372c 100644
--- a/apps/client/src/widgets/collections/board/columns.spec.ts
+++ b/apps/client/src/widgets/collections/board/columns.spec.ts
@@ -8,6 +8,7 @@ import { buildNote } from "../../../test/easy-froca";
import {
BOARD_TEMPLATE_ID,
canStoreColumnsInDefinition,
+ DEFAULT_CARD_TEMPLATES,
columnWidthClass,
getStatusDefinition,
parseColumnWidth,
@@ -236,3 +237,14 @@ describe("columnWidthClass", () => {
expect(columnWidthClass(undefined)).toBeUndefined();
});
});
+
+describe("DEFAULT_CARD_TEMPLATES", () => {
+ it("offers text, Markdown, canvas and a spreadsheet until the reader says otherwise", () => {
+ expect(DEFAULT_CARD_TEMPLATES).toEqual([
+ "type:text:text/html",
+ "type:code:text/x-markdown",
+ "type:canvas:application/json",
+ "type:spreadsheet:application/json"
+ ]);
+ });
+});
diff --git a/apps/client/src/widgets/collections/board/columns.ts b/apps/client/src/widgets/collections/board/columns.ts
index 672a32a5c9..849113e53f 100644
--- a/apps/client/src/widgets/collections/board/columns.ts
+++ b/apps/client/src/widgets/collections/board/columns.ts
@@ -1,4 +1,6 @@
-import { DEFAULT_BOARD_GROUP_BY, type DefinitionObject } from "@triliumnext/commons";
+import {
+ buildNoteTypeId, DEFAULT_BOARD_GROUP_BY, type DefinitionObject
+} from "@triliumnext/commons";
import type FAttribute from "../../../entities/fattribute";
import type FNote from "../../../entities/fnote";
@@ -20,6 +22,14 @@ export const DEFAULT_COLUMN_ICON = "bx bx-circle";
/** What a card is drawn with until an icon is picked for it, which is what a text note carries. */
export const DEFAULT_CARD_ICON = "bx bx-note";
+/** What a board offers to make its cards from until the reader picks for it. */
+export const DEFAULT_CARD_TEMPLATES = [
+ buildNoteTypeId("text", "text/html"),
+ buildNoteTypeId("code", "text/x-markdown"),
+ buildNoteTypeId("canvas", "application/json"),
+ buildNoteTypeId("spreadsheet", "application/json")
+];
+
/**
* The value identifying the inbox column: the empty string, which is what a card with no
* grouping value has.
diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.css
index 503775692f..db9b551d24 100644
--- a/apps/client/src/widgets/collections/board/index.css
+++ b/apps/client/src/widgets/collections/board/index.css
@@ -1104,46 +1104,15 @@ body#trilium-app.motion-disabled .board-view.editing-open :is(
max-width: calc(100% - 2 * var(--card-icon-inset));
}
-/* A quiet chip rather than a button: it names what the card will be, and is pressed only to change
- it. The name is cut rather than wrapped, the field being one line tall to begin with. */
-.board-view-container .card-template-pill .card-template-pill-button {
- display: flex;
- align-items: center;
- gap: 0.3em;
- max-width: 100%;
+.board-view-container .template-pill .template-pill-button {
height: var(--card-template-pill-height);
- border: 1px solid var(--main-border-color);
- border-radius: 999px;
- padding-inline: 0.5em;
- background-color: transparent;
color: var(--board-muted-text-color);
- font-size: 0.85em;
- line-height: 1;
}
-.board-view-container .card-template-pill .card-template-pill-button:hover {
- border-color: var(--main-text-color);
+.board-view-container .template-pill .template-pill-button:hover {
color: var(--board-text-color);
}
-/* The menu is drawn at the end of the page, so it is named rather than nested in the board. The
- tick stands at the trailing edge, where a shortcut would. */
-.tn-dropdown-portal.card-template-pill .dropdown-item {
- display: flex;
- align-items: center;
-}
-
-.tn-dropdown-portal.card-template-pill .card-template-current {
- margin-inline-start: auto;
- padding-inline-start: 1.5em;
-}
-
-.board-view-container .card-template-pill .card-template-name {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
/* A card or column lands where the reader may not be looking, so it announces itself. */
@keyframes board-item-appear {
from { opacity: 0; }
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index 48fe4abab0..1d722fc7d7 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -59,13 +59,12 @@ vi.mock("../../../services/utils", async (importOriginal) => ({
isMobile: () => layout.onMobile
}));
-vi.mock("../../../services/note_types", () => ({
+vi.mock("../../../services/note_types", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/note_types")>()),
getNoteTypeOptions: vi.fn(async () => {
templateReads++;
return NOTE_TYPE_OPTIONS;
}),
- resolveNoteTypeOptions: (ids: string[], available: { id: string }[]) =>
- ids.flatMap(id => available.filter(option => option.id === id)),
noteTypeOptionGroupTitle: (group: string) => `group:${group}`,
default: {}
}));
@@ -1943,7 +1942,7 @@ describe("Board column rename", () => {
await flush();
});
- return slot?.querySelector(".card-template-pill button")?.textContent ?? "";
+ return slot?.querySelector(".template-pill button")?.textContent ?? "";
}
/**
@@ -2172,7 +2171,7 @@ describe("Board column rename", () => {
const field = column.querySelector<HTMLElement>(".board-new-item.inserting");
expect(field?.querySelector(".title-editor-icon button")).toBeTruthy();
- expect(field?.querySelector(".card-template-pill button")?.textContent).toContain("Text");
+ expect(field?.querySelector(".template-pill button")?.textContent).toContain("Text");
expect(field?.querySelector("textarea")?.placeholder).toBeTruthy();
// Escape takes it down again, having made nothing.
@@ -2504,7 +2503,7 @@ describe("Board column rename", () => {
});
const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");
- const pill = slot?.querySelector<HTMLElement>(".card-template-pill button");
+ const pill = slot?.querySelector<HTMLElement>(".template-pill button");
if (!editor || !pill) throw new Error("expected the editor and its template pill");
// The first the board offers, until something else is picked.
@@ -2518,13 +2517,13 @@ describe("Board column rename", () => {
// The menu is portalled to the page, and the boards this file rendered before left theirs
// behind, so it is the last one that belongs to the board under test.
- const menu = [ ...document.querySelectorAll<HTMLElement>(".card-template-pill") ].at(-1);
+ const menu = [ ...document.querySelectorAll<HTMLElement>(".template-pill") ].at(-1);
const items = [ ...(menu?.querySelectorAll<HTMLElement>(".dropdown-item") ?? []) ];
expect(items.map(item => item.textContent?.trim())).toEqual([
"Text", "Markdown", "Canvas", "Spreadsheet", "board_view.more-templates"
]);
// The one a card would be made from is ticked, rather than standing out by its background.
- expect(items.map(item => !!item.querySelector(".card-template-current")))
+ expect(items.map(item => !!item.querySelector(".template-pill-current")))
.toEqual([ true, false, false, false, false ]);
expect(items.some(item => item.classList.contains("active"))).toBe(false);
@@ -2542,9 +2541,9 @@ describe("Board column rename", () => {
$(pill.closest(".dropdown") as HTMLElement).children("button:not([aria-expanded=true])").trigger("click");
await flush();
});
- const reopened = [ ...document.querySelectorAll<HTMLElement>(".card-template-pill") ].at(-1);
+ const reopened = [ ...document.querySelectorAll<HTMLElement>(".template-pill") ].at(-1);
expect([ ...(reopened?.querySelectorAll(".dropdown-item") ?? []) ]
- .map(item => !!item.querySelector(".card-template-current")))
+ .map(item => !!item.querySelector(".template-pill-current")))
.toEqual([ false, false, true, false, false ]);
await type(editor, "Drawn");
@@ -2555,7 +2554,7 @@ describe("Board column rename", () => {
expect(created).toHaveBeenCalledWith("Doing", "Drawn", "bottom", undefined,
expect.objectContaining({ id: "type:canvas:application/json" }));
- expect(slot?.querySelector(".card-template-pill button")?.textContent).toContain("Canvas");
+ expect(slot?.querySelector(".template-pill button")?.textContent).toContain("Canvas");
});
/**
@@ -2577,7 +2576,7 @@ describe("Board column rename", () => {
});
const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");
- const pill = slot?.querySelector<HTMLElement>(".card-template-pill button");
+ const pill = slot?.querySelector<HTMLElement>(".template-pill button");
if (!editor || !pill) throw new Error("expected the editor and its pill");
await type(editor, "Still here");
@@ -2768,7 +2767,7 @@ describe("Board column rename", () => {
await flush();
});
- const pill = slot?.querySelector<HTMLElement>(".card-template-pill button");
+ const pill = slot?.querySelector<HTMLElement>(".template-pill button");
if (!pill) throw new Error("expected the template pill");
await act(async () => {
pill.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));
@@ -2776,7 +2775,7 @@ describe("Board column rename", () => {
await flush();
});
- const menus = [ ...document.querySelectorAll<HTMLElement>(".card-template-pill") ];
+ const menus = [ ...document.querySelectorAll<HTMLElement>(".template-pill") ];
const more = [ ...(menus.at(-1)?.querySelectorAll<HTMLElement>(".dropdown-item") ?? []) ]
.find(item => item.textContent?.includes("more-templates"));
if (!more) throw new Error("expected a way to the dialog");
@@ -2877,7 +2876,7 @@ describe("Board column rename", () => {
/** Picks one of the templates the pill offers, by where it stands in its menu. */
async function pickTemplate(slot: HTMLElement | null | undefined, index: number) {
- const pill = slot?.querySelector<HTMLElement>(".card-template-pill button");
+ const pill = slot?.querySelector<HTMLElement>(".template-pill button");
if (!pill) throw new Error("expected the template pill");
await act(async () => {
@@ -2888,7 +2887,7 @@ describe("Board column rename", () => {
// The menu is portalled to the page, and the boards rendered before left theirs behind, so
// the last one is the board under test.
- const menu = [ ...document.querySelectorAll<HTMLElement>(".card-template-pill") ].at(-1);
+ const menu = [ ...document.querySelectorAll<HTMLElement>(".template-pill") ].at(-1);
const items = [ ...(menu?.querySelectorAll<HTMLElement>(".dropdown-item") ?? []) ];
await act(async () => {
items[index].click();
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 21146e55b5..1328ee2475 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -25,7 +25,7 @@ import type {
} from "../../../services/shortcut_hints";
import ws from "../../../services/ws";
import { isMobile } from "../../../services/utils";
-import { type NoteTypeOption, resolveNoteTypeOptions } from "../../../services/note_types";
+import { type NoteTypeOption } from "../../../services/note_types";
import {
type PromotedAttributeSetting, resolvePromotedAttributes, visiblePromotedAttributeNames
} from "../promoted_attributes";
@@ -38,6 +38,7 @@ import {
useTrackedElement, useTriliumEvent
} from "../../react/hooks";
import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";
+import { type TemplateChoiceConfig, useTemplateChoice } from "../../react/TemplatePill";
import { ShortcutHintOverlayButton } from "../../shortcut_hints/shortcut_hint_button";
import { onWheelHorizontalScroll } from "../../widget_utils";
import { useDragPan } from "../../react/drag_pan";
@@ -59,7 +60,6 @@ import {
COLUMN_WIDTH_LABEL, columnWidthClass, DEFAULT_GROUP_BY, getStatusDefinition, INBOX_COLUMN
} from "./columns";
import Column, { clearGap, EXPAND_MS, placeCard, settleCards } from "./column";
-import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";
import BoardGroupBy, { groupingOptions } from "./group_by";
import { useBoardReference } from "./reference";
import { openBoardContextMenu } from "./context_menu";
@@ -82,7 +82,8 @@ export interface HoldOpen {
onClosed: () => void;
}
-export interface BoardViewData {
+/** The card templates default to `DEFAULT_CARD_TEMPLATES`. */
+export interface BoardViewData extends TemplateChoiceConfig {
/**
* The columns of the default grouping. Every other grouping keeps its own list under
* `<attribute>ViewColumns`, so switching the grouping cannot mix two of them.
@@ -90,13 +91,6 @@ export interface BoardViewData {
columns?: BoardColumnData[];
/** @see BoardViewData.columns */
[key: `${string}ViewColumns`]: BoardColumnData[] | undefined;
- /**
- * What a new card can be made from, as {@link NoteTypeOption} ids. Absent until the reader picks
- * for the board, which is what `DEFAULT_CARD_TEMPLATES` stands in for.
- */
- templates?: string[];
- /** The one last used, which the next card is made from. */
- template?: string;
/**
* Which promoted attributes the cards show, and in what order. An attribute the list does not
* name is shown after the ones it does; see {@link resolvePromotedAttributes}.
@@ -658,22 +652,23 @@ function Board({
});
}, [ api, collapseAllColumns, expandAllColumns, inboxEnabled, includeArchived, isReadOnly ]);
- // Read from the api rather than from the prop, since a pick moves the api's own copy ahead of
- // the board's; keyed on the prop so that a change from anywhere else is followed too.
- const offeredTemplates = useMemo(
- () => resolveNoteTypeOptions(api.getCardTemplateIds(), availableTemplates),
- [ api, viewConfig, availableTemplates ]);
// Handed to the api as well, for the cards made from somewhere other than the editor: an
// insert beside another card reaches for the same template without being given one.
useEffect(
() => api.setAvailableCardTemplates(availableTemplates), [ api, availableTemplates ]);
- const cardTemplates = useMemo(() => ({
- offered: offeredTemplates,
- current: currentCardTemplate(offeredTemplates, api.getLastCardTemplateId()),
- onSelect: (template: NoteTypeOption) => api.setLastCardTemplateId(template.id),
- onMore: () => setIsEditingProperties(true)
- }), [ api, viewConfig, offeredTemplates ]);
+ const selectCardTemplate = useCallback(
+ (template: NoteTypeOption) => api.setLastCardTemplateId(template.id), [ api ]);
+ const editCardTemplates = useCallback(() => setIsEditingProperties(true), []);
+ // Read from the api rather than from the prop, since a pick moves the api's own copy ahead of
+ // the board's.
+ const cardTemplates = useTemplateChoice({
+ ids: api.getCardTemplateIds(),
+ lastUsedId: api.getLastCardTemplateId(),
+ available: availableTemplates,
+ onSelect: selectCardTemplate,
+ onMore: editCardTemplates
+ });
// Held while the names are the same, since a new array would redraw every card on every render.
const shownAttributesRef = useRef<string[]>([]);
diff --git a/apps/client/src/widgets/react/TemplatePill.css b/apps/client/src/widgets/react/TemplatePill.css
new file mode 100644
index 0000000000..66f2a6c469
--- /dev/null
+++ b/apps/client/src/widgets/react/TemplatePill.css
@@ -0,0 +1,35 @@
+.template-pill .template-pill-button {
+ display: flex;
+ align-items: center;
+ gap: 0.3em;
+ max-width: 100%;
+ height: 1.6em;
+ border: 1px solid var(--main-border-color);
+ border-radius: 999px;
+ padding-inline: 0.5em;
+ background-color: transparent;
+ color: var(--muted-text-color);
+ font-size: 0.85em;
+ line-height: 1;
+}
+
+.template-pill .template-pill-button:hover {
+ border-color: var(--main-text-color);
+ color: var(--main-text-color);
+}
+
+.template-pill .template-pill-name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.tn-dropdown-portal.template-pill .dropdown-item {
+ display: flex;
+ align-items: center;
+}
+
+.tn-dropdown-portal.template-pill .template-pill-current {
+ margin-inline-start: auto;
+ padding-inline-start: 1.5em;
+}
diff --git a/apps/client/src/widgets/react/TemplatePill.spec.tsx b/apps/client/src/widgets/react/TemplatePill.spec.tsx
new file mode 100644
index 0000000000..451b88d76e
--- /dev/null
+++ b/apps/client/src/widgets/react/TemplatePill.spec.tsx
@@ -0,0 +1,51 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { describe, expect, it, vi } from "vitest";
+
+import { type NoteTypeOption } from "../../services/note_types";
+import { renderInto } from "../../test/render";
+import { offeredTemplateIds, type TemplateChoice, useTemplateChoice } from "./TemplatePill";
+
+function option(id: string, title: string): NoteTypeOption {
+ return { id, title, icon: "bx bx-note", group: "type", options: { type: "text" } };
+}
+
+describe("TemplatePill", () => {
+ it("offers the stored templates, or the defaults while none are stored", () => {
+ const defaults = [ "type:text:text/html" ];
+
+ expect(offeredTemplateIds(undefined, defaults)).toBe(defaults);
+ expect(offeredTemplateIds({ templates: [] }, defaults)).toBe(defaults);
+ expect(offeredTemplateIds({ templates: [ "note:mine" ] }, defaults))
+ .toEqual([ "note:mine" ]);
+ });
+
+ it("resolves the offered ids and the last used one against what exists", () => {
+ const available = [ option("type:text:text/html", "Text"), option("note:mine", "Mine") ];
+ const onSelect = vi.fn();
+ const onMore = vi.fn();
+ const choices: TemplateChoice[] = [];
+
+ function Probe({ ids, lastUsedId }: { ids: string[], lastUsedId?: string }) {
+ choices.push(useTemplateChoice({ ids, lastUsedId, available, onSelect, onMore }));
+ return null;
+ }
+
+ const ids = [ "note:gone", "note:mine", "type:text:text/html" ];
+ const container = renderInto(<Probe ids={ids} lastUsedId="type:text:text/html" />);
+ const first = choices.at(-1);
+ expect(first?.offered.map((template) => template.title)).toEqual([ "Mine", "Text" ]);
+ expect(first?.current?.title).toBe("Text");
+ expect(first?.onSelect).toBe(onSelect);
+ expect(first?.onMore).toBe(onMore);
+
+ // The same inputs give the same choice, so a host passing it down redraws nothing.
+ act(() => render(<Probe ids={ids} lastUsedId="type:text:text/html" />, container));
+ expect(choices).toHaveLength(2);
+ expect(choices.at(-1)).toBe(first);
+
+ // A last used template that is no longer offered falls back to the first one offered.
+ act(() => render(<Probe ids={ids} lastUsedId="note:gone" />, container));
+ expect(choices.at(-1)?.current?.title).toBe("Mine");
+ });
+});
diff --git a/apps/client/src/widgets/react/TemplatePill.tsx b/apps/client/src/widgets/react/TemplatePill.tsx
new file mode 100644
index 0000000000..bd20208e81
--- /dev/null
+++ b/apps/client/src/widgets/react/TemplatePill.tsx
@@ -0,0 +1,132 @@
+import "./TemplatePill.css";
+
+import { type NoteTypeId } from "@triliumnext/commons";
+import { useMemo, useState } from "preact/hooks";
+
+import {
+ currentNoteTypeOption, type NoteTypeOption, resolveNoteTypeOptions
+} from "../../services/note_types";
+import Dropdown from "./Dropdown";
+import { FormListItem } from "./FormList";
+import Icon from "./Icon";
+
+/** What a collection creates its notes from, and how the reader picks something else. */
+export interface TemplateChoice {
+ /** What the collection offers, in the order it stores them. */
+ offered: NoteTypeOption[];
+ /** The one a new note would be made from now, absent while the options are still read. */
+ current?: NoteTypeOption;
+ onSelect: (template: NoteTypeOption) => void;
+ /** Opens the dialog that decides what the collection offers. */
+ onMore: () => void;
+}
+
+/**
+ * What a collection stores about its templates in its view config. Extended by the view config of
+ * every collection that offers a {@link TemplatePill}.
+ */
+export interface TemplateChoiceConfig {
+ /**
+ * What a new note can be made from, as {@link NoteTypeOption} ids. Absent until the reader
+ * picks for the collection, which is what the collection's defaults stand in for.
+ */
+ templates?: string[];
+ /** The one last used, which the next note is made from. */
+ template?: string;
+}
+
+/**
+ * A dropdown naming what a new note will be made from, listing what the collection offers and a
+ * way to the dialog that decides what that is.
+ *
+ * The pill reports a pick rather than storing one, so the collection decides where the last used
+ * template is kept.
+ */
+export default function TemplatePill({
+ offered, current, onSelect, onMore, title, moreText, onOpened, onClosed
+}: TemplateChoice & {
+ /** The tooltip of the button, naming what is created. */
+ title: string;
+ /** The label of the entry that calls `onMore`. */
+ moreText: string;
+ /**
+ * Called as the dropdown opens and closes, for a host that closes on losing focus: the menu
+ * takes the focus while it is open.
+ */
+ onOpened?: () => void;
+ onClosed?: () => void;
+}) {
+ const [ isShown, setIsShown ] = useState(false);
+
+ // Rebuilt only as the list changes, since a dropdown is torn down and put back up with it.
+ const items = useMemo(() => offered.map((template) => (
+ <FormListItem
+ key={template.id}
+ icon={template.icon}
+ onClick={() => onSelect(template)}
+ >
+ {template.title}
+ {/* A check mark rather than a highlight, which reads as the row under the pointer. */}
+ {template.id === current?.id && (
+ <Icon className="template-pill-current" icon="bx bx-check" />
+ )}
+ </FormListItem>
+ )), [ offered, current, onSelect ]);
+
+ return (
+ <Dropdown
+ className="template-pill"
+ buttonClassName="template-pill-button"
+ text={<span className="template-pill-name">{current?.title ?? ""}</span>}
+ title={title}
+ noSelectButtonStyle
+ onShown={() => {
+ setIsShown(true);
+ onOpened?.();
+ }}
+ onHidden={() => {
+ setIsShown(false);
+ onClosed?.();
+ }}
+ >
+ {isShown && <>
+ {items}
+ <li><hr className="dropdown-divider" /></li>
+ <FormListItem icon="bx bx-list-ul" onClick={onMore}>
+ {moreText}
+ </FormListItem>
+ </>}
+ </Dropdown>
+ );
+}
+
+/**
+ * Resolves the stored template ids against what exists into a {@link TemplateChoice}.
+ *
+ * `onSelect` and `onMore` must be stable, or every render returns a new choice.
+ */
+export function useTemplateChoice({ ids, lastUsedId, available, onSelect, onMore }: {
+ /** What the collection offers, usually from {@link offeredTemplateIds}. */
+ ids: NoteTypeId[];
+ lastUsedId: string | undefined;
+ /** Everything a note can be made from, from `useNoteTypeOptions()`. */
+ available: NoteTypeOption[];
+ onSelect: (template: NoteTypeOption) => void;
+ onMore: () => void;
+}): TemplateChoice {
+ const offered = useMemo(() => resolveNoteTypeOptions(ids, available), [ ids, available ]);
+
+ return useMemo(() => ({
+ offered,
+ current: currentNoteTypeOption(offered, lastUsedId),
+ onSelect,
+ onMore
+ }), [ offered, lastUsedId, onSelect, onMore ]);
+}
+
+/** The template ids a collection offers: the stored ones, or `defaults` until the reader picks. */
+export function offeredTemplateIds(
+ config: TemplateChoiceConfig | undefined, defaults: NoteTypeId[]
+) {
+ return config?.templates?.length ? config.templates : defaults;
+}