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(calendar): edit an event by the labels it renames for itself
Elian Doran0100e71c02d9
diff --git a/apps/client/src/widgets/collections/calendar/EventDatesEditor.spec.tsx b/apps/client/src/widgets/collections/calendar/EventDatesEditor.spec.tsxindex 170a4cb825..9460085d35 100644--- a/apps/client/src/widgets/collections/calendar/EventDatesEditor.spec.tsx+++ b/apps/client/src/widgets/collections/calendar/EventDatesEditor.spec.tsx@@ -106,4 +106,43 @@ describe("EventDatesEditor", () => {expect(setLabel).not.toHaveBeenCalled();expect(removeLabel).not.toHaveBeenCalled();});++ it("reads and writes the labels a note renames for itself, as the event builder reads them", () => {+ const note = buildNote({+ title: "Fair",+ "#calendar:startDate": "myStartDate", "#myStartDate": "2026-06-05",+ "#calendar:endDate": "myEndDate", "#myEndDate": "2026-06-07"+ });+ mount(note);++ expect(allDayBox()?.checked).toBe(true);+ expect(dateInputs()[0].value).toBe("2026-06-05");+ expect(dateInputs()[1].value).toBe("2026-06-07");++ commitValue(dateInputs()[1], "2026-06-09");+ expect(setLabel).toHaveBeenCalledWith(note.noteId, "myEndDate", "2026-06-09");+ });++ it("falls back to a stock label the renamed one holds no value over, as the builder does", () => {+ mount(buildNote({ title: "Fair", "#calendar:startDate": "myStartDate", "#startDate": "2026-06-05" }));+ expect(dateInputs()[0].value).toBe("2026-06-05");+ });++ it("clears the stock label along with the renamed one, keeping the fallback from resurrecting it", () => {+ const note = buildNote({+ title: "Meeting", "#startDate": "2026-06-05",+ "#calendar:startTime": "myStartTime", "#myStartTime": "13:00",+ "#calendar:endTime": "myEndTime", "#myEndTime": "14:30"+ });+ mount(note);+ expect(allDayBox()?.checked).toBe(false);+ expect(timeInputs()[0].value).toBe("13:00");++ act(() => allDayBox()?.click());++ expect(removeLabel).toHaveBeenCalledWith(note, "myStartTime");+ expect(removeLabel).toHaveBeenCalledWith(note, "startTime");+ expect(removeLabel).toHaveBeenCalledWith(note, "myEndTime");+ expect(removeLabel).toHaveBeenCalledWith(note, "endTime");+ });});diff --git a/apps/client/src/widgets/collections/calendar/EventDatesEditor.tsx b/apps/client/src/widgets/collections/calendar/EventDatesEditor.tsxindex a5d4ba157d..93f3c2bba2 100644--- a/apps/client/src/widgets/collections/calendar/EventDatesEditor.tsx+++ b/apps/client/src/widgets/collections/calendar/EventDatesEditor.tsx@@ -7,18 +7,17 @@ import FNote from "../../../entities/fnote";import { t } from "../../../services/i18n";import LabelValueInput from "../../attribute_widgets/label_value_input";import FormToggle from "../../react/FormToggle";-import { useNoteLabel, useUniqueName } from "../../react/hooks";+import { useUniqueName } from "../../react/hooks";import { EventField, EventFieldControls, EventFieldRow } from "./EventField";+import { useEventLabel } from "./hooks";/*** Edits when the event happens, through the date and time labels the calendar draws it by (see- * event_builder.ts). Two shapes, told apart by the all-day switch: a whole-day event is a span of- * days — a start date and, where it runs longer, an end date — while a timed one is a single day- * and the hours within it. Rendered as {@link EventField} rows, standing in the event popover's- * field column beside the recurrence.- *- * Only the stock label names, as the popover reads only those (see EVENT_LABELS in- * EventPopover.tsx).+ * event_builder.ts) — under whatever names the note draws them by, a `#calendar:startDate`+ * renaming included (see useEventLabel). Two shapes, told apart by the all-day switch: a whole-day+ * event is a span of days — a start date and, where it runs longer, an end date — while a timed+ * one is a single day and the hours within it. Rendered as {@link EventField} rows, standing in+ * the event popover's field column beside the recurrence.*/export default function EventDatesEditor({ note, repeats }: {note: FNote;@@ -26,10 +25,10 @@ export default function EventDatesEditor({ note, repeats }: {* belongs to the recurrence editor, but the room next to the switch is this editor's to give. */repeats?: ComponentChildren;}) {- const [ startDate, setStartDate ] = useNoteLabel(note, "startDate");- const [ endDate, setEndDate ] = useNoteLabel(note, "endDate");- const [ startTime, setStartTime ] = useNoteLabel(note, "startTime");- const [ endTime, setEndTime ] = useNoteLabel(note, "endTime");+ const [ startDate, setStartDate ] = useEventLabel(note, "startDate");+ const [ endDate, setEndDate ] = useEventLabel(note, "endDate");+ const [ startTime, setStartTime ] = useEventLabel(note, "startTime");+ const [ endTime, setEndTime ] = useEventLabel(note, "endTime");const startDateId = useUniqueName("event-start-date");const allDayId = useUniqueName("event-all-day");diff --git a/apps/client/src/widgets/collections/calendar/EventPopover.tsx b/apps/client/src/widgets/collections/calendar/EventPopover.tsxindex 7153dde385..6aecf23b9f 100644--- a/apps/client/src/widgets/collections/calendar/EventPopover.tsx+++ b/apps/client/src/widgets/collections/calendar/EventPopover.tsx@@ -16,16 +16,10 @@ import Popover from "../../react/Popover";import { removeFromCalendar } from "./api";import EventDatesEditor from "./EventDatesEditor";import { EventFieldList } from "./EventField";+import { useEventLabelOmissions } from "./hooks";import RecurrenceEditor from "./RecurrenceEditor";import { AnchorPoint } from "./selection";-/**- * The labels the popover already speaks for, so their fields are not repeated in the promoted grid:- * the dates the calendar draws the event by, and the recurrence the popover's own field edits.- * Only the stock names for now; a calendar naming its own (`calendar:startDate`) still shows those.- */-const EVENT_LABELS = [ "startDate", "endDate", "startTime", "endTime", "recurrence" ];-/*** The whole of an event: the note's title, its own fields — when it happens, how it repeats — its* promoted attributes and its content, each edited exactly as it is anywhere else (the@@ -238,6 +232,11 @@ function EventDetailsBody({ note, parentNote, isEditable, onClose }: {isEditable: boolean;onClose(): void;}) {+ // The labels the body's own fields already speak for, so the promoted grid does not repeat+ // them: the dates the calendar draws the event by and the recurrence — under the stock names+ // and whatever names the note draws them by instead (see useEventLabelOmissions).+ const eventLabels = useEventLabelOmissions(note);+return (<div className="calendar-event-popover-body tn-embedded-note-pane">{/* What can be done with the event: the ways of opening its note (see@@ -277,7 +276,7 @@ function EventDetailsBody({ note, parentNote, isEditable, onClose }: {</EventFieldList>)}- <PromotedAttributes omit={EVENT_LABELS} />+ <PromotedAttributes omit={eventLabels} /><NoteDetail /></div>);diff --git a/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx b/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsxindex 0fa0304067..6a94152a2f 100644--- a/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx+++ b/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx@@ -9,9 +9,10 @@ import LabelValueInput from "../../attribute_widgets/label_value_input";import Dropdown from "../../react/Dropdown";import FormSelect from "../../react/FormSelect";import FormTextBox, { FormTextBoxWithUnit } from "../../react/FormTextBox";-import { useNoteLabel, useUniqueName } from "../../react/hooks";+import { useUniqueName } from "../../react/hooks";import SegmentedChoice from "../../react/SegmentedChoice";import { EventField, EventFieldControls, EventFieldList } from "./EventField";+import { useEventLabel } from "./hooks";import {FREQUENCIES,Frequency,@@ -25,17 +26,14 @@ import {} from "./recurrence";/**- * Edits how the event repeats, through the note's `#recurrence` label — structured fields for the- * everyday rules, the raw RRULE string for one saying more than they can (see recurrence.ts for- * where that line runs). Rendered as {@link EventField} rows, so it stands in the event popover's- * field column beside the start and end dates when those grow editors of their own.- *- * Only the stock label name for now, as the popover reads only the stock names (see EVENT_LABELS- * in EventPopover.tsx); a calendar naming its own via `#calendar:recurrence` edits that label by- * hand.+ * Edits how the event repeats, through the note's `#recurrence` label — or whatever label a+ * `#calendar:recurrence` renaming points at instead (see useEventLabel) — structured fields for+ * the everyday rules, the raw RRULE string for one saying more than they can (see recurrence.ts+ * for where that line runs). Rendered as {@link EventField} rows, so it stands in the event+ * popover's field column beside the start and end dates when those grow editors of their own.*/export default function RecurrenceEditor({ note }: { note: FNote }) {- const [ storedValue, setStoredValue ] = useNoteLabel(note, "recurrence");+ const [ storedValue, setStoredValue ] = useEventLabel(note, "recurrence");const [ model, setModel ] = useState<ParsedRecurrence>(() => parseRecurrence(storedValue));// Follows the label wherever it changes from — another client, the attribute editor, an undo —diff --git a/apps/client/src/widgets/collections/calendar/api.spec.ts b/apps/client/src/widgets/collections/calendar/api.spec.tsnew file mode 100644index 0000000000..6e2aebd861--- /dev/null+++ b/apps/client/src/widgets/collections/calendar/api.spec.ts@@ -0,0 +1,86 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import { setAttribute } from "../../../services/attributes";+import dialog from "../../../services/dialog";+import { buildNote } from "../../../test/easy-froca";+import { changeEvent, removeFromCalendar } from "./api";++vi.mock("../../../services/attributes", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../../services/attributes")>(),+ setAttribute: vi.fn()+}));++vi.mock("../../../services/dialog", () => ({+ default: { confirmDeleteNoteBoxWithNote: vi.fn() }+}));++vi.mock("../../../services/note_create", () => ({ default: { createNote: vi.fn() } }));+vi.mock("../../../services/note_deletion", () => ({ deleteNoteOrBranch: vi.fn() }));++/** The labels each call wrote or cleared, in order — the name and the value it was set to. */+const writtenLabels = () => vi.mocked(setAttribute).mock.calls.map((call) => [ call[2], call[3] ]);++describe("changeEvent", () => {+ beforeEach(() => vi.mocked(setAttribute).mockClear());++ it("writes the stock labels where the note renames none", async () => {+ const note = buildNote({ title: "Fair", "#startDate": "2026-06-05" });++ await changeEvent(note, { startDate: "2026-06-06", endDate: "2026-06-08", startTime: "13:00", endTime: "14:00" });++ expect(writtenLabels()).toEqual([+ [ "startDate", "2026-06-06" ],+ [ "endDate", "2026-06-08" ],+ [ "startTime", "13:00" ],+ [ "endTime", "14:00" ]+ ]);+ });++ it("writes the labels a note renames for itself, and clears the stock fallback along with a renamed one", async () => {+ const note = buildNote({+ title: "Fair",+ "#calendar:startDate": "myStartDate", "#myStartDate": "2026-06-05",+ "#calendar:endDate": "myEndDate", "#myEndDate": "2026-06-07", "#endDate": "2026-06-06"+ });++ await changeEvent(note, { startDate: "2026-06-09", endDate: null, startTime: null, endTime: null });++ expect(writtenLabels()).toEqual([+ [ "myStartDate", "2026-06-09" ],+ // The stale stock end date goes with the renamed one: left behind, the event builder's+ // fallback would pick it up the moment the renamed label was gone.+ [ "myEndDate", null ],+ [ "endDate", null ],+ [ "startTime", null ],+ [ "endTime", null ]+ ]);+ });+});++describe("removeFromCalendar", () => {+ beforeEach(() => vi.mocked(setAttribute).mockClear());++ it("clears the start date under both its names, so the fallback cannot keep the event on", async () => {+ vi.mocked(dialog.confirmDeleteNoteBoxWithNote)+ .mockResolvedValue({ confirmed: true, isDeleteNoteChecked: false });+ const calendar = buildNote({ title: "Calendar" });+ // The renaming is configured but unfilled, so the event stands on the stock label alone —+ // removing only the renamed one would leave it on the calendar.+ const note = buildNote({ title: "Fair", "#calendar:startDate": "myStartDate", "#startDate": "2026-06-05" });++ expect(await removeFromCalendar(note, calendar)).toBe(true);+ expect(writtenLabels()).toEqual([+ [ "myStartDate", null ],+ [ "startDate", null ]+ ]);+ });++ it("does nothing where the dialog was dismissed", async () => {+ vi.mocked(dialog.confirmDeleteNoteBoxWithNote).mockResolvedValue(undefined);+ const calendar = buildNote({ title: "Calendar" });+ const note = buildNote({ title: "Fair", "#startDate": "2026-06-05" });++ expect(await removeFromCalendar(note, calendar)).toBe(false);+ expect(setAttribute).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/collections/calendar/api.ts b/apps/client/src/widgets/collections/calendar/api.tsindex 1529c2a95d..17a2bdf52a 100644--- a/apps/client/src/widgets/collections/calendar/api.ts+++ b/apps/client/src/widgets/collections/calendar/api.ts@@ -1,11 +1,12 @@import { AttributeRow } from "@triliumnext/commons";import FNote from "../../../entities/fnote";-import { setAttribute, setLabel } from "../../../services/attributes";+import { setAttribute } from "../../../services/attributes";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";import note_create from "../../../services/note_create";import { deleteNoteOrBranch } from "../../../services/note_deletion";+import { EventLabelName } from "./utils";interface NewEventOpts {/** Left out, the note is named the way any new child of the calendar is — by the calendar's@@ -99,11 +100,10 @@ export async function removeFromCalendar(note: FNote, calendarNote: FNote) {if (result.isDeleteNoteChecked) {await deleteNoteOrBranch(note.noteId, branchId);} else {- // Only the start date goes — the label the calendar draws the event by, which the note may- // name for itself (see changeEvent). Whatever else the note holds about its dates keeps:- // an end or a time without a start puts nothing on the calendar.- const startAttribute = note.getLabelValue("calendar:startDate") || "startDate";- await setAttribute(note, "label", startAttribute, undefined);+ // Only the start date goes — the label the calendar draws the event by, under whatever+ // name the note draws it by (see setEventLabel). Whatever else the note holds about its+ // dates keeps: an end or a time without a start puts nothing on the calendar.+ await setEventLabel(note, "startDate", null);}return true;@@ -115,18 +115,23 @@ export async function changeEvent(note: FNote, { startDate, endDate, startTime,endDate = undefined;}- // Since they can be customized via calendar:startDate=$foo and calendar:endDate=$bar we need to determine the- // attributes to be effectively updated- let startAttribute = note.getAttributes("label").filter(attr => attr.name == "calendar:startDate").shift()?.value||"startDate";- let endAttribute = note.getAttributes("label").filter(attr => attr.name == "calendar:endDate").shift()?.value||"endDate";-- const noteId = note.noteId;- setLabel(noteId, startAttribute, startDate, false, componentId);- setAttribute(note, "label", endAttribute, endDate, componentId);-- startAttribute = note.getAttributes("label").filter(attr => attr.name == "calendar:startTime").shift()?.value||"startTime";- endAttribute = note.getAttributes("label").filter(attr => attr.name == "calendar:endTime").shift()?.value||"endTime";+ await setEventLabel(note, "startDate", startDate, componentId);+ await setEventLabel(note, "endDate", endDate ?? null, componentId);+ await setEventLabel(note, "startTime", startTime ?? null, componentId);+ await setEventLabel(note, "endTime", endTime ?? null, componentId);+}- setAttribute(note, "label", startAttribute, startTime, componentId);- setAttribute(note, "label", endAttribute, endTime, componentId);+/**+ * Writes one of the labels the calendar draws an event by, honouring the note's own renaming of it+ * (`#calendar:startDate=$foo` and kin): where a renaming names a label, that label is the one+ * written, as it is the one the event builder reads (see getCustomisableLabel in utils.ts).+ * Clearing clears the stock label too — a value left there would put the event straight back+ * through the builder's fallback.+ */+export async function setEventLabel(note: FNote, defaultName: EventLabelName, value: string | null, componentId?: string) {+ const customName = note.getLabelValue(`calendar:${defaultName}`);+ await setAttribute(note, "label", customName || defaultName, value, componentId);+ if (customName && value === null) {+ await setAttribute(note, "label", defaultName, null, componentId);+ }}diff --git a/apps/client/src/widgets/collections/calendar/event_builder.ts b/apps/client/src/widgets/collections/calendar/event_builder.tsindex 8d3021b1ee..ea6ba62c04 100644--- a/apps/client/src/widgets/collections/calendar/event_builder.ts+++ b/apps/client/src/widgets/collections/calendar/event_builder.ts@@ -1,7 +1,6 @@import { EventInput, EventSourceFuncArg, EventSourceInput } from "@fullcalendar/core/index.js";import { dayjs } from "@triliumnext/commons";import clsx from "clsx";-import { start } from "repl";import * as rruleLib from 'rrule';import FNote from "../../../entities/fnote";diff --git a/apps/client/src/widgets/collections/calendar/hooks.ts b/apps/client/src/widgets/collections/calendar/hooks.tsnew file mode 100644index 0000000000..366018275d--- /dev/null+++ b/apps/client/src/widgets/collections/calendar/hooks.ts@@ -0,0 +1,48 @@+import FNote from "../../../entities/fnote";+import { useNoteLabel, useNoteLabelByName } from "../../react/hooks";+import { EVENT_LABELS, EventLabelName } from "./utils";++/**+ * Reads and writes one of the labels the calendar draws an event by, honouring the note's own+ * renaming of it: with `#calendar:startDate=myStartDate`, the value is `#myStartDate`'s — falling+ * back to the stock `#startDate` where the renamed label holds nothing, exactly as the event+ * builder falls back (see getCustomisableLabel) — and an edit writes the renamed label, as a drag+ * on the grid does (see changeEvent in api.ts). Clearing clears the stock label too: a stale value+ * left there would come back through the builder's fallback the moment the renamed one went.+ */+export function useEventLabel(note: FNote, defaultName: EventLabelName): [string | null, (value: string | null) => void] {+ const [ customName ] = useNoteLabel(note, `calendar:${defaultName}`);+ const [ customValue, setCustomValue ] = useNoteLabelByName(note, customName || defaultName);+ const [ stockValue, setStockValue ] = useNoteLabelByName(note, defaultName);++ const value = (customName ? customValue : null) || stockValue || null;+ const setValue = (newValue: string | null) => {+ if (customName) {+ setCustomValue(newValue);+ if (newValue === null) {+ setStockValue(null);+ }+ } else {+ setStockValue(newValue);+ }+ };++ return [ value, setValue ];+}++/**+ * The label names the event popover's own fields already speak for, so the promoted grid does not+ * repeat them (see EventDetailsBody in EventPopover.tsx): the stock names always, and whatever+ * names the note has pointed the calendar at instead.+ */+export function useEventLabelOmissions(note: FNote): string[] {+ const [ customStartDate ] = useNoteLabel(note, "calendar:startDate");+ const [ customEndDate ] = useNoteLabel(note, "calendar:endDate");+ const [ customStartTime ] = useNoteLabel(note, "calendar:startTime");+ const [ customEndTime ] = useNoteLabel(note, "calendar:endTime");+ const [ customRecurrence ] = useNoteLabel(note, "calendar:recurrence");++ const customNames = [ customStartDate, customEndDate, customStartTime, customEndTime, customRecurrence ]+ .filter((name): name is string => !!name);+ return [ ...EVENT_LABELS, ...customNames ];+}diff --git a/apps/client/src/widgets/collections/calendar/utils.ts b/apps/client/src/widgets/collections/calendar/utils.tsindex 9ab47b9f9d..e441626b72 100644--- a/apps/client/src/widgets/collections/calendar/utils.ts+++ b/apps/client/src/widgets/collections/calendar/utils.ts@@ -59,6 +59,12 @@ export function formatTimeToLocalISO(date: Date | null | undefined) {.substring(0, 5);}+/** The labels the calendar draws an event by, each of which a note may rename for itself via the+ * matching `#calendar:` label (see {@link getCustomisableLabel}). */+export type EventLabelName = "startDate" | "endDate" | "startTime" | "endTime" | "recurrence";++export const EVENT_LABELS: EventLabelName[] = [ "startDate", "endDate", "startTime", "endTime", "recurrence" ];+/*** Allows the user to customize the attribute from which to obtain a particular value. For example, if `customLabelNameAttribute` is `calendar:startDate`* and `defaultLabelName` is `startDate` and the note at hand has `#calendar:startDate=myStartDate #myStartDate=2025-02-26` then the value returned will@@ -85,13 +91,23 @@ export function getCustomisableLabel(note: FNote, defaultLabelName: string, custconst MIN_DURATION_SECONDS = 60; // 1 minuteconst MAX_DURATION_SECONDS = 24 * 60 * 60; // 24 hours-export function isValidDuration(str: string | null | undefined): boolean {- // The regex already constrains minutes/seconds to 00–59, so only the total needs bounding.+/**+ * How long a `HH:MM:SS` duration lasts, in seconds, or `null` for anything not written that way.+ * Says nothing about whether the length is one a calendar will take (see {@link isValidDuration});+ * a caller that has already asked that can read the answer here.+ */+export function parseDurationSeconds(str: string | null | undefined): number | null {const match = str?.match(/^(\d{2}):([0-5]\d):([0-5]\d)$/);- if (!match) return false;+ if (!match) return null;const [, hours, minutes, seconds] = match;- const totalSeconds = Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds);+ return Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds);+}++export function isValidDuration(str: string | null | undefined): boolean {+ // The regex already constrains minutes/seconds to 00–59, so only the total needs bounding.+ const totalSeconds = parseDurationSeconds(str);+ if (totalSeconds === null) return false;return totalSeconds >= MIN_DURATION_SECONDS && totalSeconds <= MAX_DURATION_SECONDS;}diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex b0aef548fc..7118175387 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -686,9 +686,18 @@ export function useNoteRelationTarget(note: FNote, relationName: RelationNames)* - if the value is null then the label is removed.*/export function useNoteLabel(note: FNote | undefined | null, labelName: FilterLabelsByType<string>): [string | null | undefined, (newValue: string | null | undefined) => void] {+ return useNoteLabelByName(note, labelName);+}++/**+ * The same as {@link useNoteLabel} for a label the app does not know by name — one the user named+ * themselves, e.g. a label a `#calendar:startDate` renaming points at. Prefer {@link useNoteLabel}+ * wherever the name is a builtin one, as it holds the name to the declared vocabulary.+ */+export function useNoteLabelByName(note: FNote | undefined | null, labelName: string): [string | null | undefined, (newValue: string | null | undefined) => void] {const [ , setLabelValue ] = useState<string | null | undefined>();- useEffect(() => setLabelValue(note?.getLabelValue(labelName) ?? null), [ note ]);+ useEffect(() => setLabelValue(note?.getLabelValue(labelName) ?? null), [ note, labelName ]);useTriliumEvent("entitiesReloaded", ({ loadResults }) => {for (const attr of loadResults.getAttributeRows()) {if (attr.type === "label" && attr.name === labelName && attributes.isAffecting(attr, note)) {@@ -710,7 +719,7 @@ export function useNoteLabel(note: FNote | undefined | null, labelName: FilterLaattributes.removeOwnedLabelByName(note, labelName);}}- }, [note]);+ }, [note, labelName]);useDebugValue(labelName);