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): keep an event's duration and show the day it ends on
Elian Doran2b782cbfe525
diff --git a/apps/client/src/widgets/collections/calendar/EventDatesEditor.spec.tsx b/apps/client/src/widgets/collections/calendar/EventDatesEditor.spec.tsxindex 0b0a5bb115..32213e5fd7 100644--- a/apps/client/src/widgets/collections/calendar/EventDatesEditor.spec.tsx+++ b/apps/client/src/widgets/collections/calendar/EventDatesEditor.spec.tsx@@ -93,6 +93,33 @@ describe("EventDatesEditor", () => {expect(dateInputs()).toHaveLength(2);});+ it("shows the day an event actually ends on, and writes it once an edit is made", () => {+ // Stored as ending at 08:00 on its own start day, which the calendar draws as the next day.+ const note = buildNote({+ title: "Shift", "#startDate": "2026-10-16", "#endDate": "2026-10-16",+ "#startTime": "09:00", "#endTime": "08:00"+ });+ mount(note);++ expect([ ...dateInputs() ].map((input) => input.value)).toEqual([ "2026-10-16", "2026-10-17" ]);+ expect(setLabel).not.toHaveBeenCalled();++ commitValue(timeInputs()[1], "07:00");+ expect(setLabel).toHaveBeenCalledWith(note.noteId, "endTime", "07:00");+ expect(setLabel).toHaveBeenCalledWith(note.noteId, "endDate", "2026-10-17");+ });++ it("moves the end time with the start time, keeping the duration", () => {+ const note = buildNote({ title: "Meeting", "#startDate": "2026-06-05", "#startTime": "13:00", "#endTime": "14:30" });+ mount(note);++ commitValue(timeInputs()[0], "16:00");++ expect(setLabel).toHaveBeenCalledWith(note.noteId, "startTime", "16:00");+ expect(setLabel).toHaveBeenCalledWith(note.noteId, "endTime", "17:30");+ expect(setLabel).not.toHaveBeenCalledWith(note.noteId, "endDate", expect.anything());+ });+it("shows and edits the end date of a timed event that spans several days", () => {const note = buildNote({title: "Night shift", "#startDate": "2026-06-05", "#endDate": "2026-06-06",diff --git a/apps/client/src/widgets/collections/calendar/EventDatesEditor.tsx b/apps/client/src/widgets/collections/calendar/EventDatesEditor.tsxindex affdd98c6d..e4c4c66cc3 100644--- a/apps/client/src/widgets/collections/calendar/EventDatesEditor.tsx+++ b/apps/client/src/widgets/collections/calendar/EventDatesEditor.tsx@@ -6,7 +6,7 @@ import { t } from "../../../services/i18n";import LabelValueInput from "../../attribute_widgets/label_value_input";import { EventDuration, EventRow, EventTimeRow } from "./EventField";import { useEventLabel } from "./hooks";-import { EventDraft, withAllDay } from "./selection";+import { EventDraft, normalizeEventDates, withAllDay, withStart } from "./selection";/*** Edits when an existing event happens, through the date and time labels the calendar draws it by@@ -66,7 +66,10 @@ export function EventDatesFields({ value, allDay, onChange }: {allDay: boolean;onChange(next: EventDraft): void;}) {- const { startDate, endDate, startTime, endTime } = value;+ // Shown and handed on with the end date it actually ends on, which an edit then writes back.+ const event = normalizeEventDates(value);+ const { startDate, endDate, startTime, endTime } = event;+ const change = (next: EventDraft) => onChange(normalizeEventDates(next));return (<>@@ -77,7 +80,7 @@ export function EventDatesFields({ value, allDay, onChange }: {commitOn="blur"// Never emptied: without a start date the note stops being an event at all.// The field snaps back.- onCommit={(date) => date && onChange({ ...value, startDate: date })}+ onCommit={(date) => date && change(withStart(event, { startDate: date }))}inputProps={{ className: "form-control", "aria-label": t("calendar.dates.start_date") }}/><span className="calendar-event-row-separator" aria-hidden="true">–</span>@@ -87,15 +90,15 @@ export function EventDatesFields({ value, allDay, onChange }: {commitOn="blur"// Emptied, the event ends on the day it starts: the label goes rather than// staying blank, which is how the builder reads a single-day event.- onCommit={(date) => onChange({ ...value, endDate: date || null })}+ onCommit={(date) => change({ ...event, endDate: date || null })}inputProps={{ className: "form-control", "aria-label": t("calendar.dates.end_date") }}/></EventRow><EventTimeRowhasTime={!allDay}- onAdd={() => onChange(withAllDay(value, false))}- onRemove={() => onChange(withAllDay(value, true))}+ onAdd={() => change(withAllDay(event, false))}+ onRemove={() => change(withAllDay(event, true))}><LabelValueInputlabelType="time"@@ -103,7 +106,7 @@ export function EventDatesFields({ value, allDay, onChange }: {commitOn="blur"// Never emptied either: a timed event without a start time is the all-day// shape, and the button beside the hours is the way to say that.- onCommit={(time) => time && onChange({ ...value, startTime: time })}+ onCommit={(time) => time && change(withStart(event, { startTime: time }))}inputProps={{ className: "form-control", "aria-label": t("calendar.dates.start_time") }}/><span className="calendar-event-row-separator" aria-hidden="true">–</span>@@ -111,10 +114,10 @@ export function EventDatesFields({ value, allDay, onChange }: {labelType="time"value={endTime ?? ""}commitOn="blur"- onCommit={(time) => time && onChange({ ...value, endTime: time })}+ onCommit={(time) => time && change({ ...event, endTime: time })}inputProps={{ className: "form-control", "aria-label": t("calendar.dates.end_time") }}/>- {startDate && <EventDuration event={value} />}+ {startDate && <EventDuration event={event} />}</EventTimeRow></>);diff --git a/apps/client/src/widgets/collections/calendar/GhostPopover.spec.tsx b/apps/client/src/widgets/collections/calendar/GhostPopover.spec.tsxindex 0c09d31c0c..c7294c3249 100644--- a/apps/client/src/widgets/collections/calendar/GhostPopover.spec.tsx+++ b/apps/client/src/widgets/collections/calendar/GhostPopover.spec.tsx@@ -158,6 +158,22 @@ describe("GhostPopover", () => {expect(onCommit).toHaveBeenCalledWith("", { startDate: "2026-06-08", endDate: "2026-06-10" });});+ it("leaves the end date empty for a slot within a single day", () => {+ // A drag within one day of the week view names that day as the end date too.+ act(() => render(+ <GhostPopover+ draft={{ startDate: "2026-06-05", endDate: "2026-06-05", startTime: "09:00", endTime: "09:30" }}+ anchor={null}+ container={container}+ onCommit={vi.fn()}+ onCancel={() => {}}+ onDismiss={() => {}}+ />,+ container));++ expect(dateInputs().map((input) => input.value)).toEqual([ "2026-06-05", "" ]);+ });+it("lets the hours be removed again, making the draft whole-day", async () => {const onCommit = vi.fn().mockResolvedValue(undefined);mount(onCommit);diff --git a/apps/client/src/widgets/collections/calendar/GhostPopover.tsx b/apps/client/src/widgets/collections/calendar/GhostPopover.tsxindex 6b571f740d..8e0e88d642 100644--- a/apps/client/src/widgets/collections/calendar/GhostPopover.tsx+++ b/apps/client/src/widgets/collections/calendar/GhostPopover.tsx@@ -10,7 +10,7 @@ import FormTextBox from "../../react/FormTextBox";import Modal from "../../react/Modal";import Popover from "../../react/Popover";import { EventDatesFields } from "./EventDatesEditor";-import { AnchorPoint, EventDraft, narrowAnchorRect } from "./selection";+import { AnchorPoint, EventDraft, narrowAnchorRect, normalizeEventDates } from "./selection";/*** The ghost: the form an event is decided in before its note exists. It asks for the name, shows@@ -50,8 +50,8 @@ export default function GhostPopover({ draft: initialDraft, anchor, container, o}) {const [ title, setTitle ] = useState("");// The range as dragged, until the user changes whether it is all-day or edits its hours.- const [ draft, setDraft ] = useState(initialDraft);- useEffect(() => setDraft(initialDraft), [ initialDraft ]);+ const [ draft, setDraft ] = useState(() => normalizeEventDates(initialDraft));+ useEffect(() => setDraft(normalizeEventDates(initialDraft)), [ initialDraft ]);const allDay = !draft.startTime;// Committing is asked for once, however many times Enter falls before the note arrives and// the form goes: each ask would make its own note.diff --git a/apps/client/src/widgets/collections/calendar/selection.spec.ts b/apps/client/src/widgets/collections/calendar/selection.spec.tsindex 2c4b19e58a..99e475fc0c 100644--- a/apps/client/src/widgets/collections/calendar/selection.spec.ts+++ b/apps/client/src/widgets/collections/calendar/selection.spec.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it } from "vitest";-import { narrowAnchorRect, withAllDay } from "./selection";+import { narrowAnchorRect, normalizeEventDates, withAllDay, withStart } from "./selection";describe("narrowAnchorRect", () => {afterEach(() => {@@ -57,3 +57,59 @@ describe("withAllDay", () => {.toEqual({ startDate: "2026-06-05", startTime: "09:00", endTime: "11:30" });});});++describe("normalizeEventDates", () => {+ it("moves the end date of a timed event to the day it actually ends on", () => {+ // 08:00 on the start day is before 09:00, so the event ends on the next day.+ expect(normalizeEventDates({ startDate: "2026-10-16", endDate: "2026-10-16", startTime: "09:00", endTime: "08:00" }))+ .toEqual({ startDate: "2026-10-16", endDate: "2026-10-17", startTime: "09:00", endTime: "08:00" });+ expect(normalizeEventDates({ startDate: "2026-10-31", startTime: "22:00", endTime: "01:00" }))+ .toEqual({ startDate: "2026-10-31", endDate: "2026-11-01", startTime: "22:00", endTime: "01:00" });+ // An end date before the start day is moved up to where the times fall after the start.+ expect(normalizeEventDates({ startDate: "2026-10-16", endDate: "2026-10-14", startTime: "09:00", endTime: "10:00" }))+ .toEqual({ startDate: "2026-10-16", endDate: null, startTime: "09:00", endTime: "10:00" });+ });++ it("empties an end date that is the start date, which is what an empty one means", () => {+ expect(normalizeEventDates({ startDate: "2026-10-16", endDate: "2026-10-16", startTime: "09:00", endTime: "10:00" }))+ .toEqual({ startDate: "2026-10-16", endDate: null, startTime: "09:00", endTime: "10:00" });+ expect(normalizeEventDates({ startDate: "2026-10-16", endDate: "2026-10-16", startTime: "09:00", endTime: "09:00" }))+ .toEqual({ startDate: "2026-10-16", endDate: null, startTime: "09:00", endTime: "09:00" });+ expect(normalizeEventDates({ startDate: "2026-10-16", endDate: "2026-10-16" }))+ .toEqual({ startDate: "2026-10-16", endDate: null });+ });++ it("lets an all-day end date before the start go, and leaves consistent events alone", () => {+ expect(normalizeEventDates({ startDate: "2026-10-16", endDate: "2026-10-12" }))+ .toEqual({ startDate: "2026-10-16", endDate: null });++ const allDaySpan = { startDate: "2026-10-16", endDate: "2026-10-18" };+ expect(normalizeEventDates(allDaySpan)).toEqual(allDaySpan);+ const timedSpan = { startDate: "2026-10-16", endDate: "2026-10-17", startTime: "22:00", endTime: "01:00" };+ expect(normalizeEventDates(timedSpan)).toEqual(timedSpan);+ const sameDay = { startDate: "2026-10-16", startTime: "09:00", endTime: "10:00" };+ expect(normalizeEventDates(sameDay)).toEqual(sameDay);+ });+});++describe("withStart", () => {+ it("moves the end of a timed event with its start time, keeping the duration", () => {+ expect(withStart({ startDate: "2026-10-16", startTime: "09:00", endTime: "10:00" }, { startTime: "14:00" }))+ .toEqual({ startDate: "2026-10-16", startTime: "14:00", endTime: "15:00" });+ // Pushed past midnight, the end moves to the next day.+ expect(withStart({ startDate: "2026-10-16", startTime: "21:00", endTime: "23:00" }, { startTime: "23:30" }))+ .toEqual({ startDate: "2026-10-16", endDate: "2026-10-17", startTime: "23:30", endTime: "01:30" });+ // Pulled back before midnight, it comes back to the start day.+ expect(withStart({ startDate: "2026-10-16", endDate: "2026-10-17", startTime: "22:00", endTime: "01:00" }, { startTime: "20:00" }))+ .toEqual({ startDate: "2026-10-16", endDate: null, startTime: "20:00", endTime: "23:00" });+ });++ it("moves the end date with the start date, keeping the span of days", () => {+ expect(withStart({ startDate: "2026-10-16", endDate: "2026-10-17", startTime: "22:00", endTime: "01:00" }, { startDate: "2026-10-30" }))+ .toEqual({ startDate: "2026-10-30", endDate: "2026-10-31", startTime: "22:00", endTime: "01:00" });+ expect(withStart({ startDate: "2026-10-16", endDate: "2026-10-18" }, { startDate: "2026-10-30" }))+ .toEqual({ startDate: "2026-10-30", endDate: "2026-11-01" });+ expect(withStart({ startDate: "2026-10-16" }, { startDate: "2026-10-30" }))+ .toEqual({ startDate: "2026-10-30" });+ });+});diff --git a/apps/client/src/widgets/collections/calendar/selection.ts b/apps/client/src/widgets/collections/calendar/selection.tsindex 0d500cf600..4df5253546 100644--- a/apps/client/src/widgets/collections/calendar/selection.ts+++ b/apps/client/src/widgets/collections/calendar/selection.ts@@ -1,3 +1,5 @@+import { getTimedDurationMinutes } from "./utils";+/*** An event still being decided on: the range the reader dragged out, standing for a note that does* not exist yet. Nothing is created until the draft is committed (see GhostPopover), so a ghost@@ -27,6 +29,63 @@ export function withAllDay(draft: EventDraft, allDay: boolean): EventDraft {return { ...draft, startTime: DEFAULT_START_TIME, endTime: draft.endTime ?? DEFAULT_END_TIME };}+/**+ * Makes the end date say the day an event actually ends on, so the date fields never contradict+ * how the calendar draws it (see buildEvent in event_builder.ts):+ *+ * - A timed event whose end falls before its start ends on the first day the end time comes after+ * the start: the start day itself, or the next day for an end time before the start time.+ * - An all-day event whose end date is before its start date lasts a single day.+ * - An end date equal to the start date is emptied, an empty end date meaning the event ends on the+ * day it starts.+ *+ * Returns the event unchanged where its end date is already right.+ */+export function normalizeEventDates(event: EventDraft): EventDraft {+ const { startDate, startTime, endTime } = event;+ let endDate = event.endDate || null;++ if (startTime && endTime) {+ // ISO dates and 24-hour times compare correctly as strings.+ if (`${endDate ?? startDate}T${endTime}` < `${startDate}T${startTime}`) {+ endDate = endTime < startTime ? addDays(startDate, 1) : startDate;+ }+ } else if (endDate && endDate < startDate) {+ endDate = null;+ }++ if (endDate === startDate) {+ endDate = null;+ }++ return endDate === (event.endDate || null) ? event : { ...event, endDate };+}++/**+ * Moves an event to a new start date or start time, keeping how long it lasts, as calendar apps do:+ * the end moves by as much as the start, across midnight where it has to. Only an edit of the end+ * itself changes the duration.+ */+export function withStart(event: EventDraft, start: { startDate?: string; startTime?: string }): EventDraft {+ const current = normalizeEventDates(event);+ const next = { ...current, ...start };+ const duration = getTimedDurationMinutes(current);++ if (duration !== null && next.startTime) {+ const [ hours, minutes ] = next.startTime.split(":").map(Number);+ const endMinute = hours * 60 + minutes + duration;+ const endOfDay = endMinute % (24 * 60);+ const endDay = Math.floor(endMinute / (24 * 60));+ // Back on the start day: an end date the event had is cleared, a missing one stays missing.+ next.endDate = endDay > 0 ? addDays(next.startDate, endDay) : (current.endDate ? null : current.endDate);+ next.endTime = `${pad(Math.floor(endOfDay / 60))}:${pad(endOfDay % 60)}`;+ } else if (current.endDate) {+ next.endDate = addDays(current.endDate, daysBetween(current.startDate, next.startDate));+ }++ return normalizeEventDates(next);+}+/** A point in viewport coordinates — where a click or a drag's end fell, anchoring a popover* beside it where nothing better can be found on the grid (see the anchor helpers). */export interface AnchorPoint {@@ -82,3 +141,18 @@ export function narrowAnchorRect(rect: DOMRect, point: AnchorPoint | null): DOMR* a window that narrow fills it, and the card is then placed by the viewport whatever anchor it is* handed. */const MAX_ANCHOR_WIDTH = 480;++/** Adds days to an ISO date, counted in calendar days so a daylight saving change cannot shift it. */+function addDays(isoDate: string, days: number) {+ const [ year, month, day ] = isoDate.split("-").map(Number);+ const date = new Date(Date.UTC(year, month - 1, day + days));+ return date.toISOString().slice(0, 10);+}++function daysBetween(from: string, to: string) {+ return (Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / (24 * 60 * 60 * 1000);+}++function pad(value: number) {+ return String(value).padStart(2, "0");+}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 51d3eb6449..3959380658 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@@ -44,8 +44,10 @@again, press the <span class="tn-icon bx bx-x"></span> button at the endof the row. Adding or removing a time keeps the dates, so an event canstart at a time on one day and end at a time on another (for example, a- night shift). If the end date is left empty, the event ends on the day- it starts, or on the next day when the end time is before the start time.</p>+ night shift). Changing the start date or time moves the end by the same+ amount, keeping the duration. An empty end date means the event ends on+ the day it starts; setting the end time before the start time moves the+ end date to the next day.</p><p>After creating the event, it will show up on the calendar. To edit thecontent of the event (including recurrence), click on it to bring it intothe popup view.</p>@@ -346,6 +348,10 @@ class="table"></p><p>The calendar displays all the child notes of the Collection that havea <code>#startDate</code>. An <code>#endDate</code> can optionally be added.</p>+<p>A text note with a start date is shown with the <span class="tn-icon bx bx-calendar-event"></span> icon+ in the note tree and elsewhere, unless it has an icon of its own (set with <code>#iconClass</code>).+ The start date is read from the label <code>#calendar:startDate</code> names,+ if any.</p><p>The start date & end date can easily be edited from the calendar collectionitself by clicking on the event. To edit the date while in the event noteitself, the following attributes can be added to the Collection note:</p><pre><code class="language-text-x-trilium-auto">#viewType=calendar #label:startDate(inheritable)="promoted,alias=Start Date,single,date"diff --git a/docs/User Guide/User Guide/Collections/Calendar.md b/docs/User Guide/User Guide/Collections/Calendar.mdindex 11434b33a9..4346575901 100644--- a/docs/User Guide/User Guide/Collections/Calendar.md+++ b/docs/User Guide/User Guide/Collections/Calendar.md@@ -28,7 +28,7 @@ In either cases, a small popup will show with a prompt for a title and the dateAt this point, the event hasn't been created yet to protect against accidental clicks. Add a title optionally and press the _Create_ button. If no title is provided, the event will follow the <a class="reference-link" href="../Advanced%20Usage/Default%20Note%20Title.md">Default Note Title</a> rules.-To give the event a time before creating it (for example, after clicking a day in the month view), press _Add time_ and set the start and end time; the duration is shown to the right of them. To make the event all-day again, press the <span class="tn-icon bx bx-x"></span> button at the end of the row. Adding or removing a time keeps the dates, so an event can start at a time on one day and end at a time on another (for example, a night shift). If the end date is left empty, the event ends on the day it starts, or on the next day when the end time is before the start time.+To give the event a time before creating it (for example, after clicking a day in the month view), press _Add time_ and set the start and end time; the duration is shown to the right of them. To make the event all-day again, press the <span class="tn-icon bx bx-x"></span> button at the end of the row. Adding or removing a time keeps the dates, so an event can start at a time on one day and end at a time on another (for example, a night shift). Changing the start date or time moves the end by the same amount, keeping the duration. An empty end date means the event ends on the day it starts; setting the end time before the start time moves the end date to the next day.After creating the event, it will show up on the calendar. To edit the content of the event (including recurrence), click on it to bring it into the popup view.@@ -167,6 +167,8 @@ For each note of the calendar, the following attributes can be used:The calendar displays all the child notes of the Collection that have a `#startDate`. An `#endDate` can optionally be added.+A text note with a start date is shown with the <span class="tn-icon bx bx-calendar-event"></span> icon in the note tree and elsewhere, unless it has an icon of its own (set with `#iconClass`). The start date is read from the label `#calendar:startDate` names, if any.+The start date & end date can easily be edited from the calendar collection itself by clicking on the event. To edit the date while in the event note itself, the following attributes can be added to the Collection note:```