Skip to content

Build your personal knowledge base with Trilium Notes

refactor(options): move the font settings into a module of their own

Elian Doran16ac60925e57
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.css b/apps/client/src/widgets/type_widgets/options/appearance.css
index 5adae98961..0731af2f4e 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.css
+++ b/apps/client/src/widgets/type_widgets/options/appearance.css
@@ -12,169 +12,6 @@
}
}
-/* Font Option Row */
-.font-option {
- cursor: pointer;
-
- /* Shown rather than hidden with custom fonts off, so the settings can still be read. */
- &.disabled {
- opacity: 0.5;
- pointer-events: none;
- }
-}
-
-.font-option-preview {
- display: flex;
- align-items: center;
- gap: 8px;
- color: var(--muted-text-color);
-}
-
-/* The specimen is drawn at the user's own family and size, so it can outgrow the screen: it takes
- the line below the name earlier than an ordinary option does. Measured against the card, which
- `Card.css` makes a container. */
-@container (max-width: 600px) {
- .font-option {
- flex-direction: column;
- align-items: stretch;
- }
-
- .font-option .font-option-preview {
- justify-content: space-between;
- }
-
- .font-option .font-option-specimen {
- /* `anywhere`: a family name is often one word, with no break the browser would take. */
- min-width: 0;
- overflow-wrap: anywhere;
- }
-}
-
-/* Font Picker Modal */
-body.desktop .modal.font-picker-modal {
- .modal-content-with-sidebar {
- height: 60vh;
- }
-
- /* On the sidebar rather than on the list, which a search matching nothing takes away. */
- .modal-sidebar {
- width: 280px;
- }
-}
-
-.modal.font-picker-modal {
- /* Keep the sidebar background within the rounded corners. */
- .modal-content {
- overflow: hidden;
- }
-
- .modal-body {
- padding: 0;
- display: flex;
- flex-direction: column;
- }
-
- .modal-sidebar {
- background-color: var(--card-background-color);
- }
-
- .modal-sidebar .dropdown-menu.static {
- background-color: transparent !important;
- border: none;
- border-radius: 0 !important;
- }
-
- /* Set here rather than by the field, which takes the room it is given (see SettingsSearch.css).
- Room below as well as above: the focus ring reaches past the border, and the list beneath it
- paints over whatever crosses into it. */
- .settings-search {
- margin: 8px;
- }
-
- .font-picker-list {
- flex: 1 1 0;
- min-height: 0;
- overflow: auto;
-
- .dropdown-item {
- font-size: 14px;
- }
- }
-
- .font-picker-empty {
- flex: 1 1 0;
- min-height: 0;
- padding: 16px;
- }
-
- .font-picker-settings {
- flex: 1;
- display: flex;
- flex-direction: column;
- padding: 16px;
- gap: 16px;
- }
-}
-
-.font-size-control {
- display: flex;
- flex-direction: column;
- gap: 8px;
-
- label {
- font-weight: 500;
- color: var(--muted-text-color);
- font-size: 12px;
- text-transform: uppercase;
- }
-
- .font-size-description {
- color: var(--muted-text-color);
- font-size: 12px;
- }
-}
-
-.font-size-slider {
- display: flex;
- align-items: center;
- gap: 12px;
-
- .slider {
- flex: 1;
- }
-
- .font-size-value {
- min-width: 50px;
- text-align: right;
- font-variant-numeric: tabular-nums;
- }
-}
-
-.font-preview {
- flex: 1;
- display: flex;
- flex-direction: column;
- gap: 8px;
- min-height: 0;
-
- label {
- font-weight: 500;
- color: var(--muted-text-color);
- font-size: 12px;
- text-transform: uppercase;
- }
-}
-
-.font-preview-text {
- flex: 1;
- padding: 16px;
- border: 1px solid var(--main-border-color);
- border-radius: 6px;
- background: var(--main-background-color);
- overflow: auto;
- line-height: 1.6;
-}
-
.orientation-illustration {
width: 170px;
height: 130px;
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
index 7e5f4f3d22..8fabd51d93 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
@@ -5,9 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
electron: true,
mobile: false,
- stored: {} as Record<string, string | boolean>,
- userFonts: [] as { noteId: string; title: string; blobId: string }[],
- systemFonts: [] as { family: string; monospace: boolean }[]
+ stored: {} as Record<string, string | boolean>
}));
// Both the desktop card and the illustrated layout choices turn on which kind of client this is.
@@ -34,23 +32,12 @@ vi.mock("../../../services/server", () => ({
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 })
-}));
-
-// happy-dom exposes no `queryLocalFonts`, so what the desktop app would find is stood in for.
-vi.mock("../../../services/font", async (importOriginal) => ({
- ...(await importOriginal<typeof import("../../../services/font")>()),
- listSystemFonts: async () => mocks.systemFonts
-}));
+// The fonts card reaches for the user's own fonts and the device's as it mounts, and is covered by
+// `appearance_fonts.spec.tsx`; here only its place on the page matters.
+vi.mock("./appearance_fonts", () => ({ default: () => <div className="fonts-stub" /> }));
-// useNoteTitle names the font a font option points at; the listing above is what the picker lists.
vi.mock("../../react/hooks", async (importOriginal) => ({
...(await importOriginal<typeof import("../../react/hooks")>()),
- useNoteTitle: (noteId: string | undefined) => mocks.userFonts.find((font) => font.noteId === noteId)?.title,
useTriliumOption: (name: string) => [ String(mocks.stored[name] ?? ""), vi.fn() ],
useTriliumOptionBool: (name: string) => [ mocks.stored[name] === true, vi.fn() ]
}));
@@ -63,12 +50,6 @@ beforeEach(() => {
mocks.electron = true;
mocks.mobile = false;
mocks.stored = {};
- mocks.userFonts = [];
- mocks.systemFonts = [];
- Object.defineProperty(document, "fonts", {
- configurable: true,
- value: { add: vi.fn(), delete: vi.fn() }
- });
host = document.body.appendChild(document.createElement("div"));
});
@@ -88,192 +69,6 @@ function open() {
});
}
-const fontRows = () => [ ...host.querySelectorAll(".font-option") ];
-const listedFonts = () => [ ...document.querySelectorAll(".font-picker-list .dropdown-item") ].map((item) => item.textContent?.trim());
-const listedHeaders = () => [ ...document.querySelectorAll(".font-picker-list .dropdown-header") ].map((header) => header.textContent);
-
-/**
- * Opens the picker of the first font on a server build, where the list is the stock one — the
- * families it holds are known, which is what a search can be checked against.
- */
-async function openPicker() {
- mocks.electron = false;
- mocks.stored = { overrideThemeFonts: true };
- open();
- await act(async () => {});
- await act(async () => (fontRows()[0] as HTMLElement).click());
-}
-
-/** Types into the picker's search box, as the user would. */
-function searchFonts(query: string) {
- const search = document.querySelector<HTMLInputElement>(".font-picker-modal .settings-search input");
- if (!search) throw new Error("the font picker has no search box");
-
- search.value = query;
- search.dispatchEvent(new Event("input", { bubbles: true }));
-}
-
-describe("the font settings", () => {
- it("keeps the fonts on show with custom fonts off, greyed rather than gone", () => {
- open();
-
- // What turning the switch on would put in force is the whole reason for turning it on.
- expect(fontRows()).toHaveLength(4);
- expect(fontRows().every((row) => row.className.includes("disabled"))).toBe(true);
- });
-
- it("brings them within reach once custom fonts are on", () => {
- mocks.stored = { overrideThemeFonts: true };
- open();
-
- expect(fontRows()).toHaveLength(4);
- expect(fontRows().some((row) => row.className.includes("disabled"))).toBe(false);
- });
-
- it("nests them under the switch that governs them", () => {
- open();
- expect(fontRows().every((row) => row.className.includes("tn-card-section-nested"))).toBe(true);
- });
-
- it("offers the fonts the user labelled #customFont, one entry per note", async () => {
- mocks.stored = { overrideThemeFonts: true };
- mocks.userFonts = [
- { noteId: "fontNoteA1", title: "Iosevka", blobId: "b1" },
- { noteId: "fontNoteB2", title: "Inter", blobId: "b2" },
- // Two notes can carry the same name; each is its own entry, told apart by its note.
- { noteId: "fontNoteC3", title: "Inter", 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);
- // Ahead of the stock families, which the user has to scroll past otherwise.
- expect(headers[0]).toBe("fonts.user-fonts");
-
- // Each is named by its note's own title, and stands for the note rather than for a family.
- const listed = [ ...(picker?.querySelectorAll(".dropdown-item") ?? []) ].map((item) => item.textContent?.trim());
- expect(listed.filter((entry) => entry === "Inter")).toHaveLength(2);
- expect(listed).toContain("Iosevka");
- });
-
- it("names a set custom font by its note's title, not by the reference the option holds", async () => {
- mocks.stored = { overrideThemeFonts: true, mainFontFamily: "customFont:fontNoteA1" };
- mocks.userFonts = [ { noteId: "fontNoteA1", title: "Iosevka", blobId: "b1" } ];
- open();
- await act(async () => {});
-
- expect(fontRows()[0].querySelector(".font-option-specimen")?.textContent).toBe("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("offers the fonts installed on the device in place of the guessed families", async () => {
- mocks.stored = { overrideThemeFonts: true };
- mocks.systemFonts = [
- { family: "Adwaita Mono", monospace: true },
- { family: "Inter", monospace: false }
- ];
- 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);
- // Split by the one thing a browser can tell about an installed family.
- expect(headers).toContain("fonts.proportional-system-fonts");
- expect(headers).toContain("fonts.monospace-system-fonts");
- // The named families are a guess at what a device has, and go once there is an answer.
- expect(headers).not.toContain("fonts.sans-serif-system-fonts");
- // The generics resolve wherever Trilium runs, so they stay.
- expect(headers).toContain("fonts.generic-fonts");
-
- const listed = [ ...document.querySelectorAll(".font-picker-list .dropdown-item") ].map((item) => item.textContent?.trim());
- expect(listed).toEqual(expect.arrayContaining([ "Adwaita Mono", "Inter" ]));
- });
-
- it("heads only the half of the split that has fonts in it", async () => {
- mocks.stored = { overrideThemeFonts: true };
- mocks.systemFonts = [ { family: "Inter", monospace: false } ];
- 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).toContain("fonts.proportional-system-fonts");
- expect(headers).not.toContain("fonts.monospace-system-fonts");
- });
-
- it("keeps the named families on a server build, which cannot ask what the device has", async () => {
- mocks.electron = false;
- mocks.stored = { overrideThemeFonts: true };
- mocks.systemFonts = [ { family: "Inter", monospace: false } ];
- 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.proportional-system-fonts");
- expect(headers).toContain("fonts.sans-serif-system-fonts");
- });
-
- it("narrows the list to the fonts matching what is searched for", async () => {
- await openPicker();
- await act(async () => searchFonts("georgia"));
-
- expect(listedFonts()).toEqual([ "Georgia" ]);
- // The groups left with nothing go, their headers with them.
- expect(listedHeaders()).toEqual([ "fonts.serif-system-fonts" ]);
- });
-
- it("keeps a whole group whose own name is searched for", async () => {
- await openPicker();
- await act(async () => searchFonts("handwriting"));
-
- // The group is what was asked for, so its fonts no longer have to match on their own.
- expect(listedFonts()).toEqual([ "Bradley Hand", "Brush Script MT", "Comic Sans MS", "Luminari" ]);
- });
-
- it("says so when nothing matches, rather than leaving an empty list", async () => {
- await openPicker();
- await act(async () => searchFonts("Nonesuch"));
-
- expect(document.querySelector(".font-picker-list")).toBeNull();
- expect(document.querySelector(".font-picker-empty")?.textContent).toContain("fonts.no_fonts_found");
- });
-
- it("brings the whole list back when the search is cleared", async () => {
- await openPicker();
- await act(async () => searchFonts("georgia"));
-
- // The field is the settings' own, so it comes with the button that empties it.
- const clear = document.querySelector<HTMLElement>(".font-picker-modal .settings-search-clear");
- expect(clear).not.toBeNull();
-
- await act(async () => clear?.click());
- expect(listedFonts()).toContain("Arial");
- expect(listedHeaders()).toContain("fonts.generic-fonts");
- });
-
- it("leaves ligatures alone, since they come from the theme's own font", () => {
- open();
-
- // Not nested under custom fonts: the setting is needed exactly when those are off.
- const ligatures = host.querySelector("input.switch-toggle[id^='monospace-ligatures-enabled-']");
- expect(ligatures?.closest(".tn-card-option")?.className).not.toContain("tn-card-section-nested");
- expect((ligatures as HTMLInputElement | null)?.disabled).toBe(false);
- });
-});
describe("the layout choices", () => {
it("gives each an illustrated card of its own, side by side", () => {
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.tsx b/apps/client/src/widgets/type_widgets/options/appearance.tsx
index 1251bc66be..4a777e9e5c 100644
--- a/apps/client/src/widgets/type_widgets/options/appearance.tsx
+++ b/apps/client/src/widgets/type_widgets/options/appearance.tsx
@@ -1,38 +1,28 @@
import "./appearance.css";
-import { customFontFamily, customFontNoteId, customFontOption, 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";
-import { useEffect, useMemo, useRef, useState } from "preact/hooks";
+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 { listSystemFonts, type SystemFont } from "../../../services/font";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import { isElectron, isMobile, reloadFrontendApp } from "../../../services/utils";
import { VerticalLayoutIcon } from "../../buttons/global_menu";
import { Card, CardSection, OptionCardSection } from "../../react/Card";
import Dropdown from "../../react/Dropdown";
-import { filterTokens, matchesFilter } from "../../react/filter";
-import FormList, { FormListHeader, FormListItem } from "../../react/FormList";
+import { FormListHeader, FormListItem } from "../../react/FormList";
import { FormTextBoxWithUnit } from "../../react/FormTextBox";
import FormToggle from "../../react/FormToggle";
import HelpButton from "../../react/HelpButton";
-import { useNoteTitle, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
import Icon from "../../react/Icon";
-import Modal from "../../react/Modal";
-import NoItems from "../../react/NoItems";
import SegmentedChoice, { SegmentedChoiceOption } from "../../react/SegmentedChoice";
-import Slider from "../../react/Slider";
+import Fonts from "./appearance_fonts";
import OptionsPageHeader from "./components/OptionsPageHeader";
import PlatformIndicator from "./components/PlatformIndicator";
import RadioWithIllustration from "./components/RadioWithIllustration";
import RelatedSettings from "./components/RelatedSettings";
import RestartAction from "./components/RestartAction";
-import SettingsSearch from "./components/SettingsSearch";
const MIN_CONTENT_WIDTH = 640;
@@ -77,59 +67,6 @@ function resolveTheme(themeVal: string | null): { family: ThemeFamily | null; sc
return { family, scheme, isCustom };
}
-interface FontFamilyEntry {
- value: FontFamily;
- label?: string;
-}
-
-interface FontGroup {
- title: string;
- items: FontFamilyEntry[];
-}
-
-/** Families the browser resolves for itself, so they hold wherever Trilium runs. */
-const GENERIC_FONTS: FontGroup = {
- title: t("fonts.generic-fonts"),
- items: [
- { value: "theme", label: t("fonts.theme_defined") },
- { value: "system", label: t("fonts.system-default") },
- { value: "serif", label: t("fonts.serif") },
- { value: "sans-serif", label: t("fonts.sans-serif") },
- { value: "monospace", label: t("fonts.monospace") }
- ]
-};
-
-/** Named families, offered where the device's own fonts cannot be listed (see {@link useFontGroups}). */
-const FONT_FAMILIES: FontGroup[] = [
- GENERIC_FONTS,
- {
- title: t("fonts.sans-serif-system-fonts"),
- items: [
- { value: "Arial" },
- { value: "Verdana" },
- { value: "Helvetica" },
- { value: "Tahoma" },
- { value: "Trebuchet MS" },
- { value: "Impact" },
- { value: "Microsoft YaHei" }
- ]
- },
- {
- title: t("fonts.serif-system-fonts"),
- items: [{ value: "Times New Roman" }, { value: "Georgia" }, { value: "Garamond" }, { value: "American Typewriter" }]
- },
- {
- title: t("fonts.monospace-system-fonts"),
- // "Andale Mono" carries no accent: the accented spelling matches no installed family, so CSS
- // falls through to the generic default.
- items: [{ value: "Courier New" }, { value: "Andale Mono" }, { value: "Lucida Console" }, { value: "Monaco" }]
- },
- {
- title: t("fonts.handwriting-system-fonts"),
- items: [{ value: "Bradley Hand" }, { value: "Brush Script MT" }, { value: "Comic Sans MS" }, { value: "Luminari" }]
- }
-];
-
export default function AppearanceSettings() {
return (
<>
@@ -458,361 +395,6 @@ function OrientationIllustration({ orientation }: { orientation: "vertical" | "h
);
}
-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")}>
- <OptionCardSection
- name="override-theme-fonts"
- label={t("fonts.custom_fonts")}
- description={t("fonts.custom_fonts_description")}
- // The four fonts stay on show with the switch off, greyed rather than gone: what
- // is there to be set is the whole reason for turning it on, and a switch with
- // nothing under it says nothing about what it would bring.
- subSectionsVisible
- subSections={[
- <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} />
- </OptionCardSection>
-
- {/*
- * Deliberately not nested under `overrideThemeFonts` like the fonts above: the
- * ligatures come from the *theme's* monospace font, so the setting is needed exactly
- * when custom fonts are off. Gating it would put it out of reach of everyone affected.
- */}
- <OptionCardSection
- name="monospace-ligatures-enabled"
- label={t("fonts.monospace_ligatures")}
- description={t("fonts.monospace_ligatures_description")}
- >
- <FormToggle currentValue={ligaturesEnabled} onChange={setLigaturesEnabled} />
- </OptionCardSection>
- </Card>
- );
-}
-
-/**
- * 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.
- *
- * Where the device's own fonts can be listed, they stand in for the named families: the stock list
- * is a guess at what a device has, and half of it does not resolve on any given one.
- */
-function useFontGroups(): FontGroup[] {
- const [ customFonts, setCustomFonts ] = useState<UserFont[]>([]);
- const systemFonts = useSystemFonts();
-
- useEffect(() => {
- let cancelled = false;
- const registered: FontFace[] = [];
-
- (async () => {
- const fonts = await getCustomFonts();
- if (cancelled) return;
- setCustomFonts(fonts);
-
- await Promise.all(fonts.map(async ({ noteId, blobId }) => {
- try {
- const face = await registerFontNote(noteId, customFontFamily(noteId), 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(() => {
- const stockGroups = systemFonts.length ? installedFontGroups(systemFonts) : FONT_FAMILIES;
-
- // Ahead of the rest: a font the user went and added is the one they are looking for.
- return customFonts.length
- ? [ {
- title: t("fonts.user-fonts"),
- items: customFonts.map(({ noteId, title }) => ({ value: customFontOption(noteId), label: title }))
- }, ...stockGroups ]
- : stockGroups;
- }, [ customFonts, systemFonts ]);
-}
-
-/**
- * The generic families, then the installed ones split by advance width. Serif and sans-serif cannot
- * be told apart from a browser — nothing reports a face's style — so this is as far as the grouping
- * goes, and an empty half is left out rather than headed.
- */
-function installedFontGroups(systemFonts: SystemFont[]): FontGroup[] {
- const groups = [ GENERIC_FONTS ];
- const named: [ string, SystemFont[] ][] = [
- [ t("fonts.proportional-system-fonts"), systemFonts.filter(({ monospace }) => !monospace) ],
- [ t("fonts.monospace-system-fonts"), systemFonts.filter(({ monospace }) => monospace) ]
- ];
-
- for (const [ title, fonts ] of named) {
- if (fonts.length) {
- groups.push({ title, items: fonts.map(({ family }) => ({ value: family })) });
- }
- }
-
- return groups;
-}
-
-/**
- * The fonts installed on this device, empty everywhere but the desktop app. The API behind
- * {@link listSystemFonts} also exists in a browser served over HTTPS, where reading it would cost
- * the user a permission prompt for a list the desktop app can have for free — so the ask is kept to
- * the one runtime that grants it itself (see the `local-fonts` entry in `web_contents_security.ts`).
- */
-function useSystemFonts(): SystemFont[] {
- const [ fonts, setFonts ] = useState<SystemFont[]>([]);
-
- useEffect(() => {
- if (!isElectron()) return;
-
- let cancelled = false;
- void listSystemFonts().then((found) => {
- if (!cancelled) setFonts(found);
- });
-
- return () => {
- cancelled = true;
- };
- }, []);
-
- return fonts;
-}
-
-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, groups, fontFamilyOption, fontSizeOption, disabled, isMonospace }: FontProps) {
- const [ fontFamily, setFontFamily ] = useTriliumOption(fontFamilyOption);
- const [ fontSize, setFontSize ] = useTriliumOption(fontSizeOption);
- const [ showModal, setShowModal ] = useState(false);
-
- // One of the user's own fonts is named by the note holding it, so its own title says what is
- // set — read from the cache rather than waited for from the listing, and it follows a rename.
- const customFontTitle = useNoteTitle(customFontNoteId(fontFamily) ?? undefined, undefined);
-
- // Find the current font entry to display
- const currentFont = groups
- .flatMap(group => group.items)
- .find(item => item.value === fontFamily);
- const displayLabel = customFontTitle ?? currentFont?.label ?? currentFont?.value ?? fontFamily ?? "";
-
- // Map option name to CSS variable
- const themeCssVariable = {
- mainFontFamily: "var(--main-font-family)",
- treeFontFamily: "var(--tree-font-family)",
- detailFontFamily: "var(--detail-font-family)",
- monospaceFontFamily: "var(--monospace-font-family)"
- }[fontFamilyOption] ?? "inherit";
-
- // Get the CSS font-family value for preview
- const getFontFamily = (value: string) => {
- if (value === "theme") {
- // Use the theme's CSS variable for this font option
- return themeCssVariable;
- }
- if (value === "system") {
- // Use the appropriate system font stack
- return isMonospace ? SYSTEM_MONOSPACE_FONT_STACK : SYSTEM_SANS_SERIF_FONT_STACK;
- }
- // One of the user's own fonts names the note it is stored in, not a family the browser
- // could resolve; the family it was registered under is built from the same id.
- const noteId = customFontNoteId(value);
- return noteId ? customFontFamily(noteId) : value;
- };
-
- return (
- <>
- <OptionCardSection
- className={clsx("font-option", disabled && "disabled")}
- label={label}
- description={description}
- onAction={disabled ? undefined : () => setShowModal(true)}
- >
- <span className="font-option-preview">
- <span className="font-option-specimen" style={{ fontFamily: getFontFamily(fontFamily ?? ""), fontSize: `${fontSize}%` }}>{displayLabel}</span>
- <span className="tn-card-chevron" />
- </span>
- </OptionCardSection>
-
- <FontPickerModal
- show={showModal}
- onHidden={() => setShowModal(false)}
- title={label}
- groups={groups}
- fontFamily={fontFamily ?? ""}
- fontSize={parseInt(fontSize ?? "100", 10)}
- onFontFamilyChange={setFontFamily}
- onFontSizeChange={(size) => setFontSize(String(size))}
- getFontFamily={getFontFamily}
- sizeDescription={sizeDescription}
- />
- </>
- );
-}
-
-const PREVIEW_TEXT = "The quick brown fox jumps over the lazy dog. 0123456789";
-
-interface FontPickerModalProps {
- show: boolean;
- onHidden: () => void;
- title: string;
- groups: FontGroup[];
- fontFamily: string;
- fontSize: number;
- onFontFamilyChange: (value: string) => void;
- onFontSizeChange: (value: number) => void;
- getFontFamily: (value: string) => string | undefined;
- sizeDescription?: string;
-}
-
-function FontPickerModal({ show, onHidden, title, groups, fontFamily, fontSize, onFontFamilyChange, onFontSizeChange, getFontFamily, sizeDescription }: FontPickerModalProps) {
- const [ query, setQuery ] = useState("");
- const searchRef = useRef<HTMLInputElement>(null);
- const matching = useMemo(() => filterFontGroups(groups, query), [ groups, query ]);
-
- return createPortal(
- <Modal
- className="font-picker-modal"
- title={title}
- size="lg"
- show={show}
- // The list runs to every family the device has, so the search is what the dialog opens on.
- onShown={() => searchRef.current?.focus()}
- onHidden={() => {
- setQuery("");
- onHidden();
- }}
- stackable
- sidebar={<>
- <SettingsSearch
- inputRef={searchRef}
- query={query}
- onChange={setQuery}
- placeholder={t("fonts.search_placeholder")}
- />
-
- {matching.length > 0 ? (
- <FormList fullHeight wrapperClassName="font-picker-list">
- {matching.map(group => (
- <Fragment key={group.title}>
- <FormListHeader text={group.title} />
- {group.items.map(item => (
- <FormListItem
- key={item.value}
- onClick={() => onFontFamilyChange(item.value)}
- checked={fontFamily === item.value}
- selected={fontFamily === item.value}
- >
- <span style={{ fontFamily: getFontFamily(item.value) }}>
- {item.label ?? item.value}
- </span>
- </FormListItem>
- ))}
- </Fragment>
- ))}
- </FormList>
- ) : (
- <NoItems className="font-picker-empty" icon="bx bx-search" text={t("fonts.no_fonts_found")} size="small" />
- )}
- </>}
- >
- <div className="font-picker-settings">
- <div className="font-size-control">
- <label>{t("fonts.size")}</label>
- <div className="font-size-slider">
- <Slider
- value={fontSize}
- onChange={onFontSizeChange}
- min={50}
- max={200}
- step={5}
- />
- <span className="font-size-value">{fontSize}%</span>
- </div>
- {sizeDescription && <small className="font-size-description">{sizeDescription}</small>}
- </div>
-
- <div className="font-preview">
- <label>{t("fonts.preview")}</label>
- <div
- className="font-preview-text"
- style={{
- fontFamily: getFontFamily(fontFamily),
- fontSize: `${fontSize}%`
- }}
- >
- {PREVIEW_TEXT}
- </div>
- </div>
- </div>
- </Modal>,
- document.body
- );
-}
-
-/**
- * The groups narrowed to the fonts matching `query`, those left with nothing dropped. A group whose
- * own title matches keeps all of its fonts, so a search for "monospace" offers every monospace
- * family rather than only the generic entry named after them.
- */
-function filterFontGroups(groups: FontGroup[], query: string): FontGroup[] {
- const tokens = filterTokens(query);
- if (tokens.length === 0) {
- return groups;
- }
-
- const matching: FontGroup[] = [];
- for (const group of groups) {
- if (matchesFilter(tokens, group.title)) {
- matching.push(group);
- continue;
- }
-
- // A user font is named by the note holding it; the value is that note's id, which is no
- // name to search by.
- const items = group.items.filter((item) => matchesFilter(tokens, item.label ?? item.value));
- if (items.length > 0) {
- matching.push({ ...group, items });
- }
- }
-
- return matching;
-}
-
function ElectronIntegration() {
const [ zoomFactor ] = useTriliumOption("zoomFactor");
const [ nativeTitleBarVisible, setNativeTitleBarVisible ] = useTriliumOptionBool("nativeTitleBarVisible");
diff --git a/apps/client/src/widgets/type_widgets/options/appearance_fonts.css b/apps/client/src/widgets/type_widgets/options/appearance_fonts.css
new file mode 100644
index 0000000000..5ea7dc93d7
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/appearance_fonts.css
@@ -0,0 +1,162 @@
+/* Font Option Row */
+.font-option {
+ cursor: pointer;
+
+ /* Shown rather than hidden with custom fonts off, so the settings can still be read. */
+ &.disabled {
+ opacity: 0.5;
+ pointer-events: none;
+ }
+}
+
+.font-option-preview {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: var(--muted-text-color);
+}
+
+/* The specimen is drawn at the user's own family and size, so it can outgrow the screen: it takes
+ the line below the name earlier than an ordinary option does. Measured against the card, which
+ `Card.css` makes a container. */
+@container (max-width: 600px) {
+ .font-option {
+ flex-direction: column;
+ align-items: stretch;
+ }
+
+ .font-option .font-option-preview {
+ justify-content: space-between;
+ }
+
+ .font-option .font-option-specimen {
+ /* `anywhere`: a family name is often one word, with no break the browser would take. */
+ min-width: 0;
+ overflow-wrap: anywhere;
+ }
+}
+
+/* Font Picker Modal */
+body.desktop .modal.font-picker-modal {
+ .modal-content-with-sidebar {
+ height: 60vh;
+ }
+
+ /* On the sidebar rather than on the list, which a search matching nothing takes away. */
+ .modal-sidebar {
+ width: 280px;
+ }
+}
+
+.modal.font-picker-modal {
+ /* Keep the sidebar background within the rounded corners. */
+ .modal-content {
+ overflow: hidden;
+ }
+
+ .modal-body {
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .modal-sidebar {
+ background-color: var(--card-background-color);
+ }
+
+ .modal-sidebar .dropdown-menu.static {
+ background-color: transparent !important;
+ border: none;
+ border-radius: 0 !important;
+ }
+
+ /* Set here rather than by the field, which takes the room it is given (see SettingsSearch.css).
+ Room below as well as above: the focus ring reaches past the border, and the list beneath it
+ paints over whatever crosses into it. */
+ .settings-search {
+ margin: 8px;
+ }
+
+ .font-picker-list {
+ flex: 1 1 0;
+ min-height: 0;
+ overflow: auto;
+
+ .dropdown-item {
+ font-size: 14px;
+ }
+ }
+
+ .font-picker-empty {
+ flex: 1 1 0;
+ min-height: 0;
+ padding: 16px;
+ }
+
+ .font-picker-settings {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ padding: 16px;
+ gap: 16px;
+ }
+}
+
+.font-size-control {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+
+ label {
+ font-weight: 500;
+ color: var(--muted-text-color);
+ font-size: 12px;
+ text-transform: uppercase;
+ }
+
+ .font-size-description {
+ color: var(--muted-text-color);
+ font-size: 12px;
+ }
+}
+
+.font-size-slider {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+
+ .slider {
+ flex: 1;
+ }
+
+ .font-size-value {
+ min-width: 50px;
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+ }
+}
+
+.font-preview {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-height: 0;
+
+ label {
+ font-weight: 500;
+ color: var(--muted-text-color);
+ font-size: 12px;
+ text-transform: uppercase;
+ }
+}
+
+.font-preview-text {
+ flex: 1;
+ padding: 16px;
+ border: 1px solid var(--main-border-color);
+ border-radius: 6px;
+ background: var(--main-background-color);
+ overflow: auto;
+ line-height: 1.6;
+}
diff --git a/apps/client/src/widgets/type_widgets/options/appearance_fonts.spec.tsx b/apps/client/src/widgets/type_widgets/options/appearance_fonts.spec.tsx
new file mode 100644
index 0000000000..daca8bf1bc
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/appearance_fonts.spec.tsx
@@ -0,0 +1,258 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ electron: true,
+ stored: {} as Record<string, string | boolean>,
+ userFonts: [] as { noteId: string; title: string; blobId: string }[],
+ systemFonts: [] as { family: string; monospace: boolean }[]
+}));
+
+// Only the desktop app can be asked what fonts the device has.
+vi.mock("../../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/utils")>()),
+ isElectron: () => mocks.electron
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// The 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 })
+}));
+
+// happy-dom exposes no `queryLocalFonts`, so what the desktop app would find is stood in for.
+vi.mock("../../../services/font", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/font")>()),
+ listSystemFonts: async () => mocks.systemFonts
+}));
+
+// useNoteTitle names the font a font option points at; the listing above is what the picker lists.
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useNoteTitle: (noteId: string | undefined) => mocks.userFonts.find((font) => font.noteId === noteId)?.title,
+ useTriliumOption: (name: string) => [ String(mocks.stored[name] ?? ""), vi.fn() ],
+ useTriliumOptionBool: (name: string) => [ mocks.stored[name] === true, vi.fn() ]
+}));
+
+import Fonts from "./appearance_fonts";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.electron = true;
+ mocks.stored = {};
+ mocks.userFonts = [];
+ mocks.systemFonts = [];
+ Object.defineProperty(document, "fonts", {
+ configurable: true,
+ value: { add: vi.fn(), delete: vi.fn() }
+ });
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+});
+
+/**
+ * Renders the card fresh. The tree is torn down first so that a scenario changing a setting and
+ * rendering again gets a clean mount, rather than a diff against what the previous values rendered.
+ */
+function open() {
+ act(() => {
+ render(null, host);
+ render(<Fonts />, host);
+ });
+}
+
+const fontRows = () => [ ...host.querySelectorAll(".font-option") ];
+const listedFonts = () => [ ...document.querySelectorAll(".font-picker-list .dropdown-item") ].map((item) => item.textContent?.trim());
+const listedHeaders = () => [ ...document.querySelectorAll(".font-picker-list .dropdown-header") ].map((header) => header.textContent);
+
+/**
+ * Opens the picker of the first font on a server build, where the list is the stock one — the
+ * families it holds are known, which is what a search can be checked against.
+ */
+async function openPicker() {
+ mocks.electron = false;
+ mocks.stored = { overrideThemeFonts: true };
+ open();
+ await act(async () => {});
+ await act(async () => (fontRows()[0] as HTMLElement).click());
+}
+
+/** Types into the picker's search box, as the user would. */
+function searchFonts(query: string) {
+ const search = document.querySelector<HTMLInputElement>(".font-picker-modal .settings-search input");
+ if (!search) throw new Error("the font picker has no search box");
+
+ search.value = query;
+ search.dispatchEvent(new Event("input", { bubbles: true }));
+}
+
+describe("the font settings", () => {
+ it("keeps the fonts on show with custom fonts off, greyed rather than gone", () => {
+ open();
+
+ // What turning the switch on would put in force is the whole reason for turning it on.
+ expect(fontRows()).toHaveLength(4);
+ expect(fontRows().every((row) => row.className.includes("disabled"))).toBe(true);
+ });
+
+ it("brings them within reach once custom fonts are on", () => {
+ mocks.stored = { overrideThemeFonts: true };
+ open();
+
+ expect(fontRows()).toHaveLength(4);
+ expect(fontRows().some((row) => row.className.includes("disabled"))).toBe(false);
+ });
+
+ it("nests them under the switch that governs them", () => {
+ open();
+ expect(fontRows().every((row) => row.className.includes("tn-card-section-nested"))).toBe(true);
+ });
+
+ it("offers the fonts the user labelled #customFont, one entry per note", async () => {
+ mocks.stored = { overrideThemeFonts: true };
+ mocks.userFonts = [
+ { noteId: "fontNoteA1", title: "Iosevka", blobId: "b1" },
+ { noteId: "fontNoteB2", title: "Inter", blobId: "b2" },
+ // Two notes can carry the same name; each is its own entry, told apart by its note.
+ { noteId: "fontNoteC3", title: "Inter", 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);
+ // Ahead of the stock families, which the user has to scroll past otherwise.
+ expect(headers[0]).toBe("fonts.user-fonts");
+
+ // Each is named by its note's own title, and stands for the note rather than for a family.
+ const listed = [ ...(picker?.querySelectorAll(".dropdown-item") ?? []) ].map((item) => item.textContent?.trim());
+ expect(listed.filter((entry) => entry === "Inter")).toHaveLength(2);
+ expect(listed).toContain("Iosevka");
+ });
+
+ it("names a set custom font by its note's title, not by the reference the option holds", async () => {
+ mocks.stored = { overrideThemeFonts: true, mainFontFamily: "customFont:fontNoteA1" };
+ mocks.userFonts = [ { noteId: "fontNoteA1", title: "Iosevka", blobId: "b1" } ];
+ open();
+ await act(async () => {});
+
+ expect(fontRows()[0].querySelector(".font-option-specimen")?.textContent).toBe("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("offers the fonts installed on the device in place of the guessed families", async () => {
+ mocks.stored = { overrideThemeFonts: true };
+ mocks.systemFonts = [
+ { family: "Adwaita Mono", monospace: true },
+ { family: "Inter", monospace: false }
+ ];
+ 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);
+ // Split by the one thing a browser can tell about an installed family.
+ expect(headers).toContain("fonts.proportional-system-fonts");
+ expect(headers).toContain("fonts.monospace-system-fonts");
+ // The named families are a guess at what a device has, and go once there is an answer.
+ expect(headers).not.toContain("fonts.sans-serif-system-fonts");
+ // The generics resolve wherever Trilium runs, so they stay.
+ expect(headers).toContain("fonts.generic-fonts");
+
+ const listed = [ ...document.querySelectorAll(".font-picker-list .dropdown-item") ].map((item) => item.textContent?.trim());
+ expect(listed).toEqual(expect.arrayContaining([ "Adwaita Mono", "Inter" ]));
+ });
+
+ it("heads only the half of the split that has fonts in it", async () => {
+ mocks.stored = { overrideThemeFonts: true };
+ mocks.systemFonts = [ { family: "Inter", monospace: false } ];
+ 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).toContain("fonts.proportional-system-fonts");
+ expect(headers).not.toContain("fonts.monospace-system-fonts");
+ });
+
+ it("keeps the named families on a server build, which cannot ask what the device has", async () => {
+ mocks.electron = false;
+ mocks.stored = { overrideThemeFonts: true };
+ mocks.systemFonts = [ { family: "Inter", monospace: false } ];
+ 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.proportional-system-fonts");
+ expect(headers).toContain("fonts.sans-serif-system-fonts");
+ });
+
+ it("narrows the list to the fonts matching what is searched for", async () => {
+ await openPicker();
+ await act(async () => searchFonts("georgia"));
+
+ expect(listedFonts()).toEqual([ "Georgia" ]);
+ // The groups left with nothing go, their headers with them.
+ expect(listedHeaders()).toEqual([ "fonts.serif-system-fonts" ]);
+ });
+
+ it("keeps a whole group whose own name is searched for", async () => {
+ await openPicker();
+ await act(async () => searchFonts("handwriting"));
+
+ // The group is what was asked for, so its fonts no longer have to match on their own.
+ expect(listedFonts()).toEqual([ "Bradley Hand", "Brush Script MT", "Comic Sans MS", "Luminari" ]);
+ });
+
+ it("says so when nothing matches, rather than leaving an empty list", async () => {
+ await openPicker();
+ await act(async () => searchFonts("Nonesuch"));
+
+ expect(document.querySelector(".font-picker-list")).toBeNull();
+ expect(document.querySelector(".font-picker-empty")?.textContent).toContain("fonts.no_fonts_found");
+ });
+
+ it("brings the whole list back when the search is cleared", async () => {
+ await openPicker();
+ await act(async () => searchFonts("georgia"));
+
+ // The field is the settings' own, so it comes with the button that empties it.
+ const clear = document.querySelector<HTMLElement>(".font-picker-modal .settings-search-clear");
+ expect(clear).not.toBeNull();
+
+ await act(async () => clear?.click());
+ expect(listedFonts()).toContain("Arial");
+ expect(listedHeaders()).toContain("fonts.generic-fonts");
+ });
+
+ it("leaves ligatures alone, since they come from the theme's own font", () => {
+ open();
+
+ // Not nested under custom fonts: the setting is needed exactly when those are off.
+ const ligatures = host.querySelector("input.switch-toggle[id^='monospace-ligatures-enabled-']");
+ expect(ligatures?.closest(".tn-card-option")?.className).not.toContain("tn-card-section-nested");
+ expect((ligatures as HTMLInputElement | null)?.disabled).toBe(false);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/appearance_fonts.tsx b/apps/client/src/widgets/type_widgets/options/appearance_fonts.tsx
new file mode 100644
index 0000000000..6d11ffbf26
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/appearance_fonts.tsx
@@ -0,0 +1,429 @@
+import "./appearance_fonts.css";
+
+import { customFontFamily, customFontNoteId, customFontOption, 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";
+import { useEffect, useMemo, useRef, useState } from "preact/hooks";
+
+import { getCustomFonts, registerFontNote } from "../../../services/custom_fonts";
+import { listSystemFonts, type SystemFont } from "../../../services/font";
+import { t } from "../../../services/i18n";
+import { isElectron } from "../../../services/utils";
+import { Card, OptionCardSection } from "../../react/Card";
+import { filterTokens, matchesFilter } from "../../react/filter";
+import FormList, { FormListHeader, FormListItem } from "../../react/FormList";
+import FormToggle from "../../react/FormToggle";
+import { useNoteTitle, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import Modal from "../../react/Modal";
+import NoItems from "../../react/NoItems";
+import Slider from "../../react/Slider";
+import SettingsSearch from "./components/SettingsSearch";
+
+interface FontFamilyEntry {
+ value: FontFamily;
+ label?: string;
+}
+
+interface FontGroup {
+ title: string;
+ items: FontFamilyEntry[];
+}
+
+/** Families the browser resolves for itself, so they hold wherever Trilium runs. */
+const GENERIC_FONTS: FontGroup = {
+ title: t("fonts.generic-fonts"),
+ items: [
+ { value: "theme", label: t("fonts.theme_defined") },
+ { value: "system", label: t("fonts.system-default") },
+ { value: "serif", label: t("fonts.serif") },
+ { value: "sans-serif", label: t("fonts.sans-serif") },
+ { value: "monospace", label: t("fonts.monospace") }
+ ]
+};
+
+/** Named families, offered where the device's own fonts cannot be listed (see {@link useFontGroups}). */
+const FONT_FAMILIES: FontGroup[] = [
+ GENERIC_FONTS,
+ {
+ title: t("fonts.sans-serif-system-fonts"),
+ items: [
+ { value: "Arial" },
+ { value: "Verdana" },
+ { value: "Helvetica" },
+ { value: "Tahoma" },
+ { value: "Trebuchet MS" },
+ { value: "Impact" },
+ { value: "Microsoft YaHei" }
+ ]
+ },
+ {
+ title: t("fonts.serif-system-fonts"),
+ items: [{ value: "Times New Roman" }, { value: "Georgia" }, { value: "Garamond" }, { value: "American Typewriter" }]
+ },
+ {
+ title: t("fonts.monospace-system-fonts"),
+ // "Andale Mono" carries no accent: the accented spelling matches no installed family, so CSS
+ // falls through to the generic default.
+ items: [{ value: "Courier New" }, { value: "Andale Mono" }, { value: "Lucida Console" }, { value: "Monaco" }]
+ },
+ {
+ title: t("fonts.handwriting-system-fonts"),
+ items: [{ value: "Bradley Hand" }, { value: "Brush Script MT" }, { value: "Comic Sans MS" }, { value: "Luminari" }]
+ }
+];
+
+export default 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")}>
+ <OptionCardSection
+ name="override-theme-fonts"
+ label={t("fonts.custom_fonts")}
+ description={t("fonts.custom_fonts_description")}
+ // The four fonts stay on show with the switch off, greyed rather than gone: what
+ // is there to be set is the whole reason for turning it on, and a switch with
+ // nothing under it says nothing about what it would bring.
+ subSectionsVisible
+ subSections={[
+ <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} />
+ </OptionCardSection>
+
+ {/*
+ * Deliberately not nested under `overrideThemeFonts` like the fonts above: the
+ * ligatures come from the *theme's* monospace font, so the setting is needed exactly
+ * when custom fonts are off. Gating it would put it out of reach of everyone affected.
+ */}
+ <OptionCardSection
+ name="monospace-ligatures-enabled"
+ label={t("fonts.monospace_ligatures")}
+ description={t("fonts.monospace_ligatures_description")}
+ >
+ <FormToggle currentValue={ligaturesEnabled} onChange={setLigaturesEnabled} />
+ </OptionCardSection>
+ </Card>
+ );
+}
+
+/**
+ * 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.
+ *
+ * Where the device's own fonts can be listed, they stand in for the named families: the stock list
+ * is a guess at what a device has, and half of it does not resolve on any given one.
+ */
+function useFontGroups(): FontGroup[] {
+ const [ customFonts, setCustomFonts ] = useState<UserFont[]>([]);
+ const systemFonts = useSystemFonts();
+
+ useEffect(() => {
+ let cancelled = false;
+ const registered: FontFace[] = [];
+
+ (async () => {
+ const fonts = await getCustomFonts();
+ if (cancelled) return;
+ setCustomFonts(fonts);
+
+ await Promise.all(fonts.map(async ({ noteId, blobId }) => {
+ try {
+ const face = await registerFontNote(noteId, customFontFamily(noteId), 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(() => {
+ const stockGroups = systemFonts.length ? installedFontGroups(systemFonts) : FONT_FAMILIES;
+
+ // Ahead of the rest: a font the user went and added is the one they are looking for.
+ return customFonts.length
+ ? [ {
+ title: t("fonts.user-fonts"),
+ items: customFonts.map(({ noteId, title }) => ({ value: customFontOption(noteId), label: title }))
+ }, ...stockGroups ]
+ : stockGroups;
+ }, [ customFonts, systemFonts ]);
+}
+
+/**
+ * The generic families, then the installed ones split by advance width. Serif and sans-serif cannot
+ * be told apart from a browser — nothing reports a face's style — so this is as far as the grouping
+ * goes, and an empty half is left out rather than headed.
+ */
+function installedFontGroups(systemFonts: SystemFont[]): FontGroup[] {
+ const groups = [ GENERIC_FONTS ];
+ const named: [ string, SystemFont[] ][] = [
+ [ t("fonts.proportional-system-fonts"), systemFonts.filter(({ monospace }) => !monospace) ],
+ [ t("fonts.monospace-system-fonts"), systemFonts.filter(({ monospace }) => monospace) ]
+ ];
+
+ for (const [ title, fonts ] of named) {
+ if (fonts.length) {
+ groups.push({ title, items: fonts.map(({ family }) => ({ value: family })) });
+ }
+ }
+
+ return groups;
+}
+
+/**
+ * The fonts installed on this device, empty everywhere but the desktop app. The API behind
+ * {@link listSystemFonts} also exists in a browser served over HTTPS, where reading it would cost
+ * the user a permission prompt for a list the desktop app can have for free — so the ask is kept to
+ * the one runtime that grants it itself (see the `local-fonts` entry in `web_contents_security.ts`).
+ */
+function useSystemFonts(): SystemFont[] {
+ const [ fonts, setFonts ] = useState<SystemFont[]>([]);
+
+ useEffect(() => {
+ if (!isElectron()) return;
+
+ let cancelled = false;
+ void listSystemFonts().then((found) => {
+ if (!cancelled) setFonts(found);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ return fonts;
+}
+
+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, groups, fontFamilyOption, fontSizeOption, disabled, isMonospace }: FontProps) {
+ const [ fontFamily, setFontFamily ] = useTriliumOption(fontFamilyOption);
+ const [ fontSize, setFontSize ] = useTriliumOption(fontSizeOption);
+ const [ showModal, setShowModal ] = useState(false);
+
+ // One of the user's own fonts is named by the note holding it, so its own title says what is
+ // set — read from the cache rather than waited for from the listing, and it follows a rename.
+ const customFontTitle = useNoteTitle(customFontNoteId(fontFamily) ?? undefined, undefined);
+
+ // Find the current font entry to display
+ const currentFont = groups
+ .flatMap(group => group.items)
+ .find(item => item.value === fontFamily);
+ const displayLabel = customFontTitle ?? currentFont?.label ?? currentFont?.value ?? fontFamily ?? "";
+
+ // Map option name to CSS variable
+ const themeCssVariable = {
+ mainFontFamily: "var(--main-font-family)",
+ treeFontFamily: "var(--tree-font-family)",
+ detailFontFamily: "var(--detail-font-family)",
+ monospaceFontFamily: "var(--monospace-font-family)"
+ }[fontFamilyOption] ?? "inherit";
+
+ // Get the CSS font-family value for preview
+ const getFontFamily = (value: string) => {
+ if (value === "theme") {
+ // Use the theme's CSS variable for this font option
+ return themeCssVariable;
+ }
+ if (value === "system") {
+ // Use the appropriate system font stack
+ return isMonospace ? SYSTEM_MONOSPACE_FONT_STACK : SYSTEM_SANS_SERIF_FONT_STACK;
+ }
+ // One of the user's own fonts names the note it is stored in, not a family the browser
+ // could resolve; the family it was registered under is built from the same id.
+ const noteId = customFontNoteId(value);
+ return noteId ? customFontFamily(noteId) : value;
+ };
+
+ return (
+ <>
+ <OptionCardSection
+ className={clsx("font-option", disabled && "disabled")}
+ label={label}
+ description={description}
+ onAction={disabled ? undefined : () => setShowModal(true)}
+ >
+ <span className="font-option-preview">
+ <span className="font-option-specimen" style={{ fontFamily: getFontFamily(fontFamily ?? ""), fontSize: `${fontSize}%` }}>{displayLabel}</span>
+ <span className="tn-card-chevron" />
+ </span>
+ </OptionCardSection>
+
+ <FontPickerModal
+ show={showModal}
+ onHidden={() => setShowModal(false)}
+ title={label}
+ groups={groups}
+ fontFamily={fontFamily ?? ""}
+ fontSize={parseInt(fontSize ?? "100", 10)}
+ onFontFamilyChange={setFontFamily}
+ onFontSizeChange={(size) => setFontSize(String(size))}
+ getFontFamily={getFontFamily}
+ sizeDescription={sizeDescription}
+ />
+ </>
+ );
+}
+
+const PREVIEW_TEXT = "The quick brown fox jumps over the lazy dog. 0123456789";
+
+interface FontPickerModalProps {
+ show: boolean;
+ onHidden: () => void;
+ title: string;
+ groups: FontGroup[];
+ fontFamily: string;
+ fontSize: number;
+ onFontFamilyChange: (value: string) => void;
+ onFontSizeChange: (value: number) => void;
+ getFontFamily: (value: string) => string | undefined;
+ sizeDescription?: string;
+}
+
+function FontPickerModal({ show, onHidden, title, groups, fontFamily, fontSize, onFontFamilyChange, onFontSizeChange, getFontFamily, sizeDescription }: FontPickerModalProps) {
+ const [ query, setQuery ] = useState("");
+ const searchRef = useRef<HTMLInputElement>(null);
+ const matching = useMemo(() => filterFontGroups(groups, query), [ groups, query ]);
+
+ return createPortal(
+ <Modal
+ className="font-picker-modal"
+ title={title}
+ size="lg"
+ show={show}
+ // The list runs to every family the device has, so the search is what the dialog opens on.
+ onShown={() => searchRef.current?.focus()}
+ onHidden={() => {
+ setQuery("");
+ onHidden();
+ }}
+ stackable
+ sidebar={<>
+ <SettingsSearch
+ inputRef={searchRef}
+ query={query}
+ onChange={setQuery}
+ placeholder={t("fonts.search_placeholder")}
+ />
+
+ {matching.length > 0 ? (
+ <FormList fullHeight wrapperClassName="font-picker-list">
+ {matching.map(group => (
+ <Fragment key={group.title}>
+ <FormListHeader text={group.title} />
+ {group.items.map(item => (
+ <FormListItem
+ key={item.value}
+ onClick={() => onFontFamilyChange(item.value)}
+ checked={fontFamily === item.value}
+ selected={fontFamily === item.value}
+ >
+ <span style={{ fontFamily: getFontFamily(item.value) }}>
+ {item.label ?? item.value}
+ </span>
+ </FormListItem>
+ ))}
+ </Fragment>
+ ))}
+ </FormList>
+ ) : (
+ <NoItems className="font-picker-empty" icon="bx bx-search" text={t("fonts.no_fonts_found")} size="small" />
+ )}
+ </>}
+ >
+ <div className="font-picker-settings">
+ <div className="font-size-control">
+ <label>{t("fonts.size")}</label>
+ <div className="font-size-slider">
+ <Slider
+ value={fontSize}
+ onChange={onFontSizeChange}
+ min={50}
+ max={200}
+ step={5}
+ />
+ <span className="font-size-value">{fontSize}%</span>
+ </div>
+ {sizeDescription && <small className="font-size-description">{sizeDescription}</small>}
+ </div>
+
+ <div className="font-preview">
+ <label>{t("fonts.preview")}</label>
+ <div
+ className="font-preview-text"
+ style={{
+ fontFamily: getFontFamily(fontFamily),
+ fontSize: `${fontSize}%`
+ }}
+ >
+ {PREVIEW_TEXT}
+ </div>
+ </div>
+ </div>
+ </Modal>,
+ document.body
+ );
+}
+
+/**
+ * The groups narrowed to the fonts matching `query`, those left with nothing dropped. A group whose
+ * own title matches keeps all of its fonts, so a search for "monospace" offers every monospace
+ * family rather than only the generic entry named after them.
+ */
+function filterFontGroups(groups: FontGroup[], query: string): FontGroup[] {
+ const tokens = filterTokens(query);
+ if (tokens.length === 0) {
+ return groups;
+ }
+
+ const matching: FontGroup[] = [];
+ for (const group of groups) {
+ if (matchesFilter(tokens, group.title)) {
+ matching.push(group);
+ continue;
+ }
+
+ // A user font is named by the note holding it; the value is that note's id, which is no
+ // name to search by.
+ const items = group.items.filter((item) => matchesFilter(tokens, item.label ?? item.value));
+ if (items.length > 0) {
+ matching.push({ ...group, items });
+ }
+ }
+
+ return matching;
+}