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
perf(share): preload the icon fonts the page's own icons use
Elian Doranb17046fac49d
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.htmlindex 464cee06f9..8c3b655c17 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.html@@ -155,6 +155,14 @@<td>Resolved favicon and logo URLs. Without <code>~shareLogo</code>, <code>logoUrl</code> isthe Trilium logo.</td></tr>+ <tr>+ <td><code>fontPreloads</code>+ </td>+ <td>The icon fonts to preload, each with <code>href</code> and <code>type</code> (the+ font's media type): Boxicons, and the icon packs used by the logo, the+ navigation tree or the subpages. The default template adds a <code><link rel="preload" as="font" crossorigin></code> for+ each, so that the icons do not appear only after the first paint.</td>+ </tr><tr><td><code>isStatic</code></td>diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md b/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.mdindex d602cdc77c..34aae3fbef 100644--- a/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing/Custom share template.md@@ -43,6 +43,7 @@ Your template is rendered with a context object exposing the note and its render| `subRoot` | The root of the shared subtree as `{ note, branch }` — handy for a site-wide title or logo. || `cssToLoad` / `jsToLoad` | Arrays of stylesheet / script URLs the default theme would inject (includes anything added via `~shareCss` / `~shareJs`). || `faviconUrl` / `logoUrl` | Resolved favicon and logo URLs. Without `~shareLogo`, `logoUrl` is the Trilium logo. |+| `fontPreloads` | The icon fonts to preload, each with `href` and `type` (the font's media type): Boxicons, and the icon packs used by the logo, the navigation tree or the subpages. The default template adds a `<link rel="preload" as="font" crossorigin>` for each, so that the icons do not appear only after the first paint. || `isStatic` | `true` during a static HTML export, `false` for a live server render. || `t` | The `i18next` translation function. || `utils` | Helper utilities such as `slugify()` and `stripTags()`. |diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejsindex 04c7d30bd0..ac62204cca 100644--- a/packages/share-theme/src/templates/page.ejs+++ b/packages/share-theme/src/templates/page.ejs@@ -6,6 +6,9 @@<meta name="viewport" content="width=device-width, initial-scale=1"><link rel="shortcut icon" href="<%= faviconUrl %>">+ <% for (const font of fontPreloads) { %>+ <link rel="preload" href="<%= font.href %>" as="font" type="<%= font.type %>" crossorigin>+ <% } %><% for (const url of cssToLoad) { %><link href="<%= url %>" rel="stylesheet"><% } %>diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex d6321f9826..d1497585a8 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -1434,6 +1434,7 @@ describe("content_renderer", () => {faviconUrl: "",iconPackCss: "",iconPackSupportedPrefixes: [],+ fontPreloads: [],head: getPageHead(note, note),snippets: getHtmlSnippets(note),logo: getSiteLogo(note, { sanitizeUrl: sanitize.sanitizeUrl, image: null }),@@ -1518,6 +1519,31 @@ describe("content_renderer pages", () => {expect(css).not.toContain("privateFont");});+ it("preloads the fonts of the icon packs the page's own icons use", () => {+ buildShareNote({ id: "usedPackManifest", content: "{}" });+ buildShareNote({ id: "unusedPackManifest", content: "{}" });+ const builtinPacks = iconPackService.getIconPacks();+ vi.spyOn(iconPackService, "getIconPacks").mockReturnValue([+ ...builtinPacks,+ customIconPack("used", "usedPackManifest"),+ customIconPack("unused", "unusedPackManifest")+ ]);++ const page = parse(String(renderNoteContent(buildSitePage({+ "content": "<p>x</p>",+ "#iconClass": "used used-star"+ }))));+ const preloads = page.querySelectorAll("link[rel=preload]").map((tag) => [+ tag.getAttribute("href"), tag.getAttribute("as"), tag.getAttribute("type"),+ tag.hasAttribute("crossorigin")+ ]);++ expect(preloads).toStrictEqual([+ [ "assets/fonts/boxicons.woff2", "font", "font/woff2", true ],+ [ "api/attachments/usedFont/download", "font", "font/woff2", true ]+ ]);+ });+it("renders a page with its ~shareTemplate and the template's child notes", () => {vi.spyOn(getShareProvider(), "isScriptingEnabled").mockReturnValue(true);const setDevMode = mockDevMode();@@ -1718,6 +1744,8 @@ describe("content_renderer pages", () => {]);expect(page.querySelector("#trilium-icon-packs")?.text).toContain("../assets/icon-pack-bx.");+ expect(page.querySelectorAll("link[rel=preload]").map((tag) => tag.getAttribute("href")))+ .toStrictEqual([ "../assets/icon-pack-bx.woff2" ]);const [ other, file ] = page.querySelectorAll("#content a");expect(other.getAttribute("href")).toBe("./exportOther");expect(file.hasAttribute("href")).toBe(false);diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 15a6df5c2d..a1529113cf 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -10,7 +10,7 @@ import { getLanguage, highlight, highlightAuto, syncMimeTypes } from "@triliumneimport {getChildLinks, getChildLinksLayout, getContentClasses, getHtmlSnippets, getLastUpdated, getNavigationTree, getPageHead, getPageLanguages,getPrevNextLinks, getShareLink, getSiteAncestorIds, getSiteLogo, getTableOfContents,- type PageHeading+ type NavigationItem, type PageHeading} from "@triliumnext/share-theme/model/page";import ejs from "ejs";import escapeHtml from "escape-html";@@ -116,14 +116,7 @@ export function renderNoteForExport(note: BNote, parentBranch: BBranch, basePathfaviconUrl: `${basePath}favicon.ico`,ancestors,isStatic: true,- iconPackCss: [- ...iconPacks.map(p => iconPackService.generateCss(p, `${basePath}assets/icon-pack-${p.prefix.toLowerCase()}.${iconPackService.MIME_TO_EXTENSION_MAPPINGS[p.fontMime]}`)),- iconPackService.generateIconTransformCss(),- task_states.generateTaskStateCss()- ]- .filter(Boolean)- .join("\n\n"),- iconPackSupportedPrefixes: iconPacks.map(p => p.prefix)+ ...getIconPackArgs(iconPacks, (p) => `${basePath}assets/icon-pack-${p.prefix.toLowerCase()}.${iconPackService.MIME_TO_EXTENSION_MAPPINGS[p.fontMime]}`)});}@@ -167,18 +160,53 @@ export function renderNoteContent(note: SNote, canAccessEmbed?: CanAccessEmbed)isStatic: false,canAccessEmbed,faviconUrl: note.hasRelation("shareFavicon") ? `api/notes/${note.getRelationValue("shareFavicon")}/download` : `../favicon.ico`,+ ...getIconPackArgs(iconPacks, (p) => p.builtin+ ? `assets/fonts/${p.fontAttachmentId}.${iconPackService.MIME_TO_EXTENSION_MAPPINGS[p.fontMime]}`+ : `api/attachments/${p.fontAttachmentId}/download`)+ });+}++/**+ * Returns the render arguments of the icon packs `iconPacks`, whose fonts `getFontUrl` locates: their+ * CSS, their prefixes and their fonts.+ */+function getIconPackArgs(+ iconPacks: iconPackService.ProcessedIconPack[],+ getFontUrl: (iconPack: iconPackService.ProcessedIconPack) => string+) {+ const fonts = iconPacks.map((iconPack) => ({ iconPack, url: getFontUrl(iconPack) }));+ return {iconPackCss: [- ...iconPacks.map(p => iconPackService.generateCss(p, p.builtin- ? `assets/fonts/${p.fontAttachmentId}.${iconPackService.MIME_TO_EXTENSION_MAPPINGS[p.fontMime]}`- : `api/attachments/${p.fontAttachmentId}/download`- )),+ ...fonts.map(({ iconPack, url }) => iconPackService.generateCss(iconPack, url)),iconPackService.generateIconTransformCss(),task_states.generateTaskStateCss()].filter(Boolean).join("\n\n"),- iconPackSupportedPrefixes: iconPacks.map(p => p.prefix)- });+ iconPackSupportedPrefixes: iconPacks.map((iconPack) => iconPack.prefix),+ iconPackFonts: fonts.map(({ iconPack, url }) => ({+ prefix: iconPack.prefix,+ href: url,+ type: iconPack.fontMime+ }))+ };+}++/**+ * Returns the fonts of `fonts` to preload: Boxicons, which the theme's own controls use, and every+ * pack one of `iconClasses` (the icons of the page's logo, tree and subpages) belongs to. A pack+ * only the content uses loads when the content is laid out, as without a preload, since Chrome+ * warns about a preload the page does not use.+ */+function getFontPreloads(fonts: IconPackFont[], iconClasses: string[]) {+ const usedPrefixes = new Set([ "bx", ...iconClasses.flatMap((classes) => classes.split(/\s+/)) ]);+ return fonts+ .filter((font) => usedPrefixes.has(font.prefix))+ .map(({ href, type }) => ({ href, type }));+}++function getNavigationIcons(items: NavigationItem[]): string[] {+ return items.flatMap((item) => [ item.icon, ...getNavigationIcons(item.children) ]);}interface RenderArgs {@@ -195,6 +223,15 @@ interface RenderArgs {faviconUrl: string;iconPackCss: string;iconPackSupportedPrefixes: string[];+ /** The font of each icon pack, which the page preloads when its own icons use the pack. */+ iconPackFonts: IconPackFont[];+}++interface IconPackFont {+ prefix: string;+ href: string;+ /** The font's media type. */+ type: string;}function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs) {@@ -206,6 +243,20 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)const showLoginInShareTheme = options.getOptionBool("showLoginInShareTheme");const siteRoot = renderArgs.subRoot.note;const displayLanguage = options.getOptionOrNull("locale") || "en";+ const logo = getSiteLogo(siteRoot, {+ sanitizeUrl: sanitize.sanitizeUrl,+ image: renderArgs.logoImageUrl ?? null,+ iconPackPrefixes: renderArgs.iconPackSupportedPrefixes+ });+ const navigation = getNavigationTree(siteRoot, note, renderArgs.ancestors, {+ sanitizeUrl: sanitize.sanitizeUrl,+ iconPackPrefixes: renderArgs.iconPackSupportedPrefixes+ });+ const childLinks = getChildLinks(note, {+ sanitizeUrl: sanitize.sanitizeUrl,+ iconPackPrefixes: renderArgs.iconPackSupportedPrefixes,+ getText: (child) => getExcerptSource(child as SNote | BNote, renderArgs.canAccessEmbed)+ });const opts = {note,header,@@ -220,21 +271,10 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)sanitizeUrl: sanitize.sanitizeUrl,head: getPageHead(note, siteRoot),snippets: getHtmlSnippets(note),- logo: getSiteLogo(siteRoot, {- sanitizeUrl: sanitize.sanitizeUrl,- image: renderArgs.logoImageUrl ?? null,- iconPackPrefixes: renderArgs.iconPackSupportedPrefixes- }),+ logo,prevNext: getPrevNextLinks(note, siteRoot),- navigation: getNavigationTree(siteRoot, note, renderArgs.ancestors, {- sanitizeUrl: sanitize.sanitizeUrl,- iconPackPrefixes: renderArgs.iconPackSupportedPrefixes- }),- childLinks: getChildLinks(note, {- sanitizeUrl: sanitize.sanitizeUrl,- iconPackPrefixes: renderArgs.iconPackSupportedPrefixes,- getText: (child) => getExcerptSource(child as SNote | BNote, renderArgs.canAccessEmbed)- }),+ navigation,+ childLinks,childLinksLayout: getChildLinksLayout(note),contentClasses: getContentClasses(note, isEmpty),language: getPageLanguages(note, {@@ -242,6 +282,11 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)defaultContentLanguage: options.getOptionOrNull("defaultContentLanguage")}),lastUpdated: getLastUpdated(note, displayLanguage),+ fontPreloads: getFontPreloads(renderArgs.iconPackFonts, [+ logo.icon,+ ...getNavigationIcons(navigation),+ ...childLinks.flatMap((child) => [ child.icon, ...child.children.map((grandchild) => grandchild.icon) ])+ ]),...renderArgs,};