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): add a properties dialog listing the event templates
Elian Dorana5328df30bb3
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 35f05071f0..b1ca8fb728 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -567,8 +567,8 @@ type EventMappings = {geoMapCreateChildNote: {ntxId: string | null | undefined; // TODO: deduplicate ntxId};- /** Opens the board's properties dialog, which only the board itself can show. */- showBoardProperties: { ntxId: string | null | undefined; };+ /** Opens the properties dialog of a board or calendar, which only the view itself can show. */+ showCollectionProperties: { ntxId: string | null | undefined; };tabReorder: {ntxIdsInOrder: string[];};diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex fd4f6e18b6..5afe5ffffe 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3687,7 +3687,11 @@"hours_other": "{{count}} hours","duration_minutes": "{{minutes}} min","duration_hours": "{{hours}} h",- "duration_hours_minutes": "{{hours}} h {{minutes}} min"+ "duration_hours_minutes": "{{hours}} h {{minutes}} min",+ "properties": "Calendar properties",+ "event_templates": "Event templates",+ "event_templates_hint": "Choose what note types and note templates you would like to use when creating new calendar events.",+ "new_template_name": "New event template"},"ocr": {"extracted_text": "Extracted Text (OCR)",diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 1d722fc7d7..fcf49151de 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -4520,13 +4520,13 @@ describe("Board properties from the note menu", () => {expect(isOpen()).toBe(false);await act(async () => {- await host.handleEvent("showBoardProperties", { ntxId: "ntx-2" });+ await host.handleEvent("showCollectionProperties", { ntxId: "ntx-2" });await flush();});expect(isOpen()).toBe(false);await act(async () => {- await host.handleEvent("showBoardProperties", { ntxId: "ntx-1" });+ await host.handleEvent("showCollectionProperties", { ntxId: "ntx-1" });await flush();});expect(isOpen()).toBe(true);diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 1328ee2475..68f0637eab 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -1351,7 +1351,7 @@ function Board({}, [ selection, handleBoardKeys ]);// The note actions menu offers the properties dialog, which lives here rather than in the menu.- useTriliumEvent("showBoardProperties", ({ ntxId }) => {+ useTriliumEvent("showCollectionProperties", ({ ntxId }) => {if (ntxId === noteContext?.ntxId) {setIsEditingProperties(true);}diff --git a/apps/client/src/widgets/collections/calendar/CalendarProperties.css b/apps/client/src/widgets/collections/calendar/CalendarProperties.cssnew file mode 100644index 0000000000..7c36ce5877--- /dev/null+++ b/apps/client/src/widgets/collections/calendar/CalendarProperties.css@@ -0,0 +1,4 @@+.modal.calendar-properties-dialog .modal-body {+ padding-inline: 25px;+ padding-block-end: 25px;+}diff --git a/apps/client/src/widgets/collections/calendar/CalendarProperties.spec.tsx b/apps/client/src/widgets/collections/calendar/CalendarProperties.spec.tsxnew file mode 100644index 0000000000..174d5fb378--- /dev/null+++ b/apps/client/src/widgets/collections/calendar/CalendarProperties.spec.tsx@@ -0,0 +1,108 @@+import { Modal as BootstrapModal } from "bootstrap";+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type FNote from "../../../entities/fnote";+import type { CalendarViewData } from "./api";+import CalendarProperties from "./CalendarProperties";++// i18next is never initialised under test, so every label would read as undefined.+vi.mock("../../../services/i18n", () => ({+ t: (key: string) => key+}));++/** What the stubbed card reports on the next click. */+let reported: string[] = [];++// TemplateSelectionCard is tested in its own spec. What this dialog decides is the labels it+// passes and where onChange writes.+vi.mock("../../react/TemplateSelectionCard", () => ({+ default: ({ heading, instruction, note, newTemplateName, templates, onChange }: {+ heading: string, instruction: string, note: FNote, newTemplateName?: string,+ templates: string[], onChange: (templates: string[]) => void+ }) => (+ <div+ className="templates-stub"+ data-heading={heading}+ data-instruction={instruction}+ data-note={note.noteId}+ data-new-name={newTemplateName}+ data-templates={templates.join(",")}+ onClick={() => onChange(reported)}+ />+ )+}));++describe("CalendarProperties", () => {+ let container: HTMLElement;+ let saved: CalendarViewData[];+ const calendar = { noteId: "calendar1" } as FNote;++ function draw(viewConfig: CalendarViewData | undefined) {+ act(() => {+ render(+ <CalendarProperties+ note={calendar}+ viewConfig={viewConfig}+ saveConfig={(config) => saved.push(config)}+ onClose={() => {}}+ />,+ container);+ });+ return document.querySelector<HTMLElement>(".calendar-properties-dialog .templates-stub");+ }++ beforeEach(() => {+ saved = [];+ reported = [];+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ // Unmounted before Bootstrap is disposed: a modal Bootstrap still believes is shown traps+ // the focus of every later test.+ render(null, container);+ container.remove();++ const modal = document.querySelector<HTMLElement>(".calendar-properties-dialog");+ if (modal) {+ BootstrapModal.getInstance(modal)?.dispose();+ modal.remove();+ }++ document.querySelector(".modal-backdrop")?.remove();+ document.body.classList.remove("modal-open");+ });++ it("holds the event templates, offering text until the calendar has its own", () => {+ const card = draw(undefined);++ expect(document.querySelector(".calendar-properties-dialog .modal-title")?.textContent)+ .toContain("calendar_view.properties");+ expect(card?.dataset.heading).toBe("calendar_view.event_templates");+ expect(card?.dataset.instruction).toBe("calendar_view.event_templates_hint");+ expect(card?.dataset.note).toBe("calendar1");+ expect(card?.dataset.newName).toBe("calendar_view.new_template_name");+ expect(card?.dataset.templates).toBe("type:text:text/html");++ expect(draw({ templates: [ "note:mine" ] })?.dataset.templates).toBe("note:mine");+ });++ it("stores what the card reports beside the rest of the config, and refuses an empty list", () => {+ const card = draw({ templates: [ "type:text:text/html" ], template: "type:text:text/html" });+ expect(card).not.toBeNull();++ reported = [ "type:canvas:application/json", "note:mine" ];+ act(() => card?.click());+ expect(saved).toEqual([ {+ templates: [ "type:canvas:application/json", "note:mine" ],+ template: "type:text:text/html"+ } ]);++ reported = [];+ act(() => card?.click());+ expect(saved).toHaveLength(1);+ });+});diff --git a/apps/client/src/widgets/collections/calendar/CalendarProperties.tsx b/apps/client/src/widgets/collections/calendar/CalendarProperties.tsxnew file mode 100644index 0000000000..2758b15182--- /dev/null+++ b/apps/client/src/widgets/collections/calendar/CalendarProperties.tsx@@ -0,0 +1,46 @@+import "./CalendarProperties.css";++import { useCallback } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import { t } from "../../../services/i18n";+import Modal from "../../react/Modal";+import TemplateSelectionCard from "../../react/TemplateSelectionCard";+import { offeredTemplateIds } from "../../react/TemplatePill";+import { type CalendarViewData, DEFAULT_EVENT_TEMPLATES } from "./api";++/** The calendar's settings that the collection properties bar does not hold. */+export default function CalendarProperties({ note, viewConfig, saveConfig, onClose }: {+ /** The calendar note, which is the parent of any template created here. */+ note: FNote;+ viewConfig: CalendarViewData | undefined;+ saveConfig: (config: CalendarViewData) => void;+ onClose: () => void;+}) {+ // An empty list would leave nothing to make an event from.+ const storeTemplates = useCallback((templates: string[]) => {+ if (templates.length) {+ saveConfig({ ...viewConfig, templates });+ }+ }, [ viewConfig, saveConfig ]);++ return (+ <Modal+ className="calendar-properties-dialog"+ title={t("calendar_view.properties")}+ size="lg"+ scrollable+ show+ onHidden={onClose}+ >+ <TemplateSelectionCard+ heading={t("calendar_view.event_templates")}+ instruction={t("calendar_view.event_templates_hint")}+ note={note}+ newTemplateName={t("calendar_view.new_template_name")}+ templates={offeredTemplateIds(viewConfig, DEFAULT_EVENT_TEMPLATES)}+ onChange={storeTemplates}+ />+ </Modal>+ );+}diff --git a/apps/client/src/widgets/collections/calendar/api.ts b/apps/client/src/widgets/collections/calendar/api.tsindex 17a2bdf52a..37d87c07ad 100644--- a/apps/client/src/widgets/collections/calendar/api.ts+++ b/apps/client/src/widgets/collections/calendar/api.ts@@ -1,4 +1,4 @@-import { AttributeRow } from "@triliumnext/commons";+import { AttributeRow, buildNoteTypeId } from "@triliumnext/commons";import FNote from "../../../entities/fnote";import { setAttribute } from "../../../services/attributes";@@ -6,8 +6,15 @@ import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";import note_create from "../../../services/note_create";import { deleteNoteOrBranch } from "../../../services/note_deletion";+import { type TemplateChoiceConfig } from "../../react/TemplatePill";import { EventLabelName } from "./utils";+/** What the calendar stores in its view config. */+export type CalendarViewData = TemplateChoiceConfig;++/** What a calendar offers to make its events from until the reader picks for it. */+export const DEFAULT_EVENT_TEMPLATES = [ buildNoteTypeId("text", "text/html") ];+interface NewEventOpts {/** 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). */diff --git a/apps/client/src/widgets/collections/calendar/index.tsx b/apps/client/src/widgets/collections/calendar/index.tsxindex 2a928735ff..f514c30888 100644--- a/apps/client/src/widgets/collections/calendar/index.tsx+++ b/apps/client/src/widgets/collections/calendar/index.tsx@@ -11,7 +11,7 @@ import "./index.css";import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";import clsx from "clsx";import { Calendar as FullCalendar, DateClickInfo, DateSelectInfo, EventChangeInfo, EventClickInfo, EventDisplayInfo, EventSourceFuncInfo, LocaleInput, MountInfo, PluginInput } from "fullcalendar";-import { RefObject } from "preact";+import { createPortal, RefObject } from "preact";import { lazy, Suspense } from "preact/compat";import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";@@ -31,24 +31,13 @@ import { FormListItem } from "../../react/FormList";import { useEffectiveReadOnly, useNoteContext, useNoteLabel, useNoteLabelBoolean, useSpacedUpdate, useTriliumEvent, useTriliumOption, useTriliumOptionInt } from "../../react/hooks";import { ParentComponent } from "../../react/react_utils";import { ViewModeProps } from "../interface";-import { changeEvent, newEvent } from "./api";+import { type CalendarViewData, changeEvent, newEvent } from "./api";import Calendar from "./calendar";import { openCalendarContextMenu } from "./context_menu";import { CalendarSelection, EventDraft } from "./selection";import { buildEvents, buildEventsForCalendar } from "./event_builder";import { formatDateToLocalISO, formatTimeToLocalISO, isAttributeChangeAffecting, isBranchChangeAffecting, isValidDuration, parseDurationSeconds, parseStartEndDateFromEvent, parseStartEndTimeFromEvent } from "./utils";-interface CalendarViewData {--}--interface CalendarViewData {- type: string;- name: string;- previousText: string;- nextText: string;-}-const CALENDAR_VIEWS = [{type: "timeGridDay",@@ -120,7 +109,9 @@ export const LOCALE_MAPPINGS: Record<DISPLAYABLE_LOCALE_IDS, (() => Promise<{ dear: () => import("fullcalendar/locales/ar")};-export default function CalendarView({ note, noteIds, onOpenNote }: ViewModeProps<CalendarViewData>) {+export default function CalendarView({+ note, noteIds, onOpenNote, viewConfig, saveConfig+}: ViewModeProps<CalendarViewData>) {const parentComponent = useContext(ParentComponent);const { noteContext } = useNoteContext();const isReadOnly = useEffectiveReadOnly(note, noteContext);@@ -129,6 +120,7 @@ export default function CalendarView({ note, noteIds, onOpenNote }: ViewModeProp// The event the view's popovers stand for — a chip clicked, or a range just dragged out (see// CalendarSelection).const [ selection, setSelection ] = useState<CalendarSelection | null>(null);+ const [ isEditingProperties, setIsEditingProperties ] = useState(false);const [ calendarRoot ] = useNoteLabelBoolean(note, "calendarRoot");const [ workspaceCalendarRoot ] = useNoteLabelBoolean(note, "workspaceCalendarRoot");@@ -284,6 +276,13 @@ export default function CalendarView({ note, noteIds, onOpenNote }: ViewModeProp}}, [ onOpenNote ]);+ // The note actions menu offers the properties dialog, which lives here rather than in the menu.+ useTriliumEvent("showCollectionProperties", ({ ntxId }) => {+ if (ntxId === noteContext?.ntxId && isEditable) {+ setIsEditingProperties(true);+ }+ });+// React to changes.useTriliumEvent("entitiesReloaded", ({ loadResults }) => {const api = calendarRef.current;@@ -334,6 +333,7 @@ export default function CalendarView({ note, noteIds, onOpenNote }: ViewModeProp<div className="calendar-view" ref={containerRef} tabIndex={100}><CalendarCollectionPropertiesnote={note} calendarRef={calendarRef} containerRef={containerRef} isReadOnly={isReadOnly}+ onOpenProperties={isEditable ? () => setIsEditingProperties(true) : undefined}/><Calendarevents={eventBuilder}@@ -415,15 +415,28 @@ export default function CalendarView({ note, noteIds, onOpenNote }: ViewModeProp/></Suspense>)}+ {isEditingProperties && createPortal(+ <Suspense fallback={null}>+ <CalendarProperties+ note={note}+ viewConfig={viewConfig}+ saveConfig={saveConfig}+ onClose={() => setIsEditingProperties(false)}+ />+ </Suspense>,+ document.body+ )}</div>);}-function CalendarCollectionProperties({ note, calendarRef, containerRef, isReadOnly }: {+function CalendarCollectionProperties({ note, calendarRef, containerRef, isReadOnly, onOpenProperties }: {note: FNote;calendarRef: RefObject<FullCalendar | null>;containerRef: RefObject<HTMLDivElement | null>;isReadOnly: boolean;+ /** Opens `CalendarProperties`, absent for a calendar that creates no events. */+ onOpenProperties?: () => void;}) {const { title, viewType: currentViewType } = useOnDatesSet(calendarRef);const currentViewData = CALENDAR_VIEWS.find(v => calendarRef.current && v.type === currentViewType);@@ -445,6 +458,11 @@ function CalendarCollectionProperties({ note, calendarRef, containerRef, isReadOrightChildren={<>{!isMobileLocal && <CalendarViewSwitcher calendarRef={calendarRef} containerRef={containerRef} />}</>}+ optionsChildren={onOpenProperties && (+ <FormListItem icon="bx bx-cog" onClick={onOpenProperties}>+ {t("calendar_view.properties")}+ </FormListItem>+ )}/>);}@@ -813,3 +831,5 @@ function useOnDatesSet(calendarRef: RefObject<FullCalendar | null>) {const EventPopover = lazy(() => import("./EventPopover"));/** Loaded on the first event drafted, as only an editable calendar drafts one. */const GhostPopover = lazy(() => import("./GhostPopover"));+/** Loaded when the properties dialog is first opened. */+const CalendarProperties = lazy(() => import("./CalendarProperties"));diff --git a/apps/client/src/widgets/layout/NoteActions.tsx b/apps/client/src/widgets/layout/NoteActions.tsxindex a4be5f0e16..b5bc18e93f 100644--- a/apps/client/src/widgets/layout/NoteActions.tsx+++ b/apps/client/src/widgets/layout/NoteActions.tsx@@ -82,6 +82,9 @@ export function NoteContextMenu({ note, noteContext, itemsAtStart, itemsNearNoteconst hasSource = ["text", "code", "relationMap", "mermaid", "canvas", "mindMap", "spreadsheet", "llmChat"].includes(noteType) || note.isSvg();const isSearchOrBook = ["search", "book"].includes(noteType);const isBoard = noteType === "book" && viewType === "board";+ // A calendar root makes day notes rather than events, so it has no templates to configure.+ const isEventCalendar = noteType === "book" && viewType === "calendar"+ && !note.hasLabel("calendarRoot") && !note.hasLabel("workspaceCalendarRoot");const isHelpPage = note.noteId.startsWith("_help");const [syncServerHost] = useTriliumOption("syncServerHost");const { isReadOnly, enableEditing } = useIsNoteReadOnly(note, noteContext);@@ -172,8 +175,9 @@ export function NoteContextMenu({ note, noteContext, itemsAtStart, itemsNearNote{note.type === "render" && <CommandItem command="renderActiveNote" icon="bx bx-extension" text={t("note_actions.re_render_note")}/>}- {isBoard && <CommandItem icon="bx bx-cog" text={t("board_view.properties")}- command={() => parentComponent?.triggerEvent("showBoardProperties", { ntxId: noteContext?.ntxId })} />}+ {(isBoard || isEventCalendar) && <CommandItem icon="bx bx-cog"+ text={isBoard ? t("board_view.properties") : t("calendar_view.properties")}+ command={() => parentComponent?.triggerEvent("showCollectionProperties", { ntxId: noteContext?.ntxId })} />}<FormDropdownSubmenu icon="bx bx-wrench" title={t("note_actions.advanced")}><CommandItem command="openNoteExternally" icon="bx bx-file-find" disabled={isSearchOrBook || !isElectron} text={t("note_actions.open_note_externally")} title={t("note_actions.open_note_externally_title")} />