Skip to content

Build your personal knowledge base with Trilium Notes

feat(notes): choose a new note's type from the insert menu in the chooser

Elian Doran879a5a1cfd3e
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.ts
index bdee145376..872c051ae9 100644
--- a/apps/client/src/services/note_autocomplete.spec.ts
+++ b/apps/client/src/services/note_autocomplete.spec.ts
@@ -310,11 +310,11 @@ describe("createNoteFromSuggestion", () => {
expect(createNote).toHaveBeenLastCalledWith("root/inbox", expect.objectContaining({ title: "Inboxed" }));
});
- it("puts the note where the type chooser says, over the row's own parent", async () => {
- chooseNoteType.mockResolvedValue({ success: true, noteType: "code", notePath: "chosen/path" });
+ it("puts the note where the type chooser says, over the row's own parent, as the type it says", async () => {
+ chooseNoteType.mockResolvedValue({ success: true, noteType: "code", mime: "text/x-python", notePath: "chosen/path" });
await createNoteFromSuggestion({ action: "create-child-note", noteTitle: "X", parentNoteId: "p" });
- expect(createNote).toHaveBeenCalledWith("chosen/path", expect.objectContaining({ type: "code" }));
+ expect(createNote).toHaveBeenCalledWith("chosen/path", expect.objectContaining({ type: "code", mime: "text/x-python" }));
});
it.each([
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index 2a967a6517..cce9d9f097 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -112,7 +112,7 @@ export async function getNoteSuggestions(term: string, { allowCreatingNotes, all
* need not be.
*/
export async function createNoteFromSuggestion(suggestion: Suggestion, childParentNotePath?: string | null) {
- const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();
+ const { success, noteType, mime, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();
if (!success) {
return;
}
@@ -128,6 +128,7 @@ export async function createNoteFromSuggestion(suggestion: Suggestion, childPare
title: suggestion.noteTitle,
activate: false,
type: noteType,
+ mime,
templateNoteId,
cloneToNoteIds
});
diff --git a/apps/client/src/services/note_create.spec.ts b/apps/client/src/services/note_create.spec.ts
index 1b1b0944c4..b4d740e438 100644
--- a/apps/client/src/services/note_create.spec.ts
+++ b/apps/client/src/services/note_create.spec.ts
@@ -325,12 +325,13 @@ describe("createNoteWithTypePrompt", () => {
expect(triggerCommand).toHaveBeenCalledWith("chooseNoteType", expect.anything());
});
- it("creates a note with chosen type/template, preferring the chooser notePath", async () => {
+ it("creates a note with chosen type/MIME/template, preferring the chooser notePath", async () => {
setActiveContext(true);
triggerCommand.mockImplementation((_name: string, data: any) => {
data.callback({
success: true,
noteType: "code",
+ mime: "text/x-python",
templateNoteId: "tpl-1",
notePath: "chosen-parent"
});
@@ -340,7 +341,7 @@ describe("createNoteWithTypePrompt", () => {
expect(server.post).toHaveBeenCalledWith(
`notes/chosen-parent/children?target=into&targetBranchId=`,
- expect.objectContaining({ type: "code", templateNoteId: "tpl-1" }),
+ expect.objectContaining({ type: "code", mime: "text/x-python", templateNoteId: "tpl-1" }),
undefined
);
});
diff --git a/apps/client/src/services/note_create.ts b/apps/client/src/services/note_create.ts
index ef50cafb20..ecac21c0b1 100644
--- a/apps/client/src/services/note_create.ts
+++ b/apps/client/src/services/note_create.ts
@@ -151,13 +151,14 @@ async function chooseNoteType() {
}
async function createNoteWithTypePrompt(parentNotePath: string, options: CreateNoteOpts = {}) {
- const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await chooseNoteType();
+ const { success, noteType, mime, templateNoteId, notePath, cloneToNoteIds } = await chooseNoteType();
if (!success) {
return;
}
options.type = noteType;
+ options.mime = mime;
options.templateNoteId = templateNoteId;
options.cloneToNoteIds = cloneToNoteIds;
diff --git a/apps/client/src/services/note_types.spec.ts b/apps/client/src/services/note_types.spec.ts
index 194ed5cacb..f2d5c429a6 100644
--- a/apps/client/src/services/note_types.spec.ts
+++ b/apps/client/src/services/note_types.spec.ts
@@ -235,14 +235,19 @@ describe("getBuiltInTemplates", () => {
withTemplates([], ["tpl-plain"]);
});
- it("warns and returns nothing when the templates root is missing", async () => {
+ /** Every item, those in submenus included. */
+ const allItems = (items: any[]): any[] => items.flatMap((i) => [ i, ...allItems(i.items ?? []) ]);
+ const builtInSubmenus = (items: any[]) => items
+ .filter((i) => i.title === "note_types.snippet" || i.title === "note_types.book")
+ .map((i) => i.title);
+
+ it("warns and offers no built-in templates when the templates root is missing", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const restore = withTemplatesRoot(null);
try {
const items = await noteTypesService.getNoteTypeItems();
- // No header/separator coming from built-in templates -> only blank note types remain.
- expect(items.some((i: any) => i.kind === "separator")).toBe(false);
- expect(items.some((i: any) => i.kind === "header")).toBe(false);
+ expect(allItems(items).some((i) => i.templateNoteId)).toBe(false);
+ expect(builtInSubmenus(items)).toEqual([]);
expect(warn).toHaveBeenCalled();
} finally {
restore();
@@ -250,20 +255,19 @@ describe("getBuiltInTemplates", () => {
}
});
- it("returns nothing when the templates root has no children", async () => {
+ it("offers no built-in templates when the templates root has no children", async () => {
const restore = withTemplatesRoot([]);
try {
const items = await noteTypesService.getNoteTypeItems();
- expect(items.some((i: any) => i.kind === "separator")).toBe(false);
- expect(items.some((i: any) => i.kind === "header")).toBe(false);
+ expect(allItems(items).some((i) => i.templateNoteId)).toBe(false);
+ expect(builtInSubmenus(items)).toEqual([]);
} finally {
restore();
}
});
- it("emits a separator for non-collection group and a header for the collections group, filtering by labels", async () => {
- // Children include: a plain template (non-collection), a collection template,
- // and a child that is neither a template nor matches -> skipped in both passes.
+ it("puts a template of no group after a separator and a collection in its submenu, filtering by labels", async () => {
+ // A plain template, a collection template, and a child that is not a template at all.
const plain = fakeTemplate("tpl-plain", ["template"], "Plain");
const collection = fakeTemplate("tpl-coll", ["template", "collection"], "Coll");
const notTemplate = fakeTemplate("tpl-skip", ["collection"], "Skip"); // missing "template"
@@ -271,37 +275,22 @@ describe("getBuiltInTemplates", () => {
try {
const items: any[] = await noteTypesService.getNoteTypeItems("cmd" as never);
- // Non-collection pass (filterCollections=false, title=null) pushes a separator
- // then the plain template.
- const sepIdx = items.findIndex((i) => i.kind === "separator");
- expect(sepIdx).toBeGreaterThanOrEqual(0);
- expect(items.some((i) => i.templateNoteId === "tpl-plain")).toBe(true);
+ // The plain template stands at the top level, after a separator.
+ const plainIdx = items.findIndex((i) => i.templateNoteId === "tpl-plain");
+ expect(plainIdx).toBeGreaterThan(0);
+ expect(items[plainIdx - 1].kind).toBe("separator");
- // Collections pass (filterCollections=true, title set) pushes a header then
- // the collection template.
- const headerIdx = items.findIndex((i) => i.kind === "header");
- expect(headerIdx).toBeGreaterThanOrEqual(0);
- expect(items.some((i) => i.templateNoteId === "tpl-coll")).toBe(true);
+ // The collection template is in the collections submenu, and only there.
+ const collections = items.find((i) => i.title === "note_types.book");
+ expect(collections.items.map((i: any) => i.templateNoteId)).toEqual([ "tpl-coll" ]);
+ expect(allItems(items).filter((i) => i.templateNoteId === "tpl-coll")).toHaveLength(1);
+ expect(allItems(items).filter((i) => i.templateNoteId === "tpl-plain")).toHaveLength(1);
// The note missing the "template" label is never included.
- expect(items.some((i) => i.templateNoteId === "tpl-skip")).toBe(false);
-
- // Each template is emitted in EXACTLY ONE pass — the label filter must keep
- // tpl-plain out of the collections pass and tpl-coll out of the non-collection
- // pass. An inverted/broken filter would emit a template in both passes (a
- // duplicate), which `.some(...)` above would not catch.
- const plainIdx = items.findIndex((i) => i.templateNoteId === "tpl-plain");
- const collIdx = items.findIndex((i) => i.templateNoteId === "tpl-coll");
- expect(items.filter((i) => i.templateNoteId === "tpl-plain")).toHaveLength(1);
- expect(items.filter((i) => i.templateNoteId === "tpl-coll")).toHaveLength(1);
-
- // ...and the placement reflects which pass emitted them: tpl-plain (non-collection
- // pass) precedes the collections header; tpl-coll (collections pass) follows it.
- expect(plainIdx).toBeLessThan(headerIdx);
- expect(collIdx).toBeGreaterThan(headerIdx);
+ expect(allItems(items).some((i) => i.templateNoteId === "tpl-skip")).toBe(false);
- // built-in template items carry command/type/icon/title.
- const plainItem = items.find((i) => i.templateNoteId === "tpl-plain");
+ // Built-in template items carry command/type/icon/title.
+ const plainItem = items[plainIdx];
expect(plainItem.command).toBe("cmd");
expect(plainItem.type).toBe("text");
expect(plainItem.uiIcon).toBe("tn-icon bx-x");
@@ -309,8 +298,7 @@ describe("getBuiltInTemplates", () => {
expect(plainItem.badges).toHaveLength(1);
expect(plainItem.badges[0].className).toBe("new-note-type-badge");
// The old collection template is not marked new.
- const collItem = items.find((i) => i.templateNoteId === "tpl-coll");
- expect(collItem.badges).toBeUndefined();
+ expect(collections.items[0].badges).toBeUndefined();
} finally {
restore();
}
@@ -407,7 +395,7 @@ describe("new template badges", () => {
}
});
- it("puts the collections in a submenu of the menu, and under a header of the list", async () => {
+ it("puts the collections in a submenu of the menu", async () => {
withTemplates([], [ "tpl-coll" ]);
const restore = withTemplatesRoot([
fakeTemplate("tpl-plain", [ "template" ], "Plain"),
@@ -429,11 +417,6 @@ describe("new template badges", () => {
expect(menu.some((i) => i.kind === "header")).toBe(false);
expect(menu.some((i) => i.templateNoteId === "tpl-plain")).toBe(true);
- // The note type chooser renders a flat list, so it keeps the header.
- const list: any[] = await noteTypesService.getNoteTypeItems();
- expect(list.some((i) => i.kind === "header" && i.title === "note_types.collections")).toBe(true);
- expect(list.some((i) => i.templateNoteId === "tpl-coll")).toBe(true);
- expect(list.some((i) => i.items)).toBe(false);
} finally {
restore();
}
@@ -465,13 +448,6 @@ describe("new template badges", () => {
// After the note types it holds, as the templates follow the note types everywhere in the menu.
expect(titles(more.items).slice(-2)).toEqual([ "separator", "tpl-ai" ]);
- // The chooser's flat list keeps the snippets inline, after a separator.
- const list: any[] = await noteTypesService.getNoteTypeItems();
- expect(list.some((i) => i.items)).toBe(false);
- const listed = titles(list);
- expect(listed.slice(listed.indexOf("tpl-text-snippet") - 1, listed.indexOf("tpl-text-snippet") + 2))
- .toEqual([ "separator", "tpl-text-snippet", "tpl-code-snippet" ]);
- expect(listed.indexOf("tpl-ai")).toBe(listed.indexOf("llmChat") + 1);
// Without the AI features, neither the chat nor the quick action is offered.
llmFlag.mockReturnValue(false);
@@ -512,9 +488,6 @@ describe("new template badges", () => {
const withoutAi = noteTypesService.buildNoteTypeItems(data, "insertChildNote" as never).map(key);
expect(withoutAi.slice(0, 5)).toEqual([ "text", "markdown", "code", "spreadsheet", "separator" ]);
- // The chooser's flat list keeps the order of `NOTE_TYPES`, which the note type switcher shares.
- const list = (await noteTypesService.getNoteTypeItems()).map(key);
- expect(list.slice(0, 3)).toEqual([ "text", "spreadsheet", "canvas" ]);
} finally {
restore();
}
@@ -540,16 +513,12 @@ describe("new template badges", () => {
const submenus = menu.filter((i) => i.items && i.type === undefined).map((i) => i.title);
expect(submenus).toEqual([ "note_types.snippet", "note_types.book", "note_types.more" ]);
- // The chooser's flat list keeps them inline.
- const list: any[] = await noteTypesService.getNoteTypeItems();
- expect(rare.every((type) => list.some((i) => i.type === type))).toBe(true);
- expect(list.some((i) => i.title === "note_types.more")).toBe(false);
} finally {
restore();
}
});
- it("escapes template titles for the menu, which renders HTML, and not for the list, which renders text", async () => {
+ it("escapes template titles, as a menu renders them as HTML", async () => {
const user = buildNote({ id: "userTemplateHtml", title: "<img src=x onerror=alert(1)>", "#template": "" });
withTemplates([ user.noteId ]);
const restore = withTemplatesRoot([
@@ -572,9 +541,6 @@ describe("new template badges", () => {
expect(rendered(titleOf(menu, "tpl-snippet"))).toEqual({ elements: 0, text: "A & <b>B</b>" });
expect(rendered(titleOf(menu, "tpl-coll"))).toEqual({ elements: 0, text: "<i>Board</i>" });
- const list = await noteTypesService.getNoteTypeItems();
- expect(titleOf(list, user.noteId)).toBe("<img src=x onerror=alert(1)>");
- expect(titleOf(list, "tpl-snippet")).toBe("A & <b>B</b>");
} finally {
restore();
}
@@ -608,8 +574,6 @@ describe("new template badges", () => {
const again = codeRow(noteTypesService.buildNoteTypeItems(data, "insertChildNote" as never));
expect(again.items.filter((i: any) => i.mime).map((i: any) => i.mime)).toContain("text/apl");
- // The chooser's flat list cannot open a submenu.
- expect(codeRow(await noteTypesService.getNoteTypeItems()).items).toBeUndefined();
} finally {
options.set("codeNotesMimeTypes", original);
triggerCommand.mockRestore();
diff --git a/apps/client/src/services/note_types.ts b/apps/client/src/services/note_types.ts
index e4567a5d70..3e0823371d 100644
--- a/apps/client/src/services/note_types.ts
+++ b/apps/client/src/services/note_types.ts
@@ -219,43 +219,17 @@ async function loadNoteTypeData(): Promise<NoteTypeData> {
return { builtInTemplateNotes, userTemplateNotes, newTemplates: new Set(newTemplateNoteIds) };
}
-type NoteTypeLayout = "menu" | "list";
-
/**
- * The note type items. A `"menu"` groups the note types by kind ({@link MENU_GROUPS}) and opens the
- * snippets, the collections and the rarely created note types from submenus; a `"list"`, such as
- * the note type chooser draws, cannot open one, so it lists them inline in the order of
- * {@link NOTE_TYPES}. The AI quick action template is offered only where AI is enabled: last in
- * the menu's "More" submenu, after its note types, and beside the AI chat note type in the list.
+ * The menu of what a new note can be made from, as the note tree's insert menus and the note type
+ * chooser offer it: the note types grouped by kind ({@link MENU_GROUPS}), the snippets, the
+ * collections and the rarely created note types in submenus, then the user's templates. The AI
+ * quick action template, offered only where AI is enabled, closes the "More" submenu.
*/
-function buildNoteTypeItems(data: NoteTypeData, command?: TreeCommandNames, layout: NoteTypeLayout = "menu") {
+function buildNoteTypeItems(data: NoteTypeData, command?: TreeCommandNames) {
const { builtInTemplateNotes, userTemplateNotes, newTemplates } = data;
const builtIn = (group: BuiltInTemplateGroup) =>
- getBuiltInTemplates(command, builtInTemplateNotes, group, newTemplates, layout);
+ getBuiltInTemplates(command, builtInTemplateNotes, group, newTemplates);
const blankTypes = getBlankNoteTypes(command);
-
- const items = layout === "menu"
- ? buildMenuItems(blankTypes, builtIn, command)
- : buildListItems(blankTypes, builtIn);
- items.push(...getUserTemplates(command, userTemplateNotes, newTemplates, layout));
- return items;
-}
-
-/**
- * How the menus order and group the blank note types, each group set apart by a separator. The
- * last group opens from the "More" submenu. A note type in none of them is not offered.
- */
-const MENU_GROUPS: Pick<NoteTypeMapping, "type" | "mime">[][] = [
- [ { type: "text" }, { type: "code", mime: MARKDOWN_NOTE_TYPE_MIME }, { type: "code", mime: "text/plain" }, { type: "spreadsheet" }, { type: "llmChat" } ],
- [ { type: "canvas" }, { type: "mermaid" }, { type: "mindMap" }, { type: "relationMap" } ]
-];
-const MORE_GROUP: Pick<NoteTypeMapping, "type" | "mime">[] = [
- { type: "noteMap" }, { type: "render" }, { type: "search" }, { type: "webView" }
-];
-
-type BuiltInTemplates = (group: BuiltInTemplateGroup) => MenuItem<TreeCommandNames>[];
-
-function buildMenuItems(blankTypes: MenuCommandItem<TreeCommandNames>[], builtIn: BuiltInTemplates, command?: TreeCommandNames) {
const inGroup = (group: Pick<NoteTypeMapping, "type" | "mime">[]) => group.flatMap(({ type, mime }) => {
const item = blankTypes.find((blankType) => blankType.type === type && (mime === undefined || blankType.mime === mime));
if (!item) return [];
@@ -278,23 +252,26 @@ function buildMenuItems(blankTypes: MenuCommandItem<TreeCommandNames>[], builtIn
if (collections.length > 0) items.push({ title: t("note_types.book"), uiIcon: "bx bx-book", items: collections });
const aiQuickActions = isExperimentalFeatureEnabled("llm") ? builtIn("aiQuickAction") : [];
items.push({ title: t("note_types.more"), uiIcon: "bx bx-dots-horizontal-rounded", items: [ ...inGroup(MORE_GROUP), ...withLeading(SEPARATOR, aiQuickActions) ] });
- return items;
-}
-function buildListItems(blankTypes: MenuCommandItem<TreeCommandNames>[], builtIn: BuiltInTemplates) {
- const items: MenuItem<TreeCommandNames>[] = [];
- for (const blankType of blankTypes) {
- items.push(blankType);
- if (blankType.type === "llmChat") items.push(...builtIn("aiQuickAction"));
- }
- items.push(...withLeading(SEPARATOR, [ ...builtIn("snippet"), ...builtIn("other") ]));
- items.push(...withLeading({ title: t("note_types.collections"), kind: "header" }, builtIn("collection")));
+ items.push(...getUserTemplates(command, userTemplateNotes, newTemplates));
return items;
}
-/** Builds the note type list of the note type chooser. Use {@link loadNoteTypeData} directly to build several. */
+/**
+ * How the menus order and group the blank note types, each group set apart by a separator. The
+ * last group opens from the "More" submenu. A note type in none of them is not offered.
+ */
+const MENU_GROUPS: Pick<NoteTypeMapping, "type" | "mime">[][] = [
+ [ { type: "text" }, { type: "code", mime: MARKDOWN_NOTE_TYPE_MIME }, { type: "code", mime: "text/plain" }, { type: "spreadsheet" }, { type: "llmChat" } ],
+ [ { type: "canvas" }, { type: "mermaid" }, { type: "mindMap" }, { type: "relationMap" } ]
+];
+const MORE_GROUP: Pick<NoteTypeMapping, "type" | "mime">[] = [
+ { type: "noteMap" }, { type: "render" }, { type: "search" }, { type: "webView" }
+];
+
+/** Builds a single note type menu. Use {@link loadNoteTypeData} directly to build several. */
async function getNoteTypeItems(command?: TreeCommandNames) {
- return buildNoteTypeItems(await loadNoteTypeData(), command, "list");
+ return buildNoteTypeItems(await loadNoteTypeData(), command);
}
function getBlankNoteTypes(command?: TreeCommandNames): MenuCommandItem<TreeCommandNames>[] {
@@ -345,7 +322,7 @@ function getCodeLanguageItems(command?: TreeCommandNames): MenuItem<TreeCommandN
];
}
-function getUserTemplates(command: TreeCommandNames | undefined, templateNotes: FNote[], newTemplates: Set<string>, layout: NoteTypeLayout) {
+function getUserTemplates(command: TreeCommandNames | undefined, templateNotes: FNote[], newTemplates: Set<string>) {
if (templateNotes.length === 0) {
return [];
}
@@ -359,7 +336,8 @@ function getUserTemplates(command: TreeCommandNames | undefined, templateNotes:
for (const templateNote of templateNotes) {
const item: MenuItem<TreeCommandNames> = {
- title: templateTitle(templateNote, layout),
+ // A menu renders titles as HTML.
+ title: escapeHtml(templateNote.title),
uiIcon: templateNote.getIcon(),
command,
type: templateNote.type,
@@ -395,7 +373,7 @@ function builtInTemplateGroup(templateNote: FNote): BuiltInTemplateGroup {
return "other";
}
-function getBuiltInTemplates(command: TreeCommandNames | undefined, childNotes: FNote[], group: BuiltInTemplateGroup, newTemplates: Set<string>, layout: NoteTypeLayout) {
+function getBuiltInTemplates(command: TreeCommandNames | undefined, childNotes: FNote[], group: BuiltInTemplateGroup, newTemplates: Set<string>) {
const items: MenuItem<TreeCommandNames>[] = [];
for (const templateNote of childNotes) {
@@ -404,7 +382,8 @@ function getBuiltInTemplates(command: TreeCommandNames | undefined, childNotes:
}
const item: MenuItem<TreeCommandNames> = {
- title: templateTitle(templateNote, layout),
+ // A menu renders titles as HTML.
+ title: escapeHtml(templateNote.title),
uiIcon: templateNote.getIcon(),
command,
type: templateNote.type,
@@ -427,11 +406,6 @@ function getBuiltInTemplates(command: TreeCommandNames | undefined, childNotes:
return items;
}
-/** A template's title as the layout renders it: `Menu` renders titles as HTML, a list as text. */
-function templateTitle(templateNote: FNote, layout: NoteTypeLayout) {
- return layout === "menu" ? escapeHtml(templateNote.title) : templateNote.title;
-}
-
/** `items` led by `lead`, or nothing when there are no items to lead. */
function withLeading(lead: MenuItem<TreeCommandNames>, items: MenuItem<TreeCommandNames>[]) {
return items.length > 0 ? [ lead, ...items ] : [];
diff --git a/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx b/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx
index 8063ef5439..fb19975210 100644
--- a/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx
+++ b/apps/client/src/widgets/dialogs/note_type_chooser.spec.tsx
@@ -15,10 +15,18 @@ vi.mock("../../services/i18n", () => ({
t: (key: string) => key
}));
+/** The note types as the menus lay them out: a submenu of languages and one of templates. */
const noteTypeItems = vi.hoisted(() => {
const items = [
{ title: "Text", type: "text", uiIcon: "bx bx-note" },
- { title: "Code", type: "code", uiIcon: "bx bx-code" }
+ {
+ title: "Code", type: "code", mime: "text/plain", uiIcon: "bx bx-code", items: [
+ { title: "Plain text", type: "code", mime: "text/plain" },
+ { title: "Python", type: "code", mime: "text/x-python" }
+ ]
+ },
+ { kind: "separator" },
+ { title: "note_types.book", uiIcon: "bx bx-book", items: [ { title: "Board", type: "book", templateNoteId: "_template_board" } ] }
];
let resolveItems: (value: typeof items) => void = () => {};
let promise = Promise.resolve(items);
@@ -41,7 +49,8 @@ const noteTypeItems = vi.hoisted(() => {
vi.mock("../../services/note_types", () => ({
default: {
- getNoteTypeItems: () => noteTypeItems.get()
+ loadNoteTypeData: () => noteTypeItems.get(),
+ buildNoteTypeItems: (data: unknown) => data
}
}));
@@ -107,26 +116,19 @@ describe("NoteTypeChooserDialog", () => {
container.remove();
});
- it("focuses Text on open so Enter creates a text note", async () => {
- const callback = vi.fn();
-
- await openChooser(callback);
+ it("starts at Text, so Enter creates a text note", async () => {
+ const callback = await openChooser();
await resolveNoteTypes();
- const item = textItem();
- expect(item).not.toBeNull();
- expect(document.activeElement).toBe(item);
-
- item?.dispatchEvent(new KeyboardEvent("keydown", {
- key: "Enter",
- bubbles: true,
- cancelable: true
- }));
+ await vi.waitFor(() => expect(activeRow()).toBe("Text"));
+ expect(document.activeElement).toBe(menu());
+ key("Enter");
expect(callback).toHaveBeenCalledExactlyOnceWith({
success: true,
noteType: "text",
- templateNoteId: "",
+ mime: undefined,
+ templateNoteId: undefined,
notePath: undefined
});
});
@@ -141,10 +143,63 @@ describe("NoteTypeChooserDialog", () => {
await resolveNoteTypes();
- expect(textItem()).not.toBeNull();
+ await vi.waitFor(() => expect(menu()).not.toBeNull());
expect(document.activeElement).toBe(input);
});
+ it("lists the note types as the menus do, and filters them, nested ones included", async () => {
+ const callback = await openChooser();
+ await resolveNoteTypes();
+ await vi.waitFor(() => expect(activeRow()).toBe("Text"));
+
+ // In the dialog's flow, where the list of types stood, rather than beside an anchor.
+ expect(menu()?.classList.contains("tn-menu-inline")).toBe(true);
+ expect(menu()?.parentElement?.classList.contains("note-type-chooser-list")).toBe(true);
+ // The submenus of the menus, and the input that filters through them.
+ expect(menu()?.querySelectorAll("li.dropdown-submenu")).toHaveLength(2);
+ const filter = () => menu()?.querySelector<HTMLInputElement>("input.tn-menu-filter-input");
+ expect(filter()).not.toBeNull();
+
+ key("p");
+ await vi.waitFor(() => expect(document.activeElement).toBe(filter()));
+ const input = filter();
+ if (!input) throw new Error("no filter input");
+ input.value = "pyt";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() => expect(activeRow()).toMatch(/^Python/));
+ key("Enter");
+
+ // A language is a code note of its own MIME type.
+ expect(callback).toHaveBeenCalledExactlyOnceWith({
+ success: true,
+ noteType: "code",
+ mime: "text/x-python",
+ templateNoteId: undefined,
+ notePath: undefined
+ });
+ });
+
+ it("hands back the template of a collection, and closes on Escape", async () => {
+ const callback = await openChooser();
+ await resolveNoteTypes();
+ await vi.waitFor(() => expect(activeRow()).toBe("Text"));
+
+ key("b");
+ const input = () => menu()?.querySelector<HTMLInputElement>("input.tn-menu-filter-input");
+ await vi.waitFor(() => expect(document.activeElement).toBe(input()));
+ await vi.waitFor(() => expect(activeRow()).toMatch(/^Board/));
+ key("Enter");
+ expect(callback).toHaveBeenCalledWith(expect.objectContaining({
+ success: true, noteType: "book", templateNoteId: "_template_board"
+ }));
+ await vi.waitFor(() => expect(menu()).toBeNull());
+
+ await openChooser();
+ await vi.waitFor(() => expect(activeRow()).toBe("Text"));
+ key("Escape");
+ await vi.waitFor(() => expect(menu()).toBeNull());
+ });
+
async function openChooser(callback = vi.fn()) {
await act(async () => {
await host.handleEventInChildren("chooseNoteType", { callback });
@@ -158,8 +213,20 @@ describe("NoteTypeChooserDialog", () => {
});
}
- function textItem() {
- return container.querySelector<HTMLElement>('.dropdown-item[data-value="text,"]');
+ function menu() {
+ return container.querySelector<HTMLElement>(".note-type-chooser-dialog [role=menu].tn-menu");
+ }
+
+ function key(name: string) {
+ const event = new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true });
+ (document.activeElement ?? document.body).dispatchEvent(event);
+ return event;
+ }
+
+ /** The active row's text, as the menu names it to assistive technology. */
+ function activeRow() {
+ const id = menu()?.getAttribute("aria-activedescendant");
+ return (id ? document.getElementById(id) : null)?.textContent ?? null;
}
function parentPathInput() {
diff --git a/apps/client/src/widgets/dialogs/note_type_chooser.tsx b/apps/client/src/widgets/dialogs/note_type_chooser.tsx
index a2ee1c0f03..3b95419281 100644
--- a/apps/client/src/widgets/dialogs/note_type_chooser.tsx
+++ b/apps/client/src/widgets/dialogs/note_type_chooser.tsx
@@ -1,20 +1,21 @@
-import Modal from "../react/Modal";
+import { useEffect, useRef, useState } from "preact/hooks";
+
+import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";
+import type { TreeCommandNames } from "../../menus/tree_context_menu";
import { t } from "../../services/i18n";
-import FormGroup from "../react/FormGroup";
-import NoteAutocomplete from "../react/NoteAutocomplete";
-import FormList, { FormListHeader, FormListItem } from "../react/FormList";
-import { RefObject } from "preact";
-import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import type { Suggestion } from "../../services/note_autocomplete";
import note_types from "../../services/note_types";
-import { MenuCommandItem, MenuItem } from "../../menus/context_menu";
-import { TreeCommandNames } from "../../menus/tree_context_menu";
-import { Suggestion } from "../../services/note_autocomplete";
-import SimpleBadge from "../react/Badge";
+import FormGroup from "../react/FormGroup";
import { useTriliumEvent } from "../react/hooks";
+import Menu from "../react/Menu";
+import Modal from "../react/Modal";
+import NoteAutocomplete from "../react/NoteAutocomplete";
export interface ChooseNoteTypeResponse {
success: boolean;
noteType?: string;
+ /** The MIME type of the note, for a code note of a given language. */
+ mime?: string;
templateNoteId?: string;
notePath?: string;
/** Extra parents to clone the created note into, from the template's default parents. */
@@ -23,50 +24,54 @@ export interface ChooseNoteTypeResponse {
export type ChooseNoteTypeCallback = (data: ChooseNoteTypeResponse) => void;
-const SEPARATOR_TITLE_REPLACEMENTS = [
- t("note_type_chooser.builtin_templates"),
- t("note_type_chooser.templates")
-];
-
+/**
+ * Asks what a new note is made from and where it goes. The note types are the menu the note tree
+ * offers to insert notes from, its submenus and filter included, standing in the dialog's flow.
+ */
export default function NoteTypeChooserDialogComponent() {
const [ callback, setCallback ] = useState<ChooseNoteTypeCallback>();
const [ shown, setShown ] = useState(false);
const [ parentNote, setParentNote ] = useState<Suggestion | null>();
- const [ noteTypes, setNoteTypes ] = useState<MenuItem<TreeCommandNames>[]>([]);
- const modalRef = useRef<HTMLDivElement>(null);
- const { tryFocusFirstNoteType, resetAutoFocus } = useFirstNoteTypeFocus(modalRef, shown, noteTypes.length);
+ const [ noteTypes, setNoteTypes ] = useState<MenuItem<TreeCommandNames>[]>();
+ const [ listHost, setListHost ] = useState<HTMLDivElement | null>(null);
+ const menuRef = useRef<HTMLDivElement | null>(null);
+ /**
+ * Whether the user moved to another field before the note types arrived, which the menu then
+ * leaves focus in. Until then it takes focus at Text, so Enter creates a text note.
+ */
+ const userMovedFocus = useRef(false);
useTriliumEvent("chooseNoteType", ({ callback }) => {
- resetAutoFocus();
+ userMovedFocus.current = false;
setCallback(() => callback);
setShown(true);
});
useEffect(() => {
- note_types.getNoteTypeItems().then(noteTypes => {
- let index = -1;
-
- setNoteTypes((noteTypes ?? []).map((item) => {
- if ("kind" in item && item.kind === "separator") {
- index++;
- return {
- kind: "header",
- title: SEPARATOR_TITLE_REPLACEMENTS[index]
- }
- }
-
- return item;
- }));
- });
+ note_types.loadNoteTypeData().then((data) => setNoteTypes(note_types.buildNoteTypeItems(data)));
}, []);
- function onNoteTypeSelected(value: string) {
- const [ noteType, templateNoteId ] = value.split(",");
+ /** A press or a key anywhere in the dialog but the menu is the user moving focus themselves. */
+ function onUserGesture(e: Event) {
+ if (e.target instanceof Node && menuRef.current?.contains(e.target)) return;
+ userMovedFocus.current = true;
+ }
+
+ function onSelect(item: MenuCommandItem<TreeCommandNames>, e: MouseEvent | KeyboardEvent) {
+ // A row of its own, such as the one opening the code languages' options.
+ if (item.handler) {
+ item.handler(item, e);
+ setShown(false);
+ return;
+ }
+ // A submenu's row that makes nothing itself.
+ if (!item.type) return;
callback?.({
success: true,
- noteType,
- templateNoteId,
+ noteType: item.type,
+ mime: item.mime,
+ templateNoteId: item.templateNoteId,
notePath: parentNote?.notePath
});
setShown(false);
@@ -74,13 +79,15 @@ export default function NoteTypeChooserDialogComponent() {
return (
<Modal
- modalRef={modalRef}
title={t("note_type_chooser.modal_title")}
className="note-type-chooser-dialog"
size="md"
zIndex={1100} // note type chooser needs to be higher than other dialogs from which it is triggered, e.g. "add link"
scrollable
- onShown={tryFocusFirstNoteType}
+ // Bootstrap focuses the dialog itself once shown, which the menu takes back.
+ onShown={() => {
+ if (!userMovedFocus.current) menuRef.current?.focus({ preventScroll: true });
+ }}
onHidden={() => {
callback?.({ success: false });
setShown(false);
@@ -88,91 +95,35 @@ export default function NoteTypeChooserDialogComponent() {
show={shown}
stackable
>
- <FormGroup name="parent-note" label={t("note_type_chooser.change_path_prompt")}>
- <NoteAutocomplete
- onChange={setParentNote}
- placeholder={t("note_type_chooser.search_placeholder")}
- opts={{
- allowCreatingNotes: false,
- hideGoToSelectedNoteButton: true,
- allowJumpToSearchNotes: false,
- }}
+ {/* The menu stands in here too; `onUserGesture` leaves its presses and keys to it. */}
+ <div onPointerDown={onUserGesture} onKeyDown={onUserGesture}>
+ <FormGroup name="parent-note" label={t("note_type_chooser.change_path_prompt")}>
+ <NoteAutocomplete
+ onChange={setParentNote}
+ placeholder={t("note_type_chooser.search_placeholder")}
+ opts={{
+ allowCreatingNotes: false,
+ hideGoToSelectedNoteButton: true,
+ allowJumpToSearchNotes: false,
+ }}
+ />
+ </FormGroup>
+
+ <FormGroup name="note-type" label={t("note_type_chooser.modal_body")}>
+ <div className="note-type-chooser-list" ref={setListHost} />
+ </FormGroup>
+ </div>
+
+ {shown && listHost && noteTypes && (
+ <Menu
+ anchor={listHost} container={listHost} inline
+ className="static" elementRef={menuRef}
+ items={noteTypes} filterable startAt="first"
+ isWanted={() => !userMovedFocus.current}
+ onSelect={onSelect}
+ onClose={() => setShown(false)}
/>
- </FormGroup>
-
- <FormGroup name="note-type" label={t("note_type_chooser.modal_body")}>
- <FormList onSelect={onNoteTypeSelected}>
- {noteTypes.map((_item) => {
- if ("kind" in _item && _item.kind === "separator") {
- return;
- }
-
- const item = _item as MenuCommandItem<TreeCommandNames>;
-
- if ("kind" in item && item.kind === "header") {
- return <FormListHeader text={item.title} />
- } else {
- return <FormListItem
- value={[ item.type, item.templateNoteId ].join(",") }
- icon={item.uiIcon}>
- {item.title}
- {item.badges && item.badges.map((badge) => <SimpleBadge {...badge} />)}
- </FormListItem>;
- }
- })}
- </FormList>
- </FormGroup>
+ )}
</Modal>
);
}
-
-/**
- * Focuses the first note type so Enter creates a text note, until the user moves focus themselves.
- * Both the arrival of the types and `onShown` apply it, since either can be the one that comes last.
- */
-function useFirstNoteTypeFocus(modalRef: RefObject<HTMLDivElement | null>, shown: boolean, noteTypeCount: number) {
- const userMovedFocus = useRef(false);
-
- const tryFocusFirstNoteType = useCallback(() => {
- if (userMovedFocus.current) {
- return;
- }
-
- modalRef.current?.querySelector<HTMLElement>(".dropdownWrapper .dropdown-item:not(.disabled)")?.focus();
- }, [ modalRef ]);
-
- // A gesture on the note types themselves is the auto focus landing, not the user leaving it.
- useEffect(() => {
- const modal = modalRef.current;
- if (!shown || !modal) {
- return;
- }
-
- const onUserGesture = (e: Event) => {
- const target = e.target as HTMLElement | null;
- if (target?.closest(".dropdown-item")) {
- return;
- }
- userMovedFocus.current = true;
- };
-
- modal.addEventListener("pointerdown", onUserGesture);
- modal.addEventListener("keydown", onUserGesture);
- return () => {
- modal.removeEventListener("pointerdown", onUserGesture);
- modal.removeEventListener("keydown", onUserGesture);
- };
- }, [ modalRef, shown ]);
-
- useEffect(() => {
- if (shown && noteTypeCount > 0) {
- tryFocusFirstNoteType();
- }
- }, [ shown, noteTypeCount, tryFocusFirstNoteType ]);
-
- const resetAutoFocus = useCallback(() => {
- userMovedFocus.current = false;
- }, []);
-
- return { tryFocusFirstNoteType, resetAutoFocus };
-}
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index 100a0b7f18..2166d272fb 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -51,6 +51,13 @@ body.desktop .dropdown-submenu > .dropdown-menu.tn-menu.tn-menu-immediate {
animation: none;
}
+/* A menu in the flow of what holds it, as a list is, rather than beside an anchor. */
+.dropdown-menu.tn-menu.tn-menu-inline {
+ position: static;
+ width: 100%;
+ min-width: unset;
+}
+
/* The menu holds focus for its keys; the row they act on shows where they are instead. */
.dropdown-menu.tn-menu:focus {
outline: none;
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 0cd4127344..01c04ebe90 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -31,6 +31,11 @@ export interface MenuProps<T> extends Pick<PopupProps, "anchor" | "offset" | "co
* The `.mobile-bottom-menu` rules place and cap it.
*/
bottomSheet?: boolean;
+ /**
+ * Stands in the flow of the element given as `container`, as a list does, rather than beside
+ * its anchor: a menu that is part of a dialog.
+ */
+ inline?: boolean;
/** Makes the first or the last row the active one as the menu takes focus, for a menu a key opened. */
startAt?: "first" | "last";
/** Called on a press outside the menu and its anchor. It answers Escape itself, with {@link onClose}. */
@@ -65,7 +70,7 @@ const TOP_LEVEL = { rowId: "", level: -1 };
/** How long typed letters keep adding to the text a row is looked up by. */
const TYPEAHEAD_TIMEOUT = 500;
-export default function Menu<T>({ id, className, anchor, placement, bottomSheet, startAt, items, filterable, onSelect, children, onClose, onDismiss, isWanted, elementRef, ...popupProps }: MenuProps<T>) {
+export default function Menu<T>({ id, className, anchor, placement, bottomSheet, inline, startAt, items, filterable, onSelect, children, onClose, onDismiss, isWanted, elementRef, ...popupProps }: MenuProps<T>) {
const menuRef = useRef<HTMLDivElement | null>(null);
// The submenus' layers render into the menu element, which rows reach through the context.
const [ layerHost, setLayerHost ] = useState<HTMLElement | null>(null);
@@ -375,7 +380,7 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
{...popupProps}
anchor={anchor}
placement={placement ?? (anchor instanceof HTMLElement ? "bottom-start" : "right-start")}
- placedByStylesheet={bottomSheet}
+ placedByStylesheet={bottomSheet || inline}
onPlaced={() => {
const menu = menuRef.current;
if (menu) {
@@ -387,7 +392,7 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
onDismiss={onDismiss && (() => onDismiss())}
escapeDismisses={false}
elementRef={setMenuElement} id={id} role="menu" tabIndex={-1}
- className={clsx("dropdown-menu show tn-menu", bottomSheet && "mobile-bottom-menu",
+ className={clsx("dropdown-menu show tn-menu", bottomSheet && "mobile-bottom-menu", inline && "tn-menu-inline",
keyboardDriven && "tn-menu-keyboard", className)}
onPointerMove={(e) => {
if (pointerMoved(e)) setKeyboardDriven(false);
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types.html
index 5e3ffffc67..5f291b7b15 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types.html
@@ -28,6 +28,10 @@
asked.</li>
<li>Similarly, when creating a new tab, type the desired title and press Enter.</li>
</ul>
+<p>The note type is chosen from the same menu as in the note tree, with its
+ submenus (code languages, snippets, collections and the note types created
+ less often) and its search box: type to narrow the list, then press <kbd>Enter</kbd> to
+ create the first match. <kbd>Enter</kbd> right away creates a Text note.</p>
<h2>Changing the type of a note</h2>
<p>It is possible to change the type of a note after it has been created
via the <em>Basic Properties</em> tab in the&nbsp;<a class="reference-link"
diff --git a/docs/User Guide/User Guide/Note Types.md b/docs/User Guide/User Guide/Note Types.md
index 1a7cb892c2..a71e02fb96 100644
--- a/docs/User Guide/User Guide/Note Types.md
+++ b/docs/User Guide/User Guide/Note Types.md
@@ -19,6 +19,8 @@ The note types created less often, <a class="reference-link" href="Note%20Types/
* When adding a [link](Note%20Types/Text/Links.md) in a <a class="reference-link" href="Note%20Types/Text.md">Text</a> note, type the desired title of the new note and press Enter. Afterwards the type of the note will be asked.
* Similarly, when creating a new tab, type the desired title and press Enter.
+The note type is chosen from the same menu as in the note tree, with its submenus (code languages, snippets, collections and the note types created less often) and its search box: type to narrow the list, then press <kbd>Enter</kbd> to create the first match. <kbd>Enter</kbd> right away creates a Text note.
+
## Changing the type of a note
It is possible to change the type of a note after it has been created via the _Basic Properties_ tab in the <a class="reference-link" href="Basic%20Concepts%20and%20Features/UI%20Elements/Ribbon.md">Ribbon</a>. Note that it's generally a good idea to change the note type only if the note is empty. Can also be used to edit the [source of a note](Advanced%20Usage/Note%20source.md).