Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): show a shared Mermaid note in the app's own editor, read-only

Elian Dorand8d46beca9e9
diff --git a/apps/client/vite-plugins.mts b/apps/client/vite-plugins.mts
index bc534d83f3..9c34a10e31 100644
--- a/apps/client/vite-plugins.mts
+++ b/apps/client/vite-plugins.mts
@@ -136,9 +136,12 @@ const LAZY_MODULES: Record<string, { specifier: string; importer: string }[]> =
{ specifier: "mermaid", importer: "content/mermaid.ts" },
{ specifier: "./mermaid_zoom.js", importer: "content/mermaid.ts" }
],
- collection: [
+ app: [
{ specifier: "./app_globals.js", importer: "content/app_view.ts" },
- { specifier: "./content/collection_view.js", importer: "index.ts" }
+ { specifier: "@triliumnext/client/src/components/app_context.js", importer: "content/app_view.ts" },
+ { specifier: "@triliumnext/client/src/services/i18n.js", importer: "content/app_view.ts" },
+ { specifier: "./content/collection_view.js", importer: "index.ts" },
+ { specifier: "./content/note_view.js", importer: "index.ts" }
]
};
diff --git a/packages/share-theme/src/content/app_host.tsx b/packages/share-theme/src/content/app_host.tsx
index e30378389a..44bc5df210 100644
--- a/packages/share-theme/src/content/app_host.tsx
+++ b/packages/share-theme/src/content/app_host.tsx
@@ -3,6 +3,8 @@ 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 LoadResults from "@triliumnext/client/src/services/load_results.js";
+import noteAttributeCache from "@triliumnext/client/src/services/note_attribute_cache.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";
@@ -13,6 +15,8 @@ import { createShareFrocaSource, type ShareFrocaRows } from "./share_froca_sourc
/** What core embeds next to an app view on a shared page. */
export interface AppPayload extends ShareFrocaRows {
options: Record<string, OptionValue | null>;
+ /** Where the app's assets are, such as the translations its views read. */
+ assetPath: string;
}
export interface HostedApp {
@@ -51,6 +55,35 @@ export default function ShareAppHost({ noteId, payload, children }: ShareAppHost
);
}
+/**
+ * Sets a label on a note for this page only, as a visitor cannot change notes: froca takes the new
+ * value and the views hear of it as they hear of a change in the app, through `entitiesReloaded`.
+ */
+export function setLocalLabel(noteId: string, name: string, value: string) {
+ const row = {
+ attributeId: `${noteId}-share-${name}`,
+ noteId,
+ type: "label" as const,
+ name,
+ value,
+ position: 0,
+ isInheritable: false
+ };
+ froca.addResp({ notes: [], branches: [], attributes: [ row ] });
+ noteAttributeCache.invalidate();
+
+ const loadResults = new LoadResults([ {
+ entityName: "attributes",
+ entityId: row.attributeId,
+ entity: { ...row, isDeleted: false },
+ hash: "",
+ isSynced: false,
+ isErased: false
+ } ]);
+ loadResults.addAttribute(row.attributeId, "share");
+ appContext.triggerEvent("entitiesReloaded", { loadResults });
+}
+
function loadPayload(noteId: string, payload: AppPayload): HostedApp | null {
const { options: optionValues, links, ...rows } = payload;
options.load(Object.fromEntries(Object.entries(optionValues)
diff --git a/packages/share-theme/src/content/collection_view.css b/packages/share-theme/src/content/app_view.css
similarity index 80%
rename from packages/share-theme/src/content/collection_view.css
rename to packages/share-theme/src/content/app_view.css
index 13ad7f996c..231200af69 100644
--- a/packages/share-theme/src/content/collection_view.css
+++ b/packages/share-theme/src/content/app_view.css
@@ -1,4 +1,4 @@
-body:has(#content.collection-view) {
+body:has(#content.app-view) {
#right-pane {
height: 100vh;
}
@@ -17,14 +17,14 @@ body:has(#content.collection-view) {
min-height: 0;
}
- #content > .share-collection {
+ #content > :is(.share-collection, .share-note-view) {
position: relative;
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
- > .note-list-widget {
+ > :is(.note-list-widget, .note-detail-mermaid) {
flex: 1;
min-height: 0;
}
diff --git a/packages/share-theme/src/content/app_view.ts b/packages/share-theme/src/content/app_view.ts
index 5b68cd69d5..0afb2dd3ed 100644
--- a/packages/share-theme/src/content/app_view.ts
+++ b/packages/share-theme/src/content/app_view.ts
@@ -1,3 +1,5 @@
+import type { LOCALE_IDS } from "@triliumnext/commons";
+
import type { AppPayload } from "./app_host.js";
/** A module mounting an app view, which `setupAppView()` loads on demand. */
@@ -19,8 +21,17 @@ export default async function setupAppView(container: string, load: () => Promis
return;
}
+ const payload = JSON.parse(data.textContent) as AppPayload;
await import("./app_globals.js");
await import("@triliumnext/client/src/components/app_context.js");
+
+ // The views' texts come from the app's catalogue, which `initLocale()` reads from the assets.
+ if (window.glob) {
+ window.glob.assetPath = payload.assetPath;
+ }
+ const { initLocale } = await import("@triliumnext/client/src/services/i18n.js");
+ await initLocale((payload.options.locale as LOCALE_IDS | null) ?? "en");
+
const { default: mount } = await load();
- mount(element, JSON.parse(data.textContent));
+ mount(element, payload);
}
diff --git a/packages/share-theme/src/content/note_view.tsx b/packages/share-theme/src/content/note_view.tsx
new file mode 100644
index 0000000000..f169cd8e08
--- /dev/null
+++ b/packages/share-theme/src/content/note_view.tsx
@@ -0,0 +1,80 @@
+import type FNote from "@triliumnext/client/src/entities/fnote.js";
+import { t } from "@triliumnext/client/src/services/i18n.js";
+import { TYPE_MAPPINGS, type TypeWidget } from "@triliumnext/client/src/widgets/note_types.js";
+import { useNoteLabel } from "@triliumnext/client/src/widgets/react/hooks.js";
+import OverlayControlGroup, {
+ OverlayControlButton
+} from "@triliumnext/client/src/widgets/react/OverlayControlGroup.js";
+import {
+ type DisplayMode, resolveDisplayMode
+} from "@triliumnext/client/src/widgets/type_widgets/helpers/split_editor_mode.js";
+import { render } from "preact";
+import { useEffect, useState } from "preact/hooks";
+
+import ShareAppHost, { type AppPayload, setLocalLabel } from "./app_host.js";
+
+/**
+ * Mounts the app's own widget for the note's type, read-only, in place of the content the page
+ * rendered for visitors without scripts.
+ */
+export default function mountNoteView(container: HTMLElement, payload: AppPayload) {
+ container.replaceChildren();
+ render(
+ <ShareAppHost noteId={container.dataset.noteId ?? ""} payload={payload}>
+ {({ note }) => <NoteView note={note} />}
+ </ShareAppHost>,
+ container
+ );
+}
+
+function NoteView({ note }: { note: FNote }) {
+ const [ Widget, setWidget ] = useState<TypeWidget>();
+ const mapping = TYPE_MAPPINGS[note.type as keyof typeof TYPE_MAPPINGS];
+
+ useEffect(() => {
+ Promise.resolve(mapping.view()).then((view) => {
+ const widget = "default" in view ? view.default : view;
+ setWidget(() => widget);
+ });
+ }, [ mapping ]);
+
+ return Widget && (
+ <div className={mapping.className}>
+ <Widget
+ note={note}
+ viewScope={undefined}
+ ntxId={null}
+ parentComponent={undefined}
+ noteContext={undefined}
+ isVisible
+ />
+ {note.type === "mermaid" && <DisplayModeSwitcher note={note} />}
+ </div>
+ );
+}
+
+/** The app's choice of source, split or preview, which a visitor makes for this page only. */
+function DisplayModeSwitcher({ note }: { note: FNote }) {
+ const [ displayMode ] = useNoteLabel(note, "displayMode");
+ const mode = resolveDisplayMode(displayMode, true);
+
+ return (
+ <OverlayControlGroup className="share-display-mode" placement="top-end">
+ {DISPLAY_MODES.map(({ value, icon, text }) => (
+ <OverlayControlButton
+ key={value}
+ icon={icon}
+ title={t(text)}
+ active={mode === value}
+ onClick={() => setLocalLabel(note.noteId, "displayMode", value)}
+ />
+ ))}
+ </OverlayControlGroup>
+ );
+}
+
+const DISPLAY_MODES: { value: DisplayMode; icon: string; text: string }[] = [
+ { value: "source", icon: "bx bx-code", text: "display_mode.source" },
+ { value: "split", icon: "bx bxs-dock-left", text: "display_mode.split" },
+ { value: "preview", icon: "bx bx-show", text: "display_mode.preview" }
+];
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index 72caf40b20..674bad428b 100644
--- a/packages/share-theme/src/index.ts
+++ b/packages/share-theme/src/index.ts
@@ -16,7 +16,7 @@ import "./content/external_links.css";
import "./content/task_states.css";
import "./content/adaptive_colors.css";
import "./content/link_embed.css";
-import "./content/collection_view.css";
+import "./content/app_view.css";
import setupMath from "./content/math.js";
import setupAppView from "./content/app_view.js";
import setupMermaid from "./content/mermaid.js";
@@ -70,6 +70,8 @@ document.addEventListener("DOMContentLoaded", () => {
const { classList } = document.body;
if (classList.contains("type-text") || document.querySelector("#content.ck-content")) {
setupTextNote();
+ } else if (document.querySelector("#content .share-note-view")) {
+ $try(() => setupAppView(".share-note-view", () => import("./content/note_view.js")));
} else if (classList.contains("type-mermaid")) {
$try(setupMermaid);
} else if (classList.contains("type-book")) {
diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.ts
index fb785de592..54c55eebbb 100644
--- a/packages/share-theme/src/model/page.spec.ts
+++ b/packages/share-theme/src/model/page.spec.ts
@@ -437,9 +437,9 @@ describe("getContentClasses", () => {
.toBe("type-file full-content-width");
});
- it("gives a collection view the full width", () => {
+ it("gives an app view the full width", () => {
expect(getContentClasses(fakeNote({ noteId: "map", type: "book" }), false, true))
- .toBe("type-book full-content-width collection-view");
+ .toBe("type-book full-content-width app-view");
});
});
diff --git a/packages/share-theme/src/model/page.ts b/packages/share-theme/src/model/page.ts
index b5d4f34fa4..8a7253b35c 100644
--- a/packages/share-theme/src/model/page.ts
+++ b/packages/share-theme/src/model/page.ts
@@ -343,16 +343,16 @@ export function getShareLink(note: ShareNote, sanitizeUrl: (url: string) => stri
* with `#fullContentWidth` or of a type the app always shows at full width, and `no-content` when
* empty. A Markdown note reads as text, so its type does not make it full width.
*/
-export function getContentClasses(note: ShareNote, isEmpty = false, isCollectionView = false) {
+export function getContentClasses(note: ShareNote, isEmpty = false, isAppView = false) {
const isEditorContent = note.type === "text"
|| (note.type === "code" && note.mime === "text/x-markdown");
const isFullWidth = (!isEditorContent && isFullWidthNoteType(note.type, note.mime))
- || note.isLabelTruthy("fullContentWidth") || isCollectionView;
+ || note.isLabelTruthy("fullContentWidth") || isAppView;
return [
`type-${note.type}`,
isEditorContent && "ck-content",
isFullWidth && "full-content-width",
- isCollectionView && "collection-view",
+ isAppView && "app-view",
isEmpty && "no-content"
].filter(Boolean).join(" ");
}
diff --git a/packages/share-theme/src/types.d.ts b/packages/share-theme/src/types.d.ts
index 5c3a3d736f..6576b6f961 100644
--- a/packages/share-theme/src/types.d.ts
+++ b/packages/share-theme/src/types.d.ts
@@ -3,8 +3,11 @@ declare module "katex/contrib/mhchem" {}
interface Window {
/** Set by `boot_script.ejs` before the first paint. */
glob?: {
+ isShare: boolean;
isStatic: boolean;
theme: string;
+ /** Set by `setupAppView()` for the app's views, which read their translations from it. */
+ assetPath?: string;
};
}
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index d9cf4e7ceb..05243e6c10 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -1014,14 +1014,22 @@ describe("content_renderer", () => {
mime: "text/vnd.mermaid",
content: "graph TD; A-->B[<script>]"
});
- const root = parse(String(getContent(note).content));
- const container = root.querySelector("div.mermaid-note");
+ const result = getContent(note);
+ const root = parse(String(result.content));
+ const container = root.querySelector("div.share-note-view > div.mermaid-note");
+ expect(result.isAppView).toBe(true);
+ expect(root.querySelector("div.share-note-view")?.getAttribute("data-note-id"))
+ .toBe("mermaidNote");
expect(container?.querySelector("img.mermaid-note-image")?.getAttribute("src"))
.toMatch(/^api\/images\/mermaidNote\//);
expect(container?.querySelector("details pre.mermaid-note-source")?.textContent)
.toBe("graph TD; A-->B[<script>]");
- expect(root.querySelector("script")).toBeNull();
+ // The only script is the payload the app's view reads, which the browser never runs.
+ const scripts = root.querySelectorAll("script");
+ expect(scripts.map((script) => script.getAttribute("type"))).toEqual([ "application/json" ]);
+ expect(JSON.parse(scripts[0].textContent).notes.map((row: { noteId: string }) => row.noteId))
+ .toContain("mermaidNote");
expect([ "label", "zoom-in", "zoom-out", "zoom-reset" ]
.map((name) => container?.getAttribute(`data-${name}`)))
.toEqual([ "Diagram", "Zoom in", "Zoom out", "Reset zoom" ]);
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 8c38276da2..d4967bd213 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -60,10 +60,11 @@ export interface Result {
/** Set to `true` if the provided content should be rendered as empty. */
isEmpty?: boolean;
/**
- * Set to `true` if the content is a collection view, such as a map, which takes the page
- * without the title, the subpages, the date and the links to the neighboring pages.
+ * Set to `true` if the content is shown with the app's own view, such as a map or a Mermaid
+ * note's editor, which takes the page without the title, the subpages, the date and the links
+ * to the neighboring pages.
*/
- isCollectionView?: boolean;
+ isAppView?: boolean;
}
interface Subroot {
@@ -242,7 +243,7 @@ interface IconPackFont {
function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs) {
// Static export preserves full embed nesting; the live share view renders only the first level.
- const { header, content, isEmpty, isCollectionView } = getContent(note, {
+ const { header, content, isEmpty, isAppView } = getContent(note, {
expandNestedEmbeds: renderArgs.isStatic,
canAccessEmbed: renderArgs.canAccessEmbed
});
@@ -258,7 +259,7 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)
sanitizeUrl: sanitize.sanitizeUrl,
iconPackPrefixes: renderArgs.iconPackSupportedPrefixes
});
- const childLinks = isCollectionView ? [] : getChildLinks(note, {
+ const childLinks = isAppView ? [] : getChildLinks(note, {
sanitizeUrl: sanitize.sanitizeUrl,
iconPackPrefixes: renderArgs.iconPackSupportedPrefixes,
getText: (child) => getExcerptSource(child as SNote | BNote),
@@ -280,17 +281,17 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)
head: getPageHead(note, siteRoot),
snippets: getHtmlSnippets(note),
logo,
- prevNext: isCollectionView ? { previous: null, next: null } : getPrevNextLinks(note, siteRoot),
+ prevNext: isAppView ? { previous: null, next: null } : getPrevNextLinks(note, siteRoot),
navigation,
childLinks,
childLinksLayout: getChildLinksLayout(note),
- contentClasses: getContentClasses(note, isEmpty, isCollectionView),
+ contentClasses: getContentClasses(note, isEmpty, isAppView),
language: getPageLanguages(note, {
displayLanguage,
defaultContentLanguage: options.getOptionOrNull("defaultContentLanguage")
}),
- lastUpdated: isCollectionView ? null : getLastUpdated(note, displayLanguage),
- showTitle: !isCollectionView,
+ lastUpdated: isAppView ? null : getLastUpdated(note, displayLanguage),
+ showTitle: !isAppView,
fontPreloads: getFontPreloads(renderArgs.iconPackFonts, [
logo.icon,
...getNavigationIcons(navigation),
@@ -489,6 +490,9 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}
renderCode(result, note.mime);
} else if (note.type === "mermaid") {
renderMermaid(result, note);
+ if (!(note instanceof BNote) && typeof result.content === "string") {
+ hostInAppView(result, note, "share-note-view");
+ }
} else if (["image", "canvas", "mindMap"].includes(note.type)) {
renderImage(result, note);
} else if (note.type === "file") {
@@ -909,13 +913,26 @@ function getViewType(note: SNote) {
* element to mount it into, beside the notes and the display options it starts from.
*/
function renderCollectionView(result: Result, note: SNote) {
+ result.content = "";
+ hostInAppView(result, note, "share-collection");
+}
+
+/**
+ * Wraps the content in a `container` the share theme's script mounts an app view into, beside the
+ * notes and the display options the view starts from. The content stays for a visitor without
+ * scripts until the view replaces it.
+ */
+function hostInAppView(result: Result, note: SNote, container: string) {
const payload = {
...buildFrocaPayload(note),
- options: Object.fromEntries(SHARED_OPTIONS.map((name) => [ name, options.getOptionOrNull(name) ]))
+ options: Object.fromEntries(SHARED_OPTIONS.map((name) => [ name, options.getOptionOrNull(name) ])),
+ // The app's assets, such as its translations, from a page directly below `/share/`.
+ assetPath: `../${utils.isDev() ? `${assetUrlFragment}/src` : assetUrlFragment}`
};
const json = JSON.stringify(payload).replace(/</g, "\\u003c");
- result.isCollectionView = true;
- result.content = `<div class="share-collection" data-note-id="${note.noteId}"></div>`
+ result.isAppView = true;
+ const content = String(result.content ?? "");
+ result.content = `<div class="${container}" data-note-id="${note.noteId}">${content}</div>`
+ `<script type="application/json" class="share-froca">${json}</script>`;
}