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(share): spike mounting the app's geo map view on shared pages
Elian Doranecf4429d912d
diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex 316afb93a3..689a3d53e8 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -5,7 +5,7 @@ import type { ViewMode, ViewScope } from "./link.js";const SVG_MIME = "image/svg+xml";-export const isShare = !window.glob;+export const isShare = !window.glob || !!window.glob.isShare;/*** True when the client is showing a *pre-auth* SPA screen — the login screen (`loggedIn: false`),diff --git a/apps/client/vite-plugins.mts b/apps/client/vite-plugins.mtsindex 1c49d19d66..62c08f8ef9 100644--- a/apps/client/vite-plugins.mts+++ b/apps/client/vite-plugins.mts@@ -138,6 +138,10 @@ const LAZY_MODULES: Record<string, { specifier: string; importer: string }[]> =],calendar: [{ specifier: "./calendar_view.js", importer: "content/calendar.ts" }+ ],+ geomap: [+ { specifier: "./app_globals.js", importer: "content/geomap.ts" },+ { specifier: "./geomap_view.js", importer: "content/geomap.ts" }]};@@ -476,9 +480,14 @@ function collectFiles(bundle: Record<string, BundleOutput>, entries: string[], oreturn files;}-/** Sorts `files` and makes them relative to the manifest, checking they share its directory. */+/**+ * Sorts `files` and makes them relative to the manifest, checking they share its directory or are+ * in `assets/`. A chunk refers to a file there as `../assets/<file>`, which from+ * `/share/assets/` is the same directory, so both are listed by their name alone.+ */function toManifestPaths(files: string[]) {- const outside = files.filter((file) => posix.dirname(file) !== SHARE_THEME_DIR);+ const outside = files.filter((file) =>+ posix.dirname(file) !== SHARE_THEME_DIR && posix.dirname(file) !== "assets");if (outside.length) {const list = outside.join(", ");throw new Error(`The share theme's files must all be in '${SHARE_THEME_DIR}/': ${list}.`);diff --git a/apps/server/src/routes/assets.ts b/apps/server/src/routes/assets.tsindex 8b56d8f49a..95653ba358 100644--- a/apps/server/src/routes/assets.ts+++ b/apps/server/src/routes/assets.ts@@ -108,6 +108,7 @@ async function register(app: express.Application) {app.use(`/${assetUrlFragment}/translations/`, persistentCacheStatic(path.join(publicDir, "translations")));app.use(`/node_modules/`, persistentCacheStatic(path.join(publicDir, "node_modules")));app.use(`/share/assets/`, express.static(getShareThemeAssetDir(), STATIC_OPTIONS));+ app.use(`/share/assets/`, express.static(path.join(publicDir, "assets"), STATIC_OPTIONS));}app.use(`/pdfjs/`, persistentCacheStatic(getPdfjsAssetDir()));app.use(`/${assetUrlFragment}/images`, persistentCacheStatic(path.join(resourceDir, "assets", "images")));diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex d2cfeea321..10537c573e 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -1091,6 +1091,8 @@ export type BootstrapDefinition = {arch?: string;isElectron: boolean;isStandalone: boolean;+ /** Set by a shared page's boot script, which defines a `glob` of its own. */+ isShare?: boolean;/*** Absolute URL prefix for the WebSocket (e.g. `ws://127.0.0.1:8080/`),* sent by the desktop app because the renderer page lives on thediff --git a/packages/share-theme/src/content/app_globals.ts b/packages/share-theme/src/content/app_globals.tsnew file mode 100644index 0000000000..77b6363237--- /dev/null+++ b/packages/share-theme/src/content/app_globals.ts@@ -0,0 +1,3 @@+import $ from "jquery";++Object.assign(window, { $, jQuery: $ });diff --git a/packages/share-theme/src/content/geomap.ts b/packages/share-theme/src/content/geomap.tsnew file mode 100644index 0000000000..2b6719279a--- /dev/null+++ b/packages/share-theme/src/content/geomap.ts@@ -0,0 +1,15 @@+/**+ * Mounts the app's geo map view on the page, if it shows a geo map collection. The view brings the+ * app's context along, which expects jQuery as a global, so `app_globals.ts` loads first.+ */+export default async function setupGeoMap() {+ const container = document.querySelector<HTMLElement>("#content .share-geomap");+ const data = document.querySelector("#content .share-froca");+ if (!container || !data?.textContent) {+ return;+ }++ await import("./app_globals.js");+ const { default: mountGeoMap } = await import("./geomap_view.js");+ mountGeoMap(container, JSON.parse(data.textContent));+}diff --git a/packages/share-theme/src/content/geomap_view.css b/packages/share-theme/src/content/geomap_view.cssnew file mode 100644index 0000000000..0258619e0c--- /dev/null+++ b/packages/share-theme/src/content/geomap_view.css@@ -0,0 +1,5 @@+.share-geomap {+ position: relative;+ height: 70vh;+ margin-block: 1em;+}diff --git a/packages/share-theme/src/content/geomap_view.tsx b/packages/share-theme/src/content/geomap_view.tsxnew file mode 100644index 0000000000..2d9e761bc8--- /dev/null+++ b/packages/share-theme/src/content/geomap_view.tsx@@ -0,0 +1,56 @@+import "./geomap_view.css";++import froca from "@triliumnext/client/src/services/froca.js";+import options, { type OptionValue } from "@triliumnext/client/src/services/options.js";+import GeoView from "@triliumnext/client/src/widgets/collections/geomap/index.js";+import { render } from "preact";++import type { FrocaPayload } from "./calendar_view.js";++interface GeoMapPayload extends FrocaPayload {+ options: Record<string, OptionValue | null>;+}++/**+ * Loads the map's notes into froca and the display options into `options`, then mounts the app's+ * `GeoView` over them. A `#readOnly` label added to the collection's note turns off every editing+ * control the view has.+ */+export default function mountGeoMap(container: HTMLElement, payload: GeoMapPayload) {+ const { options: optionValues, links: _links, ...rows } = payload;+ options.load(Object.fromEntries(Object.entries(optionValues)+ .flatMap(([ name, value ]) => (value === null ? [] : [ [ name, value ] ]))));++ const noteId = container.dataset.noteId ?? "";+ froca.addResp({+ ...rows,+ attributes: [ ...rows.attributes, {+ attributeId: `${noteId}-share-readOnly`,+ noteId,+ type: "label",+ name: "readOnly",+ value: "",+ position: 0,+ isInheritable: false+ } ]+ });++ const note = froca.getNoteFromCache(noteId);+ if (!note) {+ return;+ }++ render(+ <GeoView+ note={note}+ notePath={noteId}+ noteIds={note.getChildNoteIds()}+ highlightedTokens={null}+ viewConfig={undefined}+ saveConfig={() => {}}+ media="screen"+ onReady={() => {}}+ />,+ container+ );+}diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.tsindex c07dba55a9..e65383eab3 100644--- a/packages/share-theme/src/index.ts+++ b/packages/share-theme/src/index.ts@@ -18,6 +18,7 @@ import "./content/adaptive_colors.css";import "./content/link_embed.css";import setupMath from "./content/math.js";import setupCalendar from "./content/calendar.js";+import setupGeoMap from "./content/geomap.js";import setupMermaid from "./content/mermaid.js";import "virtual:code-themes.css";import "@triliumnext/ckeditor5/src/theme/ck-content.css";@@ -73,6 +74,7 @@ document.addEventListener("DOMContentLoaded", () => {$try(setupMermaid);} else if (classList.contains("type-book")) {$try(setupCalendar);+ $try(setupGeoMap);}});diff --git a/packages/share-theme/src/templates/boot_script.ejs b/packages/share-theme/src/templates/boot_script.ejsindex 8ddf6bc89c..a463654835 100644--- a/packages/share-theme/src/templates/boot_script.ejs+++ b/packages/share-theme/src/templates/boot_script.ejs@@ -18,6 +18,7 @@root.classList.add(`theme-${theme}`, `theme-preference-${preference}`);window.glob = {+ isShare: true,isStatic: <%= !!isStatic %>,theme};diff --git a/packages/share-theme/src/templates/boot_script.spec.ts b/packages/share-theme/src/templates/boot_script.spec.tsindex 0b5477a942..1e9fe7b667 100644--- a/packages/share-theme/src/templates/boot_script.spec.ts+++ b/packages/share-theme/src/templates/boot_script.spec.ts@@ -11,7 +11,7 @@ describe("boot_script.ejs", () => {});expect([ ...classes ]).toStrictEqual([ "theme-dark", "theme-preference-dark" ]);- expect(context.glob).toEqual({ isStatic: true, theme: "dark" });+ expect(context.glob).toEqual({ isShare: true, isStatic: true, theme: "dark" });expect(() => runInContext(`const el = 1; let theme = 2; let root = 3;`, context)).not.toThrow();});diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex be3b6c0d36..0323ef9fdb 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -490,6 +490,9 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}} else if (note.type === "book" && !(note instanceof BNote)&& getViewType(note) === "calendar") {renderCalendar(result, note);+ } else if (note.type === "book" && !(note instanceof BNote)+ && getViewType(note) === "geoMap") {+ renderGeoMap(result, note);} else if (note.type === "book") {result.isEmpty = true;} else if (note.type === "webView") {@@ -908,6 +911,23 @@ function renderCalendar(result: Result, note: SNote) {+ `<script type="application/json" class="share-froca">${payload}</script>`;}+/**+ * Renders a geo map collection as an element the share theme's script mounts the app's whole map+ * view into, read-only, from the notes and the display options embedded next to it.+ */+function renderGeoMap(result: Result, note: SNote) {+ const payload = {+ ...buildFrocaPayload(note),+ options: Object.fromEntries(SHARED_OPTIONS.map((name) => [ name, options.getOptionOrNull(name) ]))+ };+ const json = JSON.stringify(payload).replace(/</g, "\\u003c");+ result.content = `<div class="share-geomap" data-note-id="${note.noteId}"></div>`+ + `<script type="application/json" class="share-froca">${json}</script>`;+}++/** The options the app's collection views read, which a shared page needs to draw them alike. */+const SHARED_OPTIONS = [ "locale", "formattingLocale", "firstDayOfWeek" ] as const;+/** The `data-*` attributes of a Mermaid note that label its viewer, and their translations. */const MERMAID_VIEWER_LABELS = {"label": "share_theme.diagram",