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
fix(client): serialize template title writes; full note methods in previews
Elian Doran895f0e53db40
diff --git a/apps/client/src/widgets/bulk_actions/TemplateField.spec.tsx b/apps/client/src/widgets/bulk_actions/TemplateField.spec.tsxindex bed509bd92..09947e741a 100644--- a/apps/client/src/widgets/bulk_actions/TemplateField.spec.tsx+++ b/apps/client/src/widgets/bulk_actions/TemplateField.spec.tsx@@ -19,13 +19,18 @@ const METADATA = {describe("noteTemplateVariables", () => {it("gives the note what the server's BNote gives a template", async () => {- const note = buildNote({ title: "Meeting", "#author": "Ada" });+ const note = buildNote({ title: "Meeting", "#author": "Ada", "#tag": [ "a", "b" ] });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");+ // Every method the engine allows on a note, so that a template it accepts has a preview.+ expect(evaluateTemplate(+ "${note.getLabelValues('tag')}",+ noteTemplateVariables(note, METADATA)+ )).toBe("a,b");});});diff --git a/apps/client/src/widgets/bulk_actions/TemplateField.tsx b/apps/client/src/widgets/bulk_actions/TemplateField.tsxindex f9216a866e..b077b9d6e4 100644--- a/apps/client/src/widgets/bulk_actions/TemplateField.tsx+++ b/apps/client/src/widgets/bulk_actions/TemplateField.tsx@@ -141,7 +141,8 @@ function useTemplatePreview(template: string, noteId: string | 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`.+ * client's copy of the note: every property and method the template engine allows, with the dates+ * of `BNote`.*/export function noteTemplateVariables(note: FNote, metadata: NoteMetaData): TemplateVariables {return {@@ -158,7 +159,10 @@ export function noteTemplateVariables(note: FNote, metadata: NoteMetaData): TempdateCreatedObj: dayjs(metadata.dateCreated),utcDateCreatedObj: dayjs.utc(metadata.utcDateCreated),getLabelValue: (name: string) => note.getLabelValue(name),- getRelationValue: (name: string) => note.getRelationValue(name)+ getLabel: (name: string) => note.getLabel(name),+ getLabelValues: (name: string) => note.getLabels(name).map((label) => label.value),+ getRelationValue: (name: string) => note.getRelationValue(name),+ getAttributeValue: (type: "label" | "relation", name: string) => note.getAttributeValue(type, name)}};}diff --git a/apps/client/src/widgets/dialogs/template_properties.spec.tsx b/apps/client/src/widgets/dialogs/template_properties.spec.tsxindex 242a92b359..3a8ad7a75a 100644--- a/apps/client/src/widgets/dialogs/template_properties.spec.tsx+++ b/apps/client/src/widgets/dialogs/template_properties.spec.tsx@@ -1,9 +1,10 @@import { act } from "preact/test-utils";-import { describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import Component from "../../components/component";import attributes from "../../services/attributes";import froca from "../../services/froca";+import ws from "../../services/ws";import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";import { ParentComponent } from "../react/react_utils";@@ -38,6 +39,11 @@ vi.mock("../react/NoteAutocomplete", () => ({}));describe("TemplatePropertiesDialog", () => {+ // No server pushes entity changes here, so nothing would ever be waited for.+ beforeEach(() => {+ vi.spyOn(ws, "waitForMaxKnownEntityChangeId").mockResolvedValue();+ });+it("saves the template's own #template:titleTemplate when the field loses focus", async () => {const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue();const note = buildNote({ title: "Meeting", "#template": "", "#template:titleTemplate": "Old" });@@ -49,6 +55,7 @@ describe("TemplatePropertiesDialog", () => {// Leaving the field unchanged writes nothing.await act(async () => {field.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));+ await new Promise((resolve) => setTimeout(resolve));});expect(setLabel).not.toHaveBeenCalled();@@ -56,7 +63,8 @@ describe("TemplatePropertiesDialog", () => {await act(async () => {field.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));});- expect(setLabel).toHaveBeenCalledWith(note.noteId, "template:titleTemplate", "Meeting ${now.format('YYYY-MM-DD')}");+ await vi.waitFor(() => expect(setLabel)+ .toHaveBeenCalledWith(note.noteId, "template:titleTemplate", "Meeting ${now.format('YYYY-MM-DD')}"));setLabel.mockRestore();});@@ -70,7 +78,33 @@ describe("TemplatePropertiesDialog", () => {container.querySelector(".template-properties-dialog")?.dispatchEvent(new Event("hidden.bs.modal", { bubbles: true }));});- expect(remove).toHaveBeenCalledWith(note, "template:titleTemplate");+ await vi.waitFor(() => expect(remove).toHaveBeenCalledWith(note, "template:titleTemplate"));+ remove.mockRestore();+ });++ it("clears a title typed and saved while its first write is still under way", async () => {+ let finishWrite: () => void = () => {};+ const setLabel = vi.spyOn(attributes, "setLabel")+ .mockImplementation(() => new Promise<void>((resolve) => { finishWrite = resolve; }));+ const remove = vi.spyOn(attributes, "removeOwnedLabelByName").mockResolvedValue(true);+ const note = buildNote({ title: "Meeting", "#template": "" });++ const { container, field } = await open(note.noteId);+ type(field, "Unwanted");+ await act(async () => {+ field.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));+ });+ type(field, "");+ await act(async () => {+ container.querySelector(".template-properties-dialog")+ ?.dispatchEvent(new Event("hidden.bs.modal", { bubbles: true }));+ });+ expect(remove).not.toHaveBeenCalled();++ await act(async () => finishWrite());+ await vi.waitFor(() => expect(remove).toHaveBeenCalledWith(note, "template:titleTemplate"));+ expect(setLabel).toHaveBeenCalledTimes(1);+ setLabel.mockRestore();remove.mockRestore();});diff --git a/apps/client/src/widgets/dialogs/template_properties.tsx b/apps/client/src/widgets/dialogs/template_properties.tsxindex 514d083340..b82c457f01 100644--- a/apps/client/src/widgets/dialogs/template_properties.tsx+++ b/apps/client/src/widgets/dialogs/template_properties.tsx@@ -1,12 +1,13 @@import "./template_properties.css";import { dayjs, evaluateTemplate } from "@triliumnext/commons";-import { useEffect, useState } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";import type FNote from "../../entities/fnote";import attributes from "../../services/attributes";import froca from "../../services/froca";import { t } from "../../services/i18n";+import ws from "../../services/ws";import TemplateField, { noteTemplateVariables } from "../bulk_actions/TemplateField";import { CollectionPropertiesDialog } from "../note_bars/CollectionProperties";import { Card, OptionCardSection } from "../react/Card";@@ -25,26 +26,40 @@ export default function TemplatePropertiesDialog() {const [ shown, setShown ] = useState(false);const [ titleTemplate, setTitleTemplate ] = useState("");const [ defaultParentId, setDefaultParentId ] = useState<string>();+ /** The title template as last written, which froca can lag behind while a write is under way. */+ const savedTitleTemplate = useRef("");+ const titleWrites = useRef<Promise<void>>(Promise.resolve());const preview = useTitlePreview(titleTemplate, note);useTriliumEvent("showTemplateProperties", async ({ noteId }) => {const templateNote = await froca.getNote(noteId);if (!templateNote) return;- setTitleTemplate(templateNote.getOwnedLabelValue("template:titleTemplate") ?? "");+ const ownTitleTemplate = templateNote.getOwnedLabelValue("template:titleTemplate") ?? "";+ savedTitleTemplate.current = ownTitleTemplate;+ setTitleTemplate(ownTitleTemplate);setDefaultParentId(templateNote.getOwnedRelationValue("template:newNoteDefaultParent") ?? undefined);setNote(templateNote);setShown(true);});- async function saveTitleTemplate() {+ /**+ * Queues writing the title template. The writes run one after another, each waiting for froca to+ * hold the one before it, so the last value wins and removing finds the label just created.+ */+ function saveTitleTemplate() {if (!note) return;+ const templateNote = note;const value = titleTemplate;- if (value === (note.getOwnedLabelValue("template:titleTemplate") ?? "")) return;- if (value) {- await attributes.setLabel(note.noteId, "template:titleTemplate", value);- } else {- await attributes.removeOwnedLabelByName(note, "template:titleTemplate");- }+ titleWrites.current = titleWrites.current.catch(() => {}).then(async () => {+ if (value === savedTitleTemplate.current) return;+ if (value) {+ await attributes.setLabel(templateNote.noteId, "template:titleTemplate", value);+ } else {+ await attributes.removeOwnedLabelByName(templateNote, "template:titleTemplate");+ }+ savedTitleTemplate.current = value;+ await ws.waitForMaxKnownEntityChangeId();+ });}async function saveDefaultParent(noteId: string | undefined) {@@ -63,7 +78,7 @@ export default function TemplatePropertiesDialog() {title={t("template_properties.title")}show={shown}onHidden={() => {- void saveTitleTemplate();+ saveTitleTemplate();setShown(false);}}>@@ -81,7 +96,7 @@ export default function TemplatePropertiesDialog() {preview={preview}currentValue={titleTemplate}onChange={setTitleTemplate}- onBlur={() => void saveTitleTemplate()}+ onBlur={saveTitleTemplate}/></OptionCardSection><OptionCardSection