Skip to content

Build your personal knowledge base with Trilium Notes

client/icon pack: create an icon pack preview widget

Adorian Doranac9f693003ec
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index c6b70cc03f..9f0de34937 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1251,6 +1251,12 @@
"show_details": "Show details",
"last_valid_render": "Showing last valid render"
},
+ "icon_pack": {
+ "preview_title": "Icon pack preview",
+ "invalid_manifest": "The icon pack manifest could not be parsed. Check that it is valid JSON.",
+ "no_icons": "This icon pack contains no icons.",
+ "tooltip": "Class: {{- class}}\nGlyph code: {{- code}}\nTerms: {{- terms}}"
+ },
"editable_text": {
"placeholder": "Type the content of your note here...",
"editor_crashed_title": "The text editor crashed",
diff --git a/apps/client/src/widgets/react/IsolatedFrame.tsx b/apps/client/src/widgets/react/IsolatedFrame.tsx
new file mode 100644
index 0000000000..1e22fdffba
--- /dev/null
+++ b/apps/client/src/widgets/react/IsolatedFrame.tsx
@@ -0,0 +1,53 @@
+import { ComponentChildren } from "preact";
+import { createPortal } from "preact/compat";
+import { useLayoutEffect, useRef, useState } from "preact/hooks";
+
+interface IsolatedFrameProps {
+ className?: string;
+ /** Accessible title for the underlying `<iframe>`. */
+ title: string;
+ /** CSS injected into the isolated document's `<head>`. Kept in sync on change. */
+ css?: string;
+ children?: ComponentChildren;
+}
+
+/**
+ * Renders its children inside a same-origin, `src`-less `<iframe>`, giving them a fully isolated
+ * document: none of the host page's stylesheets, `@font-face` declarations or CSS classes leak in,
+ * and nothing rendered here leaks out. Children are Preact nodes portalled into the frame's `<body>`,
+ * so they stay live and interactive (re-render on prop changes) rather than being a static snapshot.
+ *
+ * Provide the frame's own styling via {@link IsolatedFrameProps.css}. Because the document has no
+ * base URL, any URLs referenced from that CSS must be absolute.
+ */
+export default function IsolatedFrame({ className, title, css, children }: IsolatedFrameProps) {
+ const iframeRef = useRef<HTMLIFrameElement>(null);
+ const [ body, setBody ] = useState<HTMLElement | null>(null);
+
+ // A same-origin, src-less iframe exposes an empty document synchronously once mounted; re-capture
+ // on load in case the browser swaps the initial about:blank document.
+ const captureBody = () => {
+ const nextBody = iframeRef.current?.contentDocument?.body;
+ if (nextBody) setBody(nextBody);
+ };
+ useLayoutEffect(captureBody, []);
+
+ useLayoutEffect(() => {
+ const doc = body?.ownerDocument;
+ if (!doc) return;
+ let style = doc.getElementById("isolated-frame-style") as HTMLStyleElement | null;
+ if (!style) {
+ style = doc.createElement("style");
+ style.id = "isolated-frame-style";
+ doc.head.appendChild(style);
+ }
+ style.textContent = css ?? "";
+ }, [ css, body ]);
+
+ return (
+ <>
+ <iframe ref={iframeRef} className={className} title={title} onLoad={captureBody} />
+ {body && createPortal(children, body)}
+ </>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/icon_pack/IconPack.css b/apps/client/src/widgets/type_widgets/icon_pack/IconPack.css
index 18b65680bb..84466b52bf 100644
--- a/apps/client/src/widgets/type_widgets/icon_pack/IconPack.css
+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPack.css
@@ -11,3 +11,10 @@
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.tsx
index 31d219cbbe..177520cf70 100644
--- a/apps/client/src/widgets/type_widgets/icon_pack/IconPack.tsx
+++ b/apps/client/src/widgets/type_widgets/icon_pack/IconPack.tsx
@@ -1,13 +1,22 @@
import "./IconPack.css";
+import { useEffect, useMemo, useState } from "preact/hooks";
+
import FNote from "../../../entities/fnote";
+import { t } from "../../../services/i18n";
import { isDesktop } from "../../../services/utils";
-import { useNoteBlob } from "../../react/hooks";
+import { useColorScheme, useNoteBlob, useNoteLabel } from "../../react/hooks";
+import IsolatedFrame from "../../react/IsolatedFrame";
+import NoItems from "../../react/NoItems";
import { TextPreview } from "../File";
import SplitEditor from "../helpers/SplitEditor";
import { TypeWidgetProps } from "../type_widget";
+/** How long to wait after the last edit before re-parsing and re-rendering the (potentially large) preview. */
+const PREVIEW_DEBOUNCE_MS = 1500;
+
export default function IconPack(props: TypeWidgetProps) {
+ const [ content, setContent ] = useState("");
// Icon packs shipped in distributable zips are `file` notes, whose content isn't editable as
// text and can be large — show a read-only, truncated source pane (no CodeMirror). Manually
// created `code` notes stay editable in the normal code editor.
@@ -17,8 +26,9 @@ export default function IconPack(props: TypeWidgetProps) {
noteType="code"
{...props}
forceReadOnly={isFileNote}
+ onContentChanged={setContent}
editorContent={isFileNote ? <FileSource note={props.note} /> : undefined}
- previewContent={<IconPackPreview />}
+ previewContent={<IconPackPreview note={props.note} content={content} />}
forceOrientation={isDesktop() ? "horizontal" : "vertical"}
/>
);
@@ -35,7 +45,185 @@ function FileSource({ note }: { note: FNote }) {
);
}
-function IconPackPreview() {
- // TODO: parse the icon pack JSON and render its icons here.
- return <div className="icon-pack-preview" />;
+function IconPackPreview({ note, content }: { note: FNote; content: string }) {
+ const [ prefix ] = useNoteLabel(note, "iconPack");
+ // Recompute the injected theme colors when the app switches between light and dark.
+ const colorScheme = useColorScheme();
+ // 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 ]);
+ // `getThemeColors()` reads theme-dependent CSS variables; `colorScheme` is the recompute trigger.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const css = useMemo(() => buildPreviewCss(font, getThemeColors()), [ font, colorScheme ]);
+
+ 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}>
+ <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 };
+
+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.
+ */
+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 getThemeColors() {
+ const style = getComputedStyle(document.documentElement);
+ return {
+ text: style.getPropertyValue("--main-text-color").trim() || "#000",
+ background: style.getPropertyValue("--main-background-color").trim() || "#fff"
+ };
+}
+
+function buildPreviewCss(font: IconPackFont | null, colors: { text: string; background: string }): string {
+ const fontFace = font
+ ? `@font-face { font-family: "${PREVIEW_FONT_FAMILY}"; src: url("${font.url}") format("${font.format}"); font-display: block; }`
+ : "";
+ return `
+ ${fontFace}
+ html, body { margin: 0; height: 100%; }
+ body {
+ color: ${colors.text};
+ background: ${colors.background};
+ padding: 8px;
+ box-sizing: border-box;
+ overflow: auto;
+ }
+ .ip-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, 32px);
+ gap: 8px;
+ justify-content: start;
+ }
+ .ip-cell {
+ width: 32px;
+ height: 32px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 8px;
+ border-radius: 4px;
+ cursor: default;
+ /* Skip layout/paint for off-screen cells so large packs stay responsive. */
+ content-visibility: auto;
+ contain-intrinsic-size: 32px 32px;
+ }
+ .ip-cell:hover { background: rgba(127, 127, 127, 0.2); }
+ .ip-glyph { font-family: "${PREVIEW_FONT_FAMILY}"; font-size: 32px; line-height: 1; }
+ `;
+}
+
+function useDebouncedValue<T>(value: T, delayMs: number): T {
+ const [ debounced, setDebounced ] = useState(value);
+ useEffect(() => {
+ const timer = setTimeout(() => setDebounced(value), delayMs);
+ return () => clearTimeout(timer);
+ }, [ value, delayMs ]);
+ return debounced;
}
diff --git a/packages/commons/src/lib/attribute_names.ts b/packages/commons/src/lib/attribute_names.ts
index a0a88f27c6..d6e33c4a8d 100644
--- a/packages/commons/src/lib/attribute_names.ts
+++ b/packages/commons/src/lib/attribute_names.ts
@@ -4,6 +4,7 @@
type Labels = {
color: string;
iconClass: string;
+ iconPack: string;
workspace: boolean;
workspaceTabBackgroundColor: string;
workspaceIconClass: string;