Skip to content

Build your personal knowledge base with Trilium Notes

client/ui/template selection card: add basic management for custom templates (edit, duplicate, delete)

Adorian Doran48417ab66bfa
diff --git a/apps/client/src/test/setup.ts b/apps/client/src/test/setup.ts
index eb3236bdd9..9bec34ae8c 100644
--- a/apps/client/src/test/setup.ts
+++ b/apps/client/src/test/setup.ts
@@ -28,14 +28,20 @@ function mockWebsocket() {
// Do nothing.
}
+ // Awaited by code that reads back what the server has just written. Nothing is written under
+ // test, so there is nothing to wait for.
+ async function waitForMaxKnownEntityChangeId() {}
+
return {
default: {
- subscribeToMessages
+ subscribeToMessages,
+ waitForMaxKnownEntityChangeId
},
// consumers also import these as named exports (e.g. useNoteIds); leaving them out makes
// the subscription effect throw, which silently skips every later effect of the component
subscribeToMessages,
unsubscribeToMessage,
+ waitForMaxKnownEntityChangeId,
// Code that reports a failure this way is usually in a catch block, so an undefined export
// here throws over the error being handled and loses whatever the component did about it.
logError(_message: string) {}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index cfd9a98385..e8a6cd08a5 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2527,6 +2527,7 @@
"add-title": "Add a template",
"create": "Create a new template",
"new-name": "New template",
+ "menu": "Template menu",
"remove": "Remove from the list"
},
"item_picker": {
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 7a6013bbae..5033222aaa 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -17,15 +17,13 @@ import { isIMEComposing } from "../../../services/shortcuts";
import type { ShortcutHintDefinition } from "../../../services/shortcut_hints";
import toast from "../../../services/toast";
import { escapeHtml, isMobile } from "../../../services/utils";
-import {
- getNoteTypeOptions, type NoteTypeOption, resolveNoteTypeOptions
-} from "../../../services/note_types";
+import { type NoteTypeOption, resolveNoteTypeOptions } from "../../../services/note_types";
import CollectionProperties from "../../note_bars/CollectionProperties";
import FormTextArea from "../../react/FormTextArea";
import FormTextBox from "../../react/FormTextBox";
import {
useContextualShortcutHints, useNoteContext, useNoteLabelBoolean, useNoteLabelWithDefault,
- useTrackedElement, useTriliumEvent
+ useNoteTypeOptions, useTrackedElement, useTriliumEvent
} from "../../react/hooks";
import Icon from "../../react/Icon";
import NoteAutocomplete from "../../react/NoteAutocomplete";
@@ -267,55 +265,9 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
const [ isPeekingAll, setIsPeekingAll ] = useState(false);
/** Whether the editor a column is named in is open, which the board's own menu also opens. */
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[]>([]);
+ /** Everything a card could be made from: the note types and every template. */
+ const availableTemplates = useNoteTypeOptions();
const [ isEditingProperties, setIsEditingProperties ] = useState(false);
-
- /** How many reads of the templates were asked for, and the newest one answered. */
- const readsAsked = useRef(0);
- const readAnswered = useRef(0);
- const readTemplates = useCallback(() => {
- const read = ++readsAsked.current;
- getNoteTypeOptions().then((templates) => {
- // Two reads can be in flight at once, the one made on arrival and one a template being
- // made asks for. They need not answer in the order they were asked, and one of them
- // can fail and leave no answer at all, so what is taken is what no newer answer has
- // been taken over.
- if (read > readAnswered.current) {
- readAnswered.current = read;
- setAvailableTemplates(templates);
- }
- }).catch((e) => console.error("Failed to read what a card can be made from:", e));
- }, []);
-
- useEffect(() => {
- readTemplates();
- // A read still in flight when the board goes has nothing left to answer.
- return () => { readAnswered.current = readsAsked.current + 1; };
- }, [ readTemplates ]);
-
- // A board outlives the templates it read: one made while it stands would never be offered, and
- // one deleted would go on being offered until the board was drawn afresh. A template is a note
- // carrying `#template`, and its title and icon are what the picker shows.
- useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
- const offered = new Set(availableTemplates
- .map((option) => option.options.templateNoteId)
- .filter((noteId) => !!noteId));
- // A note taking `#template` or losing it changes what a card can be made from. So does any
- // attribute of a note already offered: the icon the picker shows comes from `iconClass`,
- // from `workspaceIconClass` where there is none, and from a `#geoLocation` on a text note,
- // all of them labels rather than part of the note row a reload would report.
- const templated = loadResults.getAttributeRows().some((attribute) =>
- attribute.name === "template"
- || (!!attribute.noteId && offered.has(attribute.noteId)));
- const renamed = availableTemplates.some((option) =>
- option.options.templateNoteId
- && loadResults.isNoteReloaded(option.options.templateNoteId));
-
- if (templated || renamed) {
- readTemplates();
- }
- });
const selectColumn = useCallback<Dispatch<StateUpdater<string | undefined>>>((column) => {
setIsPeekingAll(false);
setActiveColumn(column);
diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsx
index a0450f9bce..ce46a8087f 100644
--- a/apps/client/src/widgets/collections/board/properties.tsx
+++ b/apps/client/src/widgets/collections/board/properties.tsx
@@ -28,7 +28,6 @@ export default function BoardProperties({ api, note, shown, onClose }: {
title={t("board_view.properties-title")}
size="lg"
scrollable
- zIndex={2000}
show={shown}
onHidden={onClose}
>
diff --git a/apps/client/src/widgets/dialogs/delete_notes.tsx b/apps/client/src/widgets/dialogs/delete_notes.tsx
index 4cbd896f1f..61270f5f4d 100644
--- a/apps/client/src/widgets/dialogs/delete_notes.tsx
+++ b/apps/client/src/widgets/dialogs/delete_notes.tsx
@@ -104,6 +104,7 @@ export default function DeleteNotesDialog() {
className="delete-notes-dialog"
size="lg"
title={t("delete_notes.title")}
+ zIndex={2000}
onShown={() => okButtonRef.current?.focus()}
onHidden={() => {
opts.callback?.({ proceed: false });
@@ -120,6 +121,7 @@ export default function DeleteNotesDialog() {
}} />
</>}
show={shown}
+ stackable
>
<Card>
<CardSection>
diff --git a/apps/client/src/widgets/react/SortableCard.tsx b/apps/client/src/widgets/react/SortableCard.tsx
index af7500362c..f6d17df96b 100644
--- a/apps/client/src/widgets/react/SortableCard.tsx
+++ b/apps/client/src/widgets/react/SortableCard.tsx
@@ -89,6 +89,11 @@ export interface SortableCardProps<T extends SortableItem> extends CardProps {
* when the entries carry their own controls on the trailing side.
*/
gripPlacement?: "start" | "end";
+ /**
+ * Called for a key the card does not answer itself, with the entry that had the focus. For a
+ * caller whose entries have commands of their own.
+ */
+ onItemKeyDown?: (item: T, event: KeyboardEvent) => void;
/** The selected entry, for a caller that keeps the selection itself. */
selectedKey?: string;
onSelect?: (key: string) => void;
@@ -105,8 +110,8 @@ export interface SortableCardProps<T extends SortableItem> extends CardProps {
* else identified by a key.
*/
export function SortableCard<T extends SortableItem>({
- items, onChange, renderItem, itemCreationButtons, gripPlacement = "end", selectedKey, onSelect,
- className, ...card
+ items, onChange, renderItem, itemCreationButtons, gripPlacement = "end", onItemKeyDown,
+ selectedKey, onSelect, className, ...card
}: SortableCardProps<T>) {
if ((itemCreationButtons?.length ?? 0) > MAX_CREATION_BUTTONS) {
throw new Error("Up to three item creation buttons are supported");
@@ -454,6 +459,11 @@ export function SortableCard<T extends SortableItem>({
const to = placeFor(event, index, last);
if (to === undefined) {
+ // Left to the caller, whose entries may answer keys of their own.
+ if (!control) {
+ onItemKeyDown?.(shown[index], event);
+ }
+
// Below the last entry is the creation row, which Down moves onto. It holds no entry,
// so Ctrl+Down moves nothing there.
if (!control && event.key === "ArrowDown" && index === last) {
@@ -470,7 +480,7 @@ export function SortableCard<T extends SortableItem>({
} else {
focusEntry(to);
}
- }, [ add, endDrag, focusEntry, itemCreationButtons, moveItem, shown ]);
+ }, [ add, endDrag, focusEntry, itemCreationButtons, moveItem, onItemKeyDown, shown ]);
const onAddKeyDown = useCallback((event: KeyboardEvent) => {
// Moves back into the entries. Home and End address the first and last entry here as they
diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.css b/apps/client/src/widgets/react/TemplateSelectionCard.css
index 3df0e806c2..046d2401c2 100644
--- a/apps/client/src/widgets/react/TemplateSelectionCard.css
+++ b/apps/client/src/widgets/react/TemplateSelectionCard.css
@@ -9,3 +9,7 @@
.template-selection-remove {
flex-shrink: 0;
}
+
+.template-selection-menu {
+ flex-shrink: 0;
+}
diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx b/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx
index 5a73738e51..df98d4ca8c 100644
--- a/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx
+++ b/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx
@@ -2,10 +2,18 @@ import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import appContext from "../../components/app_context";
+import Component from "../../components/component";
import type FNote from "../../entities/fnote";
+import contextMenu from "../../menus/context_menu";
+import branches from "../../services/branches";
+import froca from "../../services/froca";
import dialog from "../../services/dialog";
+import LoadResults from "../../services/load_results";
import note_create from "../../services/note_create";
import { getNoteTypeOptions, type NoteTypeOption } from "../../services/note_types";
+import server from "../../services/server";
+import { ParentComponent } from "./react_utils";
import TemplateSelectionCard from "./TemplateSelectionCard";
// i18next is never initialised under test, so every label would read as undefined.
@@ -28,7 +36,11 @@ const AVAILABLE = [
[ "template:shipped", "Shipped template", "builtin" ],
[ "template:mine", "My template", "user" ]
].map(([ id, title, group ]) => ({
- id, title, group, icon: "bx bx-note", options: { type: "text" }
+ id,
+ title,
+ group,
+ icon: "bx bx-note",
+ options: { type: "text", templateNoteId: id.split(":")[1] }
}) as NoteTypeOption);
/** The note a template made here is filed under. */
@@ -38,9 +50,11 @@ describe("TemplateSelectionCard", () => {
let container: HTMLElement;
let stored: string[][];
let offered: string[];
+ let host: Component;
beforeEach(() => {
stored = [];
+ host = new Component();
offered = [ "type:text:text/html", "type:code:text/x-markdown" ];
container = document.createElement("div");
document.body.appendChild(container);
@@ -96,6 +110,112 @@ describe("TemplateSelectionCard", () => {
expect(segments()[0].querySelector(".template-selection-remove")).toBeNull();
});
+ /**
+ * A template is a note, so it carries the commands a note has. A note type is not, and carries
+ * none.
+ */
+ describe("the commands on a template", () => {
+ beforeEach(() => {
+ offered = [ "type:text:text/html", "template:mine" ];
+ vi.spyOn(froca, "getNote").mockResolvedValue({
+ noteId: "mine",
+ title: "My template",
+ getIcon: () => "bx bx-note",
+ getParentBranches: () => [ { branchId: "b_mine", parentNoteId: "owner1" } ]
+ } as unknown as FNote);
+ });
+
+ it("offers a menu on a template and none on a note type", async () => {
+ await draw();
+
+ expect(segments()[0].querySelector(".template-selection-menu")).toBeNull();
+ expect(segments()[1].querySelector(".template-selection-menu")).not.toBeNull();
+ });
+
+ it("lists what can be done with the note, and quick-edits it", async () => {
+ const shown = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
+ const command = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);
+ await draw();
+
+ act(() => { segments()[1].querySelector<HTMLElement>(".template-selection-menu")?.click(); });
+
+ const items = shown.mock.calls.at(-1)?.[0].items ?? [];
+ expect(items.map((item) => item && "uiIcon" in item ? item.uiIcon : "---")).toEqual([
+ "bx bx-edit", "bx bx-window-open", "bx bx-outline", "---",
+ "bx bx-trash destructive-action-icon"
+ ]);
+ // The last one deletes the note itself rather than taking it off the list, and says so.
+ expect(items.map((item) => item && "title" in item ? item.title : "---")).toEqual([
+ "tree-context-menu.open-in-popup", "tree-context-menu.open-in-a-new-window",
+ "tree-context-menu.duplicate", "---", "note_actions.delete_note"
+ ]);
+
+ const quick = items[0];
+ if (!quick || !("handler" in quick)) throw new Error("expected a quick edit entry");
+ quick.handler?.(quick, {} as never);
+ expect(command).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: "mine" });
+ });
+
+ it("quick-edits and deletes from the keyboard", async () => {
+ const command = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);
+ const deleted = vi.spyOn(branches, "deleteNotes").mockResolvedValue(true);
+ await draw();
+
+ press(segments()[1], " ");
+ expect(command).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: "mine" });
+
+ press(segments()[1], "Delete");
+ await act(async () => { await Promise.resolve(); await Promise.resolve(); });
+ expect(deleted).toHaveBeenCalledWith([ "b_mine" ], false, false);
+ // Gone from the list once the note itself is gone.
+ expect(stored.at(-1)).toEqual([ "type:text:text/html" ]);
+ });
+
+ it("puts a duplicate beside the template it was copied from", async () => {
+ offered = [ "type:text:text/html", "template:mine", "type:canvas:application/json" ];
+ vi.spyOn(froca, "getNote").mockImplementation(async (noteId) => ({
+ noteId,
+ title: noteId === "copy1" ? "My template (copy)" : "My template",
+ getIcon: () => "bx bx-note",
+ getParentBranches: () => [ { branchId: `b_${noteId}`, parentNoteId: "owner1" } ]
+ } as unknown as FNote));
+ vi.spyOn(server, "post").mockResolvedValue({ note: { noteId: "copy1" } } as never);
+ const shown = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});
+ await draw();
+
+ act(() => {
+ segments()[1].querySelector<HTMLElement>(".template-selection-menu")?.click();
+ });
+ const copy = (shown.mock.calls.at(-1)?.[0].items ?? [])[2];
+ if (!copy || !("handler" in copy)) throw new Error("expected a duplicate entry");
+ await act(async () => {
+ copy.handler?.(copy, {} as never);
+ for (let step = 0; step < 6; step++) {
+ await Promise.resolve();
+ }
+ });
+
+ expect(stored.at(-1)).toEqual([
+ "type:text:text/html", "template:mine", "template:copy1",
+ "type:canvas:application/json"
+ ]);
+ expect(captions())
+ .toEqual([ "Text", "My template", "My template (copy)", "Canvas" ]);
+ });
+
+ /** A note type answers none of those keys, having no note behind it. */
+ it("leaves the keys alone on a note type", async () => {
+ // Cleared rather than made: a spy already standing comes back with its calls.
+ const command = vi.spyOn(appContext, "triggerCommand").mockReturnValue(undefined);
+ command.mockClear();
+ await draw();
+
+ press(segments()[0], " ");
+
+ expect(command).not.toHaveBeenCalled();
+ });
+ });
+
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);
@@ -190,20 +310,61 @@ describe("TemplateSelectionCard", () => {
});
});
+ /**
+ * A template is a note, and the popup editor the menu opens writes to it. The entry follows the
+ * note rather than the reading taken when the card was drawn.
+ */
+ describe("a template edited while the card is open", () => {
+ beforeEach(() => { offered = [ "type:text:text/html", "template:mine" ]; });
+
+ it("takes the new title once the note is renamed", async () => {
+ await draw();
+ expect(captions()).toEqual([ "Text", "My template" ]);
+
+ answerWith("template:mine", { title: "Renamed" });
+ await report(noteChanged("mine"));
+
+ expect(captions()).toEqual([ "Text", "Renamed" ]);
+ });
+
+ it("takes the new icon, which is a label rather than part of the note", async () => {
+ await draw();
+
+ answerWith("template:mine", { icon: "bx bx-star" });
+ await report(attributeChanged("iconClass", "mine"));
+
+ expect(icons().at(-1)).toContain("bx-star");
+ });
+
+ it("reads again for a note it offers, and not for any other", async () => {
+ await draw();
+ const reads = () => vi.mocked(getNoteTypeOptions).mock.calls.length;
+ const drawn = reads();
+
+ await report(noteChanged("someOtherNote"));
+ expect(reads()).toBe(drawn);
+
+ await report(noteChanged("mine"));
+ expect(reads()).toBe(drawn + 1);
+ });
+ });
+
// #region The dialog, and what the test does to it
/** Drawn, and given the moment it takes to read what a note can be made from. */
async function draw({ newTemplateName }: { newTemplateName?: string } = {}) {
await act(async () => {
render(
- <TemplateSelectionCard
- heading="What to use"
- instruction="Pick what a new one is made from."
- note={OWNER}
- newTemplateName={newTemplateName}
- templates={offered}
- onChange={(ids) => stored.push(ids)}
- />,
+ <ParentComponent.Provider value={host}>
+ <TemplateSelectionCard
+ heading="What to use"
+ instruction="Pick what a new one is made from."
+ note={OWNER}
+ newTemplateName={newTemplateName}
+ templates={offered}
+ onChange={(ids) => stored.push(ids)}
+ />
+ </ParentComponent.Provider>,
container);
await Promise.resolve();
});
@@ -231,6 +392,43 @@ describe("TemplateSelectionCard", () => {
});
}
+ function icons() {
+ return segments().map((element) => element.querySelector(".bx")?.className);
+ }
+
+ /** Answers the next read with one entry changed, the rest as they were. */
+ function answerWith(id: string, changed: Partial<NoteTypeOption>) {
+ vi.mocked(getNoteTypeOptions).mockResolvedValueOnce(
+ AVAILABLE.map((option) => option.id === id ? { ...option, ...changed } : option));
+ }
+
+ /** A renamed note, as the app reports one. */
+ function noteChanged(noteId: string) {
+ const results = new LoadResults([]);
+ results.addNote(noteId, "other");
+ return results;
+ }
+
+ /** A label written on a note, which is how an icon is changed. */
+ function attributeChanged(name: string, noteId: string) {
+ const results = new LoadResults([ {
+ entityName: "attributes",
+ entityId: "attr1",
+ entity: { attributeId: "attr1", noteId, type: "label", name }
+ } as never ]);
+ results.addAttribute("attr1", "other");
+ return results;
+ }
+
+ /** Hands the card what the app reports, and lets the read it asks for answer. */
+ async function report(loadResults: LoadResults) {
+ await act(async () => {
+ host.handleEvent("entitiesReloaded", { loadResults });
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ }
+
function press(target: Element, key: string, options: KeyboardEventInit = {}) {
act(() => {
target.dispatchEvent(
diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.tsx b/apps/client/src/widgets/react/TemplateSelectionCard.tsx
index f928268381..7801031af1 100644
--- a/apps/client/src/widgets/react/TemplateSelectionCard.tsx
+++ b/apps/client/src/widgets/react/TemplateSelectionCard.tsx
@@ -8,12 +8,16 @@ import dialog from "../../services/dialog";
import { t } from "../../services/i18n";
import note_create from "../../services/note_create";
import {
- getNoteTypeOptions, type NoteTypeOption, noteTypeOptionGroupTitle, resolveNoteTypeOptions
+ type NoteTypeOption, noteTypeOptionGroupTitle, resolveNoteTypeOptions
} from "../../services/note_types";
import { type PickerItem, type PickerItemGroup } from "../dialogs/item_picker";
import ActionButton from "./ActionButton";
+import { useNoteTypeOptions } from "./hooks";
import Icon from "./Icon";
import { type SortableItem, SortableCard } from "./SortableCard";
+import {
+ openTemplateMenu, quickEdit, remove, type TemplateCommands, templateNoteId
+} from "./template_commands";
export interface TemplateSelectionCardProps {
heading: string;
@@ -49,8 +53,8 @@ export default function TemplateSelectionCard({
* a caller with nothing to re-render for would otherwise leave the list unchanged.
*/
const [ ids, setIds ] = useState(templates);
- /** Everything a note can be created from, read once when the card mounts. */
- const [ available, setAvailable ] = useState<NoteTypeOption[]>([]);
+ /** Everything a note can be created from, kept current as templates are edited. */
+ const available = useNoteTypeOptions();
/**
* Templates created here, which the app has yet to report back.
*
@@ -61,19 +65,6 @@ export default function TemplateSelectionCard({
useEffect(() => setIds(templates), [ templates ]);
- useEffect(() => {
- let listening = true;
- getNoteTypeOptions()
- .then((options) => {
- if (listening) {
- setAvailable(options);
- }
- })
- .catch((e) => console.error("Failed to read what a note can be made from:", e));
-
- return () => { listening = false; };
- }, []);
-
const known = useMemo(
() => [ ...available, ...made.filter((option) => !available.some((a) => a.id === option.id)) ],
[ available, made ]);
@@ -90,6 +81,36 @@ export default function TemplateSelectionCard({
onChange(next);
}, [ onChange ]);
+ const drop = useCallback((key: string) => {
+ const next = ids.filter((id) => id !== key);
+ setIds(next);
+ onChange(next);
+ }, [ ids, onChange ]);
+
+ /** What the menu on a template does to the list, the rest acting on the note alone. */
+ const commands = useMemo<TemplateCommands>(() => ({
+ onDuplicated: (sourceNoteId, copy) => {
+ const source = offered.find(
+ (option) => option.options.templateNoteId === sourceNoteId);
+ const option: NoteTypeOption = {
+ id: buildTemplateId(copy.noteId),
+ title: copy.title,
+ icon: copy.icon,
+ group: "user",
+ options: { ...source?.options ?? { type: "text" }, templateNoteId: copy.noteId }
+ };
+
+ setMade((was) => [ ...was, option ]);
+ // Beside what it was copied from, which is where a copy is looked for.
+ const at = source ? ids.indexOf(source.id) : -1;
+ const next = [ ...ids ];
+ next.splice(at < 0 ? ids.length : at + 1, 0, option.id);
+ setIds(next);
+ onChange(next);
+ },
+ onDeleted: (noteId) => drop(buildTemplateId(noteId))
+ }), [ drop, ids, offered, onChange ]);
+
/** Asks which of the templates not already offered to add, and returns it as an entry. */
const addExisting = useCallback(async () => {
const taken = new Set(offered.map((option) => option.id));
@@ -131,11 +152,41 @@ export default function TemplateSelectionCard({
onChange={store}
// The grip leads, so the trailing edge is left to what each entry carries there.
gripPlacement="start"
+ onItemKeyDown={(item, event) => {
+ const noteId = templateNoteId(item.key);
+ if (!noteId) {
+ return;
+ }
+
+ if (event.key === " ") {
+ event.preventDefault();
+ quickEdit(noteId);
+ } else if (event.key === "Delete") {
+ event.preventDefault();
+ remove(noteId, commands);
+ }
+ }}
renderItem={(item, index) => (
<>
{item.icon && <Icon icon={item.icon} />}
<span className="template-selection-name">{item.caption}</span>
+ {/* Only a template is a note, and only a note has commands of its own. */}
+ {templateNoteId(item.key) && (
+ <ActionButton
+ className="template-selection-menu"
+ icon="bx bx-dots-vertical-rounded"
+ text={t("template_selection.menu")}
+ onClick={(event) => {
+ event.stopPropagation();
+ const noteId = templateNoteId(item.key);
+ if (noteId) {
+ openTemplateMenu(event, noteId, commands);
+ }
+ }}
+ />
+ )}
+
{/* The last template is not removable: with none offered, nothing could be
created. */}
{items.length > 1 && (
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 4ac5e40cec..ea152e4171 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -17,6 +17,7 @@ import froca from "../../services/froca";
import { t } from "../../services/i18n";
import keyboard_actions from "../../services/keyboard_actions";
import { parseNavigationStateFromUrl, ViewScope } from "../../services/link";
+import { getNoteTypeOptions, type NoteTypeOption } from "../../services/note_types";
import options, { type OptionValue } from "../../services/options";
import protected_session_holder from "../../services/protected_session_holder";
import { consumeSearchTerms } from "../../services/search_jump";
@@ -1937,6 +1938,62 @@ export function useNoteColorClass(note: FNote | null | undefined) {
return colorClass;
}
+/**
+ * Everything a note can be created from: the note types, the templates the app ships and the
+ * reader's own.
+ *
+ * Read when the caller mounts and again whenever a template is made, deleted, renamed or given
+ * another icon, so what is offered is what exists now.
+ */
+export function useNoteTypeOptions() {
+ const [ options, setOptions ] = useState<NoteTypeOption[]>([]);
+ /** How many reads were asked for, and the newest one answered. */
+ const asked = useRef(0);
+ const answered = useRef(0);
+
+ const read = useCallback(() => {
+ const attempt = ++asked.current;
+ getNoteTypeOptions().then((types) => {
+ // Two reads can be in flight at once, the one made on arrival and one a template being
+ // made asks for. They need not answer in the order they were asked, and one of them can
+ // fail and leave no answer at all, so what is taken is what no newer answer has taken
+ // over.
+ if (attempt > answered.current) {
+ answered.current = attempt;
+ setOptions(types);
+ }
+ }).catch((e) => console.error("Failed to read what a note can be made from:", e));
+ }, []);
+
+ useEffect(() => {
+ read();
+ // A read still in flight when the caller goes has nothing left to answer.
+ return () => { answered.current = asked.current + 1; };
+ }, [ read ]);
+
+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
+ const offered = new Set(options
+ .map((option) => option.options.templateNoteId)
+ .filter((noteId) => !!noteId));
+ // A note taking `#template` or losing it changes what can be created. So does any attribute
+ // of a note already offered: the icon comes from `iconClass`, from `workspaceIconClass`
+ // where there is none, and from a `#geoLocation` on a text note, all of them labels rather
+ // than part of the note row a reload would report.
+ const templated = loadResults.getAttributeRows().some((attribute) =>
+ attribute.name === "template"
+ || (!!attribute.noteId && offered.has(attribute.noteId)));
+ const renamed = options.some((option) =>
+ option.options.templateNoteId
+ && loadResults.isNoteReloaded(option.options.templateNoteId));
+
+ if (templated || renamed) {
+ read();
+ }
+ });
+
+ return options;
+}
+
export function useTextEditor(noteContext: NoteContext | null | undefined) {
const [ textEditor, setTextEditor ] = useState<CKTextEditor | null>(null);
const requestIdRef = useRef(0);
diff --git a/apps/client/src/widgets/react/template_commands.ts b/apps/client/src/widgets/react/template_commands.ts
new file mode 100644
index 0000000000..ddaf12e647
--- /dev/null
+++ b/apps/client/src/widgets/react/template_commands.ts
@@ -0,0 +1,110 @@
+import { parseNoteTypeId } from "@triliumnext/commons";
+
+import appContext from "../../components/app_context";
+import contextMenu from "../../menus/context_menu";
+import branches from "../../services/branches";
+import froca from "../../services/froca";
+import { t } from "../../services/i18n";
+import server from "../../services/server";
+import { isDesktop } from "../../services/utils";
+import ws from "../../services/ws";
+
+/** What a template entry can be asked to do, beyond being moved or taken off the list. */
+export interface TemplateCommands {
+ /** Adds the copy a duplicate made to the list, beside the template it was copied from. */
+ onDuplicated: (
+ sourceNoteId: string, copy: { noteId: string, title: string, icon: string }) => void;
+ /** Takes a template off the list once its note has been deleted. */
+ onDeleted: (noteId: string) => void;
+}
+
+/** The note a template entry stands for, or nothing for an entry that is a note type. */
+export function templateNoteId(key: string) {
+ const parsed = parseNoteTypeId(key);
+ return parsed?.kind === "template" ? parsed.templateNoteId : undefined;
+}
+
+/**
+ * Opens the menu of what can be done with a template note.
+ *
+ * The commands act on the note rather than on the list, so they are the same wherever templates are
+ * managed. Only the two that change what the list holds report back.
+ */
+export function openTemplateMenu(
+ event: { pageX: number, pageY: number }, noteId: string, commands: TemplateCommands
+) {
+ contextMenu.show({
+ x: event.pageX,
+ y: event.pageY,
+ items: [
+ {
+ title: t("tree-context-menu.open-in-popup"),
+ uiIcon: "bx bx-edit",
+ shortcut: "Space",
+ handler: () => quickEdit(noteId)
+ },
+ // A window of its own is a desktop's to give.
+ ...(isDesktop() ? [ {
+ title: t("tree-context-menu.open-in-a-new-window"),
+ uiIcon: "bx bx-window-open",
+ handler: () => appContext.triggerCommand("openInWindow", { notePath: noteId })
+ } ] : []),
+ {
+ title: t("tree-context-menu.duplicate"),
+ uiIcon: "bx bx-outline",
+ handler: () => duplicate(noteId, commands)
+ },
+ { kind: "separator" },
+ {
+ title: t("note_actions.delete_note"),
+ uiIcon: "bx bx-trash destructive-action-icon",
+ shortcut: "Delete",
+ handler: () => remove(noteId, commands)
+ }
+ ],
+ selectMenuItemHandler() {}
+ });
+}
+
+/** Opens a template in the popup editor, which leaves whatever asked for it standing. */
+export function quickEdit(noteId: string) {
+ appContext.triggerCommand("openInPopup", { noteIdOrPath: noteId });
+}
+
+/**
+ * Copies a template and reports the copy.
+ *
+ * The wait is what makes the copy readable: the server names the note, and it has to be in froca
+ * before its title and icon can be read from it.
+ */
+export async function duplicate(noteId: string, { onDuplicated }: TemplateCommands) {
+ const note = await froca.getNote(noteId);
+ const parentNoteId = note?.getParentBranches()[0]?.parentNoteId;
+ if (!parentNoteId) {
+ return;
+ }
+
+ const { note: copy } = await server.post<{ note: { noteId: string } }>(
+ `notes/${noteId}/duplicate/${parentNoteId}`);
+
+ await ws.waitForMaxKnownEntityChangeId();
+
+ const made = await froca.getNote(copy.noteId);
+ if (made) {
+ onDuplicated(noteId, { noteId: made.noteId, title: made.title, icon: made.getIcon() });
+ }
+}
+
+/** Asks whether to delete a template, and reports it once it is gone. */
+export async function remove(noteId: string, { onDeleted }: TemplateCommands) {
+ const note = await froca.getNote(noteId);
+ const branchId = note?.getParentBranches()[0]?.branchId;
+ if (!branchId) {
+ return;
+ }
+
+ const deleted = await branches.deleteNotes([ branchId ], false, false);
+ if (deleted) {
+ onDeleted(noteId);
+ }
+}