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): decide a new event in a ghost, and only then make it
Elian Doranc38bf6c7b7fe
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 3a4d8fc64c..149def5669 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3195,6 +3195,9 @@"event_color": "Event color","remove_from_calendar": "Remove from calendar","remove_from_calendar_confirmation": "Are you sure you want to remove the event \"{{title}}\" from the calendar?",+ "new_event": "New event",+ "draft_title_placeholder": "Add a title",+ "create_event": "Create","time_slots": "Time slots","slot_duration": "Duration","slot_label_interval": "Label interval",diff --git a/apps/client/src/widgets/EmbeddedNotePane.tsx b/apps/client/src/widgets/EmbeddedNotePane.tsxindex a061166e5b..cc78b7fdc2 100644--- a/apps/client/src/widgets/EmbeddedNotePane.tsx+++ b/apps/client/src/widgets/EmbeddedNotePane.tsx@@ -1,7 +1,7 @@import "./EmbeddedNotePane.css";import { ComponentChildren } from "preact";-import { useContext, useEffect, useState } from "preact/hooks";+import { useContext, useEffect, useRef, useState } from "preact/hooks";import appContext from "../components/app_context";import Component from "../components/component";@@ -13,6 +13,7 @@ import { t } from "../services/i18n";import ActionButton from "./react/ActionButton";import Dropdown from "./react/Dropdown";import { FormListItem } from "./react/FormList";+import { useNoteContext } from "./react/hooks";import { NoteContextContext, ParentComponent } from "./react/react_utils";/*@@ -112,6 +113,34 @@ export function EmbeddedNoteScope({ component, noteContext, children }: {);}+/**+ * Puts the caret in the title with the whole of the stock name selected — how a pane opens on a+ * note its host has just created, whose name is the one thing it still lacks. Rendered inside the+ * pane's {@link EmbeddedNoteScope}, and only while the host says the note is new.+ *+ * A component rather than a call after `setNote`, because only rendering says when there is an+ * input to focus: the title widget grows one as the switch's announcement works through it, over+ * more than one render, and a dispatch fired after any fixed delay is a bet on how many. This+ * hears the announcement the same way the title widget does, so by the time its effect runs, the+ * commit that mounted the input is done. The widget matches the event on the pane's ntxId, as it+ * matches the one note_create raises for a note created anywhere else.+ */+export function SelectTitleOnFirstOpen() {+ const { note, ntxId } = useNoteContext();+ const parentComponent = useContext(ParentComponent);+ // Once per opening: the note being edited re-announces itself (a rename saving, say), and the+ // caret must not jump back to the title mid-thought.+ const done = useRef(false);++ useEffect(() => {+ if (!note || done.current || !parentComponent) return;+ done.current = true;+ void parentComponent.handleEventInChildren("focusAndSelectTitle", { isNewNote: true, ntxId });+ }, [ note?.noteId, parentComponent ]);++ return null;+}+/*** The row of actions at the head of the pane: the ways of opening the note, then whatever the host* offers to change about it. Named by tooltips rather than labels, as every other row of actions indiff --git a/apps/client/src/widgets/collections/calendar/DetailDock.css b/apps/client/src/widgets/collections/calendar/DetailDock.cssindex ed16a7df27..0728f02339 100644--- a/apps/client/src/widgets/collections/calendar/DetailDock.css+++ b/apps/client/src/widgets/collections/calendar/DetailDock.css@@ -50,5 +50,36 @@min-height: 0;overflow-y: auto;padding: 10px;+ /* The scrollbar's room is kept whether or not it shows, so the fields hold one width+ across events instead of narrowing by its thickness when a longer note brings it. */+ scrollbar-gutter: stable;+ }++ /* The ghost face (see DraftForm): a heading standing where the note's title row will, and the+ little there is to say laid down the same column the note's widgets will use. */+ .calendar-detail-dock-draft-heading {+ flex: 1;+ min-width: 0;+ padding: 6px 0;+ font-weight: 600;+ }++ .calendar-detail-dock-draft-body {+ display: flex;+ flex-direction: column;+ gap: 12px;+ }++ .calendar-detail-dock-draft-when {+ display: flex;+ align-items: center;+ gap: 6px;+ color: var(--muted-text-color);+ font-size: 0.9em;+ }++ .calendar-detail-dock-draft-actions {+ display: flex;+ justify-content: flex-end;}}diff --git a/apps/client/src/widgets/collections/calendar/DetailDock.tsx b/apps/client/src/widgets/collections/calendar/DetailDock.tsxindex 5649406201..dade9e24e9 100644--- a/apps/client/src/widgets/collections/calendar/DetailDock.tsx+++ b/apps/client/src/widgets/collections/calendar/DetailDock.tsx@@ -10,6 +10,8 @@ import TitleRow from "../../layout/TitleRow";import NoteDetail from "../../NoteDetail";import PromotedAttributes from "../../PromotedAttributes";import ActionButton from "../../react/ActionButton";+import Button from "../../react/Button";+import FormTextBox from "../../react/FormTextBox";import { useLegacyComponentElement, useNote } from "../../react/hooks";import { removeFromCalendar } from "./api";import EventDatesEditor from "./EventDatesEditor";@@ -23,38 +25,82 @@ import RecurrenceEditor from "./RecurrenceEditor";*/const EVENT_LABELS = [ "startDate", "endDate", "startTime", "endTime", "recurrence" ];+/**+ * 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 {@link DraftForm}), so a+ * ghost dismissed costs nothing — no note to clean up, no tombstone in the sync history.+ */+export interface EventDraft {+ startDate: string;+ endDate?: string | null;+ startTime?: string | null;+ endTime?: string | null;+}++/**+ * Which event the dock stands for, and why it came to be selected: the note of a chip clicked, or+ * a range just dragged out whose note is yet to be (see {@link EventDraft}).+ *+ * Owned by the calendar view rather than by the dock, because a click on a chip is not the only+ * way in, and state the dock kept to itself could not be set from the code that hands drafts over.+ */+export type DockSelection =+ | { noteId: string }+ | { draft: EventDraft };+/*** A pane docked at the trailing edge of the calendar, holding the note of the selected event — the- * calendar reflowing beside it as it comes and goes.+ * calendar reflowing beside it as it comes and goes — or, for a draft, the ghost form the event is+ * decided in (see {@link DraftForm}).*/-export default function DetailDock({ noteId, parentNote, isEditable, onClose }: {- /** The note of the selected event, or `null` for a dock that is closed. */- noteId: string | null;+export default function DetailDock({ selection, parentNote, isEditable, onCommitDraft, onClose }: {+ /** The event the dock stands for, or `null` for a dock that is closed. See {@link DockSelection}. */+ selection: DockSelection | null;/** The calendar's own note, which is how the tree is told what the calendar holds a note by. */parentNote: FNote;/** The calendar may not be edited, which leaves the dock the ways of opening a note and no* more — a calendar root's day notes are not events to be recoloured or taken off it. */isEditable: boolean;+ /** Asks for the standing draft to become a note, under the given title — or, given a blank+ * one, under whatever name the calendar's own titleTemplate writes. */+ onCommitDraft(title: string): void;onClose(): void;}) {- const note = useNote(noteId ?? undefined);+ const draft = selection && "draft" in selection ? selection.draft : null;+ const note = useNote(selection && "noteId" in selection ? selection.noteId : undefined);// Held through the closing slide, so the dock empties only once it is out of sight.const [ shownNote, setShownNote ] = useState<FNote>();- const open = !!note;+ const [ shownDraft, setShownDraft ] = useState<EventDraft>();+ const open = !!note || !!draft;+ // The note keeps the pane until its closing has been announced (the effect below), so the+ // editors are still mounted when the announcement is raised — whether the pane is sliding+ // shut or a draft is taking it over.const contentNote = note ?? shownNote;+ const contentDraft = draft ?? (open ? undefined : shownDraft);const { noteContext, component: dockComponent } = useEmbeddedNoteContext(contentNote, DOCK_NTX_ID);useEffect(() => {if (note) setShownNote(note);}, [ note ]);- // Closing announces the note context's removal, which is what the editors save on — the content- // is still mounted through the slide, so the event still finds them.useEffect(() => {- if (!open && shownNote) {- void announceEmbeddedNoteClosing(dockComponent, DOCK_NTX_ID);+ if (draft) {+ setShownDraft(draft);+ } else if (note) {+ // Committed into the note the dock now holds, or moved on from: the form goes at once.+ setShownDraft(undefined);}- }, [ open ]);+ }, [ draft, note ]);++ // The editors save through the note context's removal announcement, raised while they are+ // still mounted: a closing dock keeps them up through the slide, and a draft taking the pane+ // over lets them go only here, once the announcement is out.+ useEffect(() => {+ if (note || !shownNote) return;++ void announceEmbeddedNoteClosing(dockComponent, DOCK_NTX_ID);+ if (draft) setShownNote(undefined);+ }, [ note, draft, shownNote, dockComponent ]);useEffect(() => {if (!open) return;@@ -70,14 +116,19 @@ export default function DetailDock({ noteId, parentNote, isEditable, onClose }:<divclassName={clsx("calendar-detail-dock", open && "open")}onTransitionEnd={(e) => {- if (!open && e.propertyName === "width") setShownNote(undefined);+ if (!open && e.propertyName === "width") {+ setShownNote(undefined);+ setShownDraft(undefined);+ }}}>- {contentNote && (+ {contentNote ? (<EmbeddedNoteScope component={dockComponent} noteContext={noteContext}><DockContent note={contentNote} parentNote={parentNote} isEditable={isEditable} onClose={onClose} /></EmbeddedNoteScope>- )}+ ) : contentDraft ? (+ <DraftForm draft={contentDraft} onCommit={onCommitDraft} onCancel={onClose} />+ ) : null}</div>);}@@ -154,3 +205,95 @@ function DockContent({ note, parentNote, isEditable, onClose }: {</div>);}++/**+ * The dock's ghost face: the form an event is decided in before its note exists. It asks for the+ * one thing the drag did not say — the name — and writes out the one thing it did; everything else+ * an event can hold waits for the note, one commit away. Dismissed — Escape, the close button, a+ * click that selects something else — the draft simply evaporates: nothing was created.+ *+ * Committing with the title blank is allowed and meaningful: the note is then named by the+ * calendar's own `#titleTemplate` where one is set (see getNewNoteTitle in trilium-core), which+ * the old title prompt used to override with whatever stood in its box.+ */+function DraftForm({ draft, onCommit, onCancel }: {+ draft: EventDraft;+ onCommit(title: string): void;+ onCancel(): void;+}) {+ const [ title, setTitle ] = useState("");+ // 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.+ const [ committing, setCommitting ] = useState(false);++ const commit = () => {+ if (committing) return;+ setCommitting(true);+ onCommit(title);+ };++ return (+ <div className="calendar-detail-dock-inner calendar-detail-dock-draft">+ <div className="calendar-detail-dock-header">+ <span className="calendar-detail-dock-draft-heading">{t("calendar_view.new_event")}</span>+ <ActionButton+ className="calendar-detail-dock-close"+ icon="bx bx-x"+ text={t("calendar.close_details")}+ onClick={onCancel}+ />+ </div>++ <div className="calendar-detail-dock-body calendar-detail-dock-draft-body">+ <FormTextBox+ autoFocus+ currentValue={title}+ placeholder={t("calendar_view.draft_title_placeholder")}+ onChange={setTitle}+ onKeyDown={(e) => {+ if (e.key === "Enter") commit();+ }}+ />++ <div className="calendar-detail-dock-draft-when">+ <span className="bx bx-calendar" />+ {describeDraft(draft)}+ </div>++ <div className="calendar-detail-dock-draft-actions">+ <Button+ kind="primary"+ text={t("calendar_view.create_event")}+ disabled={committing}+ onClick={commit}+ />+ </div>+ </div>+ </div>+ );+}++/**+ * When the draft happens, written out for the form: the one thing the drag already decided.+ * Decorative and short-lived — the note's real date fields take over the moment the draft is+ * committed — so the browser's own formatter is enough.+ */+function describeDraft({ startDate, endDate, startTime, endTime }: EventDraft) {+ // Taken apart by hand: `new Date("2026-08-05")` reads as UTC midnight, which is the evening+ // before in half the world's timezones.+ const date = (iso: string) => {+ const [ year, month, day ] = iso.split("-").map(Number);+ return new Date(year, month - 1, day)+ .toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short", year: "numeric" });+ };++ const spansDays = !!endDate && endDate !== startDate;++ if (startTime) {+ return spansDays+ ? `${date(startDate)}, ${startTime} – ${date(endDate ?? startDate)}, ${endTime ?? ""}`+ : `${date(startDate)}, ${startTime}${endTime ? ` – ${endTime}` : ""}`;+ }++ return spansDays ? `${date(startDate)} – ${date(endDate ?? startDate)}` : date(startDate);+}diff --git a/apps/client/src/widgets/collections/calendar/api.ts b/apps/client/src/widgets/collections/calendar/api.tsindex ac602c17d7..1529c2a95d 100644--- a/apps/client/src/widgets/collections/calendar/api.ts+++ b/apps/client/src/widgets/collections/calendar/api.ts@@ -8,7 +8,9 @@ import note_create from "../../../services/note_create";import { deleteNoteOrBranch } from "../../../services/note_deletion";interface NewEventOpts {- title: string;+ /** Left out, the note is named the way any new child of the calendar is — by the calendar's+ * `#titleTemplate` where one is set (see getNewNoteTitle in trilium-core). */+ title?: string;startDate: string;endDate?: string | null;startTime?: string | null;@@ -53,8 +55,8 @@ export async function newEvent(parentNote: FNote, { title, startDate, endDate, s});}- // Create the note.- await note_create.createNote(parentNote.noteId, {+ // Create the note, and hand it back for the detail dock to open on.+ const { note } = await note_create.createNote(parentNote.noteId, {title,isProtected: parentNote.isProtected,content: "",@@ -62,6 +64,8 @@ export async function newEvent(parentNote: FNote, { title, startDate, endDate, sattributes,activate: false}, componentId);++ return note;}/**diff --git a/apps/client/src/widgets/collections/calendar/index.tsx b/apps/client/src/widgets/collections/calendar/index.tsxindex 999fe9440b..145bdf1438 100644--- a/apps/client/src/widgets/collections/calendar/index.tsx+++ b/apps/client/src/widgets/collections/calendar/index.tsx@@ -24,7 +24,7 @@ import { ParentComponent } from "../../react/react_utils";import { ViewModeProps } from "../interface";import { changeEvent, newEvent } from "./api";import Calendar from "./calendar";-import DetailDock from "./DetailDock";+import DetailDock, { DockSelection, EventDraft } from "./DetailDock";import { openCalendarContextMenu } from "./context_menu";import { buildEvents, buildEventsForCalendar } from "./event_builder";import { formatDateToLocalISO, isValidDuration, parseStartEndDateFromEvent, parseStartEndTimeFromEvent } from "./utils";@@ -114,8 +114,9 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarViconst containerRef = useRef<HTMLDivElement>(null);const calendarMainRef = useRef<HTMLDivElement>(null);const calendarRef = useRef<FullCalendar>(null);- // The note of the selected event, which the dock at the trailing edge stands for.- const [ selectedNoteId, setSelectedNoteId ] = useState<string | null>(null);+ // The event the dock at the trailing edge stands for — a chip clicked, or a note just created+ // by drag-selecting a range (see DockSelection).+ const [ selection, setSelection ] = useState<DockSelection | null>(null);const [ calendarRoot ] = useNoteLabelBoolean(note, "calendarRoot");const [ workspaceCalendarRoot ] = useNoteLabelBoolean(note, "workspaceCalendarRoot");@@ -144,15 +145,41 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarViconst locale = useLocale();const { eventDidMount } = useEventDisplayCustomization(note, parentComponent?.componentId);- const editingProps = useEditing(note, isEditable, isCalendarRoot, parentComponent?.componentId);+ const editingProps = useEditing(note, isEditable, isCalendarRoot, parentComponent?.componentId,+ (draft) => setSelection({ draft }));++ // Turns the standing ghost into the note: created only now, at the commit, and — where the+ // reader typed nothing — named by the calendar's own titleTemplate, the very thing the old+ // title prompt used to override.+ const commitDraft = useCallback(async (title: string) => {+ if (!selection || !("draft" in selection)) return;++ const created = await newEvent(note, {+ title: title.trim() || undefined,+ ...selection.draft,+ componentId: parentComponent?.componentId+ });+ if (created) {+ setSelection({ noteId: created.noteId });+ }+ }, [ selection, note, parentComponent?.componentId ]);++ // The dragged range keeps its shading for as long as the ghost stands for it — unselectAuto is+ // off, so pressing into the dock's own form does not clear it — and is let go the moment the+ // selection is anything else: committed into a note, moved on from, or gone.+ useEffect(() => {+ if (!selection || !("draft" in selection)) {+ calendarRef.current?.unselect();+ }+ }, [ selection ]);// An event taken off the calendar takes the dock with it. Not in calendar-root mode, whose// events (day notes and their children) are not in the collection's noteIds at all.useEffect(() => {- if (!isCalendarRoot && selectedNoteId && !noteIds.includes(selectedNoteId)) {- setSelectedNoteId(null);+ if (!isCalendarRoot && selection && "noteId" in selection && !noteIds.includes(selection.noteId)) {+ setSelection(null);}- }, [ isCalendarRoot, selectedNoteId, noteIds ]);+ }, [ isCalendarRoot, selection, noteIds ]);// A click on an event opens it into the dock instead of navigating to the popup the event's// `url` names. Not on mobile, where a tap is already spoken for (see eventDidMount) and the@@ -167,7 +194,7 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarVie.jsEvent.stopPropagation();const noteId = e.event.extendedProps.noteId;if (noteId) {- setSelectedNoteId(noteId);+ setSelection({ noteId });}}, []);@@ -219,8 +246,9 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarViinitialDate={initialDate || undefined}locale={locale}{...editingProps}+ unselectAuto={false}eventClick={onEventClick}- eventClassNames={(arg) => arg.event.extendedProps.noteId === selectedNoteId ? [ "calendar-event-in-dock" ] : []}+ eventClassNames={(arg) => selection && "noteId" in selection && arg.event.extendedProps.noteId === selection.noteId ? [ "calendar-event-in-dock" ] : []}eventDidMount={eventDidMount}viewDidMount={({ view }) => {if (initialView.current !== view.type) {@@ -231,10 +259,11 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarVi/></div><DetailDock- noteId={selectedNoteId}+ selection={selection}parentNote={note}isEditable={isEditable}- onClose={() => setSelectedNoteId(null)}+ onCommitDraft={(title) => void commitDraft(title)}+ onClose={() => setSelection(null)}/></div></div>@@ -371,20 +400,31 @@ function useLocale() {return calendarLocale;}-function useEditing(note: FNote, isEditable: boolean, isCalendarRoot: boolean, componentId: string | undefined) {+function useEditing(note: FNote, isEditable: boolean, isCalendarRoot: boolean, componentId: string | undefined,+ onDraft: (draft: EventDraft) => void) {const onCalendarSelection = useCallback(async (e: DateSelectArg) => {const { startDate, endDate } = parseStartEndDateFromEvent(e);if (!startDate) return;const { startTime, endTime } = parseStartEndTimeFromEvent(e);- // Ask for the title- const title = await dialog.prompt({ message: t("relation_map.enter_title_of_new_note"), defaultValue: t("relation_map.default_new_note_title") });- if (!title?.trim()) {+ // On a phone the dock does not open (see the event click), so the title is still asked for+ // up front, in the dialog this flow always led with. Unselected by hand either way round:+ // unselectAuto is off for the ghost's sake, so nothing else clears the drag's shading.+ if (isMobile()) {+ const title = await dialog.prompt({ message: t("relation_map.enter_title_of_new_note"), defaultValue: t("relation_map.default_new_note_title") });+ if (title?.trim()) {+ await newEvent(note, { title, startDate, endDate, startTime, endTime, componentId });+ }+ e.view.calendar.unselect();return;}- newEvent(note, { title, startDate, endDate, startTime, endTime, componentId });- }, [ note, componentId ]);+ // Nothing is created yet: the range is handed over as a draft for the dock's ghost form,+ // and a note is made only when the draft is committed (see commitDraft) — a stray drag+ // dismissed costs nothing. The range keeps its shading meanwhile, standing on the grid for+ // the event to be; the view lets it go when the draft resolves.+ onDraft({ startDate, endDate, startTime, endTime });+ }, [ note, componentId, onDraft ]);const onEventChange = useCallback(async (e: EventChangeArg) => {// Only process actual date/time changes, not other property changes (e.g., title via setProp).diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsxindex 5406ebe87a..e6143189b6 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx@@ -8,14 +8,13 @@ import FNote from "../../../entities/fnote";import { copyTextWithToast } from "../../../services/clipboard_ext";import { t } from "../../../services/i18n";import link from "../../../services/link";-import { announceEmbeddedNoteClosing, EmbeddedNoteActions, EmbeddedNoteScope, NoteColorAction, OpenNoteActions, useEmbeddedNoteContext } from "../../EmbeddedNotePane";+import { announceEmbeddedNoteClosing, EmbeddedNoteActions, EmbeddedNoteScope, NoteColorAction, OpenNoteActions, SelectTitleOnFirstOpen, useEmbeddedNoteContext } from "../../EmbeddedNotePane";import TitleRow from "../../layout/TitleRow";import NoteDetail from "../../NoteDetail";import PromotedAttributes from "../../PromotedAttributes";import ActionButton from "../../react/ActionButton";-import { useLegacyComponentElement, useNoteColorClass, useNoteContext, useNoteLabel, useStaticTooltip } from "../../react/hooks";+import { useLegacyComponentElement, useNoteColorClass, useNoteLabel, useStaticTooltip } from "../../react/hooks";import OverlayPanel, { OverlayPanelBody } from "../../react/OverlayPanel";-import { ParentComponent } from "../../react/react_utils";import { removeFromMap } from "./api";import { GPX_MIME, trackHitLayers, trackSourceId } from "./GpxTrack";import { ParentMap } from "./map";@@ -236,33 +235,6 @@ export default function DetailPane({ notes, parentNote, placing, isReadOnly, sel);}-/**- * Puts the caret in the title with the whole of the stock name selected — how the pane opens on a- * note the map has just created, whose name is the one thing it still lacks (see PaneSelection).- *- * A component rather than a call after `setNote`, because only rendering says when there is an- * input to focus: the title widget grows one as the switch's announcement works through it, over- * more than one render, and a dispatch fired after any fixed delay is a bet on how many. This- * hears the announcement the same way the title widget does, so by the time its effect runs, the- * commit that mounted the input is done. The widget matches the event on the pane's ntxId, as it- * matches the one note_create raises for a note created anywhere else.- */-function SelectTitleOnFirstOpen() {- const { note } = useNoteContext();- const parentComponent = useContext(ParentComponent);- // Once per opening: the note being edited re-announces itself (a rename saving, say), and the- // caret must not jump back to the title mid-thought.- const done = useRef(false);-- useEffect(() => {- if (!note || done.current || !parentComponent) return;- done.current = true;- void parentComponent.handleEventInChildren("focusAndSelectTitle", { isNewNote: true, ntxId: PANE_NTX_ID });- }, [ note?.noteId, parentComponent ]);-- return null;-}-/** Must agree with `--geo-detail-pane-width` in DetailPane.css. */const PANE_WIDTH = 380;