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
fix(share): keep a shared note's content when its view fails to load
Elian Doran304211fe4c45
diff --git a/packages/share-theme/src/content/app_view.ts b/packages/share-theme/src/content/app_view.tsindex 41a4b6c1c5..35e85e2f60 100644--- a/packages/share-theme/src/content/app_view.ts+++ b/packages/share-theme/src/content/app_view.ts@@ -4,7 +4,7 @@ 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;+ default(container: HTMLElement, payload: AppPayload): void | Promise<void>;}/**@@ -48,5 +48,5 @@ async function mountAppView(container: string, load: () => Promise<AppViewModuleawait initLocale((payload.options.locale as LOCALE_IDS | null) ?? "en");const { default: mount } = await load();- mount(element, payload);+ await mount(element, payload);}diff --git a/packages/share-theme/src/content/note_view.spec.tsx b/packages/share-theme/src/content/note_view.spec.tsxnew file mode 100644index 0000000000..9899ca5e66--- /dev/null+++ b/packages/share-theme/src/content/note_view.spec.tsx@@ -0,0 +1,74 @@+// @vitest-environment happy-dom+import type { ComponentChildren } from "preact";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { AppPayload, HostedApp } from "./app_host.js";+import mountNoteView from "./note_view.js";++const { loadCodeView } = vi.hoisted(() => ({ loadCodeView: vi.fn() }));++// The real modules reach `window.glob`, which only the app's boot script defines.+vi.mock("@triliumnext/client/src/services/i18n.js", () => ({ t: (key: string) => key }));+vi.mock("@triliumnext/client/src/widgets/react/hooks.js", () => ({ useNoteBlob: () => null }));+vi.mock("@triliumnext/client/src/widgets/note_types.js", () => ({+ TYPE_MAPPINGS: { code: { view: loadCodeView, className: "note-detail-code" } }+}));++vi.mock("./app_host.js", () => ({+ default: ({ noteId, children }: {+ noteId: string;+ children(app: HostedApp): ComponentChildren;+ }) =>+ children({ note: { noteId, type: "code" }, parentNoteId: null } as unknown as HostedApp)+}));++describe("mountNoteView", () => {+ afterEach(() => {+ document.body.replaceChildren();+ loadCodeView.mockReset();+ });++ it("replaces the rendered content with the note's widget once the widget loads", async () => {+ loadCodeView.mockResolvedValue({ default: () => <p className="widget">Widget</p> });+ const container = buildContainer();++ await act(() => mountNoteView(container, buildPayload()));++ expect(container.querySelector(".note-detail-code > p.widget")?.textContent).toBe("Widget");+ expect(container.querySelector("p.fallback")).toBeNull();+ });++ it("keeps the rendered content when the widget fails to load", async () => {+ loadCodeView.mockRejectedValue(new Error("Failed to fetch dynamically imported module"));+ const container = buildContainer();++ await act(async () => {+ await expect(mountNoteView(container, buildPayload()))+ .rejects.toThrow("Failed to fetch");+ });++ expect(container.querySelector("p.fallback")?.textContent).toBe("Rendered");+ expect(container.querySelector(".note-detail-code")).toBeNull();+ });+});++function buildContainer() {+ const container = document.createElement("div");+ container.dataset.noteId = "codeNote";+ container.innerHTML = `<p class="fallback">Rendered</p>`;+ document.body.append(container);+ return container;+}++function buildPayload() {+ return {+ notes: [ { noteId: "codeNote", type: "code" } ],+ branches: [],+ attributes: [],+ links: {},+ options: {},+ assetPath: "",+ parentNoteId: null+ } as unknown as AppPayload;+}diff --git a/packages/share-theme/src/content/note_view.tsx b/packages/share-theme/src/content/note_view.tsxindex 38549527bf..09c05749ec 100644--- a/packages/share-theme/src/content/note_view.tsx+++ b/packages/share-theme/src/content/note_view.tsx@@ -1,10 +1,9 @@import "@triliumnext/client/src/widgets/type_widgets/NoteMap.css";-import type FNote from "@triliumnext/client/src/entities/fnote.js";import { t } from "@triliumnext/client/src/services/i18n.js";import { getNoteImageUrl } from "@triliumnext/client/src/services/image_urls.js";import type NoteMapWidget from "@triliumnext/client/src/widgets/note_map/NoteMap.js";-import { TYPE_MAPPINGS, type TypeWidget } from "@triliumnext/client/src/widgets/note_types.js";+import { TYPE_MAPPINGS } from "@triliumnext/client/src/widgets/note_types.js";import { useNoteBlob } from "@triliumnext/client/src/widgets/react/hooks.js";import { RawHtmlBlock } from "@triliumnext/client/src/widgets/react/RawHtml.js";import type RelationMapWidget from "@triliumnext/client/src/widgets/type_widgets/relation_map/RelationMap.js";@@ -18,13 +17,16 @@ import { ZoomViewer } from "./zoom_viewer.js";/*** Mounts the note in place of the content the page rendered for visitors without scripts: an* image, a canvas, a mind map or a Mermaid note's diagram in a viewer that pans and zooms it, any- * other note with the app's own widget for its type, read-only.+ * other note with the app's own widget for its type, read-only. The rendered content stays until+ * the view has loaded, and stays for good if the view fails to load.*/-export default function mountNoteView(container: HTMLElement, payload: AppPayload) {+export default async function mountNoteView(container: HTMLElement, payload: AppPayload) {+ const noteId = container.dataset.noteId ?? "";+ const View = await loadView(payload.notes.find((note) => note.noteId === noteId)?.type);container.replaceChildren();render(- <ShareAppHost noteId={container.dataset.noteId ?? ""} payload={payload}>- {(app) => <SharedNoteView app={app} />}+ <ShareAppHost noteId={noteId} payload={payload}>+ {(app) => <View app={app} />}</ShareAppHost>,container);@@ -55,35 +57,20 @@ const SHARE_NOTE_VIEWS: Partial<Record<string, () => Promise<SharedView>>> = {}};-function SharedNoteView({ app }: { app: HostedApp }) {- const load = SHARE_NOTE_VIEWS[app.note.type];- const [ View, setView ] = useState<SharedView>();-- useEffect(() => {- load?.().then((view) => setView(() => view));- }, [ load ]);-- if (!load) {- return <NoteView note={app.note} />;+/** The view of a note of `type`, once the files it draws with have loaded. */+async function loadView(type: string | undefined): Promise<SharedView> {+ const load = type ? SHARE_NOTE_VIEWS[type] : undefined;+ if (load) {+ return load();}- return View && <View app={app} />;-}-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 && (+ const mapping = TYPE_MAPPINGS[type as keyof typeof TYPE_MAPPINGS];+ const view = await mapping.view();+ const Widget = "default" in view ? view.default : view;+ return ({ app }) => (<div className={mapping.className}><Widget- note={note}+ note={app.note}viewScope={undefined}ntxId={null}parentComponent={undefined}