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): search the font picker's list
Elian Doranca65cb34e6e7
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex ab441cc7e7..1bae34176b 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1838,7 +1838,9 @@"serif": "Serif","sans-serif": "Sans Serif","monospace": "Monospace",- "system-default": "System default"+ "system-default": "System default",+ "search_placeholder": "Search fonts",+ "no_fonts_found": "No font matches what you are looking for."},"max_content_width": {"title": "Content Width",diff --git a/apps/client/src/widgets/type_widgets/options/appearance.css b/apps/client/src/widgets/type_widgets/options/appearance.cssindex 4214cd476f..5adae98961 100644--- a/apps/client/src/widgets/type_widgets/options/appearance.css+++ b/apps/client/src/widgets/type_widgets/options/appearance.css@@ -56,7 +56,8 @@ body.desktop .modal.font-picker-modal {height: 60vh;}- .font-picker-list {+ /* On the sidebar rather than on the list, which a search matching nothing takes away. */+ .modal-sidebar {width: 280px;}}@@ -83,6 +84,13 @@ body.desktop .modal.font-picker-modal {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;@@ -93,6 +101,12 @@ body.desktop .modal.font-picker-modal {}}+ .font-picker-empty {+ flex: 1 1 0;+ min-height: 0;+ padding: 16px;+ }+.font-picker-settings {flex: 1;display: flex;diff --git a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsxindex 38843341f1..7e5f4f3d22 100644--- a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx@@ -89,6 +89,29 @@ 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", () => {@@ -179,6 +202,18 @@ describe("the font settings", () => {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 };@@ -192,6 +227,44 @@ describe("the font settings", () => {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();@@ -202,18 +275,6 @@ describe("the font settings", () => {});});- 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");- });-describe("the layout choices", () => {it("gives each an illustrated card of its own, side by side", () => {open();diff --git a/apps/client/src/widgets/type_widgets/options/appearance.tsx b/apps/client/src/widgets/type_widgets/options/appearance.tsxindex 5a7fa1734d..1251bc66be 100644--- a/apps/client/src/widgets/type_widgets/options/appearance.tsx+++ b/apps/client/src/widgets/type_widgets/options/appearance.tsx@@ -4,7 +4,7 @@ import { customFontFamily, customFontNoteId, customFontOption, FontFamily, Optioimport clsx from "clsx";import { Fragment } from "preact";import { createPortal } from "preact/compat";-import { useEffect, useMemo, useState } from "preact/hooks";+import { useEffect, useMemo, useRef, useState } from "preact/hooks";import zoomService from "../../../components/zoom";import { ColorScheme, resolveColorScheme, THEME_FAMILY_SCHEMES } from "../../../services/color_scheme";@@ -16,6 +16,7 @@ import { isElectron, isMobile, reloadFrontendApp } from "../../../services/utilsimport { 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 { FormTextBoxWithUnit } from "../../react/FormTextBox";import FormToggle from "../../react/FormToggle";@@ -23,6 +24,7 @@ import HelpButton from "../../react/HelpButton";import { useNoteTitle, 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 OptionsPageHeader from "./components/OptionsPageHeader";@@ -30,6 +32,7 @@ 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;@@ -697,35 +700,55 @@ interface FontPickerModalProps {}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(<ModalclassName="font-picker-modal"title={title}size="lg"show={show}- onHidden={onHidden}+ // 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={- <FormList fullHeight wrapperClassName="font-picker-list">- {groups.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>- }+ 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">@@ -761,6 +784,35 @@ function FontPickerModal({ show, onHidden, title, groups, fontFamily, fontSize,);}+/**+ * 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/components/SettingsSearch.tsx b/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.tsxindex 9e34d38c2a..b5b687c411 100644--- a/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.tsx+++ b/apps/client/src/widgets/type_widgets/options/components/SettingsSearch.tsx@@ -1,25 +1,32 @@import "./SettingsSearch.css";-import { useRef } from "preact/hooks";+import { RefObject } from "preact";import { t } from "../../../../services/i18n";import ActionButton from "../../../react/ActionButton";import FormTextBox from "../../../react/FormTextBox";+import { useSyncedRef } from "../../../react/hooks";interface SettingsSearchProps {query: string;onChange(query: string): void;- /** Called when the field takes focus, which is what opens the search results. */- onFocus(): void;+ /** Called when the field takes focus, which is what opens the settings results. */+ onFocus?(): void;+ /** What the field looks through, where that is something other than the settings. */+ placeholder?: string;+ inputRef?: RefObject<HTMLInputElement>;}/*** The field at the top of the settings sidebar, which looks through every page at once rather than* through the one on show. Focusing it is enough to open the results, so that what is typed lands* somewhere it can be read straight away.+ *+ * Also stands over the lists of the dialogs the settings open, so that looking through one of those+ * is the same field in the same place (see the font picker in `appearance.tsx`).*/-export default function SettingsSearch({ query, onChange, onFocus }: SettingsSearchProps) {- const inputRef = useRef<HTMLInputElement>(null);+export default function SettingsSearch({ query, onChange, onFocus, placeholder = t("options.search_placeholder"), inputRef: externalInputRef }: SettingsSearchProps) {+ const inputRef = useSyncedRef<HTMLInputElement>(externalInputRef);return (<div className="settings-search">@@ -28,8 +35,8 @@ export default function SettingsSearch({ query, onChange, onFocus }: SettingsSea<FormTextBoxinputRef={inputRef}className="settings-search-input"- placeholder={t("options.search_placeholder")}- aria-label={t("options.search_placeholder")}+ placeholder={placeholder}+ aria-label={placeholder}currentValue={query}onChange={onChange}onFocus={onFocus}