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
feat(fonts): offer the notes labelled #customFont in the font picker
Elian Doran83f0ce7973a6
diff --git a/apps/client/src/services/custom_fonts.ts b/apps/client/src/services/custom_fonts.tsnew file mode 100644index 0000000000..70bb75f8ea--- /dev/null+++ b/apps/client/src/services/custom_fonts.ts@@ -0,0 +1,34 @@+import type { UserFont } from "@triliumnext/commons";++import server from "./server.js";++/** The fonts the user offers to the font picker: the file notes labelled `#customFont`. */+export async function getCustomFonts() {+ return await server.get<UserFont[]>("options/user-fonts");+}++/**+ * Loads a font note's file and registers it with the document under `family`, so anything styled+ * with that family renders in it. The caller owns the returned face and must hand it to+ * `document.fonts.delete()` once it is done with it.+ *+ * The bytes are fetched and handed to `FontFace` rather than referenced by their API URL: a `url()`+ * source is loaded by the engine itself, outside the host document's service worker and Capacitor+ * request interceptors, which is where standalone and iOS answer an API request from (see+ * `loadIconPackFont`). `version` — a blobId — keeps a replaced file from being served from the+ * cache of the one it replaced.+ */+export async function registerFontNote(noteId: string, family: string, version: string) {+ // Resolved against the host document's base URL, which also covers Electron's `trilium-app://`.+ const url = new URL(`api/notes/${noteId}/open?v=${encodeURIComponent(version)}`, document.baseURI).href;++ const response = await fetch(url);+ if (!response.ok) {+ throw new Error(`Font request failed with HTTP ${response.status}.`);+ }++ const face = await new FontFace(family, await response.arrayBuffer()).load();+ document.fonts.add(face);++ return face;+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e63858a0de..6ea4dc2efb 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -581,6 +581,7 @@"app_css": "Marks CSS notes which are loaded into the Trilium application and can thus be used to modify Trilium's looks.","app_theme": "Marks CSS notes which are full Trilium themes and are thus available in Trilium options.","app_theme_base": "Set to \"next\", \"next-light\", or \"next-dark\" to use the corresponding TriliumNext theme (auto, light or dark) as the base for a custom theme, instead of the legacy one.",+ "custom_font": "Marks font files which are offered in the font picker in Trilium options. The value is the family name to list it under; without one, the note's title is used.","css_class": "Value of this label is then added as CSS class to the node representing given note in the tree. This can be useful for advanced theming. Can be used in template notes.","icon_class": "Value of this label is added as a CSS class to the icon on the tree which can help visually distinguish the notes in the tree. Example might be bx bx-home - icons are taken from boxicons. Can be used in template notes.","page_size": "Number of items per page in note listing.",@@ -1820,6 +1821,7 @@"not_all_fonts_available": "Not all listed fonts may be available on your system","apply_changes": "Reload to apply changes","generic-fonts": "Generic fonts",+ "user-fonts": "Your fonts","sans-serif-system-fonts": "Sans-serif system fonts","serif-system-fonts": "Serif system fonts","monospace-system-fonts": "Monospace system fonts",diff --git a/apps/client/src/widgets/attribute_widgets/attr_help.ts b/apps/client/src/widgets/attribute_widgets/attr_help.tsindex 759cc8c682..586744176b 100644--- a/apps/client/src/widgets/attribute_widgets/attr_help.ts+++ b/apps/client/src/widgets/attribute_widgets/attr_help.ts@@ -27,6 +27,7 @@ export const ATTR_HELP: AttrHelpMap = {appCss: t("attribute_detail.app_css"),appTheme: t("attribute_detail.app_theme"),appThemeBase: t("attribute_detail.app_theme_base"),+ customFont: t("attribute_detail.custom_font"),cssClass: t("attribute_detail.css_class"),iconClass: t("attribute_detail.icon_class"),pageSize: t("attribute_detail.page_size"),diff --git a/apps/client/src/widgets/type_widgets/file/FontPreview.tsx b/apps/client/src/widgets/type_widgets/file/FontPreview.tsxindex 47f5bd1473..444b2a2be2 100644--- a/apps/client/src/widgets/type_widgets/file/FontPreview.tsx+++ b/apps/client/src/widgets/type_widgets/file/FontPreview.tsx@@ -5,6 +5,7 @@ import { useEffect, useState } from "preact/hooks";import type FBlob from "../../../entities/fblob";import type FNote from "../../../entities/fnote";+import { registerFontNote } from "../../../services/custom_fonts";import { t } from "../../../services/i18n";import Alert from "../../react/Alert";import FormTextBox from "../../react/FormTextBox";@@ -136,23 +137,14 @@ function useLoadedFont(note: FNote, blob: FBlob | null | undefined) {const previewFamily = `trilium-font-preview-${note.noteId}`;setFamily(undefined);- // The bytes are fetched and handed to `FontFace` directly rather than referenced by their- // API URL: a `url()` source is loaded by the engine itself, outside the host document's- // service worker and Capacitor request interceptors, which is where standalone and iOS- // answer an API request from (see loadIconPackFont in IconPackPreview.tsx). Versioned by- // blobId so a replaced file is not served from the cache of the one it replaced.- const url = new URL(`api/notes/${note.noteId}/open?v=${encodeURIComponent(blob.blobId)}`, document.baseURI).href;-(async () => {try {- const response = await fetch(url);- if (!response.ok) {- throw new Error(`Font request failed with HTTP ${response.status}.`);+ const face = await registerFontNote(note.noteId, previewFamily, blob.blobId);+ if (cancelled) {+ document.fonts.delete(face);+ return;}- const face = await new FontFace(previewFamily, await response.arrayBuffer()).load();- if (cancelled) return;- document.fonts.add(face);registered = face;setFamily(previewFamily);} catch {diff --git a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsxindex 156515dc02..9af201da24 100644--- a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx@@ -5,7 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({electron: true,mobile: false,- stored: {} as Record<string, string | boolean>+ stored: {} as Record<string, string | boolean>,+ userFonts: [] as { family: string; title: string; noteId: string; blobId: string }[]}));// Both the desktop card and the illustrated layout choices turn on which kind of client this is.@@ -38,6 +39,13 @@ vi.mock("../../react/hooks", async (importOriginal) => ({vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));+// The font picker asks for the user's own fonts and registers each one it is given; only the list+// is of interest here, so the registration is stood in for.+vi.mock("../../../services/custom_fonts", () => ({+ getCustomFonts: async () => mocks.userFonts,+ registerFontNote: async (_noteId: string, family: string) => ({ family })+}));+import AppearanceSettings from "./appearance";let host: HTMLElement;@@ -46,6 +54,11 @@ beforeEach(() => {mocks.electron = true;mocks.mobile = false;mocks.stored = {};+ mocks.userFonts = [];+ Object.defineProperty(document, "fonts", {+ configurable: true,+ value: { add: vi.fn(), delete: vi.fn() }+ });host = document.body.appendChild(document.createElement("div"));});@@ -89,6 +102,39 @@ describe("the font settings", () => {expect(fontRows().every((row) => row.className.includes("tn-card-section-nested"))).toBe(true);});+ it("offers the fonts the user labelled #customFont, one entry per family", async () => {+ mocks.stored = { overrideThemeFonts: true };+ mocks.userFonts = [+ { family: "Iosevka", title: "Iosevka.woff2", noteId: "n1", blobId: "b1" },+ { family: "Inter", title: "Inter.woff2", noteId: "n2", blobId: "b2" },+ // A second note offering a family already on the list is not a second entry.+ { family: "Inter", title: "Inter (copy).woff2", noteId: "n3", blobId: "b3" }+ ];+ open();+ await act(async () => {});++ await act(async () => (fontRows()[0] as HTMLElement).click());++ const picker = document.querySelector(".font-picker-list");+ const headers = [ ...(picker?.querySelectorAll(".dropdown-header") ?? []) ].map((header) => header.textContent);+ expect(headers).toContain("fonts.user-fonts");++ const listed = [ ...(picker?.querySelectorAll(".dropdown-item") ?? []) ].map((item) => item.textContent?.trim());+ expect(listed.filter((entry) => entry === "Inter")).toHaveLength(1);+ expect(listed).toContain("Iosevka");+ });++ it("lists only the built-in families when the user has labelled no fonts", async () => {+ mocks.stored = { overrideThemeFonts: true };+ open();+ await act(async () => {});+ await act(async () => (fontRows()[0] as HTMLElement).click());++ const headers = [ ...document.querySelectorAll(".font-picker-list .dropdown-header") ].map((header) => header.textContent);+ expect(headers).not.toContain("fonts.user-fonts");+ expect(headers).toContain("fonts.generic-fonts");+ });+it("leaves ligatures alone, since they come from the theme's own font", () => {open();diff --git a/apps/client/src/widgets/type_widgets/options/appearance.tsx b/apps/client/src/widgets/type_widgets/options/appearance.tsxindex 9e8c7781d1..e0120771a5 100644--- a/apps/client/src/widgets/type_widgets/options/appearance.tsx+++ b/apps/client/src/widgets/type_widgets/options/appearance.tsx@@ -1,6 +1,6 @@import "./appearance.css";-import { FontFamily, OptionNames, SYSTEM_MONOSPACE_FONT_STACK, SYSTEM_SANS_SERIF_FONT_STACK } from "@triliumnext/commons";+import { FontFamily, OptionNames, SYSTEM_MONOSPACE_FONT_STACK, SYSTEM_SANS_SERIF_FONT_STACK, UserFont } from "@triliumnext/commons";import clsx from "clsx";import { Fragment } from "preact";import { createPortal } from "preact/compat";@@ -8,6 +8,7 @@ import { useEffect, useMemo, useState } from "preact/hooks";import zoomService from "../../../components/zoom";import { ColorScheme, resolveColorScheme, THEME_FAMILY_SCHEMES } from "../../../services/color_scheme";+import { getCustomFonts, registerFontNote } from "../../../services/custom_fonts";import { t } from "../../../services/i18n";import server from "../../../services/server";import { isElectron, isMobile, reloadFrontendApp } from "../../../services/utils";@@ -451,6 +452,7 @@ function Fonts() {const [ overrideThemeFonts, setOverrideThemeFonts ] = useTriliumOptionBool("overrideThemeFonts");const [ ligaturesEnabled, setLigaturesEnabled ] = useTriliumOptionBool("monospaceLigaturesEnabled");const isEnabled = overrideThemeFonts === true;+ const fontGroups = useFontGroups();return (<Card className="appearance-fonts" heading={t("fonts.fonts")}>@@ -463,10 +465,10 @@ function Fonts() {// nothing under it says nothing about what it would bring.subSectionsVisiblesubSections={[- <Font key="main" label={t("fonts.main_font")} fontFamilyOption="mainFontFamily" fontSizeOption="mainFontSize" disabled={!isEnabled} />,- <Font key="tree" label={t("fonts.note_tree_font")} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="treeFontFamily" fontSizeOption="treeFontSize" disabled={!isEnabled} />,- <Font key="detail" label={t("fonts.note_detail_font")} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="detailFontFamily" fontSizeOption="detailFontSize" disabled={!isEnabled} />,- <Font key="monospace" label={t("fonts.monospace_font")} description={t("fonts.monospace_font_description")} fontFamilyOption="monospaceFontFamily" fontSizeOption="monospaceFontSize" disabled={!isEnabled} isMonospace />+ <Font key="main" label={t("fonts.main_font")} groups={fontGroups} fontFamilyOption="mainFontFamily" fontSizeOption="mainFontSize" disabled={!isEnabled} />,+ <Font key="tree" label={t("fonts.note_tree_font")} groups={fontGroups} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="treeFontFamily" fontSizeOption="treeFontSize" disabled={!isEnabled} />,+ <Font key="detail" label={t("fonts.note_detail_font")} groups={fontGroups} sizeDescription={t("fonts.size_relative_to_general")} fontFamilyOption="detailFontFamily" fontSizeOption="detailFontSize" disabled={!isEnabled} />,+ <Font key="monospace" label={t("fonts.monospace_font")} groups={fontGroups} description={t("fonts.monospace_font_description")} fontFamilyOption="monospaceFontFamily" fontSizeOption="monospaceFontSize" disabled={!isEnabled} isMonospace />]}><FormToggle currentValue={overrideThemeFonts} onChange={setOverrideThemeFonts} />@@ -488,23 +490,72 @@ function Fonts() {);}+/**+ * The picker's groups, with the fonts the user labelled `#customFont` appended. Those are also+ * registered with the document for as long as the page is open, so the picker draws each specimen+ * in the font it names.+ */+function useFontGroups(): FontGroup[] {+ const [ customFonts, setCustomFonts ] = useState<UserFont[]>([]);++ useEffect(() => {+ let cancelled = false;+ const registered: FontFace[] = [];++ (async () => {+ // By family, since that is what the picker lists and what an option holds: two notes+ // offering the same name are one entry.+ const fonts = [ ...new Map((await getCustomFonts()).map((font) => [ font.family, font ])).values() ];+ if (cancelled) return;+ setCustomFonts(fonts);++ await Promise.all(fonts.map(async ({ noteId, family, blobId }) => {+ try {+ const face = await registerFontNote(noteId, family, blobId);+ if (cancelled) {+ document.fonts.delete(face);+ } else {+ registered.push(face);+ }+ } catch {+ // The entry stays on the list and draws in the fallback family: the option can+ // still be set to a font this device happens not to be able to load.+ }+ }));+ })();++ return () => {+ cancelled = true;+ for (const face of registered) {+ document.fonts.delete(face);+ }+ };+ }, []);++ return useMemo(() => (customFonts.length+ ? [ ...FONT_FAMILIES, { title: t("fonts.user-fonts"), items: customFonts.map(({ family }) => ({ value: family })) } ]+ : FONT_FAMILIES), [ customFonts ]);+}+interface FontProps {label: string;description?: string;sizeDescription?: string;+ /** The picker's groups, the user's own fonts among them (see {@link useFontGroups}). */+ groups: FontGroup[];fontFamilyOption: OptionNames;fontSizeOption: OptionNames;disabled?: boolean;isMonospace?: boolean;}-function Font({ label, description, sizeDescription, fontFamilyOption, fontSizeOption, disabled, isMonospace }: FontProps) {+function Font({ label, description, sizeDescription, groups, fontFamilyOption, fontSizeOption, disabled, isMonospace }: FontProps) {const [ fontFamily, setFontFamily ] = useTriliumOption(fontFamilyOption);const [ fontSize, setFontSize ] = useTriliumOption(fontSizeOption);const [ showModal, setShowModal ] = useState(false);// Find the current font entry to display- const currentFont = FONT_FAMILIES+ const currentFont = groups.flatMap(group => group.items).find(item => item.value === fontFamily);const displayLabel = currentFont?.label ?? currentFont?.value ?? fontFamily ?? "";@@ -548,6 +599,7 @@ function Font({ label, description, sizeDescription, fontFamilyOption, fontSizeOshow={showModal}onHidden={() => setShowModal(false)}title={label}+ groups={groups}fontFamily={fontFamily ?? ""}fontSize={parseInt(fontSize ?? "100", 10)}onFontFamilyChange={setFontFamily}@@ -565,6 +617,7 @@ interface FontPickerModalProps {show: boolean;onHidden: () => void;title: string;+ groups: FontGroup[];fontFamily: string;fontSize: number;onFontFamilyChange: (value: string) => void;@@ -573,7 +626,7 @@ interface FontPickerModalProps {sizeDescription?: string;}-function FontPickerModal({ show, onHidden, title, fontFamily, fontSize, onFontFamilyChange, onFontSizeChange, getFontFamily, sizeDescription }: FontPickerModalProps) {+function FontPickerModal({ show, onHidden, title, groups, fontFamily, fontSize, onFontFamilyChange, onFontSizeChange, getFontFamily, sizeDescription }: FontPickerModalProps) {return createPortal(<ModalclassName="font-picker-modal"@@ -584,7 +637,7 @@ function FontPickerModal({ show, onHidden, title, fontFamily, fontSize, onFontFastackablesidebar={<FormList fullHeight wrapperClassName="font-picker-list">- {FONT_FAMILIES.map(group => (+ {groups.map(group => (<Fragment key={group.title}><FormListHeader text={group.title} />{group.items.map(item => (diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.tsindex 1a2785355d..458222bfe3 100644--- a/packages/commons/src/lib/builtin_attributes.ts+++ b/packages/commons/src/lib/builtin_attributes.ts@@ -89,6 +89,9 @@ const BUILTIN_ATTRIBUTES = [{ type: "label", name: "appThemeBase", valueType: "select", selectOptions: ["next", "next-light", "next-dark"] },+ // The family name a font file note is offered under in the font picker; the note's title+ // stands in where the label carries no value.+ { type: "label", name: "customFont", valueType: "text" },{ type: "label", name: "hidePromotedAttributes", valueType: "boolean" },{ type: "label", name: "readOnly", valueType: "boolean" },{ type: "label", name: "autoReadOnlyDisabled", valueType: "boolean" },diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 4740fb07d9..29bfb5d8aa 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -740,6 +740,16 @@ export type SimilarNoteResponse = SimilarNote[];export type SaveSearchNoteResponse = CloneResponse;+/** A font file note carrying `#customFont`, as the font picker in the options lists it. */+export interface UserFont {+ /** The family name the font is registered and selected under. */+ family: string;+ title: string;+ noteId: string;+ /** Versions the request for the font's bytes, so a replaced file is not served from the cache. */+ blobId: string;+}+export interface TemplatesResponse {/** The IDs of the user-defined templates, i.e. the notes labelled with `#template`. */templateNoteIds: string[];diff --git a/packages/trilium-core/src/routes/api/options.spec.ts b/packages/trilium-core/src/routes/api/options.spec.tsindex c13e8867ce..f89ba12c76 100644--- a/packages/trilium-core/src/routes/api/options.spec.ts+++ b/packages/trilium-core/src/routes/api/options.spec.ts@@ -1,3 +1,4 @@+import type { UserFont } from "@triliumnext/commons";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import * as i18n from "../../services/i18n";@@ -15,6 +16,18 @@ function getOptionValue(name: string): string | null {return getSql().getValue<string | null>("SELECT value FROM options WHERE name = ?", [name]);}+/** Creates a file note carrying a `#customFont` label and returns its note ID. */+async function createFontNote(title: string, family: string): Promise<string> {+ const created = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {+ body: { title, type: "file", mime: "font/woff2", content: "wOF2" }+ });+ const { noteId } = created.body.note;+ await api.put(`/api/notes/${noteId}/set-attribute`, {+ body: { type: "label", name: "customFont", value: family }+ });+ return noteId;+}+/** Creates a code note carrying a `#run` label and returns its note ID. */async function createCodeNote(title: string, mime: string): Promise<string> {const created = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {@@ -188,4 +201,20 @@ describe("Options API (core)", () => {// "Theme B!!" -> non-alphanumerics replaced with "-"expect(noValueEntry?.val).toBe("theme-b--");});++ it("returns user fonts, falling back to the title as the family when customFont has no value", async () => {+ const named = await createFontNote("Iosevka.woff2", "Iosevka");+ const unnamed = await createFontNote("Inter Variable", "");++ const res = await api.get<UserFont[]>("/api/options/user-fonts");+ expect(res.status).toBe(200);++ const namedEntry = res.body.find((font) => font.noteId === named);+ const unnamedEntry = res.body.find((font) => font.noteId === unnamed);+ expect(namedEntry?.family).toBe("Iosevka");+ expect(namedEntry?.title).toBe("Iosevka.woff2");+ // The family the picker lists it under, and the version the bytes are fetched with.+ expect(unnamedEntry?.family).toBe("Inter Variable");+ expect(unnamedEntry?.blobId).toBeTruthy();+ });});diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 10b7a1f9d5..a33d44b3af 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -1,6 +1,6 @@-import type { OptionNames } from "@triliumnext/commons";+import type { OptionNames, UserFont } from "@triliumnext/commons";import type { Request } from "express";import attributeService from "../../services/attributes.js";@@ -282,6 +282,30 @@ function getUserThemes() {return ret;}+function getUserFonts() {+ const notes = searchService.searchNotes("#customFont", { ignoreHoistedNote: true });+ const ret: UserFont[] = [];++ for (const note of notes) {+ // A font whose bytes cannot be read — a protected note outside a protected session — has+ // nothing to offer the picker.+ if (!note.isContentAvailable()) {+ continue;+ }++ const title = note.getTitleOrProtected();++ ret.push({+ family: note.getOwnedLabelValue("customFont") || title,+ title,+ noteId: note.noteId,+ blobId: note.blobId ?? ""+ });+ }++ return ret;+}+/** Check if an option can be read by the client (GET responses). */function isReadable(name: string) {return (ALLOWED_OPTIONS as Set<string>).has(name)@@ -300,5 +324,6 @@ export default {getOptions,updateOption,updateOptions,- getUserThemes+ getUserThemes,+ getUserFonts};diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 5966ef4f35..622d7232f3 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -91,6 +91,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransasyncApiRoute(PUT, "/api/options/:name/:value", optionsApiRoute.updateOption);asyncApiRoute(PUT, "/api/options", optionsApiRoute.updateOptions);apiRoute(GET, "/api/options/user-themes", optionsApiRoute.getUserThemes);+ apiRoute(GET, "/api/options/user-fonts", optionsApiRoute.getUserFonts);apiRoute(PST, "/api/notes/:noteId/convert-to-attachment", notesApiRoute.convertNoteToAttachment);apiRoute(PST, "/api/notes/:noteId/convert-format", notesApiRoute.convertNoteFormat);