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
refactor(share): host app views on shared pages through one component
Elian Doran9a85d4ab2be9
diff --git a/apps/client/vite-plugins.mts b/apps/client/vite-plugins.mtsindex 62c08f8ef9..62c9cb53da 100644--- a/apps/client/vite-plugins.mts+++ b/apps/client/vite-plugins.mts@@ -140,8 +140,8 @@ const LAZY_MODULES: Record<string, { specifier: string; importer: string }[]> ={ 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" }+ { specifier: "./app_globals.js", importer: "content/app_view.ts" },+ { specifier: "./content/geomap_view.js", importer: "index.ts" }]};diff --git a/packages/share-theme/src/content/app_host.tsx b/packages/share-theme/src/content/app_host.tsxnew file mode 100644index 0000000000..59d0b7ed8e--- /dev/null+++ b/packages/share-theme/src/content/app_host.tsx@@ -0,0 +1,100 @@+import appContext from "@triliumnext/client/src/components/app_context.js";+import Component from "@triliumnext/client/src/components/component.js";+import TabManager from "@triliumnext/client/src/components/tab_manager.js";+import type FNote from "@triliumnext/client/src/entities/fnote.js";+import froca from "@triliumnext/client/src/services/froca.js";+import options, { type OptionValue } from "@triliumnext/client/src/services/options.js";+import { ParentComponent } from "@triliumnext/client/src/widgets/react/react_utils.js";+import type { ComponentChildren } from "preact";+import { useLayoutEffect, useState } from "preact/hooks";++import { createShareFrocaSource, type ShareFrocaRows } from "./share_froca_source.js";++/** What core embeds next to an app view on a shared page. */+export interface AppPayload extends ShareFrocaRows {+ options: Record<string, OptionValue | null>;+ /** The view the collection saved, such as a map's position, for the view to start from. */+ viewConfig?: unknown;+}++export interface HostedApp {+ /** The note the page shows, read-only. */+ note: FNote;+ /** Opens a note on its shared page, in place of the app's own way. */+ openNote(noteId: string): void;+}++interface ShareAppHostProps {+ noteId: string;+ payload: AppPayload;+ children(app: HostedApp): ComponentChildren;+}++/**+ * Hosts app views on a shared page: fills `options` and froca from `payload`, has froca read any+ * other note from the share, marks the note `#readOnly` so the views leave out their editing+ * controls, starts the part of `appContext` the views rely on and mounts them under a component of+ * their own, as the app mounts every view.+ */+export default function ShareAppHost({ noteId, payload, children }: ShareAppHostProps) {+ const [ app ] = useState(() => loadPayload(noteId, payload));+ const [ component ] = useState(() => new Component());++ useLayoutEffect(() => {+ startAppContext();+ appContext.child(component);+ return () => appContext.removeChild(component);+ }, [ component ]);++ return app && (+ <ParentComponent.Provider value={component}>+ {children(app)}+ </ParentComponent.Provider>+ );+}++function loadPayload(noteId: string, payload: AppPayload): HostedApp | null {+ const { options: optionValues, links, viewConfig: _viewConfig, ...rows } = payload;+ options.load(Object.fromEntries(Object.entries(optionValues)+ .flatMap(([ name, value ]) => (value === null ? [] : [ [ name, value ] ]))));++ froca.setSource(createShareFrocaSource(links));+ 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 null;+ }++ return {+ note,+ openNote: (openedNoteId) => {+ const link = links[openedNoteId];+ if (link) {+ window.location.href = link;+ }+ }+ };+}++/**+ * Gives `appContext` the part of `start()` the views rely on, a `TabManager` for the note contexts+ * their panes register. The app's layout, commands and shortcuts are left out.+ */+function startAppContext() {+ if (!appContext.tabManager) {+ appContext.tabManager = new TabManager();+ appContext.child(appContext.tabManager);+ }+}diff --git a/packages/share-theme/src/content/app_view.ts b/packages/share-theme/src/content/app_view.tsnew file mode 100644index 0000000000..ebe8bc73ba--- /dev/null+++ b/packages/share-theme/src/content/app_view.ts@@ -0,0 +1,23 @@+import type { AppPayload } from "./app_host.js";++/** A module mounting an app view, which `setupAppView()` loads on demand. */+export interface AppViewModule {+ default(container: HTMLElement, payload: AppPayload): void;+}++/**+ * Mounts an app view on the page, if `#content` has its `container`, from the payload core embeds+ * beside it. The view brings the app's context along, which expects jQuery as a global, so+ * `app_globals.ts` loads before the view's module.+ */+export default async function setupAppView(container: string, load: () => Promise<AppViewModule>) {+ const element = document.querySelector<HTMLElement>(`#content ${container}`);+ const data = document.querySelector("#content .share-froca");+ if (!element || !data?.textContent) {+ return;+ }++ await import("./app_globals.js");+ const { default: mount } = await load();+ mount(element, JSON.parse(data.textContent));+}diff --git a/packages/share-theme/src/content/geomap.ts b/packages/share-theme/src/content/geomap.tsdeleted file mode 100644index 2b6719279a..0000000000--- a/packages/share-theme/src/content/geomap.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * 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.tsx b/packages/share-theme/src/content/geomap_view.tsxindex 667535d9d0..9e8b1394f0 100644--- a/packages/share-theme/src/content/geomap_view.tsx+++ b/packages/share-theme/src/content/geomap_view.tsx@@ -1,90 +1,28 @@import "./geomap_view.css";-import appContext from "@triliumnext/client/src/components/app_context.js";-import Component from "@triliumnext/client/src/components/component.js";-import TabManager from "@triliumnext/client/src/components/tab_manager.js";-import froca from "@triliumnext/client/src/services/froca.js";-import options, { type OptionValue } from "@triliumnext/client/src/services/options.js";import GeoView, { type MapData } from "@triliumnext/client/src/widgets/collections/geomap/index.js";-import { ParentComponent } from "@triliumnext/client/src/widgets/react/react_utils.js";import { render } from "preact";-import type { FrocaPayload } from "./calendar_view.js";-import { createShareFrocaSource } from "./share_froca_source.js";--interface GeoMapPayload extends FrocaPayload {- options: Record<string, OptionValue | null>;- viewConfig?: MapData;-}--/**- * Loads the map's notes into froca, which reads any other note from the share, and the display- * options into `options`, then mounts the app's `GeoView` over them, under a component of its own- * as the app mounts every view. 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, viewConfig, ...rows } = payload;- options.load(Object.fromEntries(Object.entries(optionValues)- .flatMap(([ name, value ]) => (value === null ? [] : [ [ name, value ] ]))));-- const noteId = container.dataset.noteId ?? "";- froca.setSource(createShareFrocaSource(links));- 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;- }+import ShareAppHost, { type AppPayload } from "./app_host.js";+/** Mounts the app's `GeoView` over the map's notes and its saved view. */+export default function mountGeoMap(container: HTMLElement, payload: AppPayload) {render(- <ParentComponent.Provider value={startAppContext()}>- <GeoView- note={note}- notePath={noteId}- noteIds={note.getChildNoteIds()}- highlightedTokens={null}- viewConfig={viewConfig}- saveConfig={() => {}}- media="screen"- onReady={() => {}}- onOpenNote={(openedNoteId) => openLink(links[openedNoteId])}- />- </ParentComponent.Provider>,+ <ShareAppHost noteId={container.dataset.noteId ?? ""} payload={payload}>+ {({ note, openNote }) => (+ <GeoView+ note={note}+ notePath={note.noteId}+ noteIds={note.getChildNoteIds()}+ highlightedTokens={null}+ viewConfig={payload.viewConfig as MapData | undefined}+ saveConfig={() => {}}+ media="screen"+ onReady={() => {}}+ onOpenNote={openNote}+ />+ )}+ </ShareAppHost>,container);}--/** Opens a note's shared page, which the map does in place of its detail pane. */-function openLink(link: string | undefined) {- if (link) {- window.location.href = link;- }-}--/**- * Gives `appContext` the part of `start()` that the view relies on, a `TabManager` for the note- * contexts its panes register, and returns a component under it for the view to mount below.- * The app's layout, commands and shortcuts are left out.- */-function startAppContext() {- if (!appContext.tabManager) {- appContext.tabManager = new TabManager();- appContext.child(appContext.tabManager);- }-- const component = new Component();- appContext.child(component);- return component;-}diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.tsindex e2e8d7b350..798827658b 100644--- a/packages/share-theme/src/index.ts+++ b/packages/share-theme/src/index.ts@@ -19,7 +19,7 @@ import "./content/link_embed.css";import "./content/collection_view.css";import setupMath from "./content/math.js";import setupCalendar from "./content/calendar.js";-import setupGeoMap from "./content/geomap.js";+import setupAppView from "./content/app_view.js";import setupMermaid from "./content/mermaid.js";import "virtual:code-themes.css";import "@triliumnext/ckeditor5/src/theme/ck-content.css";@@ -75,7 +75,7 @@ document.addEventListener("DOMContentLoaded", () => {$try(setupMermaid);} else if (classList.contains("type-book")) {$try(setupCalendar);- $try(setupGeoMap);+ $try(() => setupAppView(".share-geomap", () => import("./content/geomap_view.js")));}});