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
build(share): split the share theme's app bundle by view and note type
Elian Doran4d73698164a4
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 063927b838..92830139b2 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -33,7 +33,6 @@ import openService from "./open.js";import { waitForPendingRenders } from "./pending_renders.js";import protectedSessionService from "./protected_session.js";import protectedSessionHolder from "./protected_session_holder.js";-import renderService from "./render.js";import server from "./server.js";import { applySingleBlockSyntaxHighlight } from "./syntax_highlight.js";import { getErrorMessage } from "./utils.js";@@ -213,6 +212,7 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo} else if (type === "render" && entity instanceof FNote) {const $content = $("<div>");+ const { default: renderService } = await CONTENT_RENDERERS.render();await renderService.render(entity, $content, (e, noteId) => {showRenderError($content, e, noteId).catch((cardError) => console.error("Failed to render the script error card:", cardError));}, options.parentComponent);@@ -273,6 +273,29 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo};}+/**+ * The modules that render the content of a note type, which load only when a note of the type is+ * rendered. The app build reads the `import()` expressions of each entry to give the note type a+ * group of files in the share theme's manifest, `content:<key>`; the editors of an embed are kept+ * under keys of their own, which a read-only page never loads.+ */+const CONTENT_RENDERERS = {+ markdown: () => import("@triliumnext/commons/src/lib/markdown_renderer"),+ iconPack: () => import("../widgets/type_widgets/icon_pack/IconPackPreview"),+ image: () => import("../widgets/react/ImageViewer"),+ file: {+ canvasDrawing: () => import("../widgets/type_widgets/canvas/CanvasDrawing"),+ pdf: () => import("../widgets/type_widgets/file/PdfViewer"),+ media: () => import("../widgets/type_widgets/file/MediaPreview")+ },+ mermaid: () => import("mermaid"),+ render: () => import("./render.js"),+ webView: () => import("../widgets/type_widgets/WebView"),+ llmChat: () => import("../widgets/type_widgets/llm_chat/ChatPreview"),+ editableText: () => import("../widgets/type_widgets/text/TextEmbed"),+ editableCode: () => import("../widgets/type_widgets/code/CodeEmbed")+};+/*** Renders a text note, or the blocks of it that `options.block` points at, which `TextEmbed`* edits in place while the Editable toggle of its embed is on. Blocks that cannot be edited apart@@ -290,7 +313,7 @@ async function renderEditableText(};const [ blob, { default: TextEmbed } ] = await Promise.all([note.getBlob(),- import("../widgets/type_widgets/text/TextEmbed")+ CONTENT_RENDERERS.editableText()]);const content = blob?.content ?? "";const preview = await renderPreview(content);@@ -334,8 +357,7 @@ async function renderMarkdown(note: FNote | FAttachment, $renderedContent: JQuerreturn;}- // The markdown renderer pulls in marked, so it is only loaded when a markdown note is rendered.- const { renderToHtml } = await import("@triliumnext/commons/src/lib/markdown_renderer");+ const { renderToHtml } = await CONTENT_RENDERERS.markdown();const html = renderToHtml(source, note.title, {sanitize: (dirty) => DOMPurify.sanitize(dirty),wikiLink: { formatHref: (id) => `#root/${id}` }@@ -360,7 +382,7 @@ async function renderIconPack(note: FNote, $renderedContent: JQuery<HTMLElement>return;}- const { IconPackPreview } = await import("../widgets/type_widgets/icon_pack/IconPackPreview");+ const { IconPackPreview } = await CONTENT_RENDERERS.iconPack();const $container = $('<div class="icon-pack-rendered">');const container = $container.get(0);if (container) {@@ -391,7 +413,7 @@ async function renderCode(return;}- const { default: CodeEmbed } = await import("../widgets/type_widgets/code/CodeEmbed");+ const { default: CodeEmbed } = await CONTENT_RENDERERS.editableCode();const $container = $('<div class="code-embed">');const container = $container.get(0);if (container) {@@ -508,7 +530,7 @@ async function renderImageViewer(entity: FNote | FAttachment,$renderedContent: JQuery<HTMLElement>) {- const ImageViewer = (await import("../widgets/react/ImageViewer")).default;+ const ImageViewer = (await CONTENT_RENDERERS.image()).default;const $container = $('<div class="rendered-image-viewer">');const container = $container.get(0);if (container) {@@ -533,7 +555,7 @@ async function renderCanvasDrawing(options: RenderOptions) {const { default: CanvasDrawing, renderCanvasDrawingPicture } =- await import("../widgets/type_widgets/canvas/CanvasDrawing");+ await CONTENT_RENDERERS.file.canvasDrawing();if (options.interactive && entity instanceof FAttachment) {const $container = $('<div class="canvas-drawing">');@@ -602,7 +624,7 @@ async function renderFile(entity: FNote | FAttachment, type: string, $renderedCoif (type === "pdf") {const $viewer = $(`<div style="height: 100%">`);- const { default: PdfViewer, getPdfUrl } = await import("../widgets/type_widgets/file/PdfViewer");+ const { default: PdfViewer, getPdfUrl } = await CONTENT_RENDERERS.file.pdf();const url = getPdfUrl(`${entityType}/${entityId}/open`);render(h(PdfViewer, {pdfUrl: url, editable: false, toolbar: options.pdfToolbar ?? false}), $viewer.get(0)!);@@ -735,7 +757,7 @@ function getEntityTypeAndId(entity: FNote | FAttachment): { entityType: "notes"* {@link disposeInteractiveContent} — otherwise the Preact root leaks and its media keeps playing.*/async function renderMedia(entity: FNote | FAttachment, environment: MediaEnvironment, $content: JQuery<HTMLElement>) {- const MediaPreview = (await import("../widgets/type_widgets/file/MediaPreview")).default;+ const MediaPreview = (await CONTENT_RENDERERS.file.media()).default;const $container = $('<div class="rendered-media">');const container = $container.get(0);if (container) {@@ -745,7 +767,7 @@ async function renderMedia(entity: FNote | FAttachment, environment: MediaEnviro}async function renderMermaid(note: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>) {- const mermaid = (await import("mermaid")).default;+ const mermaid = (await CONTENT_RENDERERS.mermaid()).default;const blob = await note.getBlob();const content = blob?.content || "";@@ -772,7 +794,7 @@ async function renderMermaid(note: FNote | FAttachment, $renderedContent: JQuery* Loaded lazily so the widget (and its dependencies) are only pulled in when a web view is embedded.*/async function renderWebView(note: FNote, $renderedContent: JQuery<HTMLElement>) {- const WebView = (await import("../widgets/type_widgets/WebView")).default;+ const WebView = (await CONTENT_RENDERERS.webView()).default;const $container = $('<div class="note-detail-web-view">');const container = $container.get(0);if (container) {@@ -823,7 +845,7 @@ async function renderLlmChat(note: FNote, $renderedContent: JQuery<HTMLElement>,}if (messages.length === 0) return;- const ChatPreview = (await import("../widgets/type_widgets/llm_chat/ChatPreview")).default;+ const ChatPreview = (await CONTENT_RENDERERS.llmChat()).default;const $container = $('<div class="note-detail-llm-chat-preview">');const container = $container.get(0);if (!container) return;diff --git a/apps/client/vite-plugins.mts b/apps/client/vite-plugins.mtsindex 64309f62fc..5f738207cf 100644--- a/apps/client/vite-plugins.mts+++ b/apps/client/vite-plugins.mts@@ -1,8 +1,12 @@+import { readFile } from "node:fs/promises";import type { ServerResponse } from "node:http";import { join, posix } from "node:path";import { fileURLToPath } from "node:url";import type { ShareThemeManifest } from "@triliumnext/commons";+import {+ resolveShareThemeGroups, SHARE_HOSTED_NOTE_TYPES, SHARE_HOSTED_VIEW_TYPES+} from "@triliumnext/commons/src/lib/share_hosting.js";import {buildVsCodeThemeCss, VS_CODE_DARK, VS_CODE_LIGHT} from "@triliumnext/highlightjs/src/vs_code_theme.js";@@ -109,6 +113,9 @@ function replaceOnce(code: string, pattern: RegExp, replacer: (match: string, ../** The share theme's sources, which the app build bundles into the files shared pages load. */const SHARE_THEME_SRC = join(import.meta.dirname, "../../packages/share-theme/src");+/** The app's sources, whose views the share theme reuses. */+const CLIENT_SRC = join(import.meta.dirname, "src");+/*** The directory the share theme's files go to: the one the app's chunks go to, so the share theme* imports the chunks it shares with the app by their file name.@@ -130,22 +137,80 @@ const SHARE_THEME_TARGET = "chrome96";/*** The modules the share theme imports on demand that a share-theme export copies only for the* pages that use them, grouped by their name in {@link ShareThemeManifest.lazy}: mermaid, and the- * viewer a Mermaid note's diagram goes into.+ * viewer a Mermaid note's diagram goes into; the script API a render note runs its scripts with;+ * and what every app view loads first.*/const LAZY_MODULES: Record<string, { specifier: string; importer: string }[]> = {mermaid: [- { specifier: "mermaid", importer: "content/mermaid.ts" },- { specifier: "./zoom_viewer.js", importer: "content/mermaid.ts" }+ { specifier: "mermaid", importer: join(SHARE_THEME_SRC, "content/mermaid.ts") },+ { specifier: "./zoom_viewer.js", importer: join(SHARE_THEME_SRC, "content/mermaid.ts") }+ ],+ scripting: [+ {+ specifier: "./frontend_script_api.js",+ importer: join(CLIENT_SRC, "services/script_context.ts")+ }],app: [- { specifier: "./app_globals.js", importer: "content/app_view.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" }+ { specifier: "./app_globals.js", importer: join(SHARE_THEME_SRC, "content/app_view.ts") },+ {+ specifier: "@triliumnext/client/src/components/app_context.js",+ importer: join(SHARE_THEME_SRC, "content/app_view.ts")+ },+ {+ specifier: "@triliumnext/client/src/services/i18n.js",+ importer: join(SHARE_THEME_SRC, "content/app_view.ts")+ },+ { specifier: "./content/collection_view.js", importer: join(SHARE_THEME_SRC, "index.ts") },+ { specifier: "./content/note_view.js", importer: join(SHARE_THEME_SRC, "index.ts") }]};+/**+ * The tables of loaders by which the app picks the view of a collection or the widget of a note+ * type, each giving its keys a group of the manifest, `<prefix><key>`, of the modules the+ * `import()` expressions of `property` load. A later table replaces the groups of an earlier one.+ */+const TYPE_TABLES: LoaderTable[] = [+ {+ file: join(CLIENT_SRC, "widgets/collections/NoteList.tsx"),+ name: "ViewComponents",+ property: "normal",+ prefix: "view:"+ },+ {+ file: join(CLIENT_SRC, "widgets/note_types.tsx"),+ name: "TYPE_MAPPINGS",+ property: "view",+ prefix: "type:"+ },+ {+ file: join(SHARE_THEME_SRC, "content/note_view.tsx"),+ name: "SHARE_NOTE_VIEWS",+ prefix: "type:"+ },+ {+ file: join(CLIENT_SRC, "services/content_renderer.ts"),+ name: "CONTENT_RENDERERS",+ prefix: "content:"+ }+];++/**+ * The groups of {@link LAZY_MODULES} a page loads by what its content holds, such as a diagram or+ * a render note, which the share-theme export finds in the notes it writes.+ */+const CONTENT_GROUPS = [ "mermaid", "scripting" ];++interface LoaderTable {+ file: string;+ /** The variable holding the table, an object literal keyed by type. */+ name: string;+ /** The property of each entry whose `import()` expressions make the group, else the entry. */+ property?: string;+ prefix: string;+}+const CODE_THEMES_ID = "virtual:code-themes.css";interface ShareThemeOptions {@@ -298,18 +363,31 @@ async function emitShareTheme(config: ResolvedConfig | undefined,options: ShareThemeOptions) {- const lazyEntries: Record<string, string[]> = {};+ const resolve = async (specifier: string, importer: string) => {+ const resolved = await context.resolve(specifier, importer);+ if (!resolved) {+ throw new Error(`Unable to resolve '${specifier}' from ${importer}.`);+ }+ return resolved.id;+ };++ const groups: ShareThemeGroups = {+ shared: {}, byContent: CONTENT_GROUPS, typed: {}, gated: []+ };for (const [ name, modules ] of Object.entries(LAZY_MODULES)) {- lazyEntries[name] = [];- for (const { specifier, importer } of modules) {- const resolved = await context.resolve(specifier, join(SHARE_THEME_SRC, importer));- if (!resolved) {- const source = `'${specifier}' from the share theme's ${importer}`;- throw new Error(`Unable to resolve ${source}.`);- }- lazyEntries[name].push(resolved.id);+ groups.shared[name] = await Promise.all(modules.map(({ specifier, importer }) =>+ resolve(specifier, importer)));+ }+ for (const table of TYPE_TABLES) {+ const { entries, all } = await readLoaderTable(table);+ for (const [ key, specifiers ] of Object.entries(entries)) {+ groups.typed[`${table.prefix}${key}`] = await Promise.all(specifiers.map((specifier) =>+ resolve(specifier, table.file)));}+ groups.gated.push(...await Promise.all(all.map((specifier) =>+ resolve(specifier, table.file))));}+ checkHostedGroups(Object.keys(groups.typed));const [ tree, styles ] = await Promise.all([ buildTreeScript(config), buildStyles(config) ]);const emit = (fileName: string, source: string | Uint8Array) =>@@ -327,7 +405,7 @@ async function emitShareTheme(}const assetNames = styleAssets.map((asset) => asset.fileName);- const manifest = buildShareThemeManifest(bundle, lazyEntries, assetNames);+ const manifest = buildShareThemeManifest(bundle, groups, assetNames);emit(SHARE_THEME_MANIFEST_FILE, JSON.stringify(manifest));const { stubDir } = options;@@ -445,31 +523,67 @@ type BundleOutput =viteMetadata?: { importedCss: Set<string>; importedAssets: Set<string> };};+/** The modules of the share theme's groups of files, as the IDs the build resolves them to. */+export interface ShareThemeGroups {+ /** The groups a page loads whole when it needs them, such as `mermaid`, by their name. */+ shared: Record<string, string[]>;+ /**+ * The shared groups a page loads by what its content holds, such as `mermaid` for a diagram.+ * Reaching one of their modules adds them to a group's `requires` only from the group's own+ * modules.+ */+ byContent: string[];+ /** The groups a page loads by the type of what it shows, such as `view:<viewType>`. */+ typed: Record<string, string[]>;+ /**+ * Every module the type tables load, those of no group included, such as a print view. The+ * files of a group stop where they load one that is not their own on demand, as the type of a+ * note decides whether a page loads it.+ */+ gated: string[];+}+/*** Lists the files the share theme loads: the page's three files, `styleAssets` that `scripts.css`* references, and every chunk `scripts.js` loads, statically or on demand, with what each loads in* turn. The styles of the chunks `scripts.js` imports statically are in `scripts.css`, so their- * stylesheets are listed only when a chunk loaded on demand imports them, which preloads them. What- * only the modules in `lazyEntries` load is listed under the name of their group, each module given- * as the ID the build resolves it to.+ * stylesheets are listed only when a chunk loaded on demand imports them, which preloads them.+ *+ * What only the modules of a group in `groups` load is listed under the name of the group, without+ * the files of the groups it requires. The files of a group stop where they load the modules of+ * another group or of `groups.gated` on demand; loading those of a shared group adds that group to+ * the group's `requires`.*/export function buildShareThemeManifest(bundle: Record<string, BundleOutput>,- lazyEntries: Record<string, string[]>,+ groups: ShareThemeGroups,styleAssets: string[]): ShareThemeManifest {- const lazyChunks = new Map<string, string>();- for (const [ name, ids ] of Object.entries(lazyEntries)) {- for (const id of ids) {- const chunk = Object.values(bundle).find((output) =>- output.type === "chunk" && output.facadeModuleId === id);- if (!chunk) {- throw new Error(`The bundle has no chunk for '${id}' of the share theme's`- + ` '${name}'.`);- }- lazyChunks.set(chunk.fileName, name);+ const findChunk = (id: string, name: string) => {+ const chunk = Object.values(bundle).find((output) =>+ output.type === "chunk" && output.facadeModuleId === id);+ if (!chunk) {+ throw new Error(`The bundle has no chunk for '${id}' of the share theme's '${name}'.`);+ }+ return chunk.fileName;+ };++ const entries = new Map<string, string[]>();+ const sharedGroupOf = new Map<string, string>();+ for (const [ name, ids ] of Object.entries(groups.shared)) {+ const chunks = ids.map((id) => findChunk(id, name));+ entries.set(name, chunks);+ for (const chunk of chunks) {+ sharedGroupOf.set(chunk, name);}}+ for (const [ name, ids ] of Object.entries(groups.typed)) {+ entries.set(name, ids.map((id) => findChunk(id, name)));+ }+ const stops = new Set([+ ...[ ...entries.values() ].flat(),+ ...groups.gated.map((id) => findChunk(id, "type tables"))+ ]);const appOnly = new Set(Object.values(bundle).flatMap((output) =>(output.type === "chunk" && output.moduleIds?.some(isAppOnlyModule) ? [ output.fileName ] : [])));@@ -480,33 +594,184 @@ export function buildShareThemeManifest(});const files = new Set([...pageFiles,- ...collectFiles(bundle, onDemand, { dynamic: true, excluded: new Set([ ...lazyChunks.keys(), ...appOnly ]) }),+ ...collectFiles(bundle, onDemand, {+ dynamic: true, excluded: new Set([ ...stops, ...appOnly ])+ }),TREE_FILE,STYLES_FILE,...styleAssets]);+ const collected = new Map<string, Set<string>>();+ const requires: Record<string, string[]> = {};+ for (const [ name, own ] of entries) {+ const isShared = name in groups.shared;+ const required = new Set<string>();+ const groupFiles = new Set<string>();+ const pending: [ string, boolean ][] = own.map((fileName) => [ fileName, true ]);+ for (let item = pending.pop(); item !== undefined; item = pending.pop()) {+ const [ fileName, onDemand ] = item;+ const isOwn = own.includes(fileName);+ if (groupFiles.has(fileName)) {+ continue;+ }+ const output = bundle[fileName];+ if (files.has(fileName)) {+ // The group's chunks preload the stylesheets of the page's chunks they import,+ // which `scripts.css` holds and the page does not load apart.+ if (output?.type === "chunk") {+ for (const stylesheet of output.viteMetadata?.importedCss ?? []) {+ pending.push([ stylesheet, false ]);+ }+ }+ continue;+ }+ const sharedGroup = sharedGroupOf.get(fileName);+ if (sharedGroup !== undefined && sharedGroup !== name && (onDemand || isOwn)) {+ if (isOwn || !groups.byContent.includes(sharedGroup)) {+ required.add(sharedGroup);+ }+ continue;+ }+ const isGated = stops.has(fileName) || (isShared && appOnly.has(fileName));+ if (onDemand && !isOwn && isGated) {+ continue;+ }++ groupFiles.add(fileName);+ if (output?.type === "chunk") {+ const { importedAssets = [], importedCss = [] } = output.viteMetadata ?? {};+ for (const imported of [ ...output.imports, ...importedAssets, ...importedCss ]) {+ pending.push([ imported, false ]);+ }+ for (const imported of output.dynamicImports) {+ pending.push([ imported, true ]);+ }+ }+ }+ collected.set(name, groupFiles);+ requires[name] = [ ...required ].sort();+ }+const lazy: Record<string, string[]> = {};- for (const name of Object.keys(lazyEntries)) {- const chunks = [ ...lazyChunks ].flatMap(([ fileName, group ]) =>- (group === name ? [ fileName ] : []));- const lazyFiles = collectFiles(bundle, chunks, { dynamic: true, excluded: appOnly });- lazy[name] = toManifestPaths([ ...lazyFiles ].filter((file) => !files.has(file)));+ for (const [ name, groupFiles ] of collected) {+ const inherited = new Set(resolveShareThemeGroups(requires, [ name ]).flatMap((other) =>+ (other === name ? [] : [ ...collected.get(other) ?? [] ])));+ lazy[name] = toManifestPaths([ ...groupFiles ].filter((file) => !inherited.has(file)));+ }++ return { files: toManifestPaths([ ...files ]), lazy, requires };+}++/**+ * Reads the type table `table`: for each key, the specifiers of the `import()` expressions in its+ * entry's `property`, and every specifier the table imports.+ */+export async function readLoaderTable(table: LoaderTable) {+ const code = await readFile(table.file, "utf-8");+ const { program } = await parse(table.file, code);+ const declarator = program.body+ .flatMap((node) => {+ const declaration = node.type === "ExportNamedDeclaration" ? node.declaration : node;+ return declaration?.type === "VariableDeclaration" ? declaration.declarations : [];+ })+ .find((candidate) =>+ candidate.id.type === "Identifier" && candidate.id.name === table.name);+ let init: AstNode | null | undefined = declarator?.init as AstNode | null | undefined;+ while (init && (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression")) {+ init = init.expression as AstNode;+ }+ if (init?.type !== "ObjectExpression") {+ throw new Error(`${table.file} has no object literal '${table.name}' to read the types`+ + " from.");+ }++ const entries: Record<string, string[]> = {};+ for (const property of init.properties as AstNode[]) {+ const key = readPropertyKey(property);+ if (key === undefined) {+ throw new Error(`'${table.name}' in ${table.file} has an entry whose key is not a`+ + " literal.");+ }+ const value = property.value as AstNode;+ const properties = value.type === "ObjectExpression" ? value.properties as AstNode[] : [];+ const selected = table.property+ ? properties.find((inner) => readPropertyKey(inner) === table.property)?.value+ : value;+ entries[key] = selected ? collectImportSpecifiers(selected as AstNode) : [];}+ return { entries, all: collectImportSpecifiers(init) };+}++/** A node of the tree `parse()` returns, read loosely. */+type AstNode = { type: string; [key: string]: unknown };++function readPropertyKey(property: AstNode) {+ const key = property.key as AstNode | undefined;+ if (property.type !== "Property" || !key || property.computed) {+ return undefined;+ }+ if (key.type === "Identifier") {+ return key.name as string;+ }+ return key.type === "Literal" && typeof key.value === "string" ? key.value : undefined;+}++/** Returns the specifiers of the `import()` expressions below `node` that are string literals. */+function collectImportSpecifiers(node: AstNode) {+ const specifiers: string[] = [];+ const visit = (value: unknown) => {+ if (Array.isArray(value)) {+ for (const item of value) {+ visit(item);+ }+ return;+ }+ if (!value || typeof value !== "object" || !("type" in value)) {+ return;+ }+ const child = value as AstNode;+ const source = child.source as AstNode | undefined;+ if (child.type === "ImportExpression" && source?.type === "Literal"+ && typeof source.value === "string") {+ specifiers.push(source.value);+ }+ for (const [ key, nested ] of Object.entries(child)) {+ if (key !== "type") {+ visit(nested);+ }+ }+ };+ visit(node);+ return specifiers;+}- return { files: toManifestPaths([ ...files ]), lazy };+/**+ * Checks that every view type and note type core shows with an app view on a shared page has a+ * group among `groupNames`, so that a page of the type finds its files in an export.+ */+export function checkHostedGroups(groupNames: string[]) {+ const names = new Set(groupNames);+ const missing = [+ ...SHARE_HOSTED_VIEW_TYPES.map((type) => `view:${type}`),+ ...SHARE_HOSTED_NOTE_TYPES.map((type) => `type:${type}`)+ ].filter((name) => !names.has(name));+ if (missing.length) {+ throw new Error("The share theme hosts types with no group of files:"+ + ` ${missing.join(", ")}. Add them to a type table of \`TYPE_TABLES\`.`);+ }}/*** 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.+ * demand, on paths a shared page never takes unless it shows a type that needs them, 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",@@ -542,8 +807,9 @@ function collectFiles(bundle: Record<string, BundleOutput>, entries: string[], o/*** 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.+ * in `assets/`, such as a worker, which they list as `../assets/<file>`. A chunk refers to a file+ * there as `../assets/<file>`, which from `/share/assets/` and from an export's `assets/` is the+ * same directory, so an export writes both by their name alone.*/function toManifestPaths(files: string[]) {const outside = files.filter((file) =>@@ -552,5 +818,5 @@ function toManifestPaths(files: string[]) {const list = outside.join(", ");throw new Error(`The share theme's files must all be in '${SHARE_THEME_DIR}/': ${list}.`);}- return files.map((file) => posix.basename(file)).sort();+ return files.map((file) => posix.relative(SHARE_THEME_DIR, file)).sort();}diff --git a/apps/client/vite-plugins.spec.ts b/apps/client/vite-plugins.spec.tsindex fea6d41a98..493d9dace0 100644--- a/apps/client/vite-plugins.spec.ts+++ b/apps/client/vite-plugins.spec.ts@@ -1,12 +1,16 @@-import { readdirSync, readFileSync } from "fs";+import { SHARE_HOSTED_NOTE_TYPES, SHARE_HOSTED_VIEW_TYPES } from "@triliumnext/commons";+import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from "fs";import { createRequire } from "module";+import { tmpdir } from "os";import { dirname, join } from "path";import { describe, expect, it } from "vitest";import {buildShareThemeManifest,+ checkHostedGroups,ENGINE_RENDER_ENTRY,LANGUAGE_DETECTOR_PACKAGE,+ readLoaderTable,resolveUniverHyphenationStub,stripUniverEmojiSource,UI_ENTRY@@ -124,6 +128,11 @@ describe("stripUniverEmojiData", () => {describe("buildShareThemeManifest", () => {const MERMAID_ID = "/node_modules/mermaid/dist/mermaid.core.mjs";const VIEWER_ID = "/packages/share-theme/src/content/zoom_viewer.tsx";+ const COLLECTION_ID = "/packages/share-theme/src/content/collection_view.tsx";+ const SCRIPT_API_ID = "/apps/client/src/services/frontend_script_api.ts";+ const CALENDAR_ID = "/apps/client/src/widgets/collections/calendar/index.tsx";+ const GEOMAP_ID = "/apps/client/src/widgets/collections/geomap/index.tsx";+ const PRINT_ID = "/apps/client/src/widgets/collections/table/TablePrintView.tsx";const chunk = (fileName: string, extra: { facade?: string; imports?: string[];dynamicImports?: string[]; css?: string[]; assets?: string[] } = {}) => ({type: "chunk" as const,@@ -140,7 +149,10 @@ describe("buildShareThemeManifest", () => {const bundle = Object.fromEntries([chunk("src/scripts.js", {imports: [ "src/shared-a.js", "src/shared-k.js" ],- dynamicImports: [ "src/fuse-b.js", "src/mermaid.core-c.js", "src/zoom_viewer-l.js" ],+ dynamicImports: [+ "src/fuse-b.js", "src/mermaid.core-c.js", "src/zoom_viewer-l.js",+ "src/collection_view-n.js"+ ],css: [ "src/scripts-j.css" ]}),chunk("src/shared-a.js", { css: [ "src/shared-a.css" ] }),@@ -160,32 +172,88 @@ describe("buildShareThemeManifest", () => {chunk("src/dagre-f.js"),chunk("src/flowchart-g.js"),chunk("src/index-h.js", { imports: [ "src/shared-a.js" ] }),+ chunk("src/collection_view-n.js", {+ facade: COLLECTION_ID,+ imports: [ "src/NoteList-o.js" ]+ }),+ chunk("src/NoteList-o.js", {+ imports: [ "src/content_renderer-s.js" ],+ dynamicImports: [ "src/calendar-p.js", "src/geomap-q.js", "src/print-r.js" ]+ }),+ chunk("src/content_renderer-s.js", {+ dynamicImports: [ "src/mermaid.core-c.js", "src/script_api-t.js" ]+ }),+ chunk("src/script_api-t.js", { facade: SCRIPT_API_ID, imports: [ "src/ckeditor-w.js" ] }),+ chunk("src/ckeditor-w.js"),+ chunk("src/calendar-p.js", { facade: CALENDAR_ID, imports: [ "src/fullcalendar-v.js" ] }),+ chunk("src/fullcalendar-v.js"),+ chunk("src/geomap-q.js", {+ facade: GEOMAP_ID,+ imports: [ "src/NoteList-o.js", "src/zoom_viewer-l.js" ],+ dynamicImports: [ "src/collection_view-n.js" ],+ assets: [ "assets/worker-x.js" ]+ }),+ chunk("src/print-r.js", { facade: PRINT_ID }),...[ "scripts-j.css", "shared-a.css", "shared-k.css", "fuse-d.css", "font-e.woff2" ].map((name) => asset(`src/${name}`))].map((output) => [ output.fileName, output ]));+ const groups = {+ shared: {+ mermaid: [ MERMAID_ID, VIEWER_ID ],+ scripting: [ SCRIPT_API_ID ],+ app: [ COLLECTION_ID ]+ },+ byContent: [ "mermaid", "scripting" ],+ typed: { "view:calendar": [ CALENDAR_ID ], "view:geoMap": [ GEOMAP_ID ] },+ gated: [ CALENDAR_ID, GEOMAP_ID, PRINT_ID ]+ };- it("lists what every page loads apart from what only the modules of mermaid load", () => {+ it("lists what every page loads apart from what only the modules of each group load", () => {// The styles of the chunks `scripts.js` imports are in `scripts.css`, but a chunk loaded on// demand preloads the stylesheets of the chunks it imports.- const styleAssets = [ "src/KaTeX-i.woff2" ];- const lazyEntries = { mermaid: [ MERMAID_ID, VIEWER_ID ] };- const manifest = buildShareThemeManifest(bundle, lazyEntries, styleAssets);- expect(manifest).toEqual({- files: [- "KaTeX-i.woff2", "font-e.woff2", "fuse-b.js", "fuse-d.css", "scripts.css",- "scripts.js", "shared-a.css", "shared-a.js", "shared-k.js", "tree.js"- ],- lazy: {- mermaid: [- "dagre-f.js", "flowchart-g.js", "mermaid.core-c.js", "preact-m.js",- "shared-k.css", "zoom_viewer-l.js"- ]- }- });+ const manifest = buildShareThemeManifest(bundle, groups, [ "src/KaTeX-i.woff2" ]);+ expect(manifest.files).toEqual([+ "KaTeX-i.woff2", "font-e.woff2", "fuse-b.js", "fuse-d.css", "scripts.css",+ "scripts.js", "shared-a.css", "shared-a.js", "shared-k.js", "tree.js"+ ]);+ expect(manifest.lazy.mermaid).toEqual([+ "dagre-f.js", "flowchart-g.js", "mermaid.core-c.js", "preact-m.js", "shared-k.css",+ "zoom_viewer-l.js"+ ]);+ expect(manifest.lazy.scripting).toEqual([ "ckeditor-w.js", "script_api-t.js" ]);+ });++ it("stops a group where it loads another group on demand, requiring the shared ones", () => {+ const { lazy, requires } = buildShareThemeManifest(bundle, groups, []);++ // The note list loads every view and the content renderer loads the script API and mermaid+ // on demand, by the type and the content of a note, so none of them joins the app's files.+ expect(lazy.app)+ .toEqual([ "NoteList-o.js", "collection_view-n.js", "content_renderer-s.js" ]);+ expect(requires.app).toEqual([]);+ expect(lazy["view:calendar"]).toEqual([ "calendar-p.js", "fullcalendar-v.js" ]);+ expect(requires["view:calendar"]).toEqual([]);++ // The map loads the app on demand, so it requires it and leaves out the files the app+ // holds, and imports the viewer statically, which it then holds itself.+ // A worker the build writes to `assets/` is listed by its path from the manifest.+ expect(lazy["view:geoMap"])+ .toEqual([ "../assets/worker-x.js", "geomap-q.js", "preact-m.js", "zoom_viewer-l.js" ]);+ expect(requires["view:geoMap"]).toEqual([ "app" ]);+ expect(Object.values(lazy).flat()).not.toContain("print-r.js");+ });++ it("requires a shared group that is a group's own module, even one chosen by content", () => {+ const { lazy, requires } = buildShareThemeManifest(bundle,+ { ...groups, typed: { ...groups.typed, "type:mermaid": [ MERMAID_ID ] } }, []);++ expect(lazy["type:mermaid"]).toEqual([]);+ expect(requires["type:mermaid"]).toEqual([ "mermaid" ]);});- it("rejects a bundle without a library's chunk or with files outside one directory", () => {- expect(() => buildShareThemeManifest(bundle, { mermaid: [ "/elsewhere/mermaid.mjs" ] }, []))+ it("rejects a bundle without a group's chunk or with files outside one directory", () => {+ const withMermaid = (ids: string[]) => ({ ...groups, shared: { mermaid: ids } });+ expect(() => buildShareThemeManifest(bundle, withMermaid([ "/elsewhere/mermaid.mjs" ]), [])).toThrow("no chunk for '/elsewhere/mermaid.mjs' of the share theme's 'mermaid'");const nested = {@@ -193,11 +261,64 @@ describe("buildShareThemeManifest", () => {"src/fuse-b.js": chunk("src/fuse-b.js", { imports: [ "src/nested/k.js" ] }),"src/nested/k.js": chunk("src/nested/k.js")};- expect(() => buildShareThemeManifest(nested, { mermaid: [ MERMAID_ID ] }, []))+ expect(() => buildShareThemeManifest(nested, withMermaid([ MERMAID_ID ]), [])).toThrow("must all be in 'src/': src/nested/k.js");});});+describe("readLoaderTable", () => {+ const writeTable = (source: string) => {+ const file = join(mkdtempSync(join(tmpdir(), "loader-table-")), "table.tsx");+ writeFileSync(file, source);+ return file;+ };++ it("reads the imports of each entry's property, and of the whole table", async () => {+ const file = writeTable(`+ const VIEWS: Record<string, { normal: () => unknown; print?: () => unknown }> = {+ list: {+ normal: lazy(() => import("./list.js").then((m) => m.List)),+ print: () => import("./print.js")+ },+ "geo-map": { normal: async () => (await import("./geomap.js")).default },+ empty: { normal: () => (props: unknown) => <></> },+ inline: () => import("./inline.js")+ } satisfies Views;+ export const OTHER = { list: () => import("./other.js") };+ `);++ const table = { file, name: "VIEWS", property: "normal", prefix: "view:" };+ expect(await readLoaderTable(table)).toEqual({+ entries: { list: [ "./list.js" ], "geo-map": [ "./geomap.js" ], empty: [], inline: [] },+ all: [ "./list.js", "./print.js", "./geomap.js", "./inline.js" ]+ });+ expect((await readLoaderTable({ file, name: "OTHER", prefix: "type:" })).entries)+ .toEqual({ list: [ "./other.js" ] });+ });++ it("rejects a table it cannot read the types from", async () => {+ const file = writeTable(`const COMPUTED = { [key]: () => import("./a.js") };`);++ await expect(readLoaderTable({ file, name: "MISSING", prefix: "type:" }))+ .rejects.toThrow("has no object literal 'MISSING'");+ await expect(readLoaderTable({ file, name: "COMPUTED", prefix: "type:" }))+ .rejects.toThrow("has an entry whose key is not a literal");+ });+});++describe("checkHostedGroups", () => {+ it("accepts groups for every hosted type and names those missing one", () => {+ const all = [+ ...SHARE_HOSTED_VIEW_TYPES.map((type) => `view:${type}`),+ ...SHARE_HOSTED_NOTE_TYPES.map((type) => `type:${type}`)+ ];+ expect(() => checkHostedGroups(all)).not.toThrow();+ const partial = all.filter((name) => name !== "view:calendar" && name !== "type:noteMap");+ expect(() => checkHostedGroups(partial))+ .toThrow("hosts types with no group of files: view:calendar, type:noteMap.");+ });+});+/** Reads the generated `PATTERN_LOADERS` map, whose keys are the locales Univer hyphenates. */function patternLoaders(): { locale: string; source: string }[] {const entries = entrySource.matchAll(/\["([a-z0-9-]+)"\]\s*:\s*\(\)\s*=>\s*import\("(\.[^"]*)"\)/g);diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex 8665ebab70..e95e11d5ee 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -16,6 +16,7 @@ export * from "./lib/bulk_actions.js";export * from "./lib/server_api.js";export * from "./lib/shared_constants.js";export * from "./lib/shared_types.js";+export * from "./lib/share_hosting.js";export * from "./lib/ws_api.js";export * from "./lib/attribute_names.js";export * from "./lib/search_syntax.js";diff --git a/packages/commons/src/lib/share_hosting.spec.ts b/packages/commons/src/lib/share_hosting.spec.tsnew file mode 100644index 0000000000..c99a24fc38--- /dev/null+++ b/packages/commons/src/lib/share_hosting.spec.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from "vitest";++import { resolveShareThemeGroups } from "./share_hosting.js";++describe("share theme groups", () => {+ it("resolves the groups each group requires, transitively and once", () => {+ const requires = { a: [ "b" ], b: [ "c", "a" ], c: [] };++ expect(resolveShareThemeGroups(requires, [ "a" ]).sort()).toEqual([ "a", "b", "c" ]);+ expect(resolveShareThemeGroups(requires, [ "unknown" ])).toEqual([ "unknown" ]);+ });+});diff --git a/packages/commons/src/lib/share_hosting.ts b/packages/commons/src/lib/share_hosting.tsnew file mode 100644index 0000000000..62032ddc98--- /dev/null+++ b/packages/commons/src/lib/share_hosting.ts@@ -0,0 +1,35 @@+/**+ * The view types of the collections a shared page shows with the app's own view. The app build+ * checks that each has a `view:<viewType>` group in the share theme's manifest.+ */+export const SHARE_HOSTED_VIEW_TYPES: readonly string[] = [+ "board", "calendar", "dashboard", "geoMap", "presentation", "table"+];++/**+ * The note types a shared page shows with the app's own widget, or with a viewer of the share+ * theme. The app build checks that each has a `type:<noteType>` group in the share theme's+ * manifest.+ */+export const SHARE_HOSTED_NOTE_TYPES: readonly string[] = [+ "canvas", "image", "mermaid", "mindMap", "noteMap", "relationMap", "render", "spreadsheet"+];++/**+ * Returns `names` and every group they require in `requires`, directly or through the groups+ * they require, each once.+ */+export function resolveShareThemeGroups(+ requires: Record<string, string[]>,+ names: Iterable<string>+) {+ const resolved = new Set<string>();+ const pending = [ ...names ];+ for (let name = pending.pop(); name !== undefined; name = pending.pop()) {+ if (!resolved.has(name)) {+ resolved.add(name);+ pending.push(...requires[name] ?? []);+ }+ }+ return [ ...resolved ];+}diff --git a/packages/commons/src/lib/shared_types.ts b/packages/commons/src/lib/shared_types.tsindex 5572f72213..33974e4f26 100644--- a/packages/commons/src/lib/shared_types.ts+++ b/packages/commons/src/lib/shared_types.ts@@ -15,6 +15,12 @@ export interface Contributor {export interface ShareThemeManifest {/** The files every page can load. */files: string[];- /** The further files of each library loaded on demand, such as `mermaid`, by its name. */+ /**+ * The further files of each group loaded on demand, by its name: a library such as `mermaid`,+ * `app` for what every app view loads, `view:<viewType>` for a collection's view and+ * `type:<noteType>` for a note type's widget.+ */lazy: Record<string, string[]>;+ /** The other groups whose files each group loads, by its name. */+ requires: Record<string, string[]>;}diff --git a/packages/share-theme/src/content/note_view.tsx b/packages/share-theme/src/content/note_view.tsxindex daedc2934b..b7672fab36 100644--- a/packages/share-theme/src/content/note_view.tsx+++ b/packages/share-theme/src/content/note_view.tsx@@ -2,14 +2,14 @@ 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 NoteMap from "@triliumnext/client/src/widgets/note_map/NoteMap.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 { useNoteBlob } from "@triliumnext/client/src/widgets/react/hooks.js";import { RawHtmlBlock } from "@triliumnext/client/src/widgets/react/RawHtml.js";-import { render } from "preact";+import type RelationMapWidget from "@triliumnext/client/src/widgets/type_widgets/relation_map/RelationMap.js";+import { type ComponentType, render } from "preact";import { useEffect, useRef, useState } from "preact/hooks";-import type RelationMapWidget from "@triliumnext/client/src/widgets/type_widgets/relation_map/RelationMap.js";import ShareAppHost, { type AppPayload, type HostedApp } from "./app_host.js";import { drawMermaid, loadMermaid, readMermaidTheme } from "./mermaid.js";import { ZoomViewer } from "./zoom_viewer.js";@@ -29,22 +29,43 @@ export default function mountNoteView(container: HTMLElement, payload: AppPayloa);}+type SharedView = ComponentType<{ app: HostedApp }>;++/**+ * The views of the note types the share theme draws its own way, by type, each loading what it+ * draws with. The app build reads the `import()` of each entry to give the type its group of+ * files in the share theme's manifest; the other types use `TYPE_MAPPINGS`, read the same way.+ */+const SHARE_NOTE_VIEWS: Partial<Record<string, () => Promise<SharedView>>> = {+ image: async () => ImageView,+ canvas: async () => ImageView,+ mindMap: async () => ImageView,+ // Loads the library ahead of the view, which draws with it.+ mermaid: () => import("mermaid").then(() => MermaidView),+ noteMap: async () => {+ const { default: NoteMap } = await import(+ "@triliumnext/client/src/widgets/note_map/NoteMap.js");+ return ({ app }) => <NoteMapView app={app} NoteMap={NoteMap} />;+ },+ relationMap: async () => {+ const { default: RelationMap } = await import(+ "@triliumnext/client/src/widgets/type_widgets/relation_map/RelationMap.js");+ return ({ app }) => <RelationMapView app={app} RelationMap={RelationMap} />;+ }+};+function SharedNoteView({ app }: { app: HostedApp }) {- const { note } = app;- switch (note.type) {- case "image":- case "canvas":- case "mindMap":- return <ImageView note={note} />;- case "mermaid":- return <MermaidView note={note} />;- case "noteMap":- return <NoteMapView app={app} />;- case "relationMap":- return <RelationMapView app={app} />;- default:- return <NoteView note={note} />;+ 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} />;}+ return View && <View app={app} />;}function NoteView({ note }: { note: FNote }) {@@ -76,7 +97,7 @@ function NoteView({ note }: { note: FNote }) {* Shows the image the share serves for an image note, or the SVG a canvas or a mind map note keeps* of its drawing, in a viewer that takes the page.*/-function ImageView({ note }: { note: FNote }) {+function ImageView({ app: { note } }: { app: HostedApp }) {const src = `api/images/${note.noteId}/${encodeURIComponent(note.title)}?${note.blobId}`;return (<ZoomViewer labels={getZoomPanLabels("image_viewer.viewport")} fillsPage>@@ -89,7 +110,7 @@ function ImageView({ note }: { note: FNote }) {* Draws a Mermaid note the way the page draws the diagrams of a text note, in a viewer that takes* the page, and draws it again when the theme changes.*/-function MermaidView({ note }: { note: FNote }) {+function MermaidView({ app: { note } }: { app: HostedApp }) {const blob = useNoteBlob(note);const theme = useMermaidTheme();const [ svg, setSvg ] = useState<string>();@@ -120,7 +141,7 @@ function MermaidView({ note }: { note: FNote }) {* Draws a note map note's map, from the note's parent on the share unless the note names another* root, and opens a clicked note on its shared page.*/-function NoteMapView({ app }: { app: HostedApp }) {+function NoteMapView({ app, NoteMap }: { app: HostedApp; NoteMap: typeof NoteMapWidget }) {const containerRef = useRef<HTMLDivElement>(null);return (<div ref={containerRef} className="note-detail-note-map">@@ -136,15 +157,11 @@ function NoteMapView({ app }: { app: HostedApp }) {}/** Draws a relation map note's map, and opens a clicked note on its shared page. */-function RelationMapView({ app }: { app: HostedApp }) {- const [ RelationMap, setRelationMap ] = useState<typeof RelationMapWidget>();-- useEffect(() => {- import("@triliumnext/client/src/widgets/type_widgets/relation_map/RelationMap.js")- .then(({ default: widget }) => setRelationMap(() => widget));- }, []);-- return RelationMap && (+function RelationMapView({ app, RelationMap }: {+ app: HostedApp;+ RelationMap: typeof RelationMapWidget;+}) {+ return (<div className="note-detail-relation-map"><RelationMapnote={app.note}diff --git a/packages/trilium-core/src/services/export/zip/share_theme.spec.ts b/packages/trilium-core/src/services/export/zip/share_theme.spec.tsindex fd893997f4..2176b1c9ca 100644--- a/packages/trilium-core/src/services/export/zip/share_theme.spec.ts+++ b/packages/trilium-core/src/services/export/zip/share_theme.spec.ts@@ -352,7 +352,8 @@ describe("hasMermaidDiagrams", () => {describe("getShareThemeExportFiles", () => {const manifest = {files: [ "scripts.js", "scripts.css" ],- lazy: { mermaid: [ "mermaid.core-a.js" ] }+ lazy: { mermaid: [ "mermaid.core-a.js" ] },+ requires: {}};it("adds the files of mermaid only for a subtree with a diagram", () => {@@ -363,7 +364,7 @@ describe("getShareThemeExportFiles", () => {const withoutDiagram = subtreeOf({ type: "text", content: "<p>No diagram.</p>" });expect(getShareThemeExportFiles(manifest, withoutDiagram)).toEqual([ "scripts.js", "scripts.css" ]);- expect(getShareThemeExportFiles({ files: [ "scripts.js" ], lazy: {} },+ expect(getShareThemeExportFiles({ files: [ "scripts.js" ], lazy: {}, requires: {} },subtreeOf({ type: "text", content: diagram }))).toEqual([ "scripts.js" ]);});});diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex aca5bd9bdb..9332f0eb41 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -2,7 +2,7 @@ import {getAttachmentEmbedHref, getEmbedKey, getNestedEmbedOptions, getNoteEmbedHref, isHttpUrl,isImageAttachmentRole, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor, readLinkPreviewData,renderLinkEmbedHtml, renderLinkMentionHtml, resolveContentEmbed, resolveEnabledMimeTypes,- shouldSyntaxHighlight, sliceToBlockReference+ SHARE_HOSTED_NOTE_TYPES, SHARE_HOSTED_VIEW_TYPES, shouldSyntaxHighlight, sliceToBlockReference} from "@triliumnext/commons";import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";@@ -506,7 +506,7 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}} else if (note.type === "file") {renderFile(note, result);} else if (note.type === "book" && !(note instanceof BNote)- && HOSTED_VIEW_TYPES.has(getViewType(note) ?? "")) {+ && SHARE_HOSTED_VIEW_TYPES.includes(getViewType(note) ?? "")) {renderCollectionView(result, note, options.canAccessEmbed);} else if (note.type === "book") {result.isEmpty = true;@@ -940,7 +940,8 @@ function renderCollectionView(result: Result, note: SNote, canAccess: CanAccessE* keep the content alone.*/function hostNoteView(result: Result, note: SNote | BNote, canAccess: CanAccessEmbed | undefined) {- if (!(note instanceof BNote) && typeof result.content === "string" && !result.isEmpty) {+ if (!(note instanceof BNote) && typeof result.content === "string" && !result.isEmpty+ && SHARE_HOSTED_NOTE_TYPES.includes(note.type)) {hostInAppView(result, note, "share-note-view", canAccess);}}@@ -967,9 +968,6 @@ function hostInAppView(result: Result, note: SNote, container: string, canAccess+ `<script type="application/json" class="share-froca">${json}</script>`;}-/** The view types of the collections the share theme shows with the app's own view. */-const HOSTED_VIEW_TYPES = new Set([ "board", "calendar", "dashboard", "geoMap", "presentation", "table" ]);-/*** The options the app's views read to draw a note as the app does, which a shared page receives. Only* display options: the rest of the options can hold secrets, such as API keys.