Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(bulk_actions): edit the rename-note title as a checked template
Elian Doranfb44c41a6c66
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 62bb709a08..75f4cf42f4 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -947,8 +947,31 @@},"rename_note": {"rename_note": "Rename note",- "new_note_title": "new note title",- "description": "Sets the title of each note. The title is a JavaScript template string, so ${note.title} stands for the current title."+ "description": "Sets the title of each note. Expressions between ${ and } are filled in for each note, such as ${note.title} for its current title.",+ "placeholder": "e.g. NEW: ${note.title}"+ },+ "template_field": {+ "preview": "Preview: {{result}}",+ "error_unclosed": "This ${ is never closed, so it stays in the title as text.",+ "error_unsupported": "Only a property such as note.title, or a method such as note.getLabelValue('name'), can go between ${ and }.",+ "error_unknown_variable": "There is no variable named “{{name}}”.",+ "error_property_not_allowed": "The property “{{name}}” cannot be used in a template.",+ "error_method_not_allowed": "The method “{{name}}” cannot be used in a template.",+ "variable_note": "The note being renamed",+ "member_title": "The note's title",+ "member_note_id": "The note's ID",+ "member_type": "The note's type, such as text or code",+ "member_mime": "The note's MIME type",+ "member_date_created_obj": "The creation date, to use with format('…')",+ "member_utc_date_created_obj": "The creation date in UTC, to use with format('…')",+ "member_date_created": "When the note was created, in local time",+ "member_date_modified": "When the note was last modified, in local time",+ "member_utc_date_created": "When the note was created, in UTC",+ "member_utc_date_modified": "When the note was last modified, in UTC",+ "member_is_protected": "Whether the note is protected",+ "member_get_label_value": "The value of the label with the given name",+ "member_get_relation_value": "The ID of the note the relation with the given name points to",+ "member_format": "The date in the given format, such as YYYY-MM-DD"},"add_relation": {"add_relation": "Add relation",diff --git a/apps/client/src/widgets/bulk_actions/TemplateField.css b/apps/client/src/widgets/bulk_actions/TemplateField.cssnew file mode 100644index 0000000000..47ce3f0b3a--- /dev/null+++ b/apps/client/src/widgets/bulk_actions/TemplateField.css@@ -0,0 +1,15 @@+.template-field {+ display: flex;+ flex-direction: column;+ flex: 1;+ min-width: 0;+ gap: 4px;+}++.template-field-preview {+ overflow: hidden;+ color: var(--muted-text-color);+ font-size: 0.85em;+ text-overflow: ellipsis;+ white-space: nowrap;+}diff --git a/apps/client/src/widgets/bulk_actions/TemplateField.spec.tsx b/apps/client/src/widgets/bulk_actions/TemplateField.spec.tsxnew file mode 100644index 0000000000..f390d9f25b--- /dev/null+++ b/apps/client/src/widgets/bulk_actions/TemplateField.spec.tsx@@ -0,0 +1,70 @@+import { act } from "preact/test-utils";+import { describe, expect, it, vi } from "vitest";++import { buildNote } from "../../test/easy-froca";+import { renderInto } from "../../test/render";+import TemplateField, { noteTemplateVariables, TemplatePreviewNoteContext } from "./TemplateField";++vi.mock("../../services/i18n", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../services/i18n")>(),+ t: (key: string, opts?: { result?: string }) => (opts?.result !== undefined ? `${key}:${opts.result}` : key)+}));++const METADATA = {+ dateCreated: "2024-03-05 10:00:00.000+0100",+ dateModified: "2024-04-01 09:00:00.000+0100",+ utcDateCreated: "2024-03-05 09:00:00.000Z",+ utcDateModified: "2024-04-01 08:00:00.000Z"+};++describe("noteTemplateVariables", () => {+ it("gives the note what the server's BNote gives a template", async () => {+ const note = buildNote({ title: "Meeting", "#author": "Ada" });+ const { evaluateTemplate } = await import("@triliumnext/commons");++ expect(evaluateTemplate(+ "${note.title} ${note.dateCreatedObj.format('MM-DD')} ${note.getLabelValue('author')} ${note.type}",+ noteTemplateVariables(note, METADATA)+ )).toBe("Meeting 03-05 Ada text");+ });+});++describe("TemplateField", () => {+ it("shows the template filled in for the preview note, and nothing for a refused one", async () => {+ const note = buildNote({ title: "Meeting" });+ vi.spyOn(note, "getMetadata").mockResolvedValue(METADATA);++ const container = await mount("NEW: ${note.title}", note.noteId);+ expect(container.querySelector(".template-field-preview")?.textContent)+ .toBe("template_field.preview:NEW: Meeting");++ const refused = await mount("NEW: ${note.constructor}", note.noteId);+ expect(refused.querySelector(".cm-editor")).not.toBeNull();+ expect(refused.querySelector(".template-field-preview")).toBeNull();+ });++ it("shows no preview without a note to preview against", async () => {+ const container = await mount("NEW: ${note.title}", undefined);+ expect(container.querySelector(".cm-editor")).not.toBeNull();+ expect(container.querySelector(".template-field-preview")).toBeNull();+ });+});++async function mount(value: string, noteId: string | undefined) {+ let container: HTMLElement | undefined;+ await act(async () => {+ container = renderInto(+ <TemplatePreviewNoteContext.Provider value={noteId}>+ <TemplateField currentValue={value} onChange={() => {}} variables={{ note: "note" }} />+ </TemplatePreviewNoteContext.Provider>+ );+ });+ // The note and its metadata are read asynchronously.+ for (let attempt = 0; attempt < 5; attempt++) {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 1));+ });+ }+ if (!container) throw new Error("Not rendered.");+ return container;+}diff --git a/apps/client/src/widgets/bulk_actions/TemplateField.tsx b/apps/client/src/widgets/bulk_actions/TemplateField.tsxnew file mode 100644index 0000000000..7896053ed4--- /dev/null+++ b/apps/client/src/widgets/bulk_actions/TemplateField.tsx@@ -0,0 +1,155 @@+import "../search_field_editor.css";+import "./TemplateField.css";++import { hostedCompletion, type HostedCompletionState } from "@triliumnext/codemirror/src/extensions/hosted_completion";+import { triliumTemplate } from "@triliumnext/codemirror/src/extensions/trilium_template";+import { createFieldEditor, type FieldEditor } from "@triliumnext/codemirror/src/field_editor";+import { dayjs, evaluateTemplate, type TemplateVariables } from "@triliumnext/commons";+import clsx from "clsx";+import { createContext } from "preact";+import { useContext, useEffect, useRef, useState } from "preact/hooks";++import type FNote from "../../entities/fnote";+import type { NoteMetaData } from "../../entities/fnote";+import froca from "../../services/froca";+import { t } from "../../services/i18n";+import { CommandMentionList, createHostedList, filterCommandEntries } from "../react/NoteAutocomplete";+import { SEARCH_FIELD_EDITOR_CLASS } from "../search_field_editor";+import { type TemplateCompletion, templateCompletionAt, type TemplateEntry, type TemplateVariableTypes } from "./template_completions";++/** The note a template is previewed against, such as the first of the notes a bulk action runs on. */+export const TemplatePreviewNoteContext = createContext<string | undefined>(undefined);++interface TemplateFieldProps {+ currentValue: string;+ onChange(value: string): void;+ /** The variables the template can read, as the server passes them to `evaluateTemplate()`. */+ variables: TemplateVariableTypes;+ placeholder?: string;+ ariaLabel?: string;+}++/**+ * A one-line field for a template filled in by `evaluateTemplate()`: the `${...}` expressions are+ * coloured, completed and checked by the same rules the server applies, and the result for the note+ * in {@link TemplatePreviewNoteContext} is shown below the field.+ */+export default function TemplateField({ currentValue, onChange, variables, placeholder, ariaLabel }: TemplateFieldProps) {+ const parentRef = useRef<HTMLDivElement>(null);+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;+ const preview = useTemplatePreview(currentValue, useContext(TemplatePreviewNoteContext));++ useEffect(() => {+ if (!parentRef.current) return;++ const editor: FieldEditor = createFieldEditor({+ parent: parentRef.current,+ doc: currentValue,+ placeholder,+ ariaLabel,+ singleLine: true,+ onChange: (value) => onChangeRef.current(value),+ extensions: [+ triliumTemplate(Object.keys(variables), templateLintMessages()),+ hostedCompletion({+ match: (before) => templateCompletionAt(before, variables),+ list: createTemplateCompletionList+ })+ ]+ });++ return () => editor.destroy();+ // Builds the editor once; the field owns its document from then on.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ return (+ <div className="template-field">+ <div ref={parentRef} className={clsx(SEARCH_FIELD_EDITOR_CLASS, "form-control tn-input-field")} />+ {preview && <div className="template-field-preview">{t("template_field.preview", { result: preview })}</div>}+ </div>+ );+}++function templateLintMessages() {+ return {+ unclosed: t("template_field.error_unclosed"),+ unsupported: t("template_field.error_unsupported"),+ unknownVariable: (name: string) => t("template_field.error_unknown_variable", { name }),+ propertyNotAllowed: (name: string) => t("template_field.error_property_not_allowed", { name }),+ methodNotAllowed: (name: string) => t("template_field.error_method_not_allowed", { name })+ };+}++function createTemplateCompletionList() {+ return createHostedList<HostedCompletionState<TemplateCompletion>>((state, props) => {+ const { match } = state;+ return (+ <CommandMentionList<TemplateEntry>+ key={`${match.key}:${match.from}`}+ {...props}+ query={match.query}+ source={async (query) => filterCommandEntries(match.entries(), query)}+ onPick={(entry) => state.commit(entry.insert)}+ />+ );+ });+}++/**+ * The template filled in for the note `noteId`, or `undefined` while there is none, the template+ * has no expression to show the effect of, or the template is refused (the field underlines why).+ */+function useTemplatePreview(template: string, noteId: string | undefined) {+ const [ variables, setVariables ] = useState<TemplateVariables>();++ useEffect(() => {+ let cancelled = false;+ setVariables(undefined);+ if (!noteId) return;++ // A preview that cannot be built is left out; the field works the same without it.+ (async () => {+ const note = await froca.getNote(noteId, true);+ if (!note) return;+ const metadata = await note.getMetadata();+ if (!cancelled) setVariables(noteTemplateVariables(note, metadata));+ })().catch(() => {});++ return () => {+ cancelled = true;+ };+ }, [ noteId ]);++ if (!variables || !template.includes("${")) return undefined;+ try {+ return evaluateTemplate(template, variables);+ } catch {+ return undefined;+ }+}++/**+ * The `note` variable the server passes to `evaluateTemplate()` for a bulk rename, rebuilt from the+ * client's copy of the note: the same allowed properties and methods, with the dates of `BNote`.+ */+export function noteTemplateVariables(note: FNote, metadata: NoteMetaData): TemplateVariables {+ return {+ note: {+ title: note.title,+ noteId: note.noteId,+ type: note.type,+ mime: note.mime,+ isProtected: note.isProtected,+ dateCreated: metadata.dateCreated,+ dateModified: metadata.dateModified,+ utcDateCreated: metadata.utcDateCreated,+ utcDateModified: metadata.utcDateModified,+ dateCreatedObj: dayjs(metadata.dateCreated),+ utcDateCreatedObj: dayjs.utc(metadata.utcDateCreated),+ getLabelValue: (name: string) => note.getLabelValue(name),+ getRelationValue: (name: string) => note.getRelationValue(name)+ }+ };+}diff --git a/apps/client/src/widgets/bulk_actions/note/rename_note.tsx b/apps/client/src/widgets/bulk_actions/note/rename_note.tsxindex 6e50575695..b9c76c8541 100644--- a/apps/client/src/widgets/bulk_actions/note/rename_note.tsx+++ b/apps/client/src/widgets/bulk_actions/note/rename_note.tsx@@ -1,9 +1,12 @@import AbstractBulkAction, { ActionDefinition } from "../abstract_bulk_action.js";import { t } from "../../../services/i18n.js";import BulkAction from "../BulkAction.jsx";-import FormTextBox from "../../react/FormTextBox.jsx";import { useEffect, useState } from "preact/hooks";import { useSpacedUpdate } from "../../react/hooks.jsx";+import TemplateField from "../TemplateField.jsx";++/** What the server's `renameNote` handler passes to `evaluateTemplate()`. */+const RENAME_TEMPLATE_VARIABLES = { note: "note" } as const;function RenameNoteBulkActionComponent({ bulkAction, actionDef }: { bulkAction: AbstractBulkAction, actionDef: ActionDefinition}) {const [ newTitle, setNewTitle ] = useState<string>(actionDef.newTitle ?? "");@@ -14,9 +17,10 @@ function RenameNoteBulkActionComponent({ bulkAction, actionDef }: { bulkAction:<BulkActionbulkAction={bulkAction}>- <FormTextBox- placeholder={t("rename_note.new_note_title")}- title={t("rename_note.description")}+ <TemplateField+ variables={RENAME_TEMPLATE_VARIABLES}+ placeholder={t("rename_note.placeholder")}+ ariaLabel={t("rename_note.rename_note")}currentValue={newTitle} onChange={setNewTitle}/></BulkAction>diff --git a/apps/client/src/widgets/bulk_actions/template_completions.spec.ts b/apps/client/src/widgets/bulk_actions/template_completions.spec.tsnew file mode 100644index 0000000000..895777543e--- /dev/null+++ b/apps/client/src/widgets/bulk_actions/template_completions.spec.ts@@ -0,0 +1,48 @@+import { TEMPLATE_ALLOWED_METHODS, TEMPLATE_ALLOWED_PROPERTIES } from "@triliumnext/commons";+import { describe, expect, it, vi } from "vitest";++import { NOTE_TEMPLATE_MEMBERS, templateCompletionAt } from "./template_completions";++vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));++const VARIABLES = { note: "note" } as const;++function titlesAt(before: string) {+ const completion = templateCompletionAt(before, VARIABLES);+ return completion && {+ from: completion.from,+ query: completion.query,+ titles: completion.entries().map((entry) => entry.title)+ };+}++describe("templateCompletionAt", () => {+ it("offers nothing outside an expression", () => {+ expect(templateCompletionAt("NEW: ", VARIABLES)).toBeNull();+ expect(templateCompletionAt("${note.title} and more", VARIABLES)).toBeNull();+ });++ it("offers the variables right after ${", () => {+ expect(titlesAt("NEW: ${")).toStrictEqual({ from: 7, query: "", titles: [ "note" ] });+ expect(titlesAt("NEW: ${no")).toStrictEqual({ from: 7, query: "no", titles: [ "note" ] });+ });++ it("offers the members of what the path before the dot is", () => {+ const onNote = titlesAt("${note.ti");+ expect(onNote?.from).toBe(7);+ expect(onNote?.query).toBe("ti");+ expect(onNote?.titles).toContain("title");+ expect(onNote?.titles).toContain("getLabelValue('…')");++ expect(titlesAt("${note.dateCreatedObj.")?.titles).toStrictEqual([ "format('…')" ]);+ expect(titlesAt("${note.title.")).toBeNull();+ expect(titlesAt("${other.")).toBeNull();+ });++ it("offers only what the template engine allows", () => {+ for (const member of NOTE_TEMPLATE_MEMBERS) {+ const allowed = member.kind === "method" ? TEMPLATE_ALLOWED_METHODS : TEMPLATE_ALLOWED_PROPERTIES;+ expect(allowed.has(member.name), member.name).toBe(true);+ }+ });+});diff --git a/apps/client/src/widgets/bulk_actions/template_completions.ts b/apps/client/src/widgets/bulk_actions/template_completions.tsnew file mode 100644index 0000000000..94c2775424--- /dev/null+++ b/apps/client/src/widgets/bulk_actions/template_completions.ts@@ -0,0 +1,156 @@+import type { HostedCompletionInsert } from "@triliumnext/codemirror/src/extensions/hosted_completion";++import { t } from "../../services/i18n";+import type { CommandEntry } from "../react/NoteAutocomplete";++/**+ * Completions for the templates `evaluateTemplate()` fills in: the variables right after `${`, and+ * the members of what the path before a `.` resolves to. Only members the template engine allows,+ * and that give a readable value on the server's `BNote`, are offered.+ */++/** What a template variable or member holds, which decides the members offered after it. */+export type TemplateValueType = "note" | "date" | "text";++/** The variables a template can read, by name, and what each holds. */+export type TemplateVariableTypes = Readonly<Record<string, TemplateValueType>>;++export interface TemplateMember {+ name: string;+ kind: "property" | "method";+ type: TemplateValueType;+ /** Translation key of what the member gives. */+ descriptionKey: string;+}++export const NOTE_TEMPLATE_MEMBERS: readonly TemplateMember[] = [+ { name: "title", kind: "property", type: "text", descriptionKey: "template_field.member_title" },+ { name: "noteId", kind: "property", type: "text", descriptionKey: "template_field.member_note_id" },+ { name: "type", kind: "property", type: "text", descriptionKey: "template_field.member_type" },+ { name: "mime", kind: "property", type: "text", descriptionKey: "template_field.member_mime" },+ { name: "dateCreatedObj", kind: "property", type: "date", descriptionKey: "template_field.member_date_created_obj" },+ { name: "utcDateCreatedObj", kind: "property", type: "date", descriptionKey: "template_field.member_utc_date_created_obj" },+ { name: "dateCreated", kind: "property", type: "text", descriptionKey: "template_field.member_date_created" },+ { name: "dateModified", kind: "property", type: "text", descriptionKey: "template_field.member_date_modified" },+ { name: "utcDateCreated", kind: "property", type: "text", descriptionKey: "template_field.member_utc_date_created" },+ { name: "utcDateModified", kind: "property", type: "text", descriptionKey: "template_field.member_utc_date_modified" },+ { name: "isProtected", kind: "property", type: "text", descriptionKey: "template_field.member_is_protected" },+ { name: "getLabelValue", kind: "method", type: "text", descriptionKey: "template_field.member_get_label_value" },+ { name: "getRelationValue", kind: "method", type: "text", descriptionKey: "template_field.member_get_relation_value" }+];++const DATE_TEMPLATE_MEMBERS: readonly TemplateMember[] = [+ { name: "format", kind: "method", type: "text", descriptionKey: "template_field.member_format" }+];++const MEMBERS: Readonly<Record<TemplateValueType, readonly TemplateMember[]>> = {+ note: NOTE_TEMPLATE_MEMBERS,+ date: DATE_TEMPLATE_MEMBERS,+ text: []+};++/** An entry of the list, and what a pick puts in place of what was typed. */+export interface TemplateEntry extends CommandEntry {+ insert: HostedCompletionInsert;+}++export interface TemplateCompletion {+ /** Where the typed name starts, which a pick replaces. */+ from: number;+ query: string;+ /** Identifies the entries offered at this place, so the list keeps them while it stays open. */+ key: string;+ entries(): TemplateEntry[];+}++// The expression typed so far, from the last `${` that is not closed before the caret.+const OPEN_EXPRESSION = /\$\{([^{}]*)$/;+const VARIABLE_START = /^\s*([a-zA-Z_]\w*)?$/;+const MEMBER_START = /^\s*([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)?$/;++/**+ * Finds what can be completed at the end of `before`, the text up to the caret, given the variables+ * the template can read. Returns `null` outside an expression and after a path that holds nothing+ * with members, such as a title.+ */+export function templateCompletionAt(before: string, variables: TemplateVariableTypes): TemplateCompletion | null {+ const open = OPEN_EXPRESSION.exec(before);+ if (!open) {+ return null;+ }+ const expression = open[1];++ const variable = VARIABLE_START.exec(expression);+ if (variable) {+ const query = variable[1] ?? "";+ return {+ from: before.length - query.length,+ query,+ key: "variables",+ entries: () => Object.keys(variables).map((name) => ({+ id: name,+ title: name,+ icon: "bx bx-note",+ description: t(`template_field.variable_${name}`),+ insert: name+ }))+ };+ }++ const member = MEMBER_START.exec(expression);+ if (!member) {+ return null;+ }++ const type = resolvePathType(member[1].split("."), variables);+ const members = type ? MEMBERS[type] : [];+ if (members.length === 0) {+ return null;+ }++ const query = member[2] ?? "";+ return {+ from: before.length - query.length,+ query,+ key: `members:${member[1]}`,+ entries: () => members.map(toEntry)+ };+}++function resolvePathType([ root, ...properties ]: string[], variables: TemplateVariableTypes): TemplateValueType | undefined {+ let type: TemplateValueType | undefined = variables[root];+ for (const property of properties) {+ type = type && MEMBERS[type].find((m) => m.kind === "property" && m.name === property)?.type;+ }+ return type;+}++function toEntry(member: TemplateMember): TemplateEntry {+ const description = t(member.descriptionKey);++ if (member.kind === "method") {+ return {+ id: member.name,+ title: `${member.name}('…')`,+ icon: "bx bx-code-curly",+ description,+ // The argument is the one thing left to type, so the caret goes between the quotes.+ insert: (view, from, to) => {+ const text = `${member.name}('')`;+ view.dispatch({+ changes: { from, to, insert: text },+ selection: { anchor: from + text.length - 2 }+ });+ }+ };+ }++ return {+ id: member.name,+ title: member.name,+ icon: member.type === "date" ? "bx bx-calendar" : "bx bx-purchase-tag",+ description,+ // A value with members of its own takes the dot, which opens the list on them.+ insert: MEMBERS[member.type].length > 0 ? `${member.name}.` : member.name+ };+}diff --git a/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx b/apps/client/src/widgets/dialogs/bulk_actions.spec.tsxindex 3448f07605..eb476dc8a3 100644--- a/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx+++ b/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx@@ -122,12 +122,12 @@ describe("BulkActionsDialog", () => {for (const [ index, ActionClass ] of bulk_action.ACTION_CLASSES.entries()) {const row = rows[index];const content = row.cells[0].cloneNode(true) as HTMLElement;- for (const select of content.querySelectorAll("select")) select.remove();+ for (const field of content.querySelectorAll("select, .template-field")) field.remove();expect(content.textContent?.trim(), ActionClass.actionName).toBe(ActionClass.actionTitle);expect(row.querySelectorAll(".tn-icon:not(.bulk-action-arrow)"), ActionClass.actionName).toHaveLength(1);const arrow = row.querySelector(".bulk-action-arrow");- const fieldCount = row.querySelectorAll("input:not([type=hidden]), select").length;+ const fieldCount = row.querySelectorAll("input:not([type=hidden]), select, .template-field").length;expect(!!arrow, ActionClass.actionName).toBe(fieldCount === 2);}});diff --git a/apps/client/src/widgets/dialogs/bulk_actions.tsx b/apps/client/src/widgets/dialogs/bulk_actions.tsxindex 2c972ea32e..92cfdcef79 100644--- a/apps/client/src/widgets/dialogs/bulk_actions.tsx+++ b/apps/client/src/widgets/dialogs/bulk_actions.tsx@@ -10,6 +10,7 @@ import NoItems from "../react/NoItems";import { OptionsRowWithToggle } from "../type_widgets/options/components/OptionsRow";import bulk_action from "../../services/bulk_action";import AddBulkActionButton from "../bulk_actions/AddBulkActionButton";+import { TemplatePreviewNoteContext } from "../bulk_actions/TemplateField";import Icon from "../react/Icon";import dialog from "../../services/dialog";import toast from "../../services/toast";@@ -148,7 +149,9 @@ export default function BulkActionsDialog() {</Card><Card className="bulk-actions-chosen-actions" heading={t("bulk_actions.chosen_actions")}>- <ExistingActionsList existingActions={existingActions} />+ <TemplatePreviewNoteContext.Provider value={selectedOrActiveNoteIds?.[0]}>+ <ExistingActionsList existingActions={existingActions} />+ </TemplatePreviewNoteContext.Provider><CardSection className="bulk-actions-add-action"><AddBulkActionButtonnoteId="_bulkAction"diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.htmlindex 8c00aee2ea..f690856208 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html@@ -126,15 +126,21 @@<li><strong>Rename note</strong><ul><li>For each note, it will change the title of the note to the given one.</li>- <li>As a more advanced use case, the note can be a “template string” which- allows for dynamic values with access to the note information via <a- class="reference-link" href="#root/_help_habiZ3HU8Kw8">FNote</a>, for example:+ <li>The title can contain expressions between <code>${</code> and <code>}</code>,+ which are filled in for each note. They can read the note's properties,+ such as <code>${note.title}</code>, <code>${note.noteId}</code> or <code>${note.type}</code>,+ and call <code>getLabelValue('name')</code>, <code>getRelationValue('name')</code> or,+ on a date such as <code>dateCreatedObj</code>, <code>format('…')</code>.+ For example:<ul><li><code>NEW: ${note.title}</code> will prefix all notes with <code>NEW:</code> .</li><li><code>${note.dateCreatedObj.format('MM-DD:')}: ${note.title}</code> willprefix the note titles with each note's creation date (in month-day format).</li></ul></li>+ <li>Only property access and those methods are allowed, not arbitrary JavaScript.+ While typing, the field completes the expressions, underlines one that+ is not allowed and shows the resulting title for the first selected note.</li></ul></li><li><strong>Move note</strong>diff --git a/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md b/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.mdindex b733e2f02b..1068396571 100644--- a/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md+++ b/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md@@ -59,9 +59,10 @@ These actions operate the <a class="reference-link" href="Attributes/Relations.* **Rename note*** For each note, it will change the title of the note to the given one.- * As a more advanced use case, the note can be a “template string” which allows for dynamic values with access to the note information via <a class="reference-link" href="../Scripting/Script%20API/Frontend%20API/FNote.dat">FNote</a>, for example:+ * The title can contain expressions between `${` and `}`, which are filled in for each note. They can read the note's properties, such as `${note.title}`, `${note.noteId}` or `${note.type}`, and call `getLabelValue('name')`, `getRelationValue('name')` or, on a date such as `dateCreatedObj`, `format('…')`. For example:* `NEW: ${note.title}` will prefix all notes with `NEW:` .* `${note.dateCreatedObj.format('MM-DD:')}: ${note.title}` will prefix the note titles with each note's creation date (in month-day format).+ * Only property access and those methods are allowed, not arbitrary JavaScript. While typing, the field completes the expressions, underlines one that is not allowed and shows the resulting title for the first selected note.* **Move note*** For each note, it will be moved to the specified parent note.* A note with several parents is cloned to the new parent instead, since it is not clear which of its places to remove.diff --git a/packages/codemirror/src/extensions/trilium_template.spec.ts b/packages/codemirror/src/extensions/trilium_template.spec.tsnew file mode 100644index 0000000000..8ad7d7bbf2--- /dev/null+++ b/packages/codemirror/src/extensions/trilium_template.spec.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from "vitest";++import { diagnoseTemplate, type TemplateLintMessages, tokenizeTemplate } from "./trilium_template.js";++const MESSAGES: TemplateLintMessages = {+ unclosed: "unclosed",+ unsupported: "unsupported",+ unknownVariable: (name) => `variable:${name}`,+ propertyNotAllowed: (name) => `property:${name}`,+ methodNotAllowed: (name) => `method:${name}`+};++function tokensOf(text: string) {+ return tokenizeTemplate(text).map(({ from, to, kind }) => `${kind}:${text.slice(from, to)}`);+}++describe("tokenizeTemplate", () => {+ it("colours the expressions and leaves the literal text alone", () => {+ expect(tokensOf("NEW: ${note.title}")).toStrictEqual([+ "delimiter:${", "variable:note", "property:.title", "delimiter:}"+ ]);+ });++ it("tells a method call and its string argument from a property", () => {+ expect(tokensOf("${note.dateCreatedObj.format('MM-DD')}")).toStrictEqual([+ "delimiter:${", "variable:note", "property:.dateCreatedObj", "method:.format",+ "punctuation:(", "string:'MM-DD'", "punctuation:)", "delimiter:}"+ ]);+ });++ it("colours an expression still being typed, up to the end of the text", () => {+ expect(tokensOf("A ${note.")).toStrictEqual([ "delimiter:${", "variable:note", "property:." ]);+ });+});++describe("diagnoseTemplate", () => {+ it("underlines each refused expression with the consumer's wording", () => {+ const diagnostics = diagnoseTemplate("${note.title} ${note.constructor} ${other} ${note.title", [ "note" ], MESSAGES);++ expect(diagnostics.map((d) => d.message)).toStrictEqual([+ "property:constructor", "variable:other", "unclosed"+ ]);+ expect(diagnostics.every((d) => d.severity === "error")).toBe(true);+ expect([ diagnostics[0].from, diagnostics[0].to ]).toStrictEqual([ 14, 33 ]);+ });++ it("has nothing to say about a valid template", () => {+ expect(diagnoseTemplate("NEW: ${note.title}", [ "note" ], MESSAGES)).toStrictEqual([]);+ });+});diff --git a/packages/codemirror/src/extensions/trilium_template.ts b/packages/codemirror/src/extensions/trilium_template.tsnew file mode 100644index 0000000000..24adea2758--- /dev/null+++ b/packages/codemirror/src/extensions/trilium_template.ts@@ -0,0 +1,141 @@+import { type Diagnostic, linter } from "@codemirror/lint";+import { type EditorState, type Extension, RangeSetBuilder, StateField } from "@codemirror/state";+import { Decoration, type DecorationSet, EditorView } from "@codemirror/view";+import { findTemplateIssues } from "@triliumnext/commons";++/**+ * Highlighting and linting for the templates `evaluateTemplate()` in `@triliumnext/commons` fills+ * in, such as the title a bulk rename gives each note: literal text with `${...}` expressions that+ * read a variable's properties and call a whitelisted method with one string argument.+ */++export type TemplateTokenKind = "delimiter" | "variable" | "property" | "method" | "punctuation" | "string";++export interface TemplateToken {+ from: number;+ to: number;+ kind: TemplateTokenKind;+}++const IDENTIFIER = /[a-zA-Z_]\w*/y;+const MEMBER = /\.(?:[a-zA-Z_]\w*)?/y;+const CALL = /\s*\(/y;+const STRING = /(['"])(?:(?!\1)[^])*(?:\1|$)/y;+const SPACE = /\s+/y;++/**+ * Splits a template into the parts of its expressions worth colouring. An expression whose `}` is+ * not typed yet runs to the end of the text, so it colours while it is being written.+ */+export function tokenizeTemplate(text: string): TemplateToken[] {+ const tokens: TemplateToken[] = [];+ let pos = 0;++ const match = (pattern: RegExp) => {+ pattern.lastIndex = pos;+ return pattern.exec(text);+ };+ const take = (kind: TemplateTokenKind, to: number) => {+ tokens.push({ from: pos, to, kind });+ pos = to;+ };++ while (pos < text.length) {+ const start = text.indexOf("${", pos);+ if (start < 0) {+ break;+ }+ pos = start;+ take("delimiter", start + 2);++ let expectsVariable = true;+ while (pos < text.length && text[pos] !== "}") {+ if (match(SPACE)) {+ pos = SPACE.lastIndex;+ } else if (expectsVariable && match(IDENTIFIER)) {+ take("variable", IDENTIFIER.lastIndex);+ expectsVariable = false;+ } else if (match(MEMBER)) {+ const end = MEMBER.lastIndex;+ CALL.lastIndex = end;+ take(CALL.test(text) ? "method" : "property", end);+ } else if (match(STRING)) {+ take("string", STRING.lastIndex);+ } else if (text[pos] === "(" || text[pos] === ")") {+ take("punctuation", pos + 1);+ } else {+ pos++;+ }+ }++ if (text[pos] === "}") {+ take("delimiter", pos + 1);+ }+ }++ return tokens;+}++/** The wording of the diagnostics, supplied by the consumer because this package holds no translations. */+export interface TemplateLintMessages {+ unclosed: string;+ unsupported: string;+ unknownVariable(name: string): string;+ propertyNotAllowed(name: string): string;+ methodNotAllowed(name: string): string;+}++/** Marks the expressions `evaluateTemplate()` refuses, given the variables it is called with. */+export function diagnoseTemplate(text: string, variableNames: readonly string[], messages: TemplateLintMessages): Diagnostic[] {+ return findTemplateIssues(text, variableNames).map(({ kind, from, to, name }) => ({+ from,+ to,+ severity: "error",+ message: kind === "unclosed" || kind === "unsupported" ? messages[kind] : messages[kind](name ?? "")+ }));+}++const MARKS: Record<TemplateTokenKind, Decoration> = {+ delimiter: Decoration.mark({ class: "cm-template-delimiter" }),+ variable: Decoration.mark({ class: "cm-template-variable" }),+ property: Decoration.mark({ class: "cm-template-property" }),+ method: Decoration.mark({ class: "cm-template-method" }),+ punctuation: Decoration.mark({ class: "cm-template-punctuation" }),+ string: Decoration.mark({ class: "cm-template-string" })+};++/** Drawn with the search highlighter's palette, so the app's two small languages read alike. */+const templateHighlightTheme = EditorView.baseTheme({+ ".cm-template-delimiter": { color: "var(--search-operator-color, var(--muted-text-color))" },+ ".cm-template-variable": { color: "var(--search-relation-color, #8957e5)" },+ ".cm-template-property": { color: "var(--search-property-color, #268a8a)" },+ ".cm-template-method": { color: "var(--search-label-color, #539bf5)" },+ ".cm-template-punctuation": { color: "var(--search-bracket-color, var(--muted-text-color))" },+ ".cm-template-string": { color: "var(--search-string-color, #2ea043)" }+});++const templateHighlightField = StateField.define<DecorationSet>({+ create: (state) => buildTemplateDecorations(state),+ update: (decorations, tr) => (tr.docChanged ? buildTemplateDecorations(tr.state) : decorations),+ provide: (field) => EditorView.decorations.from(field)+});++function buildTemplateDecorations(state: EditorState): DecorationSet {+ const builder = new RangeSetBuilder<Decoration>();+ for (const token of tokenizeTemplate(state.doc.toString())) {+ builder.add(token.from, token.to, MARKS[token.kind]);+ }+ return builder.finish();+}++/**+ * The extension to register on an editor holding a template whose expressions can read+ * `variableNames`. It colours the expressions and underlines the ones the evaluator refuses.+ */+export function triliumTemplate(variableNames: readonly string[], messages: TemplateLintMessages): Extension {+ return [+ templateHighlightField,+ templateHighlightTheme,+ linter((view) => diagnoseTemplate(view.state.doc.toString(), variableNames, messages), { delay: 250 })+ ];+}diff --git a/packages/commons/src/lib/safe_template.spec.ts b/packages/commons/src/lib/safe_template.spec.tsindex b4bf0147e5..c792e90a56 100644--- a/packages/commons/src/lib/safe_template.spec.ts+++ b/packages/commons/src/lib/safe_template.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { evaluateTemplate } from "./safe_template.js";+import { evaluateTemplate, findTemplateIssues } from "./safe_template.js";/*** A stand-in for the note-like objects passed into template evaluation. Only the@@ -189,3 +189,49 @@ describe("safe_template - rejected expressions", () => {).toThrow(/is not a supported expression/);});});++describe("safe_template - findTemplateIssues", () => {+ const variables = [ "note" ];++ it("accepts what evaluateTemplate accepts", () => {+ expect(findTemplateIssues("NEW: ${note.title}", variables)).toStrictEqual([]);+ expect(findTemplateIssues("${note.dateCreatedObj.format('MM-DD')} ${note.getLabelValue(\"x\")}", variables))+ .toStrictEqual([]);+ expect(findTemplateIssues("plain text, no expression", variables)).toStrictEqual([]);+ });++ it("reports each refused expression with its offsets", () => {+ const template = "a ${missing.title} b ${note.constructor} c ${note.toString()} d ${1 + 1}";+ const issues = findTemplateIssues(template, variables);++ expect(issues.map(({ kind, name }) => ({ kind, name }))).toStrictEqual([+ { kind: "unknownVariable", name: "missing" },+ { kind: "propertyNotAllowed", name: "constructor" },+ { kind: "methodNotAllowed", name: "toString" },+ { kind: "unsupported", name: undefined }+ ]);+ for (const issue of issues) {+ expect(template.slice(issue.from, issue.to)).toMatch(/^\$\{.*\}$/);+ }+ });++ it("reports a ${ that is never closed, which evaluateTemplate leaves as text", () => {+ const issues = findTemplateIssues("NEW: ${note.title", variables);+ expect(issues).toStrictEqual([ { kind: "unclosed", from: 5, to: 17, name: undefined } ]);+ });++ it("agrees with evaluateTemplate on every case", () => {+ const note = fakeNote();+ for (const template of [ "${note.title}", "${note.nope}", "${note.eval('x')}", "${note['title']}", "${other}" ]) {+ const throws = (() => {+ try {+ evaluateTemplate(template, { note });+ return false;+ } catch {+ return true;+ }+ })();+ expect(findTemplateIssues(template, variables).length > 0).toBe(throws);+ }+ });+});diff --git a/packages/commons/src/lib/safe_template.ts b/packages/commons/src/lib/safe_template.tsindex 7107c168b1..1433a4cbb7 100644--- a/packages/commons/src/lib/safe_template.ts+++ b/packages/commons/src/lib/safe_template.ts@@ -17,7 +17,7 @@*//** Allowed method names that can be called on template variables. */-const ALLOWED_METHODS = new Set([+export const TEMPLATE_ALLOWED_METHODS: ReadonlySet<string> = new Set(["format","getLabelValue","getLabel",@@ -27,7 +27,7 @@ const ALLOWED_METHODS = new Set([]);/** Allowed property names that can be accessed on template variables. */-const ALLOWED_PROPERTIES = new Set([+export const TEMPLATE_ALLOWED_PROPERTIES: ReadonlySet<string> = new Set(["title","type","mime",@@ -46,6 +46,23 @@ export interface TemplateVariables {[key: string]: unknown;}+/** Why {@link findTemplateIssues} refuses an expression, which `evaluateTemplate()` would throw for. */+export type TemplateIssueKind = "unclosed" | "unsupported" | "unknownVariable" | "propertyNotAllowed" | "methodNotAllowed";++export interface TemplateIssue {+ kind: TemplateIssueKind;+ /** Where the `${...}` expression starts and ends in the template. */+ from: number;+ to: number;+ /** The variable, property or method that is refused, for the kinds that name one. */+ name: string | undefined;+}++// `{` is excluded too, so a `${` without a closing brace scans only to the next brace.+const EXPRESSION = /\$\{([^{}]+)\}/g;+const METHOD_CALL = /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*(?:'([^']*)'|"([^"]*)")?\s*\)$/;+const PROPERTY_CHAIN = /^[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*$/;+/*** Evaluates a template string safely without using eval().*@@ -58,13 +75,79 @@ export interface TemplateVariables {* @throws Error if an expression cannot be safely evaluated*/export function evaluateTemplate(template: string, variables: TemplateVariables): string {- // `{` is excluded too, so a `${` without a closing brace scans only to the next brace.- return template.replace(/\$\{([^{}]+)\}/g, (_match, expression: string) => {+ return template.replace(EXPRESSION, (_match, expression: string) => {const result = evaluateExpression(expression.trim(), variables);return result == null ? "" : String(result);});}+/**+ * Lists the expressions of `template` that `evaluateTemplate()` refuses when given `variableNames`,+ * without evaluating anything, so an editor can mark them as they are typed. Also lists a `${` that+ * is never closed, which `evaluateTemplate()` leaves in the result as text.+ */+export function findTemplateIssues(template: string, variableNames: readonly string[]): TemplateIssue[] {+ const issues: TemplateIssue[] = [];+ const known = new Set(variableNames);+ let closedUpTo = 0;++ for (const match of template.matchAll(EXPRESSION)) {+ const from = match.index ?? 0;+ const to = from + match[0].length;+ reportUnclosed(template.slice(closedUpTo, from), closedUpTo, issues);+ closedUpTo = to;++ const problem = checkExpression(parseExpression(match[1].trim()), known);+ if (problem) {+ issues.push({ ...problem, from, to });+ }+ }++ reportUnclosed(template.slice(closedUpTo), closedUpTo, issues);+ return issues;+}++function reportUnclosed(text: string, offset: number, issues: TemplateIssue[]) {+ const start = text.indexOf("${");+ if (start >= 0) {+ issues.push({ kind: "unclosed", from: offset + start, to: offset + text.length, name: undefined });+ }+}++/** An expression broken into the variable, the properties read off it and the method called last. */+interface ParsedExpression {+ chain: string[];+ method?: { name: string; arg: string | undefined };+}++function parseExpression(expr: string): ParsedExpression | null {+ const methodCall = expr.match(METHOD_CALL);+ if (methodCall) {+ const [ , chain, name, singleQuoteArg, doubleQuoteArg ] = methodCall;+ return { chain: chain.split("."), method: { name, arg: singleQuoteArg ?? doubleQuoteArg } };+ }++ return PROPERTY_CHAIN.test(expr) ? { chain: expr.split(".") } : null;+}++/** What `evaluateExpression()` throws for `parsed`, short of what depends on the values. */+function checkExpression(parsed: ParsedExpression | null, known: ReadonlySet<string>): Omit<TemplateIssue, "from" | "to"> | null {+ if (!parsed) {+ return { kind: "unsupported", name: undefined };+ }+ if (parsed.method && !TEMPLATE_ALLOWED_METHODS.has(parsed.method.name)) {+ return { kind: "methodNotAllowed", name: parsed.method.name };+ }++ const [ root, ...properties ] = parsed.chain;+ if (!known.has(root)) {+ return { kind: "unknownVariable", name: root };+ }++ const refused = properties.find((property) => !TEMPLATE_ALLOWED_PROPERTIES.has(property));+ return refused ? { kind: "propertyNotAllowed", name: refused } : null;+}+/*** Evaluates a single expression like "now.format('YYYY-MM-DD')" or "parentNote.title".*@@ -73,75 +156,45 @@ export function evaluateTemplate(template: string, variables: TemplateVariables)* - `varName.prop` -> variables[varName].prop* - `varName.prop1.prop2` -> variables[varName].prop1.prop2* - `varName.method('arg')` -> variables[varName].method('arg')+ * - `varName.method()` -> variables[varName].method()* - `varName.prop.method('arg')` -> variables[varName].prop.method('arg')*/function evaluateExpression(expr: string, variables: TemplateVariables): unknown {- // First, check for a method call at the end: .methodName('arg') or .methodName("arg")- const methodCallMatch = expr.match(- /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*(?:'([^']*)'|"([^"]*)")\s*\)$/- );-- if (methodCallMatch) {- const [, chainStr, methodName, singleQuoteArg, doubleQuoteArg] = methodCallMatch;- const methodArg = singleQuoteArg !== undefined ? singleQuoteArg : doubleQuoteArg;-- if (!ALLOWED_METHODS.has(methodName)) {- throw new Error(`Method '${methodName}' is not allowed in template expressions`);- }+ const parsed = parseExpression(expr);- const target = resolvePropertyChain(chainStr, variables);- if (target == null) {- return null;- }-- const method = (target as Record<string, unknown>)[methodName];- if (typeof method !== "function") {- throw new Error(`'${methodName}' is not a function on the resolved object`);- }-- return (method as (arg: string) => unknown).call(target, methodArg as string);+ if (!parsed) {+ throw new Error(`Template expression '${expr}' is not a supported expression. ` ++ `Only property access and whitelisted method calls are allowed.`);}- // Check for a no-arg method call at the end: .methodName()- const noArgMethodMatch = expr.match(- /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*\)$/- );-- if (noArgMethodMatch) {- const [, chainStr, methodName] = noArgMethodMatch;-- if (!ALLOWED_METHODS.has(methodName)) {- throw new Error(`Method '${methodName}' is not allowed in template expressions`);- }-- const target = resolvePropertyChain(chainStr, variables);- if (target == null) {- return null;- }+ if (!parsed.method) {+ return resolvePropertyChain(parsed.chain, variables);+ }- const method = (target as Record<string, unknown>)[methodName];- if (typeof method !== "function") {- throw new Error(`'${methodName}' is not a function on the resolved object`);- }+ const { name, arg } = parsed.method;+ if (!TEMPLATE_ALLOWED_METHODS.has(name)) {+ throw new Error(`Method '${name}' is not allowed in template expressions`);+ }- return (method as () => unknown).call(target);+ const target = resolvePropertyChain(parsed.chain, variables);+ if (target == null) {+ return null;}- // Otherwise it's a pure property chain: varName.prop1.prop2...- const propChainMatch = expr.match(/^[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*$/);- if (!propChainMatch) {- throw new Error(`Template expression '${expr}' is not a supported expression. ` +- `Only property access and whitelisted method calls are allowed.`);+ const method = (target as Record<string, unknown>)[name];+ if (typeof method !== "function") {+ throw new Error(`'${name}' is not a function on the resolved object`);}- return resolvePropertyChain(expr, variables);+ return arg === undefined+ ? (method as () => unknown).call(target)+ : (method as (arg: string) => unknown).call(target, arg);}/**- * Resolves a dot-separated property chain like "parentNote.title" against variables.+ * Resolves a property chain like ["parentNote", "title"] against variables.*/-function resolvePropertyChain(chain: string, variables: TemplateVariables): unknown {- const parts = chain.split(".");+function resolvePropertyChain(parts: string[], variables: TemplateVariables): unknown {const rootName = parts[0];if (!(rootName in variables)) {@@ -156,7 +209,7 @@ function resolvePropertyChain(chain: string, variables: TemplateVariables): unkn}const prop = parts[i];- if (!ALLOWED_PROPERTIES.has(prop)) {+ if (!TEMPLATE_ALLOWED_PROPERTIES.has(prop)) {throw new Error(`Property '${prop}' is not allowed in template expressions`);}