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): title each occurrence of a recurring event with #calendar:titleTemplate
Clauded4d5938982f9
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 2bb525dd1d..2c39c9cadd 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -757,6 +757,7 @@"calendar_slot_duration": "How long each timeslot of a calendar lasts, as <code>HH:MM:SS</code>. Defaults to 15 minutes.","calendar_slot_label_interval": "How often the timeslots of a calendar are labeled, as <code>HH:MM:SS</code>. Defaults to an hour.","calendar_title": "Names the attribute an event takes its title from, instead of the note title. Either a label or a relation, written without <code>#</code> or <code>~</code>.",+ "calendar_title_template": "How an event is titled on the calendar, filled in for every occurrence of a repeating one. Reads <code>${title}</code>, <code>${age}</code> (whole years since the start date) and the dates <code>${date}</code> and <code>${startDate}</code>, e.g. <code>${title} (${age})</code> on a yearly birthday.","calendar_displayed_attributes": "Comma-delimited attribute names whose values are shown on the event. A relation is shown as the title of the note it points at.","calendar_start_date": "Names the label an event reads its start date from, instead of <code>#startDate</code>. Written without the <code>#</code>.","calendar_end_date": "Names the label an event reads its end date from, instead of <code>#endDate</code>.",diff --git a/apps/client/src/widgets/attribute_widgets/attr_help.ts b/apps/client/src/widgets/attribute_widgets/attr_help.tsindex b6d85fb8ba..37016a5265 100644--- a/apps/client/src/widgets/attribute_widgets/attr_help.ts+++ b/apps/client/src/widgets/attribute_widgets/attr_help.ts@@ -167,6 +167,7 @@ export const ATTR_HELP: AttrHelpMap = {"calendar:slotDuration": t("attribute_detail.calendar_slot_duration"),"calendar:slotLabelInterval": t("attribute_detail.calendar_slot_label_interval"),"calendar:title": t("attribute_detail.calendar_title"),+ "calendar:titleTemplate": t("attribute_detail.calendar_title_template"),"calendar:displayedAttributes": t("attribute_detail.calendar_displayed_attributes"),"calendar:startDate": t("attribute_detail.calendar_start_date"),"calendar:endDate": t("attribute_detail.calendar_end_date"),diff --git a/apps/client/src/widgets/collections/calendar/event_builder.spec.ts b/apps/client/src/widgets/collections/calendar/event_builder.spec.tsindex da3f81fe95..7894543c8b 100644--- a/apps/client/src/widgets/collections/calendar/event_builder.spec.ts+++ b/apps/client/src/widgets/collections/calendar/event_builder.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from "vitest";import { buildNote, buildNotes } from "../../../test/easy-froca.js";-import { buildEvent, buildEvents } from "./event_builder.js";+import { buildEvent, buildEvents, buildOccurrenceTitle } from "./event_builder.js";import { LOCALE_MAPPINGS } from "./index.js";import { isValidDuration, parseDurationSeconds } from "./utils.js";import { LOCALES } from "@triliumnext/commons";@@ -389,6 +389,70 @@ describe("Recurrence", () => {expect(calledWithInvalid).toBe(true);consoleSpy.mockRestore();});++ it("carries the title template and the day the series starts on", async () => {+ const noteIds = buildNotes([+ {+ title: "John Smith",+ "#startDate": "1990-05-12",+ "#startTime": "09:00",+ "#recurrence": "RRULE:FREQ=YEARLY",+ "#calendar:titleTemplate": "${title} (${age})"+ }+ ]);+ const events = await buildEvents(noteIds);++ expect(events[0]).toMatchObject({+ title: "John Smith",+ titleTemplate: "${title} (${age})",+ // The date as the label holds it, the start time not yet worked into it.+ seriesStart: "1990-05-12"+ });+ });+});++/**+ * The title a chip is drawn under, which a repeating event names once per occurrence: the calendar+ * asks for it as each chip is drawn (see eventContent in index.tsx), the occurrence's own date in+ * hand.+ */+describe("buildOccurrenceTitle", () => {+ /** An event as FullCalendar hands it to a chip, this occurrence falling on the given day. */+ function occurrence(titleTemplate: string | null, start: Date, seriesStart = "1990-05-12") {+ return { title: "John Smith", start, extendedProps: { titleTemplate, seriesStart } };+ }++ it("leaves an event with no template under its plain title", () => {+ expect(buildOccurrenceTitle(occurrence(null, new Date(2026, 4, 12)))).toBe("John Smith");+ });++ it("counts the whole years from the start date to the occurrence", () => {+ expect(buildOccurrenceTitle(occurrence("${title} (${age})", new Date(2026, 4, 12))))+ .toBe("John Smith (36)");+ expect(buildOccurrenceTitle(occurrence("${title} turns ${age}", new Date(2027, 4, 12))))+ .toBe("John Smith turns 37");+ // The day the series itself starts on, which is where the count starts.+ expect(buildOccurrenceTitle(occurrence("${title} (${age})", new Date(1990, 4, 12))))+ .toBe("John Smith (0)");+ });++ it("reads both the occurrence's date and the series'", () => {+ const template =+ "${title}, born ${startDate.format('YYYY')}, turns ${age} in ${date.format('YYYY')}";+ expect(buildOccurrenceTitle(occurrence(template, new Date(2026, 4, 12))))+ .toBe("John Smith, born 1990, turns 36 in 2026");+ });++ it("falls back to the plain title for a template the evaluator rejects, saying so once", () => {+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const broken = occurrence("${nmae} (${age})", new Date(2026, 4, 12));++ expect(buildOccurrenceTitle(broken)).toBe("John Smith");+ expect(buildOccurrenceTitle(broken)).toBe("John Smith");+ expect(consoleSpy).toHaveBeenCalledOnce();+ expect(consoleSpy.mock.calls[0]?.[0]).toContain("#calendar:titleTemplate");+ consoleSpy.mockRestore();+ });});diff --git a/apps/client/src/widgets/collections/calendar/event_builder.ts b/apps/client/src/widgets/collections/calendar/event_builder.tsindex cec3ef745d..15f0d8e4c9 100644--- a/apps/client/src/widgets/collections/calendar/event_builder.ts+++ b/apps/client/src/widgets/collections/calendar/event_builder.ts@@ -1,4 +1,4 @@-import { dayjs } from "@triliumnext/commons";+import { dayjs, evaluateTemplate } from "@triliumnext/commons";import clsx from "clsx";import { EventInput, EventSourceFuncInfo, EventSourceInput } from "fullcalendar";import * as rruleLib from 'rrule';@@ -8,7 +8,7 @@ import FNote from "../../../entities/fnote";import froca from "../../../services/froca";import server from "../../../services/server";import toastService from "../../../services/toast";-import { getCustomisableLabel, getMonthsInDateRange } from "./utils";+import { formatDateToLocalISO, getCustomisableLabel, getMonthsInDateRange } from "./utils";interface Event {startDate: string,@@ -100,6 +100,11 @@ export async function buildEvent(note: FNote, { startDate, endDate, startTime, econst colorClass = note.getColorClass();const events: EventInput[] = [];+ // The day the series starts on, read before the code below appends the start time and the+ // exclusive end date. buildOccurrenceTitle() counts every occurrence from it.+ const seriesStart = startDate;+ const titleTemplate = note.getLabelValue("calendar:titleTemplate");+const calendarDisplayedAttributes = note.getLabelValue("calendar:displayedAttributes")?.split(",");let displayedAttributesData: Array<[string, string]> | null = null;if (calendarDisplayedAttributes) {@@ -144,6 +149,8 @@ export async function buildEvent(note: FNote, { startDate, endDate, startTime, eurl: `#${note.noteId}?popup`,noteId: note.noteId,iconClass: note.getLabelValue("iconClass"),+ titleTemplate,+ seriesStart,promotedAttributes: displayedAttributesData,className: clsx({archived: isArchived}, colorClass)};@@ -181,6 +188,69 @@ export async function buildEvent(note: FNote, { startDate, endDate, startTime, ereturn events;}+/**+ * Builds the title one occurrence of an event is drawn with: the note's `#calendar:titleTemplate`+ * filled in for the day the occurrence falls on, or the plain title when the note has no template.+ *+ * Runs as the chip is drawn rather than in {@link buildEvent} because FullCalendar expands a+ * `#recurrence` rule into occurrences itself: a repeating event is one {@link EventInput} with+ * one title, so `${age}` — the whole years from `#startDate` to this occurrence — is only known+ * here.+ *+ * A template {@link evaluateTemplate} rejects leaves the event with its plain title.+ */+export function buildOccurrenceTitle({ title, start, extendedProps }: OccurrenceEvent) {+ const { titleTemplate, seriesStart } = extendedProps;+ if (!titleTemplate || !seriesStart) {+ return title;+ }++ // Both dates as plain days, without the time: a DST shift between them would otherwise take an+ // hour off the span and round `age` down by a year.+ const occurrenceDay = formatDateToLocalISO(start);+ const seriesStartDay = dayjs(seriesStart.split("T")[0]);+ const occurrence = occurrenceDay ? dayjs(occurrenceDay) : seriesStartDay;++ try {+ return evaluateTemplate(titleTemplate, {+ title,+ age: occurrence.diff(seriesStartDay, "year"),+ date: occurrence,+ startDate: seriesStartDay+ });+ } catch (error) {+ reportBrokenTitleTemplate(titleTemplate, error);+ return title;+ }+}++/** The parts of a FullCalendar event {@link buildOccurrenceTitle} reads. */+interface OccurrenceEvent {+ title: string;+ /** Where this occurrence starts; the template is filled in for that day. */+ start: Date | null;+ extendedProps: {+ titleTemplate?: string | null;+ /** The `#startDate` the series is counted from, as {@link buildEvent} wrote it. */+ seriesStart?: string | null;+ };+}++/** Templates already reported. {@link buildOccurrenceTitle} runs for every chip the calendar+ * draws, so a rejected template would otherwise be logged once per chip. */+const brokenTitleTemplates = new Set<string>();++/** Logs a template {@link evaluateTemplate} rejects, once per template. */+function reportBrokenTitleTemplate(template: string, error: unknown) {+ if (brokenTitleTemplates.has(template)) {+ return;+ }++ brokenTitleTemplates.add(template);+ const reason = error instanceof Error ? error.message : error;+ console.error(`Invalid #calendar:titleTemplate "${template}": ${reason}`);+}+/*** How long one occurrence of a recurring event lasts, as the duration object FullCalendar builds* its own from rather than as an `HH:mm` string. A string of hours and minutes has nowhere to putdiff --git a/apps/client/src/widgets/collections/calendar/index.tsx b/apps/client/src/widgets/collections/calendar/index.tsxindex de30fd06ef..f2391226bc 100644--- a/apps/client/src/widgets/collections/calendar/index.tsx+++ b/apps/client/src/widgets/collections/calendar/index.tsx@@ -36,7 +36,7 @@ import EventPopover from "./EventPopover";import GhostPopover from "./GhostPopover";import { openCalendarContextMenu } from "./context_menu";import { CalendarSelection, EventDraft } from "./selection";-import { buildEvents, buildEventsForCalendar } from "./event_builder";+import { buildEvents, buildEventsForCalendar, buildOccurrenceTitle } from "./event_builder";import { formatDateToLocalISO, formatTimeToLocalISO, isAttributeChangeAffecting, isBranchChangeAffecting, isValidDuration, parseDurationSeconds, parseStartEndDateFromEvent, parseStartEndTimeFromEvent } from "./utils";interface CalendarViewData {@@ -676,6 +676,9 @@ function useEventDisplayCustomization(parentNote: FNote, componentId: string | u* v7 names its elements with hashed classes, so there is no `.fc-event-title` left to find. The* theme hands out the very classes its time and title would have worn, so what is drawn here is* Forma's chip with an icon in it rather than something of ours standing in for one.+ *+ * The title comes from buildOccurrenceTitle() rather than from the event, so a repeating event+ * can title each of its occurrences differently.*/const eventContent = useCallback((e: EventDisplayInfo) => {const { iconClass, promotedAttributes } = e.event.extendedProps;@@ -685,7 +688,7 @@ function useEventDisplayCustomization(parentNote: FNote, componentId: string | u{e.timeText && <div className={e.timeClass}>{e.timeText}</div>}<div className={e.titleClass}>{iconClass && <span className={`calendar-event-icon ${iconClass}`} />}- {e.event.title}+ {buildOccurrenceTitle(e.event)}</div>{!!promotedAttributes?.length && roomForAttributes(e) && (<div className="calendar-event-attributes">diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Calendar.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Calendar.htmlindex 1349f80a01..8de8c48402 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Calendar.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Calendar.html@@ -279,6 +279,13 @@ class="table">than the title, can either a label or a relation (without the <code>#</code> or <code>~</code> symbol).See <em>Use-cases</em> for more information.</td></tr>+ <tr>+ <td><code>#calendar:titleTemplate</code>+ </td>+ <td>Changes the title an event is displayed with on the calendar, filled in+ again for every occurrence of a repeating event. See <em>Use-cases</em> for+ displaying an age on a birthday.</td>+ </tr><tr><td><code>#calendar:displayedAttributes</code></td>@@ -550,4 +557,56 @@ class="table">target note (e.g. “John Smith”) which will try to render an attribute ofit. Note that it's not possible to use a relation here as well for safetyreasons (an accidental recursion of attributes could cause the application- to loop infinitely).</p><pre><code class="language-text-x-trilium-auto">#calendar:title="shortName" #shortName="John S."</code></pre>\ No newline at end of file+ to loop infinitely).</p><pre><code class="language-text-x-trilium-auto">#calendar:title="shortName" #shortName="John S."</code></pre>+<h3>Displaying an age on a recurring event</h3>+<p>A birthday or an anniversary repeats every year, and what is interesting+ about each occurrence is the number of years it marks. <code>#calendar:titleTemplate</code> sets+ the title an event is displayed with, and is filled in again for every occurrence+ the recurrence rule produces:</p><pre><code class="language-text-x-trilium-auto">#startDate=1990-05-12 #recurrence="FREQ=YEARLY" #calendar:titleTemplate="${title} (${age})"</code></pre>+<p>The event is then displayed as “John Smith (35)” in 2025, “John+ Smith (36)” in 2026, and so on. Only the calendar is affected; the+ note keeps its own title.</p>+<p>The following values can be used in the template:</p>+<figure+class="table">+ <table>+ <thead>+ <tr>+ <th>Value</th>+ <th>Description</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td><code>${title}</code>+ </td>+ <td>The title the event would otherwise be displayed with: the note title,+ or the attribute <code>#calendar:title</code> points to.</td>+ </tr>+ <tr>+ <td><code>${age}</code>+ </td>+ <td>The whole years between <code>#startDate</code> and the occurrence being+ displayed. It is <code>0</code> on the first occurrence.</td>+ </tr>+ <tr>+ <td><code>${date}</code>+ </td>+ <td>The date of the occurrence being displayed, as a <a href="https://day.js.org/docs/en/display/format">day.js</a> object.+ For example, <code>${date.format('YYYY')}</code>.</td>+ </tr>+ <tr>+ <td><code>${startDate}</code>+ </td>+ <td>The date the event starts on, in the same form. For example, <code>${startDate.format('YYYY')}</code>.</td>+ </tr>+ </tbody>+ </table>+</figure>+<p>To use the same template for every event of a calendar, make the label+ inheritable on the Collection note:</p><pre><code class="language-text-x-trilium-auto">#calendar:titleTemplate(inheritable)="${title} (${age})"</code></pre>+<aside class="admonition note">+ <p>A template that cannot be read — an unknown value, or an expression+ other than a value and the <code>format</code> call shown above — leaves+ the event with its plain title and reports the reason in the browser console.</p>+</aside>diff --git a/docs/User Guide/User Guide/Collections/Calendar.md b/docs/User Guide/User Guide/Collections/Calendar.mdindex 981c8c198e..740f92f07b 100644--- a/docs/User Guide/User Guide/Collections/Calendar.md+++ b/docs/User Guide/User Guide/Collections/Calendar.md@@ -151,6 +151,7 @@ For each note of the calendar, the following attributes can be used:| `#calendar:color` | **❌️ Removed since v0.100.0. Use** `#color` **instead.** <br> <br>Similar to `#color`, but applies the color only for the event in the calendar and not for other places such as the note tree. || `#iconClass` | If present, the icon of the note will be displayed to the left of the event title. || `#calendar:title` | Changes the title of an event to point to an attribute of the note other than the title, can either a label or a relation (without the `#` or `~` symbol). See _Use-cases_ for more information. |+| `#calendar:titleTemplate` | Changes the title an event is displayed with on the calendar, filled in again for every occurrence of a repeating event. See _Use-cases_ for displaying an age on a birthday. || `#calendar:displayedAttributes` | Allows displaying the value of one or more attributes in the calendar like this: <br> <br> <br> <br>`#weight="70" #Mood="Good" #calendar:displayedAttributes="weight,Mood"` <br> <br>It can also be used with relations, case in which it will display the title of the target note: <br> <br>`~assignee=@My assignee #calendar:displayedAttributes="assignee"` || `#calendar:startDate` | Allows using a different label to represent the start date, other than `startDate` (e.g. `expiryDate`). The label name **must not be** prefixed with `#`. If the label is not defined for a note, the default will be used instead. || `#calendar:endDate` | Similar to `#calendar:startDate`, allows changing the attribute which is being used to read the end date. |@@ -291,4 +292,32 @@ Moreover, if there are more relations of the same name, they will be displayed a```#calendar:title="shortName" #shortName="John S."-```\ No newline at end of file+```++### Displaying an age on a recurring event++A birthday or an anniversary repeats every year, and what is interesting about each occurrence is the number of years it marks. `#calendar:titleTemplate` sets the title an event is displayed with, and is filled in again for every occurrence the recurrence rule produces:++```+#startDate=1990-05-12 #recurrence="FREQ=YEARLY" #calendar:titleTemplate="${title} (${age})"+```++The event is then displayed as “John Smith (35)” in 2025, “John Smith (36)” in 2026, and so on. Only the calendar is affected; the note keeps its own title.++The following values can be used in the template:++| Value | Description |+| --- | --- |+| `${title}` | The title the event would otherwise be displayed with: the note title, or the attribute `#calendar:title` points to. |+| `${age}` | The whole years between `#startDate` and the occurrence being displayed. It is `0` on the first occurrence. |+| `${date}` | The date of the occurrence being displayed, as a [day.js](https://day.js.org/docs/en/display/format) object. For example, `${date.format('YYYY')}`. |+| `${startDate}` | The date the event starts on, in the same form. For example, `${startDate.format('YYYY')}`. |++To use the same template for every event of a calendar, make the label inheritable on the Collection note:++```+#calendar:titleTemplate(inheritable)="${title} (${age})"+```++> [!NOTE]+> A template that cannot be read — an unknown value, or an expression other than a value and the `format` call shown above — leaves the event with its plain title and reports the reason in the browser console.diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.tsindex b81b42c3a7..4eaf474484 100644--- a/packages/commons/src/lib/builtin_attributes.ts+++ b/packages/commons/src/lib/builtin_attributes.ts@@ -287,6 +287,7 @@ const BUILTIN_ATTRIBUTES = [{ type: "label", name: "calendar:slotDuration", valueType: "text", hasUserValue: true },{ type: "label", name: "calendar:slotLabelInterval", valueType: "text", hasUserValue: true },{ type: "label", name: "calendar:title", valueType: "text", hasUserValue: true },+ { type: "label", name: "calendar:titleTemplate", valueType: "text", hasUserValue: true },{ type: "label", name: "calendar:displayedAttributes", valueType: "text", hasUserValue: true },// Each names the label an event reads a given field from, overriding the default listed after it.{ type: "label", name: "calendar:startDate", valueType: "text", hasUserValue: true },