Skip to content

Build your personal knowledge base with Trilium Notes

feat(calendar): choose which attributes the events show

Elian Doran241b6b4feafe
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 3cbf280555..e5b89905cd 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3695,7 +3695,10 @@
"event_template": "Select an event template",
"more_templates": "More templates…",
"template": "Template",
- "general": "General"
+ "general": "General",
+ "event_attributes": "Event attributes",
+ "event_attributes_hint": "Choose which attributes appear on the events, and in what order. New attributes are hidden until you turn them on.",
+ "event_attributes_overridden": "This calendar has a calendar:displayedAttributes label, so the events show the attributes listed there instead of the ones chosen here."
},
"ocr": {
"extracted_text": "Extracted Text (OCR)",
diff --git a/apps/client/src/widgets/collections/calendar/CalendarProperties.spec.tsx b/apps/client/src/widgets/collections/calendar/CalendarProperties.spec.tsx
index 37e21ac584..a3589528d1 100644
--- a/apps/client/src/widgets/collections/calendar/CalendarProperties.spec.tsx
+++ b/apps/client/src/widgets/collections/calendar/CalendarProperties.spec.tsx
@@ -40,16 +40,45 @@ vi.mock("../../react/TemplateSelectionCard", () => ({
)
}));
+// PromotedAttributesCard is tested in its own spec. These tests check the props the dialog passes
+// and where onChange writes.
+vi.mock("../../react/PromotedAttributesCard", () => ({
+ default: ({
+ heading, instruction, settings, drawnByCollection, itemNotes, unarrangedHidden, onChange
+ }: {
+ heading: string, instruction: string, settings?: { name: string }[],
+ drawnByCollection?: string[], itemNotes?: FNote[], unarrangedHidden?: boolean,
+ onChange: (attributes: { name: string, hidden: boolean }[]) => void
+ }) => (
+ <div
+ className="attributes-stub"
+ data-heading={heading}
+ data-instruction={instruction}
+ data-settings={settings?.map((setting) => setting.name).join(",")}
+ data-drawn={drawnByCollection?.join(",")}
+ data-items={itemNotes?.map((item) => item.noteId).join(",")}
+ data-unarranged-hidden={String(!!unarrangedHidden)}
+ onClick={() => onChange([
+ { name: "mood", hidden: false }, { name: "where", hidden: true }
+ ])}
+ />
+ )
+}));
+
describe("CalendarProperties", () => {
let container: HTMLElement;
let saved: CalendarViewData[];
- const calendar = buildNote({ id: "calendar1", title: "Calendar" }) as unknown as FNote;
+ const calendar = buildNote({
+ id: "calendar1", title: "Calendar", "#calendar:startDate": "myStart",
+ children: [ { id: "event1", title: "Fair", "#startDate": "2025-05-05" } ]
+ }) as unknown as FNote;
- function draw(viewConfig: CalendarViewData | undefined) {
+ function draw(viewConfig: CalendarViewData | undefined, note = calendar) {
act(() => {
render(
<CalendarProperties
- note={calendar}
+ note={note}
+ eventNoteIds={[ "event1" ]}
viewConfig={viewConfig}
saveConfig={(config) => saved.push(config)}
onClose={() => {}}
@@ -115,6 +144,38 @@ describe("CalendarProperties", () => {
});
/** On a phone the new-event form is itself a dialog, opened before this one from its template field. */
+ it("lists the event attributes, which start hidden, and stores them beside the rest", () => {
+ draw({ template: "type:text:text/html", promotedAttributes: [ { name: "mood" } ] });
+ const card = document.querySelector<HTMLElement>(
+ ".calendar-properties-dialog .attributes-stub");
+
+ expect(card?.dataset.heading).toBe("calendar_view.event_attributes");
+ expect(card?.dataset.instruction).toBe("calendar_view.event_attributes_hint");
+ expect(card?.dataset.settings).toBe("mood");
+ expect(card?.dataset.unarrangedHidden).toBe("true");
+ // The date labels, custom names included, are drawn by the calendar itself.
+ expect(card?.dataset.drawn?.split(",")).toEqual([
+ "startDate", "endDate", "startTime", "endTime", "recurrence", "myStart"
+ ]);
+ expect(card?.dataset.items).toBe("event1");
+
+ act(() => card?.click());
+ expect(saved).toEqual([ {
+ template: "type:text:text/html",
+ promotedAttributes: [ { name: "mood" }, { name: "where", hidden: true } ]
+ } ]);
+ });
+
+ it("mentions the #calendar:displayedAttributes label when the calendar has one", () => {
+ const labelled = buildNote({
+ title: "Labelled", "#calendar:displayedAttributes": "mood"
+ }) as unknown as FNote;
+ draw(undefined, labelled);
+
+ expect(document.querySelector<HTMLElement>(".attributes-stub")?.dataset.instruction)
+ .toBe("calendar_view.event_attributes_overridden");
+ });
+
it("opens over the dialog already open rather than closing it", () => {
const sheet = document.createElement("div");
sheet.className = "modal";
diff --git a/apps/client/src/widgets/collections/calendar/CalendarProperties.tsx b/apps/client/src/widgets/collections/calendar/CalendarProperties.tsx
index e8eb4d0713..96dbcc60c2 100644
--- a/apps/client/src/widgets/collections/calendar/CalendarProperties.tsx
+++ b/apps/client/src/widgets/collections/calendar/CalendarProperties.tsx
@@ -1,24 +1,33 @@
-import { useCallback } from "preact/hooks";
+import { useCallback, useMemo } from "preact/hooks";
import type FNote from "../../../entities/fnote";
+import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
import {
CollectionPropertiesDialog, INCLUDE_ARCHIVED_PROPERTY
} from "../../note_bars/CollectionProperties";
import { bookPropertiesConfig } from "../../note_bars/collection-properties-config";
import { Card } from "../../react/Card";
+import { useNoteLabel } from "../../react/hooks";
import { ViewPropertySection } from "../../react/NotePropertyMenu";
+import PromotedAttributesCard from "../../react/PromotedAttributesCard";
import TemplateSelectionCard from "../../react/TemplateSelectionCard";
import { offeredTemplateIds } from "../../react/TemplateDropdown";
+import { type PromotedAttribute, storedPromotedAttributes } from "../promoted_attributes";
import { type CalendarViewData, DEFAULT_EVENT_TEMPLATES } from "./api";
+import { useEventLabelOmissions } from "./hooks";
/**
- * The calendar's settings: those of the collection's settings dropdown, and the event templates,
- * which only this dialog holds.
+ * The calendar's settings: those of the collection's settings dropdown, and the attributes its
+ * events show and the templates they are made from, which only this dialog holds.
*/
-export default function CalendarProperties({ note, viewConfig, saveConfig, onClose }: {
+export default function CalendarProperties({
+ note, eventNoteIds, viewConfig, saveConfig, onClose
+}: {
/** The calendar note, which is the parent of any template created here. */
note: FNote;
+ /** The notes the calendar shows, whose own definitions are listed with the calendar's. */
+ eventNoteIds: string[];
viewConfig: CalendarViewData | undefined;
saveConfig: (config: CalendarViewData) => void;
onClose: () => void;
@@ -29,6 +38,14 @@ export default function CalendarProperties({ note, viewConfig, saveConfig, onClo
saveConfig({ ...viewConfig, templates });
}
}, [ viewConfig, saveConfig ]);
+ const storeAttributes = useCallback((attributes: PromotedAttribute[]) => {
+ saveConfig({ ...viewConfig, promotedAttributes: storedPromotedAttributes(attributes) });
+ }, [ viewConfig, saveConfig ]);
+ const drawnLabels = useEventLabelOmissions(note);
+ const eventNotes = useMemo(() => froca.getNotesFromCache(eventNoteIds, true), [ eventNoteIds ]);
+ // The events usually inherit the calendar's `#calendar:displayedAttributes`, which takes
+ // precedence over this list (see `buildEvent()`).
+ const [ displayedLabel ] = useNoteLabel(note, "calendar:displayedAttributes");
return (
<CollectionPropertiesDialog
@@ -44,6 +61,19 @@ export default function CalendarProperties({ note, viewConfig, saveConfig, onClo
))}
</Card>
+ <PromotedAttributesCard
+ heading={t("calendar_view.event_attributes")}
+ instruction={displayedLabel === null || displayedLabel === undefined
+ ? t("calendar_view.event_attributes_hint")
+ : t("calendar_view.event_attributes_overridden")}
+ note={note}
+ settings={viewConfig?.promotedAttributes}
+ drawnByCollection={drawnLabels}
+ itemNotes={eventNotes}
+ unarrangedHidden
+ onChange={storeAttributes}
+ />
+
<TemplateSelectionCard
heading={t("calendar_view.event_templates")}
instruction={t("calendar_view.event_templates_hint")}
diff --git a/apps/client/src/widgets/collections/calendar/api.ts b/apps/client/src/widgets/collections/calendar/api.ts
index 95a960e259..d33c7ca98e 100644
--- a/apps/client/src/widgets/collections/calendar/api.ts
+++ b/apps/client/src/widgets/collections/calendar/api.ts
@@ -8,10 +8,14 @@ import note_create from "../../../services/note_create";
import { deleteNoteOrBranch } from "../../../services/note_deletion";
import { type NoteTypeOption } from "../../../services/note_types";
import { type TemplateChoiceConfig } from "../../react/TemplateDropdown";
+import { type PromotedAttributeSetting } from "../promoted_attributes";
import { EventLabelName } from "./utils";
/** What the calendar stores in its view config. */
-export type CalendarViewData = TemplateChoiceConfig;
+export interface CalendarViewData extends TemplateChoiceConfig {
+ /** Which attributes the events show, and in what order. See `buildEvents()`. */
+ promotedAttributes?: PromotedAttributeSetting[];
+}
/** What a calendar offers to make its events from until the reader picks for it. */
export const DEFAULT_EVENT_TEMPLATES = [ buildNoteTypeId("text", "text/html") ];
diff --git a/apps/client/src/widgets/collections/calendar/event_builder.spec.ts b/apps/client/src/widgets/collections/calendar/event_builder.spec.ts
index 40b161a7ef..d326c880d7 100644
--- a/apps/client/src/widgets/collections/calendar/event_builder.spec.ts
+++ b/apps/client/src/widgets/collections/calendar/event_builder.spec.ts
@@ -211,6 +211,63 @@ describe("Promoted attributes", () => {
]);
});
+ describe("chosen in the calendar's properties", () => {
+ let built = 0;
+
+ /** A calendar with two events, under ids of their own: froca keeps attributes across builds. */
+ function calendar() {
+ built++;
+ const note = buildNote({
+ title: "Calendar",
+ "#label:location(inheritable)": "promoted,alias=Where,single,text",
+ "#label:mood(inheritable)": "promoted,single,text",
+ "#label:weight(inheritable)": "promoted,single,text",
+ "#label:startDate(inheritable)": "promoted,single,date",
+ children: [
+ {
+ id: `fair${built}`, title: "Fair", "#startDate": "2025-05-05",
+ "#location": "Park", "#mood": "good", "#weight": "70"
+ },
+ {
+ id: `gym${built}`, title: "Gym", "#startDate": "2025-05-06", "#weight": "71",
+ "#mood": "tired", "#calendar:displayedAttributes": "weight"
+ }
+ ]
+ });
+ return { note, fair: `fair${built}`, gym: `gym${built}` };
+ }
+
+ it("shows the attributes switched on in the settings, in order, under their alias", async () => {
+ const { note, fair } = calendar();
+ const events = await buildEvents([ fair ], {
+ calendar: note,
+ settings: [ { name: "mood" }, { name: "weight", hidden: true }, { name: "location" } ]
+ });
+
+ expect(events[0]?.promotedAttributes).toEqual([ [ "mood", "good" ], [ "Where", "Park" ] ]);
+ });
+
+ it("leaves off what nobody arranged, and the dates the calendar draws itself", async () => {
+ const { note, fair } = calendar();
+ const events = await buildEvents([ fair ], {
+ calendar: note,
+ settings: [ { name: "startDate" }, { name: "mood" } ]
+ });
+
+ expect(events[0]?.promotedAttributes).toEqual([ [ "mood", "good" ] ]);
+ });
+
+ it("gives way to an event's own #calendar:displayedAttributes", async () => {
+ const { note, gym } = calendar();
+ const events = await buildEvents([ gym ], {
+ calendar: note,
+ settings: [ { name: "mood" } ]
+ });
+
+ expect(events[0]?.promotedAttributes).toEqual([ [ "weight", "71" ] ]);
+ });
+ });
+
it("supports start time and end time", async () => {
const noteIds = buildNotes([
{ title: "Note 1", "#startDate": "2025-05-05", "#startTime": "13:36", "#endTime": "14:56" },
diff --git a/apps/client/src/widgets/collections/calendar/event_builder.ts b/apps/client/src/widgets/collections/calendar/event_builder.ts
index 3a6c8d898d..508bd2bc47 100644
--- a/apps/client/src/widgets/collections/calendar/event_builder.ts
+++ b/apps/client/src/widgets/collections/calendar/event_builder.ts
@@ -8,7 +8,10 @@ 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 {
+ type PromotedAttributeSetting, resolvePromotedAttributes, visiblePromotedAttributeNames
+} from "../promoted_attributes";
+import { drawnEventLabels, getCustomisableLabel, getMonthsInDateRange } from "./utils";
interface Event {
startDate: string,
@@ -17,11 +20,27 @@ interface Event {
endTime?: string | null,
isArchived?: boolean,
recurrence?: string | null;
+ /**
+ * The attributes shown on the event, by name and in order, unless the note has its own
+ * `#calendar:displayedAttributes` list.
+ */
+ displayedAttributes?: string[];
}
-export async function buildEvents(noteIds: string[]) {
+export async function buildEvents(noteIds: string[], displayed?: {
+ /** The calendar, which defines the attributes its events can show. */
+ calendar: FNote;
+ /** What the calendar's properties arranged, as its view config stores it. */
+ settings: PromotedAttributeSetting[] | undefined;
+}) {
const notes = await froca.getNotes(noteIds);
const events: EventSourceInput = [];
+ // Resolved against the events as well, which can define attributes of their own.
+ const displayedAttributes = displayed
+ ? visiblePromotedAttributeNames(resolvePromotedAttributes(
+ displayed.calendar, displayed.settings, drawnEventLabels(displayed.calendar), notes,
+ { unarrangedHidden: true }))
+ : [];
for (const note of notes) {
// An event template created from `CalendarProperties` is a child of the calendar, not an event.
@@ -41,7 +60,9 @@ export async function buildEvents(noteIds: string[]) {
const recurrence = getCustomisableLabel(note, "recurrence", "calendar:recurrence");
const isArchived = note.hasLabel("archived");
try {
- events.push(await buildEvent(note, { startDate, endDate, startTime, endTime, recurrence, isArchived }));
+ events.push(await buildEvent(note, {
+ startDate, endDate, startTime, endTime, recurrence, isArchived, displayedAttributes
+ }));
} catch (error) {
if (error instanceof Error) {
const errorMessage = error.message;
@@ -99,16 +120,19 @@ export async function buildEventsForCalendar(note: FNote, e: EventSourceFuncInfo
return events.flat();
}
-export async function buildEvent(note: FNote, { startDate, endDate, startTime, endTime, recurrence, isArchived }: Event) {
+export async function buildEvent(note: FNote, {
+ startDate, endDate, startTime, endTime, recurrence, isArchived, displayedAttributes = []
+}: Event) {
const customTitleAttributeName = note.getLabelValue("calendar:title");
const titles = await parseCustomTitle(customTitleAttributeName, note);
const colorClass = note.getColorClass();
const events: EventInput[] = [];
- const calendarDisplayedAttributes = note.getLabelValue("calendar:displayedAttributes")?.split(",");
+ const shownAttributes =
+ note.getLabelValue("calendar:displayedAttributes")?.split(",") ?? displayedAttributes;
let displayedAttributesData: Array<[string, string]> | null = null;
- if (calendarDisplayedAttributes) {
- displayedAttributesData = await buildDisplayedAttributes(note, calendarDisplayedAttributes);
+ if (shownAttributes.length) {
+ displayedAttributesData = await buildDisplayedAttributes(note, shownAttributes);
}
// An event with no start time takes the whole day, which is how the editor writes one too (see
@@ -240,8 +264,10 @@ async function parseCustomTitle(customTitlettributeName: string | null, note: FN
return [note.title];
}
-async function buildDisplayedAttributes(note: FNote, calendarDisplayedAttributes: string[]) {
- const filteredDisplayedAttributes = note.getAttributes().filter((attr): boolean => calendarDisplayedAttributes.includes(attr.name));
+/** The values of the named attributes, in the order named. */
+async function buildDisplayedAttributes(note: FNote, names: string[]) {
+ const all = note.getAttributes();
+ const filteredDisplayedAttributes = names.flatMap((name) => all.filter((attr) => attr.name === name));
const result: Array<[string, string]> = [];
for (const attribute of filteredDisplayedAttributes) {
diff --git a/apps/client/src/widgets/collections/calendar/hooks.ts b/apps/client/src/widgets/collections/calendar/hooks.ts
index c77a0b95cc..e040271cba 100644
--- a/apps/client/src/widgets/collections/calendar/hooks.ts
+++ b/apps/client/src/widgets/collections/calendar/hooks.ts
@@ -1,6 +1,6 @@
import FNote from "../../../entities/fnote";
import { useNoteLabel, useNoteLabelByName } from "../../react/hooks";
-import { EVENT_LABELS, EventLabelName } from "./utils";
+import { drawnEventLabels, EventLabelName } from "./utils";
/**
* Reads and writes one of the labels the calendar draws an event by, honouring the note's own
@@ -32,13 +32,11 @@ export function useEventLabel(note: FNote, defaultName: EventLabelName): [string
* names the note has pointed the calendar at instead.
*/
export function useEventLabelOmissions(note: FNote): string[] {
- const [ customStartDate ] = useNoteLabel(note, "calendar:startDate");
- const [ customEndDate ] = useNoteLabel(note, "calendar:endDate");
- const [ customStartTime ] = useNoteLabel(note, "calendar:startTime");
- const [ customEndTime ] = useNoteLabel(note, "calendar:endTime");
- const [ customRecurrence ] = useNoteLabel(note, "calendar:recurrence");
-
- const customNames = [ customStartDate, customEndDate, customStartTime, customEndTime, customRecurrence ]
- .filter((name): name is string => !!name);
- return [ ...EVENT_LABELS, ...customNames ];
+ // Read for their changes: each redraws the caller, which `drawnEventLabels()` then reads again.
+ useNoteLabel(note, "calendar:startDate");
+ useNoteLabel(note, "calendar:endDate");
+ useNoteLabel(note, "calendar:startTime");
+ useNoteLabel(note, "calendar:endTime");
+ useNoteLabel(note, "calendar:recurrence");
+ return drawnEventLabels(note);
}
diff --git a/apps/client/src/widgets/collections/calendar/index.tsx b/apps/client/src/widgets/collections/calendar/index.tsx
index 211af2c9c6..7b474a6482 100644
--- a/apps/client/src/widgets/collections/calendar/index.tsx
+++ b/apps/client/src/widgets/collections/calendar/index.tsx
@@ -145,7 +145,14 @@ export default function CalendarView({
// of the function, and a new one empties the grid before it fetches.
const rootEventBuilder = useMemo(() =>
async (e: EventSourceFuncInfo) => await buildEventsForCalendar(note, e), [note]);
- const collectionEventBuilder = useMemo(() => async () => await buildEvents(noteIds), [noteIds]);
+ // Keyed on the settings' content, since a restored config replaces the array.
+ const attributeSettings = viewConfig?.promotedAttributes;
+ const attributeSettingsKey = JSON.stringify(attributeSettings ?? []);
+ const collectionEventBuilder = useMemo(
+ () => async () =>
+ await buildEvents(noteIds, { calendar: note, settings: attributeSettings }),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [ noteIds, note, attributeSettingsKey ]);
const eventBuilder = isCalendarRoot ? rootEventBuilder : collectionEventBuilder;
const plugins = usePlugins(isEditable, isCalendarRoot);
@@ -441,6 +448,7 @@ export default function CalendarView({
<CalendarProperties
note={note}
viewConfig={viewConfig}
+ eventNoteIds={noteIds}
saveConfig={saveConfig}
onClose={() => setIsEditingProperties(false)}
/>
diff --git a/apps/client/src/widgets/collections/calendar/utils.ts b/apps/client/src/widgets/collections/calendar/utils.ts
index 8af64f3af6..b811eae6fd 100644
--- a/apps/client/src/widgets/collections/calendar/utils.ts
+++ b/apps/client/src/widgets/collections/calendar/utils.ts
@@ -119,6 +119,17 @@ export type EventLabelName = "startDate" | "endDate" | "startTime" | "endTime" |
export const EVENT_LABELS: EventLabelName[] = [ "startDate", "endDate", "startTime", "endTime", "recurrence" ];
+/**
+ * The label names the calendar draws events by: the stock ones, and the custom names `note` sets
+ * through `#calendar:startDate` and its siblings.
+ */
+export function drawnEventLabels(note: FNote): string[] {
+ const customNames = EVENT_LABELS
+ .map((name) => note.getLabelValue(`calendar:${name}`))
+ .filter((name): name is string => !!name);
+ return [ ...EVENT_LABELS, ...customNames ];
+}
+
/**
* Allows the user to customize the attribute from which to obtain a particular value. For example, if `customLabelNameAttribute` is `calendar:startDate`
* and `defaultLabelName` is `startDate` and the note at hand has `#calendar:startDate=myStartDate #myStartDate=2025-02-26` then the value returned will
diff --git a/apps/client/src/widgets/collections/promoted_attributes.spec.ts b/apps/client/src/widgets/collections/promoted_attributes.spec.ts
index c2e95d090f..bdaab70819 100644
--- a/apps/client/src/widgets/collections/promoted_attributes.spec.ts
+++ b/apps/client/src/widgets/collections/promoted_attributes.spec.ts
@@ -102,6 +102,16 @@ describe("resolvePromotedAttributes", () => {
expect(visiblePromotedAttributeNames(resolved)).toEqual([ "requiresResearch", "owner" ]);
});
+ it("hides an attribute the settings have never named, for a collection that opts in", () => {
+ const resolved = resolvePromotedAttributes(
+ collection(DEFINED), [ { name: "owner" } ], [], [], { unarrangedHidden: true });
+
+ expect(visiblePromotedAttributeNames(resolved)).toEqual([ "owner" ]);
+ // Still listed, after the arranged ones, so the reader can switch it on.
+ expect(resolved.map((attribute) => attribute.name))
+ .toEqual([ "owner", "dueDate", "requiresResearch" ]);
+ });
+
/** Writing the result back is what prunes the config. */
it("leaves out what the settings name and the note no longer defines", () => {
const settings: PromotedAttributeSetting[] = [
diff --git a/apps/client/src/widgets/collections/promoted_attributes.ts b/apps/client/src/widgets/collections/promoted_attributes.ts
index 061c21a5ad..dcaa68eefe 100644
--- a/apps/client/src/widgets/collections/promoted_attributes.ts
+++ b/apps/client/src/widgets/collections/promoted_attributes.ts
@@ -63,9 +63,10 @@ export interface PromotedAttribute {
/**
* The attributes a collection can show on its items, in the order the reader put them.
*
- * The stored settings lead, in their own order, and anything the note has gained since is appended
- * and shown: an attribute nobody has arranged is one the reader has yet to see. What the settings
- * name but the note no longer defines is left out, so writing the result back prunes the config.
+ * The stored settings lead, in their own order, and anything the note has gained since is appended,
+ * shown unless `unarrangedHidden` is set: an attribute nobody has arranged is one the reader has yet
+ * to see. Attributes listed in the settings but no longer defined by the note are left out, so
+ * writing the result back prunes the config.
*
* Read from `getAttributeDefinitions()` rather than from the promoted ones: a definition that is
* not promoted is still drawn on an item, only without an alias, and a note carrying
@@ -83,7 +84,14 @@ export function resolvePromotedAttributes(
/** Names the collection draws itself, such as the label a board groups by. */
drawnByCollection: string[] = [],
/** The notes the collection shows, such as the cards of a board. */
- items: Iterable<FNote> = []
+ items: Iterable<FNote> = [],
+ { unarrangedHidden = false }: {
+ /**
+ * Hides what the settings have never named, for a collection whose items have little room,
+ * such as a calendar's events. Otherwise it is shown.
+ */
+ unarrangedHidden?: boolean;
+ } = {}
): PromotedAttribute[] {
const defined = new Map<string, PromotedAttribute>();
@@ -149,6 +157,7 @@ export function resolvePromotedAttributes(
for (const attribute of defined.values()) {
if (!ordered.includes(attribute)) {
+ attribute.hidden = unarrangedHidden;
ordered.push(attribute);
}
}
diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx b/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx
index eacf7fbb27..ee5d17c58e 100644
--- a/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx
+++ b/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx
@@ -84,6 +84,7 @@ describe("PromotedAttributesCard", () => {
let settings: PromotedAttributeSetting[] | undefined;
let drawnByCollection: string[] | undefined;
let itemNotes: FNote[] | undefined;
+ let unarrangedHidden: boolean | undefined;
beforeEach(() => {
vi.clearAllMocks();
@@ -91,6 +92,7 @@ describe("PromotedAttributesCard", () => {
settings = undefined;
drawnByCollection = undefined;
itemNotes = undefined;
+ unarrangedHidden = undefined;
defined = [ definition("label:dueDate", { alias: "Due" }), definition("label:owner") ];
mocks.detail.opts = null;
mocks.confirm.mockResolvedValue(true);
@@ -473,6 +475,48 @@ describe("PromotedAttributesCard", () => {
});
});
+ describe("for a collection that hides what nobody has arranged", () => {
+ beforeEach(() => { unarrangedHidden = true; });
+
+ it("lists every definition, switched off until the reader shows it", () => {
+ settings = [ { name: "owner" } ];
+ draw();
+
+ expect(names()).toEqual([ unnamed("owner"), "Due" ]);
+ expect(shown()).toEqual([ true, false ]);
+ });
+
+ it("shows what was created here, and reports it", async () => {
+ draw();
+ act(() => { adder()?.click(); });
+
+ await save({
+ type: "label", name: "label:priority", value: "promoted,single,text",
+ isInheritable: true
+ });
+ defined = [ ...defined, definition("label:priority") ];
+ await reported();
+
+ expect(names()).toEqual([ "Due", unnamed("owner"), unnamed("priority") ]);
+ expect(shown()).toEqual([ false, false, true ]);
+ expect(stored.at(-1)?.map(({ name, hidden }) => ({ name, hidden }))).toEqual([
+ { name: "dueDate", hidden: true },
+ { name: "owner", hidden: true },
+ { name: "priority", hidden: false }
+ ]);
+ });
+
+ it("keeps a definition made elsewhere switched off, writing nothing", async () => {
+ draw();
+
+ defined = [ ...defined, definition("label:priority") ];
+ await reported();
+
+ expect(shown()).toEqual([ false, false, false ]);
+ expect(stored).toEqual([]);
+ });
+ });
+
// #region The card, and what the test does to it
function draw() {
@@ -486,6 +530,7 @@ describe("PromotedAttributesCard", () => {
settings={settings}
drawnByCollection={drawnByCollection}
itemNotes={itemNotes}
+ unarrangedHidden={unarrangedHidden}
onChange={(attributes) => stored.push(attributes)}
/>
</ParentComponent.Provider>,
diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.tsx b/apps/client/src/widgets/react/PromotedAttributesCard.tsx
index a05bdffbe1..d9de34c10c 100644
--- a/apps/client/src/widgets/react/PromotedAttributesCard.tsx
+++ b/apps/client/src/widgets/react/PromotedAttributesCard.tsx
@@ -56,6 +56,11 @@ export interface PromotedAttributesCardProps {
* ones only these notes define have no edit or delete button.
*/
itemNotes?: Iterable<FNote>;
+ /**
+ * Starts what the settings have never named switched off, for a collection whose items have
+ * little room. A definition created from this card is shown all the same.
+ */
+ unarrangedHidden?: boolean;
/** Called with the whole list after every change, for the caller to store. */
onChange: (attributes: PromotedAttribute[]) => void;
}
@@ -68,10 +73,15 @@ export interface PromotedAttributesCardProps {
* reports the order and what is hidden, which the caller stores.
*/
export default function PromotedAttributesCard({
- heading, instruction, note, settings, drawnByCollection, itemNotes, onChange
+ heading, instruction, note, settings, drawnByCollection, itemNotes, unarrangedHidden, onChange
}: PromotedAttributesCardProps) {
- const [ shown, setShown ] =
- useState(() => resolvePromotedAttributes(note, settings, drawnByCollection, itemNotes));
+ const resolve = (stored: PromotedAttributeSetting[] | undefined) => resolvePromotedAttributes(
+ note, stored, drawnByCollection, itemNotes, { unarrangedHidden });
+ const [ shown, setShown ] = useState(() => resolve(settings));
+ const shownRef = useRef(shown);
+ shownRef.current = shown;
+ /** Names of the definitions created from this card, to show once they load. */
+ const madeHere = useRef(new Set<string>());
// What the collection draws can change while the card stands, a board being regrouped from
// its header. The rows are marked again where they are, keeping their order and what is
// hidden; the marks are not stored, so nothing is written back for them.
@@ -90,8 +100,7 @@ export default function PromotedAttributesCard({
const [ lastItemDefinitions, setLastItemDefinitions ] = useState(itemDefinitions);
if (lastItemDefinitions !== itemDefinitions) {
setLastItemDefinitions(itemDefinitions);
- setShown((was) => resolvePromotedAttributes(
- note, storedPromotedAttributes(was), drawnByCollection, itemNotes));
+ setShown((was) => resolve(storedPromotedAttributes(was)));
}
const [ detail, setDetail ] = useState<AttributeDetailOpts | null>(null);
/** The definition the editor last reported, which `save` writes. */
@@ -105,10 +114,25 @@ export default function PromotedAttributesCard({
const notes = [ note, ...itemNotes ?? [] ];
const affects = loadResults.getAttributeRows().some((attribute) =>
notes.some((affected) => attributes.isAffecting(attribute, affected)));
- if (affects) {
- setShown((was) => resolvePromotedAttributes(
- note, storedPromotedAttributes(was), drawnByCollection, itemNotes));
+ if (!affects) return;
+
+ const was = shownRef.current;
+ const next = resolve(storedPromotedAttributes(was));
+ // A definition made here is one the reader asked for, so it is shown even where what nobody
+ // has arranged starts hidden, and stored as such.
+ const made = next.filter((attribute) => attribute.hidden
+ && madeHere.current.has(attribute.name)
+ && !was.some((previous) => previous.name === attribute.name));
+ if (!made.length) {
+ setShown(next);
+ return;
}
+
+ for (const attribute of made) {
+ madeHere.current.delete(attribute.name);
+ }
+ store(next.map((attribute) =>
+ made.includes(attribute) ? { ...attribute, hidden: false } : attribute));
});
const items = useMemo(() => shown.map((attribute) => ({
@@ -180,6 +204,9 @@ export default function PromotedAttributesCard({
const [ type, name ] = extractAttributeDefinitionTypeAndName(definition.name);
const isRenamed = !!was && was.name !== definition.name;
+ if (!was) {
+ madeHere.current.add(name);
+ }
if (isRenamed && was) {
const [ , previous ] = extractAttributeDefinitionTypeAndName(was.name);
await renameAttributeInSubtree(note.noteId, type, previous, name);
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.html
index bd402a5d1c..0c87613e13 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
@@ -183,6 +183,27 @@
<p>The dialog is not available on a read-only calendar, or on a calendar
marked with <code>#calendarRoot</code> or <code>#workspaceCalendarRoot</code> (see <a
href="#using-with-the-journal--calendar">Using with the Journal / calendar</a>).</p>
+<h3>Event attributes</h3>
+<p>Events can show the values of their attributes below their title, in the
+ month view, and in the week and day views for all-day events and for timed
+ ones tall enough to hold them. To choose which attributes are shown, open
+ the <span class="tn-icon bx bx-cog"></span> <em>Calendar properties</em> dialog
+ (see <a href="#event-templates">Event templates</a> for how to open it) and
+ find <em>Event attributes</em>. It lists the <a class="reference-link" href="#root/_help_OFXdgB2nNk1F">Promoted Attributes</a> the
+ calendar defines, and those its events define themselves. Here you can:</p>
+<ul>
+ <li>Turn an attribute on to show it on the events. New attributes are hidden
+ until you turn them on, which keeps the calendar from getting cluttered.</li>
+ <li>Drag an attribute by its handle to change the order in which the events
+ show them.</li>
+ <li>Create a new attribute, which is shown on the events right away, or edit
+ or delete one the calendar defines.</li>
+</ul>
+<p>The dates, times and recurrence of the events are drawn by the calendar
+ itself, so they are listed but cannot be switched on.</p>
+<p>If an event has a <code>#calendar:displayedAttributes</code> label, including
+ one inherited from the calendar, the attributes listed in that label are
+ shown instead.</p>
<h2>Configuring the calendar using attributes</h2>
<p>The following attributes can be added to the Collection type:</p>
<figure
@@ -335,8 +356,9 @@ class="table">
<tr>
<td><code>#calendar:displayedAttributes</code>
</td>
- <td>Allows displaying the value of one or more attributes in the calendar
- like this:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+ <td>Takes precedence over the <a href="#event-attributes">Event attributes</a> chosen
+ in the calendar's properties. Allows displaying the value of one or more
+ attributes in the calendar, in the order given, like this:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<br>
<br>
<img src="6_Calendar_image.png">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
diff --git a/docs/User Guide/User Guide/Collections/Calendar.md b/docs/User Guide/User Guide/Collections/Calendar.md
index af7bf0e27a..0b65562a5e 100644
--- a/docs/User Guide/User Guide/Collections/Calendar.md
+++ b/docs/User Guide/User Guide/Collections/Calendar.md
@@ -111,6 +111,18 @@ By default, a new event is a <a class="reference-link" href="../Note%20Types/Te
The dialog is not available on a read-only calendar, or on a calendar marked with `#calendarRoot` or `#workspaceCalendarRoot` (see [Using with the Journal / calendar](#using-with-the-journal--calendar)).
+### Event attributes
+
+Events can show the values of their attributes below their title, in the month view, and in the week and day views for all-day events and for timed ones tall enough to hold them. To choose which attributes are shown, open the <span class="tn-icon bx bx-cog"></span> _Calendar properties_ dialog (see [Event templates](#event-templates) for how to open it) and find _Event attributes_. It lists the <a class="reference-link" href="../Advanced%20Usage/Attributes/Promoted%20Attributes.md">Promoted Attributes</a> the calendar defines, and those its events define themselves. Here you can:
+
+* Turn an attribute on to show it on the events. New attributes are hidden until you turn them on, which keeps the calendar from getting cluttered.
+* Drag an attribute by its handle to change the order in which the events show them.
+* Create a new attribute, which is shown on the events right away, or edit or delete one the calendar defines.
+
+The dates, times and recurrence of the events are drawn by the calendar itself, so they are listed but cannot be switched on.
+
+If an event has a `#calendar:displayedAttributes` label, including one inherited from the calendar, the attributes listed in that label are shown instead.
+
## Configuring the calendar using attributes
The following attributes can be added to the Collection type:
@@ -171,7 +183,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:displayedAttributes` | Allows displaying the value of one or more attributes in the calendar like this:           <br> <br>![](6_Calendar_image.png)          <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:displayedAttributes` | Takes precedence over the [Event attributes](#event-attributes) chosen in the calendar's properties. Allows displaying the value of one or more attributes in the calendar, in the order given, like this:           <br> <br>![](6_Calendar_image.png)          <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. |
| `#calendar:startTime` | Similar to `#calendar:startDate`, allows changing the attribute which is being used to read the start time. |