Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): render calendar collections with the app's calendar

Elian Doran8c6cd9be0e37
diff --git a/apps/client/vite-plugins.mts b/apps/client/vite-plugins.mts
index d1c78fdb3b..1c49d19d66 100644
--- a/apps/client/vite-plugins.mts
+++ b/apps/client/vite-plugins.mts
@@ -135,6 +135,9 @@ const LAZY_MODULES: Record<string, { specifier: string; importer: string }[]> =
mermaid: [
{ specifier: "mermaid", importer: "content/mermaid.ts" },
{ specifier: "./mermaid_zoom.js", importer: "content/mermaid.ts" }
+ ],
+ calendar: [
+ { specifier: "./calendar_view.js", importer: "content/calendar.ts" }
]
};
@@ -372,6 +375,7 @@ type BundleOutput =
type: "chunk";
fileName: string;
facadeModuleId: string | null;
+ moduleIds?: string[];
imports: string[];
dynamicImports: string[];
viteMetadata?: { importedCss: Set<string>; importedAssets: Set<string> };
@@ -403,6 +407,8 @@ export function buildShareThemeManifest(
}
}
+ const appOnly = new Set(Object.values(bundle).flatMap((output) =>
+ (output.type === "chunk" && output.moduleIds?.some(isAppOnlyModule) ? [ output.fileName ] : [])));
const pageFiles = collectFiles(bundle, [ SCRIPTS_FILE ], { dynamic: false });
const onDemand = [ ...pageFiles ].flatMap((fileName) => {
const output = bundle[fileName];
@@ -410,7 +416,7 @@ export function buildShareThemeManifest(
});
const files = new Set([
...pageFiles,
- ...collectFiles(bundle, onDemand, { dynamic: true, excluded: new Set(lazyChunks.keys()) }),
+ ...collectFiles(bundle, onDemand, { dynamic: true, excluded: new Set([ ...lazyChunks.keys(), ...appOnly ]) }),
TREE_FILE,
STYLES_FILE,
...styleAssets
@@ -420,13 +426,29 @@ export function buildShareThemeManifest(
for (const name of Object.keys(lazyEntries)) {
const chunks = [ ...lazyChunks ].flatMap(([ fileName, group ]) =>
(group === name ? [ fileName ] : []));
- const lazyFiles = collectFiles(bundle, chunks, { dynamic: true });
+ const lazyFiles = collectFiles(bundle, chunks, { dynamic: true, excluded: appOnly });
lazy[name] = toManifestPaths([ ...lazyFiles ].filter((file) => !files.has(file)));
}
return { files: toManifestPaths([ ...files ]), lazy };
}
+/**
+ * Whether `id` is one of the app's modules that the client code the share theme reuses imports on
+ * demand, on paths a shared page never takes, such as running a script note.
+ */
+function isAppOnlyModule(id: string) {
+ return APP_ONLY_MODULES.some((module) => id.endsWith(module));
+}
+
+const APP_ONLY_MODULES = [
+ "/apps/client/src/components/app_context.ts",
+ "/apps/client/src/services/search.ts",
+ "/apps/client/src/services/bundle.ts",
+ "/apps/client/src/services/backend_scripting.ts",
+ "/apps/client/src/services/dialog.ts"
+];
+
/**
* Collects `entries` and the chunks and assets they import, without descending into `excluded`.
* With `dynamic`, also the chunks they load on demand and the stylesheets they preload.
diff --git a/packages/share-theme/src/content/calendar.ts b/packages/share-theme/src/content/calendar.ts
new file mode 100644
index 0000000000..9935cfaeb2
--- /dev/null
+++ b/packages/share-theme/src/content/calendar.ts
@@ -0,0 +1,14 @@
+/**
+ * Draws the calendar collection on the page, if there is one, with the app's own calendar. The
+ * view and FullCalendar load on demand, as only a calendar page needs them.
+ */
+export default async function setupCalendar() {
+ const container = document.querySelector<HTMLElement>("#content .share-calendar");
+ const data = document.querySelector("#content .share-froca");
+ if (!container || !data?.textContent) {
+ return;
+ }
+
+ const { default: mountCalendar } = await import("./calendar_view.js");
+ await mountCalendar(container, JSON.parse(data.textContent));
+}
diff --git a/packages/share-theme/src/content/calendar_view.css b/packages/share-theme/src/content/calendar_view.css
new file mode 100644
index 0000000000..ef4d09ecad
--- /dev/null
+++ b/packages/share-theme/src/content/calendar_view.css
@@ -0,0 +1,3 @@
+.share-calendar {
+ margin-block: 1em;
+}
diff --git a/packages/share-theme/src/content/calendar_view.tsx b/packages/share-theme/src/content/calendar_view.tsx
new file mode 100644
index 0000000000..4fef7d3de2
--- /dev/null
+++ b/packages/share-theme/src/content/calendar_view.tsx
@@ -0,0 +1,69 @@
+import "fullcalendar/skeleton.css";
+import "fullcalendar/themes/forma/theme.css";
+import "@triliumnext/client/src/widgets/collections/calendar/palette.css";
+import "./calendar_view.css";
+
+import froca from "@triliumnext/client/src/services/froca.js";
+import Calendar from "@triliumnext/client/src/widgets/collections/calendar/calendar.js";
+import { buildEvents } from "@triliumnext/client/src/widgets/collections/calendar/event_builder.js";
+import type { EventClickInfo, EventInput, PluginInput } from "fullcalendar";
+import { render } from "preact";
+
+type SubtreeResponse = Parameters<typeof froca.addResp>[0];
+
+/** The notes of a calendar, as core's `buildFrocaPayload()` embeds them in the page. */
+export interface FrocaPayload extends SubtreeResponse {
+ links: Record<string, string>;
+}
+
+/**
+ * Loads the notes of the calendar into froca, so that the app's `buildEvents()` reads them as it
+ * does in the app, and draws the app's calendar from its events. A click on an event opens the
+ * note's shared page.
+ */
+export default async function mountCalendar(container: HTMLElement, payload: FrocaPayload) {
+ froca.addResp(payload);
+ const noteId = container.dataset.noteId ?? "";
+ const childNoteIds = froca.getNoteFromCache(noteId)?.getChildNoteIds() ?? [];
+ const [ events, plugins ] = await Promise.all([ buildEvents(childNoteIds), loadPlugins() ]);
+
+ render(<ShareCalendar events={events} plugins={plugins} links={payload.links} />, container);
+}
+
+interface ShareCalendarProps {
+ events: EventInput[];
+ plugins: PluginInput[];
+ links: Record<string, string>;
+}
+
+function ShareCalendar({ events, plugins, links }: ShareCalendarProps) {
+ const onEventClick = (info: EventClickInfo) => {
+ info.jsEvent.preventDefault();
+ const link = links[String(info.event.extendedProps.noteId)];
+ if (link) {
+ window.location.href = link;
+ }
+ };
+
+ return (
+ <Calendar
+ events={events}
+ plugins={plugins}
+ initialView="dayGridMonth"
+ headerToolbar={{ start: "title", end: "today prev,next" }}
+ height="auto"
+ editable={false}
+ eventClick={onEventClick}
+ />
+ );
+}
+
+/** The read-only subset of the plugins the app's calendar loads. */
+async function loadPlugins(): Promise<PluginInput[]> {
+ const modules = await Promise.all([
+ import("fullcalendar/themes/forma"),
+ import("fullcalendar/daygrid"),
+ import("@fullcalendar/rrule")
+ ]);
+ return modules.map((module) => module.default);
+}
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index 17a7a259cd..c07dba55a9 100644
--- a/packages/share-theme/src/index.ts
+++ b/packages/share-theme/src/index.ts
@@ -17,6 +17,7 @@ import "./content/task_states.css";
import "./content/adaptive_colors.css";
import "./content/link_embed.css";
import setupMath from "./content/math.js";
+import setupCalendar from "./content/calendar.js";
import setupMermaid from "./content/mermaid.js";
import "virtual:code-themes.css";
import "@triliumnext/ckeditor5/src/theme/ck-content.css";
@@ -70,6 +71,8 @@ document.addEventListener("DOMContentLoaded", () => {
setupTextNote();
} else if (classList.contains("type-mermaid")) {
$try(setupMermaid);
+ } else if (classList.contains("type-book")) {
+ $try(setupCalendar);
}
});
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 2a284c989b..be3b6c0d36 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -28,6 +28,7 @@ import options from "../services/options.js";
import * as sanitize from "../services/sanitizer.js";
import * as task_states from "../services/task_states.js";
import * as utils from "../services/utils/index.js";
+import { buildFrocaPayload } from "./froca_payload.js";
import { getShareProvider } from "./share_provider.js";
import SAttachment from "./shaca/entities/sattachment.js";
import SBranch from "./shaca/entities/sbranch.js";
@@ -486,6 +487,9 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}
renderImage(result, note);
} else if (note.type === "file") {
renderFile(note, result);
+ } else if (note.type === "book" && !(note instanceof BNote)
+ && getViewType(note) === "calendar") {
+ renderCalendar(result, note);
} else if (note.type === "book") {
result.isEmpty = true;
} else if (note.type === "webView") {
@@ -873,6 +877,37 @@ function renderMermaid(result: Result, note: SNote | BNote) {
</div>`;
}
+/**
+ * The view type of a collection: its own `#viewType`, else the one of a built-in template such as
+ * `_template_calendar`, which lives in the hidden subtree and so is never in shaca.
+ */
+function getViewType(note: SNote) {
+ const viewType = note.getLabelValue("viewType");
+ if (viewType) {
+ return viewType;
+ }
+
+ for (const relation of note.getOwnedRelations("template")) {
+ if (relation.value.startsWith("_template_")) {
+ const templateViewType = becca.getNote(relation.value)?.getLabelValue("viewType");
+ if (templateViewType) {
+ return templateViewType;
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Renders a calendar collection as an element the share theme's script draws the client's calendar
+ * into, from the notes `buildFrocaPayload()` embeds next to it.
+ */
+function renderCalendar(result: Result, note: SNote) {
+ const payload = JSON.stringify(buildFrocaPayload(note)).replace(/</g, "\\u003c");
+ result.content = `<div class="share-calendar" data-note-id="${note.noteId}"></div>`
+ + `<script type="application/json" class="share-froca">${payload}</script>`;
+}
+
/** The `data-*` attributes of a Mermaid note that label its viewer, and their translations. */
const MERMAID_VIEWER_LABELS = {
"label": "share_theme.diagram",
diff --git a/packages/trilium-core/src/share/froca_payload.ts b/packages/trilium-core/src/share/froca_payload.ts
new file mode 100644
index 0000000000..6ca9ac7076
--- /dev/null
+++ b/packages/trilium-core/src/share/froca_payload.ts
@@ -0,0 +1,69 @@
+import { getShareLink } from "@triliumnext/share-theme/model/page";
+
+import * as sanitize from "../services/sanitizer.js";
+import type SNote from "./shaca/entities/snote.js";
+
+/**
+ * The notes a collection view reads, as the rows the client's `froca.addResp()` takes, so that the
+ * share page builds the same `FNote`s the app does. `links` maps each note to its share link.
+ */
+export interface FrocaPayload {
+ notes: ReturnType<typeof getNoteRow>[];
+ branches: ReturnType<SNote["parentBranches"][number]["getPojo"]>[];
+ attributes: ReturnType<SNote["ownedAttributes"][number]["getPojo"]>[];
+ links: Record<string, string>;
+}
+
+/**
+ * Collects `note`, its visible children and the notes their relations point to (templates and
+ * `#calendar:title` relations), with their owned attributes and the branches between them.
+ * Shaca holds only shared notes, so a relation to a note outside the share is left out.
+ */
+export function buildFrocaPayload(note: SNote): FrocaPayload {
+ const notes = new Map<string, SNote>();
+ const add = (candidate: SNote | null | undefined) => {
+ if (candidate && !candidate.isProtected) {
+ notes.set(candidate.noteId, candidate);
+ }
+ };
+
+ add(note);
+ for (const child of note.getVisibleChildNotes()) {
+ add(child);
+ }
+ for (const owner of [ ...notes.values() ]) {
+ for (const relation of owner.ownedAttributes) {
+ if (relation.type === "relation") {
+ add(relation.targetNote);
+ }
+ }
+ }
+
+ const payload: FrocaPayload = { notes: [], branches: [], attributes: [], links: {} };
+ for (const included of notes.values()) {
+ payload.notes.push(getNoteRow(included));
+ payload.links[included.noteId] = getShareLink(included, sanitize.sanitizeUrl).href;
+ for (const branch of included.parentBranches) {
+ if (notes.has(branch.parentNoteId)) {
+ payload.branches.push(branch.getPojo());
+ }
+ }
+ for (const attribute of included.ownedAttributes) {
+ if (attribute.type === "label" || notes.has(attribute.value)) {
+ payload.attributes.push(attribute.getPojo());
+ }
+ }
+ }
+ return payload;
+}
+
+function getNoteRow(note: SNote) {
+ return {
+ noteId: note.noteId,
+ title: note.title,
+ isProtected: note.isProtected,
+ type: note.type,
+ mime: note.mime,
+ blobId: note.utcDateModified
+ };
+}
diff --git a/packages/trilium-core/src/share/shaca/entities/sbranch.ts b/packages/trilium-core/src/share/shaca/entities/sbranch.ts
index d06aaf39cd..37696947af 100644
--- a/packages/trilium-core/src/share/shaca/entities/sbranch.ts
+++ b/packages/trilium-core/src/share/shaca/entities/sbranch.ts
@@ -54,6 +54,18 @@ class SBranch extends AbstractShacaEntity {
getParentNote() {
return this.parentNote;
}
+
+ getPojo() {
+ return {
+ branchId: this.branchId,
+ noteId: this.noteId,
+ parentNoteId: this.parentNoteId,
+ notePosition: this.parentNote.children.indexOf(this.childNote) * 10,
+ prefix: this.prefix,
+ isExpanded: this.isExpanded,
+ fromSearchNote: false
+ };
+ }
}
export default SBranch;