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): open a clicked event into a dock beside the grid
Elian Dorand2210f602e88
diff --git a/apps/client/src/widgets/collections/calendar/DetailDock.css b/apps/client/src/widgets/collections/calendar/DetailDock.cssnew file mode 100644index 0000000000..04c42cd28d--- /dev/null+++ b/apps/client/src/widgets/collections/calendar/DetailDock.css@@ -0,0 +1,107 @@+.calendar-view .calendar-detail-dock {+ /* One fixed width for the animated shell and the inner column, so the contents keep their+ shape while the shell slides rather than reflowing at every frame of it. The percentage cap+ belongs to the shell alone: on the inner column it would resolve against the shell's own+ (already capped) width and halve the contents. On a narrow view the shell simply clips the+ trailing end of the column. */+ --calendar-dock-width: 360px;++ flex: 0 0 auto;+ width: 0;+ overflow: hidden;+ transition: width 250ms ease;++ &.open {+ width: min(var(--calendar-dock-width), 50%);+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }++ .calendar-detail-dock-inner {+ width: var(--calendar-dock-width);+ height: 100%;+ box-sizing: border-box;+ display: flex;+ flex-direction: column;+ border-inline-start: 1px solid var(--main-border-color);+ background: var(--main-background-color);+ }++ .calendar-detail-dock-header {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 4px 9px;+ border-bottom: 1px solid var(--main-border-color);++ > .title-row {+ flex: 1;+ min-width: 0;+ }+ }++ .calendar-detail-dock-body {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 10px;+ }++ /* The note fills the rest of the dock rather than ending where its content does, so that+ clicking below a short note still puts the caret in it. */+ .note-detail {+ flex: 1;+ /* Written for a note split, where the split hands it one; there is no split here. */+ max-width: none;+ min-height: 120px;+ }++ /* The note's promoted fields, one under the other: laid out for a third of the width they are+ written for (as the geo pane lays them). */+ .promoted-attributes-container {+ flex-direction: column;+ align-items: stretch;+ gap: 8px;+ margin: 0;+ /* The body of the dock is the one thing that scrolls. */+ max-height: none;+ overflow: visible;+ }++ .promoted-attribute-cell {+ margin: 0;++ > .input-group,+ > .promoted-attribute-values {+ flex: 1;+ min-width: 0;+ margin-inline-start: 8px;+ }++ input[type="text"],+ input[type="number"] {+ width: auto !important;+ }++ > label {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .tn-field {+ min-width: 0;+ padding: 0;+ }+ }++ /* An event promoting nothing would still take its share of the body's gap. */+ .promoted-attributes-widget:not(:has(.promoted-attribute-cell)) {+ display: none;+ }+}diff --git a/apps/client/src/widgets/collections/calendar/DetailDock.tsx b/apps/client/src/widgets/collections/calendar/DetailDock.tsxnew file mode 100644index 0000000000..742a755736--- /dev/null+++ b/apps/client/src/widgets/collections/calendar/DetailDock.tsx@@ -0,0 +1,150 @@+import "./DetailDock.css";++import clsx from "clsx";+import { useContext, useEffect, useRef, useState } from "preact/hooks";++import appContext from "../../../components/app_context";+import Component from "../../../components/component";+import NoteContext from "../../../components/note_context";+import FNote from "../../../entities/fnote";+import { t } from "../../../services/i18n";+import TitleRow from "../../layout/TitleRow";+import NoteDetail from "../../NoteDetail";+import PromotedAttributes from "../../PromotedAttributes";+import ActionButton from "../../react/ActionButton";+import { useLegacyComponentElement, useNote } from "../../react/hooks";+import { NoteContextContext, ParentComponent } from "../../react/react_utils";++/**+ * The dates the calendar already draws the event by, so their fields are not repeated in the dock.+ * Only the stock names for now; a calendar naming its own (`calendar:startDate`) still shows those.+ */+const EVENT_DATE_LABELS = [ "startDate", "endDate", "startTime", "endTime" ];++/**+ * 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.+ *+ * SPIKE: the note-context plumbing is lifted from the geo map's DetailPane (see usePaneNoteContext+ * there); if this lands, the shared parts should be extracted rather than kept twice.+ */+export default function DetailDock({ noteId, onClose }: {+ /** The note of the selected event, or `null` for a dock that is closed. */+ noteId: string | null;+ onClose(): void;+}) {+ const note = useNote(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 contentNote = note ?? shownNote;+ const { noteContext, dockComponent } = useDockNoteContext(contentNote);++ 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. Not waited on, as the geo+ // pane does not wait: the save is under way by the time the call returns.+ useEffect(() => {+ if (!open && shownNote) {+ void dockComponent.handleEventInChildren("beforeNoteContextRemove", { ntxIds: [ DOCK_NTX_ID ] });+ }+ }, [ open ]);++ useEffect(() => {+ if (!open) return;++ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, [ open, onClose ]);++ return (+ <div+ className={clsx("calendar-detail-dock", open && "open")}+ onTransitionEnd={(e) => {+ if (!open && e.propertyName === "width") setShownNote(undefined);+ }}+ >+ {contentNote && (+ <ParentComponent.Provider value={dockComponent}>+ <NoteContextContext.Provider value={noteContext}>+ <DockContent onClose={onClose} />+ </NoteContextContext.Provider>+ </ParentComponent.Provider>+ )}+ </div>+ );+}++/** The dock's own ntxId, as the geo pane and the quick editor have one of their own. */+const DOCK_NTX_ID = "_calendar-detail-dock";++/**+ * A note context of the dock's own, pointed at whichever event is selected, behind a component of+ * its own so the collection view around the calendar does not hear the dock's note switches and+ * rebind to them. Lifted from the geo map's usePaneNoteContext, where each choice is explained.+ */+function useDockNoteContext(note: FNote | undefined) {+ const parentComponent = useContext(ParentComponent);+ const [ noteContext ] = useState(() => new NoteContext(DOCK_NTX_ID));+ const [ dockComponent ] = useState(() => new Component());++ useEffect(() => {+ if (!parentComponent) return;++ parentComponent.child(dockComponent);+ return () => parentComponent.removeChild(dockComponent);+ }, [ parentComponent, dockComponent ]);++ useEffect(() => {+ noteContext.triggerEvent = (name, data) => dockComponent.handleEventInChildren(name, data);+ }, [ noteContext, dockComponent ]);++ useEffect(() => {+ if (!note) return;++ const notePath = note.getBestNotePathString(appContext.tabManager.getActiveContext()?.hoistedNoteId);+ void noteContext.setNote(notePath, {+ keepActiveDialog: true,+ viewScope: {+ readOnlyTemporarilyDisabled: !note.hasLabel("readOnly"),+ // The dock has a third of a note's width, which is not a toolbar's worth.+ floatingToolbar: true+ }+ });+ }, [ noteContext, note?.noteId ]);++ return { noteContext, dockComponent };+}++/** The dock's contents, reading the note out of the context the dock provides. */+function DockContent({ onClose }: { onClose(): void }) {+ // The dock stands for its component in the DOM, which is how the text editor finds its host —+ // without this it resolves the widget enclosing the calendar instead (see the geo pane).+ const innerRef = useRef<HTMLDivElement>(null);+ useLegacyComponentElement(innerRef);++ return (+ <div className="calendar-detail-dock-inner" ref={innerRef}>+ <div className="calendar-detail-dock-header">+ <TitleRow compact />+ <ActionButton+ className="calendar-detail-dock-close"+ icon="bx bx-x"+ text={t("calendar.close_details")}+ onClick={onClose}+ />+ </div>++ <div className="calendar-detail-dock-body">+ <PromotedAttributes omit={EVENT_DATE_LABELS} />+ <NoteDetail />+ </div>+ </div>+ );+}diff --git a/apps/client/src/widgets/collections/calendar/index.css b/apps/client/src/widgets/collections/calendar/index.cssindex 378a43fbcf..c21a656813 100644--- a/apps/client/src/widgets/collections/calendar/index.css+++ b/apps/client/src/widgets/collections/calendar/index.css@@ -39,6 +39,18 @@bottom: 0;}+/* The calendar and the detail dock side by side, under the properties bar. */+.calendar-view .calendar-body {+ flex: 1;+ min-height: 0;+ display: flex;+}++.calendar-view .calendar-main {+ flex: 1;+ min-width: 0;+}+.calendar-container {height: 100%;--fc-page-bg-color: var(--main-background-color);@@ -162,6 +174,12 @@--border-color: var(--custom-color, var(--input-focus-outline-color));}+/* The event the detail dock stands for, marked the way a focused event is. */+.calendar-view a.fc-timegrid-event.calendar-event-in-dock,+.calendar-view a.fc-daygrid-event.calendar-event-in-dock {+ --border-color: var(--custom-color, var(--input-focus-outline-color));+}+.calendar-view a.fc-timegrid-event:hover,.calendar-view a.fc-daygrid-event:hover {filter: var(--calendar-coll-event-hover-filter, none);diff --git a/apps/client/src/widgets/collections/calendar/index.tsx b/apps/client/src/widgets/collections/calendar/index.tsxindex c6f2a5774a..90cca62611 100644--- a/apps/client/src/widgets/collections/calendar/index.tsx+++ b/apps/client/src/widgets/collections/calendar/index.tsx@@ -1,7 +1,7 @@import "./index.css";import { Calendar as FullCalendar } from "@fullcalendar/core";-import { DateSelectArg, EventChangeArg, EventMountArg, EventSourceFuncArg, LocaleInput, PluginDef } from "@fullcalendar/core/index.js";+import { DateSelectArg, EventChangeArg, EventClickArg, EventMountArg, EventSourceFuncArg, LocaleInput, PluginDef } from "@fullcalendar/core/index.js";import { DateClickArg } from "@fullcalendar/interaction";import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";import { RefObject } from "preact";@@ -24,6 +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 { openCalendarContextMenu } from "./context_menu";import { buildEvents, buildEventsForCalendar } from "./event_builder";import { formatDateToLocalISO, isValidDuration, parseStartEndDateFromEvent, parseStartEndTimeFromEvent } from "./utils";@@ -111,7 +112,10 @@ export const LOCALE_MAPPINGS: Record<DISPLAYABLE_LOCALE_IDS, (() => Promise<{ deexport default function CalendarView({ note, noteIds }: ViewModeProps<CalendarViewData>) {const parentComponent = useContext(ParentComponent);const 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);const [ calendarRoot ] = useNoteLabelBoolean(note, "calendarRoot");const [ workspaceCalendarRoot ] = useNoteLabelBoolean(note, "workspaceCalendarRoot");@@ -124,7 +128,9 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarViconst [ slotLabelInterval ] = useNoteLabel(note, "calendar:slotLabelInterval");const initialView = useRef(calendarView);const viewSpacedUpdate = useSpacedUpdate(() => setCalendarView(initialView.current));- useResizeObserver(containerRef, () => calendarRef.current?.updateSize());+ // Observed on the calendar's own wrapper rather than the view root, so the grid also reflows+ // frame by frame while the detail dock slides open or closed beside it.+ useResizeObserver(calendarMainRef, () => calendarRef.current?.updateSize());const isCalendarRoot = (calendarRoot || workspaceCalendarRoot);const isEditable = !isCalendarRoot;const eventBuilder = useMemo(() => {@@ -140,6 +146,31 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarViconst { eventDidMount } = useEventDisplayCustomization(note, parentComponent?.componentId);const editingProps = useEditing(note, isEditable, isCalendarRoot, parentComponent?.componentId);+ // 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);+ }+ }, [ isCalendarRoot, selectedNoteId, 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+ // dock would take the whole of the screen.+ const onEventClick = useCallback((e: EventClickArg) => {+ if (isMobile()) return;++ // The chip is an anchor at the event's `url`, and the app's document-level link handler+ // (see the delegated listeners in link.ts) would open the popup it names no matter what+ // FullCalendar makes of the click — so the click must not reach the document at all.+ e.jsEvent.preventDefault();+ e.jsEvent.stopPropagation();+ const noteId = e.event.extendedProps.noteId;+ if (noteId) {+ setSelectedNoteId(noteId);+ }+ }, []);+// React to changes.useTriliumEvent("entitiesReloaded", ({ loadResults }) => {const api = calendarRef.current;@@ -169,31 +200,38 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarVireturn (plugins &&<div className="calendar-view" ref={containerRef} tabIndex={100}><CalendarCollectionProperties note={note} calendarRef={calendarRef} />- <Calendar- events={eventBuilder}- calendarRef={calendarRef}- plugins={plugins}- initialView={initialView.current && SUPPORTED_CALENDAR_VIEW_TYPE.includes(initialView.current) ? initialView.current : "dayGridMonth"}- headerToolbar={false}- firstDay={firstDayOfWeek ?? 0}- weekends={!hideWeekends}- weekNumbers={weekNumbers}- slotDuration={isValidDuration(slotDuration) ? slotDuration : DEFAULT_SLOT_DURATION}- slotLabelInterval={isValidDuration(slotLabelInterval) ? slotLabelInterval : DEFAULT_SLOT_LABEL_INTERVAL}- height="100%"- nowIndicator- handleWindowResize={false}- initialDate={initialDate || undefined}- locale={locale}- {...editingProps}- eventDidMount={eventDidMount}- viewDidMount={({ view }) => {- if (initialView.current !== view.type) {- initialView.current = view.type;- viewSpacedUpdate.scheduleUpdate();- }- }}- />+ <div className="calendar-body">+ <div className="calendar-main" ref={calendarMainRef}>+ <Calendar+ events={eventBuilder}+ calendarRef={calendarRef}+ plugins={plugins}+ initialView={initialView.current && SUPPORTED_CALENDAR_VIEW_TYPE.includes(initialView.current) ? initialView.current : "dayGridMonth"}+ headerToolbar={false}+ firstDay={firstDayOfWeek ?? 0}+ weekends={!hideWeekends}+ weekNumbers={weekNumbers}+ slotDuration={isValidDuration(slotDuration) ? slotDuration : DEFAULT_SLOT_DURATION}+ slotLabelInterval={isValidDuration(slotLabelInterval) ? slotLabelInterval : DEFAULT_SLOT_LABEL_INTERVAL}+ height="100%"+ nowIndicator+ handleWindowResize={false}+ initialDate={initialDate || undefined}+ locale={locale}+ {...editingProps}+ eventClick={onEventClick}+ eventClassNames={(arg) => arg.event.extendedProps.noteId === selectedNoteId ? [ "calendar-event-in-dock" ] : []}+ eventDidMount={eventDidMount}+ viewDidMount={({ view }) => {+ if (initialView.current !== view.type) {+ initialView.current = view.type;+ viewSpacedUpdate.scheduleUpdate();+ }+ }}+ />+ </div>+ <DetailDock noteId={selectedNoteId} onClose={() => setSelectedNoteId(null)} />+ </div></div>);}