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
client/icon pack: add a preview-mode content renderer for icon packs
Adorian Doran450770c3f1f5
diff --git a/apps/client/src/services/content_renderer.css b/apps/client/src/services/content_renderer.cssindex 2ebb969c6a..eb50f24bef 100644--- a/apps/client/src/services/content_renderer.css+++ b/apps/client/src/services/content_renderer.css@@ -25,3 +25,8 @@.rendered-collection:has(> .note-list-widget.full-height) {height: 100%;}++.rendered-content .icon-pack-rendered {+ height: 100%;+ min-height: 120px;+}diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 652fedfa81..b110e4bae1 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -83,6 +83,8 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNoawait renderMarkdown(entity, $renderedContent, options);} else if (type === "code") {await renderCode(entity, $renderedContent);+ } else if (type === "iconPack" && !options.tooltip && entity instanceof FNote) {+ await renderIconPack(entity, $renderedContent, options);} else if (["image", "canvas", "mindMap", "spreadsheet"].includes(type)) {await renderImage(entity, $renderedContent, options);} else if (!options.tooltip && ["file", "pdf", "audio", "video"].includes(type)) {@@ -176,6 +178,33 @@ async function renderMarkdown(note: FNote | FAttachment, $renderedContent: JQuerawait postProcessRichContent(note, $renderedContent, options);}+/**+ * Renders an icon pack as its glyph grid (the same isolated-frame preview used by the editor),+ * mounted like the PDF viewer. Its own module keeps the editor stack (SplitEditor/CodeMirror) out+ * of this path. Falls back to the children list for an empty manifest.+ */+async function renderIconPack(note: FNote, $renderedContent: JQuery<HTMLElement>, options: RenderOptions) {+ const blob = await note.getBlob();+ const content = blob?.content ?? "";++ if (!content.trim()) {+ if (!options.noChildrenList) {+ await renderChildrenList($renderedContent, note, options.includeArchivedNotes ?? false);+ }+ return;+ }++ const { IconPackPreview } = await import("../widgets/type_widgets/icon_pack/IconPackPreview");+ const $container = $('<div class="icon-pack-rendered">');+ const container = $container.get(0);+ if (container) {+ render(h(IconPackPreview, { note, content }), container);+ // Mark the standalone Preact root so disposeInteractiveContent() can unmount the frame/effects.+ container.setAttribute(INTERACTIVE_MOUNT_ATTR, "");+ }+ $renderedContent.append($container);+}+/*** Renders a code note, by displaying its content and applying syntax highlighting based on the selected MIME type.*/@@ -508,13 +537,16 @@ function getRenderingType(entity: FNote | FAttachment) {}const mime = "mime" in entity && entity.mime;- const isIconPack = entity instanceof FNote && entity.hasLabel("iconPack");+ const isIconPack = entity instanceof FNote && entity.isIconPack();- if (type === "file" && mime === "application/pdf") {+ if (isIconPack) {+ // Icon packs (JSON `code`/`file` notes with #iconPack) render as their glyph grid, not as raw JSON.+ type = "iconPack";+ } else if (type === "file" && mime === "application/pdf") {type = "pdf";} else if (type === "code" && entity instanceof FNote && entity.isMarkdown()) {type = "markdown";- } else if ((type === "file" || type === "viewConfig") && mime && CODE_MIME_TYPES.has(mime) && !isIconPack) {+ } else if ((type === "file" || type === "viewConfig") && mime && CODE_MIME_TYPES.has(mime)) {type = "code";} else if (type === "file" && mime && mime.startsWith("audio/")) {type = "audio";diff --git a/apps/client/src/widgets/type_widgets/icon_pack/IconPack.css b/apps/client/src/widgets/type_widgets/icon_pack/IconPack.cssindex 84466b52bf..7cffed69ff 100644--- a/apps/client/src/widgets/type_widgets/icon_pack/IconPack.css+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPack.css@@ -1,20 +1,4 @@-.note-detail-icon-pack .icon-pack-preview {- display: flex;- align-items: center;- justify-content: center;- height: 100%;- padding: 1em;- overflow: auto;-}-.note-detail-icon-pack .icon-pack-file-source {height: 100%;overflow: auto;}--.note-detail-icon-pack .icon-pack-frame {- display: block;- width: 100%;- height: 100%;- border: none;-}diff --git a/apps/client/src/widgets/type_widgets/icon_pack/IconPack.tsx b/apps/client/src/widgets/type_widgets/icon_pack/IconPack.tsxindex 1604de9699..8e125b9a6b 100644--- a/apps/client/src/widgets/type_widgets/icon_pack/IconPack.tsx+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPack.tsx@@ -1,29 +1,14 @@import "./IconPack.css";-import { useEffect, useMemo, useState } from "preact/hooks";+import { useState } from "preact/hooks";import FNote from "../../../entities/fnote";-import debounce from "../../../services/debounce";-import { t } from "../../../services/i18n";import { isDesktop } from "../../../services/utils";-import { useNoteBlob, useNoteLabel } from "../../react/hooks";-import IsolatedFrame from "../../react/IsolatedFrame";-import NoItems from "../../react/NoItems";+import { useNoteBlob } from "../../react/hooks";import { TextPreview } from "../File";import SplitEditor from "../helpers/SplitEditor";import { TypeWidgetProps } from "../type_widget";-import previewStylesheet from "./icon_pack_preview.css?raw";--/** How long to wait after the last edit before re-parsing and re-rendering the (potentially large) preview. */-const PREVIEW_DEBOUNCE_MS = 1500;--/** Theme variables forwarded into the isolated preview frame so it matches the app's colours. */-const PREVIEW_CSS_VARS = [- "--main-text-color",- "--main-background-color",- "--hover-item-background-color",- "--hover-item-text-color"-];+import { IconPackPreview } from "./IconPackPreview";export default function IconPack(props: TypeWidgetProps) {const [ content, setContent ] = useState("");@@ -54,145 +39,3 @@ function FileSource({ note }: { note: FNote }) {</div>);}--function IconPackPreview({ note, content }: { note: FNote; content: string }) {- const [ prefix ] = useNoteLabel(note, "iconPack");- // The user isn't meant to see the preview update on every keystroke — it lags a beat behind.- const debounced = useDebouncedValue(content, PREVIEW_DEBOUNCE_MS);- const font = useIconPackFont(note);-- const parsed = useMemo(() => parseManifest(debounced), [ debounced ]);- const css = useMemo(() => buildPreviewCss(font), [ font ]);-- if (!parsed.ok) {- return <div className="icon-pack-preview"><NoItems icon="bx bx-error-circle" text={t("icon_pack.invalid_manifest")} /></div>;- }- // Empty content means the manifest hasn't been loaded/typed yet — stay blank rather than flashing- // the "no icons" state before the real content arrives.- if (!debounced.trim()) {- return <div className="icon-pack-preview" />;- }- if (!parsed.icons.length) {- return <div className="icon-pack-preview"><NoItems icon="bx bx-images" text={t("icon_pack.no_icons")} /></div>;- }-- return (- <IsolatedFrame className="icon-pack-frame" title={t("icon_pack.preview_title")} css={css} cssVars={PREVIEW_CSS_VARS}>- <div className="ip-grid">- {parsed.icons.map((icon) => (- <div className="ip-cell" key={icon.id} title={iconTooltip(prefix, icon)}>- <span className="ip-glyph">{icon.glyph}</span>- </div>- ))}- </div>- </IsolatedFrame>- );-}--interface PreviewIcon {- id: string;- glyph: string;- terms: string[];-}--/** Builds the hover tooltip: the usable CSS class, the glyph's escaped code point, and the search terms. */-function iconTooltip(prefix: string | null | undefined, icon: PreviewIcon): string {- const cssClass = prefix ? `${prefix} ${icon.id}` : icon.id;- const codePoint = icon.glyph.codePointAt(0);- const code = codePoint != null ? `\\${codePoint.toString(16)}` : "";- return t("icon_pack.tooltip", { class: cssClass, code, terms: icon.terms.join(", ") });-}--type ParsedManifest =- | { ok: true; icons: PreviewIcon[] }- | { ok: false };--export function parseManifest(content: string): ParsedManifest {- if (!content.trim()) return { ok: true, icons: [] };-- let data: unknown;- try {- data = JSON.parse(content);- } catch {- return { ok: false };- }-- const rawIcons = (data as { icons?: unknown })?.icons;- if (!rawIcons || typeof rawIcons !== "object") return { ok: false };-- const icons = Object.entries(rawIcons as Record<string, unknown>).map(([ id, value ]) => {- const entry = value as { glyph?: unknown; terms?: unknown };- const glyph = typeof entry?.glyph === "string" ? resolveGlyph(entry.glyph) : "";- const terms = Array.isArray(entry?.terms) ? entry.terms.filter((term): term is string => typeof term === "string") : [];- return { id, glyph, terms };- });- return { ok: true, icons };-}--/**- * Returns the actual glyph character. Some manifests store the glyph as a literal escape string- * (e.g. a CSS-style escape) rather than the real character; those are converted to their code- * point. A value that is already a real character is returned unchanged.- */-export function resolveGlyph(raw: string): string {- const match = raw.match(/^\\u?([0-9a-fA-F]{2,6})$/);- if (match) {- const codePoint = parseInt(match[1], 16);- if (!Number.isNaN(codePoint)) return String.fromCodePoint(codePoint);- }- return raw;-}--/** MIME types recognised as icon-pack fonts, in the same order of preference the server uses. */-const FONT_MIME_TO_FORMAT: Record<string, string> = {- "font/woff2": "woff2",- "font/woff": "woff",- "font/ttf": "truetype"-};--interface IconPackFont {- url: string;- format: string;-}--/** Resolves the best font attachment on the note to an absolute download URL, mirroring the server's selection. */-function useIconPackFont(note: FNote): IconPackFont | null {- const [ font, setFont ] = useState<IconPackFont | null>(null);- useEffect(() => {- let cancelled = false;- note.getAttachmentsByRole("file").then((attachments) => {- if (cancelled) return;- const best = Object.keys(FONT_MIME_TO_FORMAT)- .map((mime) => attachments.find((attachment) => attachment.mime === mime))- .find(Boolean);- // Resolve against the host document's base URL since the isolated frame has none.- setFont(best- ? { url: new URL(`api/attachments/download/${best.attachmentId}`, document.baseURI).href, format: FONT_MIME_TO_FORMAT[best.mime] }- : null);- }).catch(() => {- if (!cancelled) setFont(null);- });- return () => { cancelled = true; };- }, [ note ]);- return font;-}--const PREVIEW_FONT_FAMILY = "tn-icon-pack-preview";--function buildPreviewCss(font: IconPackFont | null): string {- const fontFace = font- ? `@font-face { font-family: "${PREVIEW_FONT_FAMILY}"; src: url("${font.url}") format("${font.format}"); font-display: block; }`- : "";- // The static rules live in icon_pack_preview.css (its `.ip-glyph` uses PREVIEW_FONT_FAMILY).- return `${fontFace}\n${previewStylesheet}`;-}--function useDebouncedValue<T>(value: T, delayMs: number): T {- const [ debounced, setDebounced ] = useState(value);- const commit = useMemo(() => debounce(setDebounced, delayMs), [ delayMs ]);- useEffect(() => {- commit(value);- return commit.clear;- }, [ value, commit ]);- return debounced;-}diff --git a/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.css b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.cssnew file mode 100644index 0000000000..7a9a392f31--- /dev/null+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.css@@ -0,0 +1,18 @@+/* Unscoped so the preview renders both in the note detail and in the read-only content renderer+ (collection tiles, child listings), where the `.note-detail-icon-pack` ancestor is absent. */++.icon-pack-preview {+ display: flex;+ align-items: center;+ justify-content: center;+ height: 100%;+ padding: 1em;+ overflow: auto;+}++.icon-pack-frame {+ display: block;+ width: 100%;+ height: 100%;+ border: none;+}diff --git a/apps/client/src/widgets/type_widgets/icon_pack/IconPack.spec.tsx b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.spec.tsxsimilarity index 97%rename from apps/client/src/widgets/type_widgets/icon_pack/IconPack.spec.tsxrename to apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.spec.tsxindex b4a7ed5d16..c39c5516a3 100644--- a/apps/client/src/widgets/type_widgets/icon_pack/IconPack.spec.tsx+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.spec.tsx@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { parseManifest, resolveGlyph } from "./IconPack";+import { parseManifest, resolveGlyph } from "./IconPackPreview";// U+E964 is the code point used across the escape-form assertions below.const E964 = String.fromCodePoint(0xe964);diff --git a/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsx b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsxnew file mode 100644index 0000000000..1543036708--- /dev/null+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPackPreview.tsx@@ -0,0 +1,168 @@+import "./IconPackPreview.css";++import { useEffect, useMemo, useState } from "preact/hooks";++import FNote from "../../../entities/fnote";+import debounce from "../../../services/debounce";+import { t } from "../../../services/i18n";+import { useNoteLabel } from "../../react/hooks";+import IsolatedFrame from "../../react/IsolatedFrame";+import NoItems from "../../react/NoItems";+import previewStylesheet from "./icon_pack_preview.css?raw";++/** How long to wait after the last edit before re-parsing and re-rendering the (potentially large) preview. */+const PREVIEW_DEBOUNCE_MS = 1500;++/** Theme variables forwarded into the isolated preview frame so it matches the app's colours. */+const PREVIEW_CSS_VARS = [+ "--main-text-color",+ "--main-background-color",+ "--hover-item-background-color",+ "--hover-item-text-color"+];++/**+ * Renders an icon pack's manifest as a grid of glyphs inside an isolated frame. Shared between the+ * icon-pack editor's preview pane and the read-only content renderer (collections, child listings).+ */+export function IconPackPreview({ note, content }: { note: FNote; content: string }) {+ const [ prefix ] = useNoteLabel(note, "iconPack");+ // The user isn't meant to see the preview update on every keystroke — it lags a beat behind.+ const debounced = useDebouncedValue(content, PREVIEW_DEBOUNCE_MS);+ const font = useIconPackFont(note);++ const parsed = useMemo(() => parseManifest(debounced), [ debounced ]);+ const css = useMemo(() => buildPreviewCss(font), [ font ]);++ if (!parsed.ok) {+ return <div className="icon-pack-preview"><NoItems icon="bx bx-error-circle" text={t("icon_pack.invalid_manifest")} /></div>;+ }+ // Empty content means the manifest hasn't been loaded/typed yet — stay blank rather than flashing+ // the "no icons" state before the real content arrives.+ if (!debounced.trim()) {+ return <div className="icon-pack-preview" />;+ }+ if (!parsed.icons.length) {+ return <div className="icon-pack-preview"><NoItems icon="bx bx-images" text={t("icon_pack.no_icons")} /></div>;+ }++ return (+ <IsolatedFrame className="icon-pack-frame" title={t("icon_pack.preview_title")} css={css} cssVars={PREVIEW_CSS_VARS}>+ <div className="ip-grid">+ {parsed.icons.map((icon) => (+ <div className="ip-cell" key={icon.id} title={iconTooltip(prefix, icon)}>+ <span className="ip-glyph">{icon.glyph}</span>+ </div>+ ))}+ </div>+ </IsolatedFrame>+ );+}++interface PreviewIcon {+ id: string;+ glyph: string;+ terms: string[];+}++/** Builds the hover tooltip: the usable CSS class, the glyph's escaped code point, and the search terms. */+function iconTooltip(prefix: string | null | undefined, icon: PreviewIcon): string {+ const cssClass = prefix ? `${prefix} ${icon.id}` : icon.id;+ const codePoint = icon.glyph.codePointAt(0);+ const code = codePoint != null ? `\\${codePoint.toString(16)}` : "";+ return t("icon_pack.tooltip", { class: cssClass, code, terms: icon.terms.join(", ") });+}++type ParsedManifest =+ | { ok: true; icons: PreviewIcon[] }+ | { ok: false };++export function parseManifest(content: string): ParsedManifest {+ if (!content.trim()) return { ok: true, icons: [] };++ let data: unknown;+ try {+ data = JSON.parse(content);+ } catch {+ return { ok: false };+ }++ const rawIcons = (data as { icons?: unknown })?.icons;+ if (!rawIcons || typeof rawIcons !== "object") return { ok: false };++ const icons = Object.entries(rawIcons as Record<string, unknown>).map(([ id, value ]) => {+ const entry = value as { glyph?: unknown; terms?: unknown };+ const glyph = typeof entry?.glyph === "string" ? resolveGlyph(entry.glyph) : "";+ const terms = Array.isArray(entry?.terms) ? entry.terms.filter((term): term is string => typeof term === "string") : [];+ return { id, glyph, terms };+ });+ return { ok: true, icons };+}++/**+ * Returns the actual glyph character. Some manifests store the glyph as a literal escape string+ * (e.g. a CSS-style escape) rather than the real character; those are converted to their code+ * point. A value that is already a real character is returned unchanged.+ */+export function resolveGlyph(raw: string): string {+ const match = raw.match(/^\\u?([0-9a-fA-F]{2,6})$/);+ if (match) {+ const codePoint = parseInt(match[1], 16);+ if (!Number.isNaN(codePoint)) return String.fromCodePoint(codePoint);+ }+ return raw;+}++/** MIME types recognised as icon-pack fonts, in the same order of preference the server uses. */+const FONT_MIME_TO_FORMAT: Record<string, string> = {+ "font/woff2": "woff2",+ "font/woff": "woff",+ "font/ttf": "truetype"+};++interface IconPackFont {+ url: string;+ format: string;+}++/** Resolves the best font attachment on the note to an absolute download URL, mirroring the server's selection. */+function useIconPackFont(note: FNote): IconPackFont | null {+ const [ font, setFont ] = useState<IconPackFont | null>(null);+ useEffect(() => {+ let cancelled = false;+ note.getAttachmentsByRole("file").then((attachments) => {+ if (cancelled) return;+ const best = Object.keys(FONT_MIME_TO_FORMAT)+ .map((mime) => attachments.find((attachment) => attachment.mime === mime))+ .find(Boolean);+ // Resolve against the host document's base URL since the isolated frame has none.+ setFont(best+ ? { url: new URL(`api/attachments/download/${best.attachmentId}`, document.baseURI).href, format: FONT_MIME_TO_FORMAT[best.mime] }+ : null);+ }).catch(() => {+ if (!cancelled) setFont(null);+ });+ return () => { cancelled = true; };+ }, [ note ]);+ return font;+}++const PREVIEW_FONT_FAMILY = "tn-icon-pack-preview";++function buildPreviewCss(font: IconPackFont | null): string {+ const fontFace = font+ ? `@font-face { font-family: "${PREVIEW_FONT_FAMILY}"; src: url("${font.url}") format("${font.format}"); font-display: block; }`+ : "";+ // The static rules live in icon_pack_preview.css (its `.ip-glyph` uses PREVIEW_FONT_FAMILY).+ return `${fontFace}\n${previewStylesheet}`;+}++function useDebouncedValue<T>(value: T, delayMs: number): T {+ const [ debounced, setDebounced ] = useState(value);+ const commit = useMemo(() => debounce(setDebounced, delayMs), [ delayMs ]);+ useEffect(() => {+ commit(value);+ return commit.clear;+ }, [ value, commit ]);+ return debounced;+}