From ea74995af2260a06eae269a4fc814d7b574dbd71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20T=C3=B3th?= <39777981+tothatt81@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:42:28 +0100 Subject: [PATCH] feat(packages/excalidraw): Extended fonts support (#11601) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Extended fonts support * Refactor fonts + improve picker * Move font logic into AppFonts * Consolidate the font metrics fallback * chore: refresh history snapshot after rebase onto master Co-Authored-By: Claude Fable 5.1 * feat(editor): font provider search and hover-preview revert in the font picker - optional `FontProvider.search` hook: matches and suggestions shared fairly across providers, "+N more" footer, "Did you mean" suggestions - font preview text helpers - revert a hover preview when the picker closes from outside (canvas click, compact mode); restore by cached id rather than selection * fix(editor): font picker scene groups, search announcements and preview revert - keep a hover preview out of the "In this scene" group while fonts register - announce a searched family only from the search rows, not when it's listed already - leave elements deleted meanwhile deleted when reverting a hover preview - keep the focus in the picker after a selection that keeps it open while editing text - skip the scene font reflow once the editor unmounted - memoize the top picks, so hovering doesn't re-run their effects * fix(editor): load fonts even when `document.fonts.check()` passes Chrome's `check()` reports any family whose name matches an installed system font as loaded, even while its web faces are unloaded (e.g. anyone with Excalifont installed). Scene fonts then never got loaded explicitly, so the first paint used the fallback font, and a font change measured text with the fallback and never repaired it once the faces arrived (a wrong bbox for good). - scene font loading always calls `load()`, which settles right away (~0.1ms) when the faces are loaded already - font family changes still redraw synchronously when `check()` passes, but load the faces regardless and re-measure when the load brought in faces that weren't loaded at measure time Claude Opus 5.5 (xhigh) * feat(fonts): custom fonts rework after the design review Format and loading: - a custom font id is `:`. The provider key is `google` or a reverse-DNS name (`isValidFontProviderKey`, `GOOGLE_FONT_PROVIDER_KEY`) - a custom font is registered under a generated CSS name (`xf--`), so its id never reaches CSS - restore keeps font families it doesn't know, instead of resetting them - loading a font no longer rewrites elements. It invalidates caches, and only text measured before the font's metrics arrived gets repaired - under collab, a scene with custom fonts no longer runs a font pass every second: only a family nothing of which has arrived yet schedules one - a StrictMode remount no longer leaves the editor on a `Fonts` instance without its undo-safety hooks Exports: - `registerFontResolvers(resolvers)` registers resolvers for every image export of a page or worker, also exported from `@excalidraw/utils`. A per-call `config.fontResolvers` wins for the providers it names - an export warns once per family it has no resolver for Google Fonts, as a new entry `@excalidraw/excalidraw/fonts/google`: - a catalog of the families with their vertical metrics, generated by `yarn gen:google-fonts` and append-only - `createGoogleFontResolver()`: resolves a family through `css2`, retries transient failures, shares in-flight requests, and takes a `fetch` for servers - `searchGoogleFonts`, `getGoogleFontPreviewText` and a list of default picks Font picker and provider API: - `availableFonts` and `search()` take `{ id, label }` entries besides plain names (`ProvidedFont`); search results are `{ kind, fonts }` - typing a name no longer resolves it as a font id: the picker only offers what a provider lists or finds - `fontPickerTip` replaces the picker's tip, i.e. to point at where a host manages its fonts - `onNewFontUsed` is gone from `FontProvider` Claude Opus 5.5 and Claude Fable 5.2 (effort 40 to 80) * feat(fonts): Google catalog of text fonts only, with a browse list - catalog: 1,895 families. Out are the 33 non-text families (symbols, emoji, knitting charts, SignWriting), Libertinus Math, which draws relation signs over the preceding letter, and the 28 families which take over 10 ms to draw a line of text in Chromium (median: 1.5 ms). Added since the first run: Agrave Pro, Firjar; kept: STIX Two Math and Noto Sans Math - generator: the exclusion rules above, by classification and by name with the reason; a family new to Google's list whose font file looks slow to draw (huge outlines, colour layers) is held back until it's measured, `--allow` lets it in; output in prettier's format - `loadMoreGoogleFonts` pages through the `GOOGLE_FONT_BROWSE_LIMIT` (100) most popular families, for a provider's `loadMore`; search still covers the whole catalog - default picks are provisional, to be hand-picked before release Claude Fable 5.2 (effort 30 to 80) * feat(editor): font picker favorites, "Browse more fonts", faster list - `fontFavorites={{ fonts, onChange }}`: the user's favorite fonts, kept by the host. A font is dragged onto a zone over the search to add it, and a favorite onto the same zone to remove it. Without the prop the picker has no favorites - list order: fonts in the scene, favorites, then the available ones with the editor's own fonts first. A font only counts as in the scene once an element uses it - `FontProvider.loadMore({ offset, limit, signal })`: a "Browse more fonts" row which pages through the provider's further fonts, and loads on by itself once clicked. What it loaded stays for when the picker reopens, and a font picked from it keeps its place. At the end, a provider with `search` gets a "Use search for more" note - rows are memoized and skip rendering while off screen (`content-visibility`), so a list of a few hundred fonts stays responsive Claude Fable 5.2 (effort 30 to 80) * feat(app): resolve Google fonts on excalidraw.com, without the picker What the app ships of the custom fonts: the package's Google Fonts resolver alone. Nothing changes in the font picker, but a text in a Google font - from a file, a shared link or a paste from another app such as Excalidraw+ - renders in that font, and is listed among the scene's fonts. - `fontProviders` with the resolver and no fonts on offer, no search - the resolver is registered for image exports made outside of the editor (the frame snapshot for diagram-to-code), which otherwise draw such text in the fallback font Claude Fable 5.2 (effort 30) * fix(fonts): font repairs and retries found in review - A font repair no longer lands during a text edit, where it took what had been typed out of undo's reach. It waits for the edit to be submitted, as it does for a drag. - One loaded face no longer counts as the font being in for text which needs another `unicode-range` subset: such text is measured again once its subset arrives. - A font file which failed to download is retried when the family is asked for again, i.e. by picking the font. - New provider callbacks under the same key are used without rebuilding the `Fonts` instance. - SVG export keeps a face whose `unicodeRange` is lowercase or uses wildcards. Claude Fable 5.2, effort 80 * feat(fonts): drop 43 Google families the editor can't lay out reliably The catalog goes from 1,895 to 1,852 families. Nothing has shipped, so the entries are removed rather than kept. - 12 whose text jumps when the text editor opens, as browsers don't agree on their vertical metrics, or whose line height is unusable. - 29 whose lines the canvas and the text editor lay out at different widths in Chrome or Safari, with no setting to bring them together. - 2 which don't draw as text fonts (Vibur, Libertinus Keyboard). The generator names each with what was measured, and holds back a new family whose font file shows the first kind. Provisional: the catalog gets another pass before release. Claude Fable 5.2, effort 80 * fix(editor): kern text the same on canvas, in the text editor and in SVG Left on the default (`font-kerning: auto`), browsers skip the kerning between a letter and a space in places: Chrome on canvas but not in the DOM, Firefox everywhere. So a line was measured and drawn wider on canvas than Chrome's text editor laid it out (6 px for "A V A T A R" in Liberation Sans at 20 px), and wider in Firefox than in Chrome's editor. Kerning is now `normal` wherever text is measured or drawn: the measuring canvas, the element canvas, the text editor and exported SVG. Claude Fable 5.2, effort 30 * fix(editor): wrap text and place the caret by the same kerning Review follow-ups to the kerning change: - Wrapping added up the widths of single-character tokens (and of the characters of a word too long for a line) one by one, which leaves out the kerning between them. "A V A T A R A V A T A R" in a 105 px box wrapped to three lines where the text editor shows two. Before a line breaks on such a sum, it's now measured as a whole. - The hidden element which finds the caret for a click was still kerned with `auto`, so in Firefox the caret could land a character early. Claude Fable 5.2, effort 80 * fix(editor): shape canvas text as a whole line, as the text editor does Chrome's canvas shapes a line word by word by default. A font which picks a letter's shape by what's around it, across spaces too (Caveat, Itim, Sriracha), then measures and draws several px a line wider or narrower on canvas than in the text editor, which the DOM lays out as a whole. `textRendering = "optimizeLegibility"` has the canvas shape the whole line. It changes nothing for a font without such rules, the built-in ones included, and is set on the canvas only: the DOM, Firefox's canvas and skia-canvas shape whole lines as it is. Claude Fable 5.2, effort 80 * fix(editor): leave font-kerning on the browser's default Kerning was set to `normal` wherever text is measured or drawn, so that Firefox would kern a letter against a space as Chrome does. Set on the text, it also has Firefox close up Japanese and Chinese: full-width punctuation and kana lose their side space, by 7 to 22% on a line, in 17 Google families and in system fonts such as Yu Gothic and Hiragino. `font-kerning` is no longer set on the canvas, in the text editor or in exported SVG. `textRendering = "optimizeLegibility"` stays on the canvas, which is what brings Chrome's canvas to its text editor, the kerning next to a space included. The price: Firefox doesn't kern a letter against a space, so a line with such pairs is a little wider there than in Chrome ("A V A T A R To WA" in Liberation Sans at 20 px: 285 px against 273). Claude Fable 5.2, effort 30 * feat(fonts): offer 9 Google families, not Google's whole list The catalog held every family that passed the generator's checks (1,852). It now holds the ones we offer: 9, picked by hand, each looked at on the canvas and in the text editor at 16 to 36 px in Chrome and Firefox, on a low and a high pixel density display. Safari 15.5 has seen all but Open Sans and Bevan. - handwriting: Kalam, Patrick Hand, Pacifico - sans: Open Sans - serif: Literata - monospace: Fira Mono - display: Bevan - Japanese: Zen Maru Gothic - Korean: Gowun Dodum No Chinese family yet: none of Google's fits Simplified Chinese (LXGW WenKai TC has the characters, in older forms than mainland's and with Taiwan's punctuation), and a Traditional one alone would leave the larger group out. Zen Maru Gothic has every kana and JIS X 0208 kanji, Gowun Dodum every Hangul syllable, read from the font files. All are under the SIL Open Font License with no reserved font name. All but Zen Maru Gothic have the letters of Czech, Slovak, Polish, Hungarian, Turkish and Romanian, also read from the font files: Google's "latin-ext" label doesn't tell. The generator works from that list (`OFFERED_FAMILIES`) and writes the catalog in its order, so the order no longer follows Google's popularity figures. A catalog can grow later; it can't shrink once a release has had a name. `GOOGLE_FONT_DEFAULT_PICKS` is the same list. Claude Fable 5.2, effort 30 * feat(fonts): list a family by a glyph of its own script A Japanese or Korean family has a Latin name, and its row in the font list looked like any other of its provider: the provider's icon, then the name. Nothing said which script it writes. The row now takes the family's preview text for its icon, written in the family ("あ", "한"), where the provider's `getPreviewText` gives one. It is the sample the top picks already show for a pinned family. A family without one keeps the provider's icon. `getPreviewText` is asked for every listed family, not only the pinned ones; the answer is still kept for the session. Claude Fable 5.2, effort 30 * feat(fonts): a provider's families get the icons our own fonts have In the font list every family of a provider had the provider's icon. The icon column said where a font comes from, the same on every row, and nothing about the font. Our own fonts say what they're for there: handwriting, text, code, headings. A provider can now tell a family's kind: `getKind`, answering one of `FontKind` ("hand-drawn", "normal", "code", "heading"). The row gets the icon our own fonts of that kind have, so a host imports no icon of ours. A row's icon is, in this order: the family's preview text (a glyph of its script), the icon of its kind, the provider's `icon`, a normal font's. `FontProvider.icon` is optional with that: it's what a family gets which its provider says nothing about. The Google catalog has a kind per family (`getGoogleFontKind`), set by hand next to the name in the generator's `OFFERED_FAMILIES`: Google's own categories file Bevan, a display face, as a serif. An entry is now [name, unitsPerEm, ascender, descender, lineGap, kind, script?]. excalidraw.com's provider drops Google's icon, and passes the kind and the preview text for the fonts it lists (the ones a scene uses). fontPreviewText.ts is fontProviderInfo.ts now: one cache for what a provider says about a family, the preview text and the kind. Claude Fable 5.2, effort 30 * feat(fonts): offer "Browse more fonts" only when there are more A provider able to page (`loadMore`) turned "Browse more fonts" on, whether or not it had a font beyond the ones listed. One offering all of its fonts up front, as the Google catalog's 9 are, got a button which brought nothing and then went away. The picker now asks for the first page as it opens, once per editor and set of providers, and offers the button only if that brings a font it doesn't list yet. Those fonts are what the first click lists; later pages load as before. Claude Fable 5.2, effort 30 * fix(fonts): findings of Astra's review - Closing the font picker restored every selected element from the copy taken when it opened, as a newer version: whatever a collaborator had changed meanwhile was lost for everyone, and opening and closing the picker alone gave each element a new version. Now only a live preview is taken back, to the scene as it was when that preview started, and only what a preview changes: the font of a text and the layout that follows (its wrapping, size and position, on a sticky note its fitted font size; its container's size). A text edited during the preview gets its font back and is laid out anew. Whatever else is selected along with a text is never touched. A hover resets a container's size the same way, not the whole element. - A headless export (no `document.fonts`, no `FontFace`) threw: on plain Helvetica text, on a font of a provider nobody configured, and on any custom font once a resolver was configured. A font face built its `FontFace` as it was created, and so did the registry for every built-in font. It's built when first asked for now, which such an export never does: nothing is installed or retried without a font set. Telling that a font is local, or registered, doesn't build the registry either (the font metadata, as on master; `hasCustomFamily`). - Beyond what master could do: an SVG export embeds its fonts where there is no `window`, `document` or `FontFace` at all (i.e. Node, given a document to build in). A font face read `window.EXCALIDRAW_ASSET_PATH` unguarded, and asked its `FontFace` for the unicode range it covers when its descriptors named none; it covers everything then, as in CSS. - `Fonts.loadElementsFonts(elements, ownerDocument)`, master's signature, threw: the second argument had become a `Fonts`. It takes either. - The font picker called React 18's `useSyncExternalStore`, with React 17 among the peer dependencies. `hooks/useSyncExternalStore` falls back to a subscription in an effect there, like `hooks/useTransition`. - An export resolved the fonts of deleted elements, before it dropped them. - An export loaded its fonts into the global document, whatever document it was given to draw in (`environment.document`): an editor in a popout window got them in its opener's, where its canvas can't use them. As on master, where it's an omission too. They go into the given document if it has a font set. - "Browse more fonts" went missing with its group: when the scene uses every available font, the group is empty and wasn't rendered. A group with a footer is. Left as they are, as rare: a collaborator moving or resizing a text or its container within the seconds of someone's hover preview of it, a family picked in a popout which another document registered, a provider added in the middle of a gesture, a failing resolver asked three times by one export, a slow pinned font overtaking a later pick, and the look-ahead's five page limit. Claude Fable 5.2, effort 30 * feat(fonts): favorites are pinned fonts The font picker's "Favorites" are "Pinned" now, and so is everything that names them: - the prop: `fontFavorites` -> `pinnedFonts` (same shape, `fonts` and `onChange`) - the list's section "Pinned", the drop zone's "Pin" and "Unpin" - the locale keys `fontList.pinnedFonts`, `pinFont`, `unpinFont` The tip at the bottom of the picker reads "Drag a font to pin". It spoke of the top picks alone, while a drag also offers the pin zone, which only shows up once the drag starts. Claude Fable 5.2, effort 30 * feat(fonts): createGoogleFontProvider A host had to put the Google provider together from the parts: the resolver, the offered families, the search, the paging, the preview text and, since this week, the kind. Each new part meant a change in every host. `createGoogleFontProvider()` in `fonts/google` returns the whole `FontProvider`. `offerInPicker: false` leaves the fonts out of the font picker (none listed, found by search or browsed to), while a scene's Google fonts still render: what excalidraw.com ships, in one call now. `resolve` takes a resolver of the host's own. Claude Fable 5.2, effort 30 * feat(fonts): Escape closes the font picker; "Drop to pin" and a hint icon - Escape closes the font picker, from its search too. It never did: the key took a hover preview back and left the popup open, as a focus moving out does. A live preview is still taken back, and the focus goes to the canvas, or back to the text being edited. - The pin drop zone reads "Drop to pin" and "Drop to unpin". - The hint "Drag a font to pin" has a drag-and-drop icon. A host's own `fontPickerTip` is shown as given. Claude Fable 5.2, effort 30 * feat(app): keep Google's font stylesheets for offline use Resolving a `google:` font asks Google for the family's stylesheet, which lists its files. The service worker kept the files (the `.woff2` rule) and not the stylesheet, so offline such a font resolved only for as long as the browser's HTTP cache held it: a day, by Google's headers. After that the text fell back to another font, its files in the cache or not. A runtime caching rule for `fonts.googleapis.com/css2` keeps it for 90 days, served from the cache and refreshed in the background. Nothing is fetched ahead: a stylesheet is stored when its family is first resolved. Tried in a production build with the network cut for everything but localhost: with the HTTP cache cleared, a text in Kalam is drawn in Kalam with the rule and in the fallback font without it. Claude Fable 5.2, effort 30 * docs: changelog for custom fonts Claude Fable 5.2, effort 30 * fix(fonts): a font picked after its hover preview settled can be undone Hovering a font in the picker previews it on the selected text without capturing it. A font repair landing meanwhile (the hovered font itself finishing to load, or any other) was committed as never-to-be-captured, which took the previewed font into the store's snapshot along with it. Picking that font then changed nothing against the snapshot: no undo entry, and undo left the new font in place. A live hover preview now counts among the changes yet to be captured, as a drag and a text edit do, so repairs wait for it to end. The preview's own redraw, once its font has loaded, runs as part of the preview. Found by mtolmacs in review. Claude Fable 5.2, effort 30 * fix(editor): load the custom fonts of a dropped scene Dropping an `.excalidraw` file applied its scene without asking for its fonts, and nothing else resolves a scene's custom fonts on that path, so its text stayed in a fallback font until a reload. The "Open" action asked already. Found by mtolmacs in review. Claude Fable 5.2, effort 30 * fix(build): keep the Google font catalog out of the package's fonts folder The package build names a code-split chunk by its source folder, so the catalog, imported from `fonts/google/`, was emitted as `dist/prod/fonts/google/catalog-.js`: a script inside the folder of font files which hosts copy over to serve them themselves (Excalidraw+, and `examples/with-nextjs` here). It's an entry point of its own now, emitted next to `fonts-google.js` as `fonts-google-catalog.js`. Claude Fable 5.2, effort 30 * feat(fonts): pinned fonts are favorites again "Pin" already names what a drag onto the top picks does, so a second kind of pinning in the same picker was easy to confuse with it. The naming goes back: - the prop: `pinnedFonts` -> `fontFavorites` (same shape, `fonts` and `onChange`) - the list's section "Favorites", the drop zone's "Drag to favorite" and "Remove favorite" - the locale keys `fontList.favoriteFonts`, `addToFavorites`, `removeFromFavorites` The tip stays "Drag a font to pin". Claude Fable 5.2, effort 10 --------- Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 --- excalidraw-app/App.tsx | 2 + excalidraw-app/data/googleFonts.tsx | 28 + excalidraw-app/vite.config.mts | 26 + package.json | 1 + packages/common/src/constants.ts | 157 +- packages/common/src/font-metadata.ts | 97 +- packages/common/src/utils.ts | 22 +- packages/common/tests/fontFamily.test.ts | 162 ++ packages/element/src/newElement.ts | 5 +- packages/element/src/renderElement.ts | 12 + packages/element/src/textMeasurements.ts | 2 + packages/element/src/textWrapping.ts | 27 +- packages/element/src/transform.ts | 7 +- packages/element/src/types.ts | 21 +- packages/element/tests/textElement.test.ts | 51 +- packages/element/tests/textWrapping.test.ts | 48 + packages/excalidraw/CHANGELOG.md | 14 + .../excalidraw/actions/actionClipboard.tsx | 2 + .../actions/actionDuplicateSelection.test.tsx | 63 + .../actions/actionDuplicateSelection.tsx | 1 + packages/excalidraw/actions/actionExport.tsx | 2 + .../excalidraw/actions/actionProperties.tsx | 529 +++- packages/excalidraw/actions/types.ts | 1 + .../excalidraw/components/App.clipboard.ts | 2 + .../excalidraw/components/App.duplicate.ts | 2 + packages/excalidraw/components/App.fonts.ts | 614 +++++ packages/excalidraw/components/App.text.ts | 10 + packages/excalidraw/components/App.tsx | 83 +- .../components/FontPicker/FontPicker.scss | 153 ++ .../components/FontPicker/FontPicker.test.tsx | 2307 ++++++++++++++++- .../components/FontPicker/FontPicker.tsx | 163 +- .../components/FontPicker/FontPickerList.tsx | 737 ++++-- .../FontPicker/FontPickerListItem.tsx | 130 + .../FontPicker/FontPickerTrigger.tsx | 4 +- .../FontPicker/fontProviderInfo.test.tsx | 119 + .../components/FontPicker/fontProviderInfo.ts | 141 + .../components/FontPicker/fontTopPicksDnD.ts | 51 +- .../FontPicker/keyboardNavHandlers.ts | 5 +- .../components/FontPicker/useFontCatalog.tsx | 588 +++++ .../FontPicker/useFontResolution.ts | 139 + .../components/FontPicker/useFontSearch.ts | 102 + .../components/FontPicker/useMoreFonts.ts | 244 ++ .../FontPicker/useVisibleFontRegistration.ts | 155 ++ .../components/ImageExportDialog.tsx | 8 + packages/excalidraw/components/LayerUI.tsx | 1 + .../excalidraw/components/QuickSearch.tsx | 2 +- .../excalidraw/components/ScrollableList.tsx | 28 +- .../components/TopPicksDnD/TopPicksTip.tsx | 7 +- .../components/TopPicksDnD/topPicksDnD.tsx | 67 +- packages/excalidraw/components/UserList.tsx | 2 +- packages/excalidraw/components/icons.tsx | 17 + packages/excalidraw/data/index.ts | 14 +- packages/excalidraw/data/resave.ts | 3 + packages/excalidraw/data/restore.ts | 64 +- .../excalidraw/fonts/ExcalidrawFontFace.ts | 149 +- packages/excalidraw/fonts/FontRegistry.ts | 280 ++ packages/excalidraw/fonts/Fonts.ts | 996 +++++-- packages/excalidraw/fonts/FontsCache.ts | 170 ++ packages/excalidraw/fonts/google/catalog.json | 11 + packages/excalidraw/fonts/google/index.ts | 529 ++++ packages/excalidraw/fonts/index.ts | 4 + packages/excalidraw/fonts/providerKey.ts | 48 + packages/excalidraw/fonts/resolvers.ts | 64 + .../hooks/useSyncExternalStore.test.tsx | 34 + .../excalidraw/hooks/useSyncExternalStore.ts | 34 + packages/excalidraw/index.tsx | 33 + packages/excalidraw/locales/en.json | 12 +- packages/excalidraw/package.json | 6 + packages/excalidraw/scene/export.ts | 88 +- packages/excalidraw/scene/types.ts | 11 +- .../tests/MermaidToExcalidraw.test.tsx | 4 + .../tests/__snapshots__/history.test.tsx.snap | 518 ++++ packages/excalidraw/tests/clipboard.test.tsx | 72 + .../excalidraw/tests/crossDocument.test.tsx | 4 +- .../excalidraw/tests/data/restore.test.ts | 113 + packages/excalidraw/tests/fileDrop.test.tsx | 44 + .../excalidraw/tests/fontTopPicks.test.ts | 5 +- packages/excalidraw/tests/fonts.test.ts | 1494 +++++++++++ packages/excalidraw/tests/googleFonts.test.ts | 261 ++ packages/excalidraw/tests/helpers/mocks.ts | 30 + packages/excalidraw/tests/history.test.tsx | 101 + .../scene/__snapshots__/export.test.ts.snap | 62 +- .../excalidraw/tests/scene/export.test.ts | 281 +- packages/excalidraw/types.ts | 209 +- .../excalidraw/wysiwyg/textWysiwyg.test.tsx | 23 + packages/excalidraw/wysiwyg/textWysiwyg.tsx | 30 +- packages/utils/src/index.ts | 2 + scripts/buildGoogleFontsCatalog.mjs | 721 ++++++ scripts/buildPackage.js | 14 +- setupTests.ts | 13 +- 90 files changed, 12796 insertions(+), 916 deletions(-) create mode 100644 excalidraw-app/data/googleFonts.tsx create mode 100644 packages/common/tests/fontFamily.test.ts create mode 100644 packages/excalidraw/components/App.fonts.ts create mode 100644 packages/excalidraw/components/FontPicker/FontPickerListItem.tsx create mode 100644 packages/excalidraw/components/FontPicker/fontProviderInfo.test.tsx create mode 100644 packages/excalidraw/components/FontPicker/fontProviderInfo.ts create mode 100644 packages/excalidraw/components/FontPicker/useFontCatalog.tsx create mode 100644 packages/excalidraw/components/FontPicker/useFontResolution.ts create mode 100644 packages/excalidraw/components/FontPicker/useFontSearch.ts create mode 100644 packages/excalidraw/components/FontPicker/useMoreFonts.ts create mode 100644 packages/excalidraw/components/FontPicker/useVisibleFontRegistration.ts create mode 100644 packages/excalidraw/fonts/FontRegistry.ts create mode 100644 packages/excalidraw/fonts/FontsCache.ts create mode 100644 packages/excalidraw/fonts/google/catalog.json create mode 100644 packages/excalidraw/fonts/google/index.ts create mode 100644 packages/excalidraw/fonts/providerKey.ts create mode 100644 packages/excalidraw/fonts/resolvers.ts create mode 100644 packages/excalidraw/hooks/useSyncExternalStore.test.tsx create mode 100644 packages/excalidraw/hooks/useSyncExternalStore.ts create mode 100644 packages/excalidraw/tests/fonts.test.ts create mode 100644 packages/excalidraw/tests/googleFonts.test.ts create mode 100644 scripts/buildGoogleFontsCatalog.mjs diff --git a/excalidraw-app/App.tsx b/excalidraw-app/App.tsx index 31edcababf..7694b45025 100644 --- a/excalidraw-app/App.tsx +++ b/excalidraw-app/App.tsx @@ -144,6 +144,7 @@ import DebugCanvas, { import { useSimulatedCollaborators } from "./debugCollaborators"; import { AIComponents } from "./components/AI"; import { ExcalidrawPlusIframeExport } from "./ExcalidrawPlusIframeExport"; +import { fontProviders } from "./data/googleFonts"; import "./index.scss"; @@ -962,6 +963,7 @@ const ExcalidrawWrapper = () => { })} > ` */ +export const fontProviders: FontProviders = { + [GOOGLE_FONT_PROVIDER_KEY]: provider, +}; diff --git a/excalidraw-app/vite.config.mts b/excalidraw-app/vite.config.mts index f7ddd0f724..638c178e5b 100644 --- a/excalidraw-app/vite.config.mts +++ b/excalidraw-app/vite.config.mts @@ -370,6 +370,32 @@ export default defineConfig(({ mode }) => { }, }, }, + { + // A Google font's stylesheet, which lists the font's files: + // what resolving a `google:` font asks for first (the files + // themselves fall under the `.woff2` rule above). Without it + // such a font resolves offline only for as long as the + // browser's HTTP cache happens to hold the stylesheet, a day + // by Google's headers. Served from the cache and refreshed in + // the background - the files stay at the urls an older + // stylesheet lists. + urlPattern: new RegExp( + "^https://fonts\\.googleapis\\.com/css2\\?", + ), + handler: "StaleWhileRevalidate", + options: { + cacheName: "google-fonts-stylesheets", + expiration: { + maxEntries: 100, + maxAgeSeconds: 60 * 60 * 24 * 90, // <== 90 days + }, + cacheableResponse: { + // a CORS response - never an opaque one, which could be + // an error page + statuses: [200], + }, + }, + }, { urlPattern: new RegExp("locales/[^/]+.js"), handler: "CacheFirst", diff --git a/package.json b/package.json index 32d974ff38..e79b1fbb8f 100644 --- a/package.json +++ b/package.json @@ -82,6 +82,7 @@ "fix:code": "yarn test:code --fix", "fix:other": "yarn prettier --write", "fix": "yarn fix:other && yarn fix:code", + "gen:google-fonts": "node scripts/buildGoogleFontsCatalog.mjs", "locales-coverage": "node scripts/build-locales-coverage.js", "locales-coverage:description": "node scripts/locales-coverage-description.js", "prepare": "husky install", diff --git a/packages/common/src/constants.ts b/packages/common/src/constants.ts index cf04e8a31c..a3a134d50b 100644 --- a/packages/common/src/constants.ts +++ b/packages/common/src/constants.ts @@ -1,7 +1,4 @@ -import type { - ExcalidrawElement, - FontFamilyValues, -} from "@excalidraw/element/types"; +import type { ExcalidrawElement } from "@excalidraw/element/types"; import type { AppProps, AppState, @@ -156,6 +153,131 @@ export const FONT_FAMILY = { Assistant: 10, }; +/** separates the provider id from the family name, i.e. "google:Roboto" */ +export const FONT_PROVIDER_SEPARATOR = ":"; + +/** + * A custom font family, qualified by the provider able to resolve it. + * + * WARN: the type only enforces the separator's presence - either side may + * still be empty (i.e. ":Roboto"), so anything trusting the parts has to go + * through {@link parseProviderFontFamily} regardless. + */ +export type CustomFontFamily = + `${string}${typeof FONT_PROVIDER_SEPARATOR}${string}`; + +/** numeric id for built-ins ({@link FONT_FAMILY}), qualified name for custom */ +export type FontFamily = number | CustomFontFamily; + +/** + * Whether the family is a custom one, i.e. "google:Roboto". + * + * WARN: only tells built-in from custom - not whether the family is + * well-formed, let alone resolvable. Use {@link parseProviderFontFamily} for + * anything which needs the provider. + */ +export const isCustomFontFamily = ( + fontFamily: FontFamily, +): fontFamily is CustomFontFamily => typeof fontFamily === "string"; + +/** whether the family is a built-in one (see {@link FONT_FAMILY}) */ +export const isBuiltInFontFamily = ( + fontFamily: FontFamily, +): fontFamily is number => typeof fontFamily === "number"; + +/** + * Parse a provider-qualified custom font family, i.e. "google:Roboto". Splits + * on the first separator, so family names may contain one themselves. + * + * @returns `null` when the separator is missing, leading (":Roboto") or + * trailing ("google:") + */ +export const parseProviderFontFamily = ( + fontFamily: string, +): { providerId: string; familyName: string } | null => { + const separatorIndex = fontFamily.indexOf(FONT_PROVIDER_SEPARATOR); + + if (separatorIndex <= 0 || separatorIndex === fontFamily.length - 1) { + return null; + } + + return { + providerId: fontFamily.slice(0, separatorIndex), + familyName: fontFamily.slice(separatorIndex + 1), + }; +}; + +/** + * Type-guard flavor of {@link parseProviderFontFamily}, for narrowing plain + * strings at data boundaries (i.e. restored documents, DOM round-trips). + */ +export const isProviderQualifiedFontFamily = ( + fontFamily: string, +): fontFamily is CustomFontFamily => + parseProviderFontFamily(fontFamily) !== null; + +/** build a provider-qualified custom font family from its parts */ +export const createProviderFontFamily = ( + providerId: string, + familyName: string, +): CustomFontFamily => `${providerId}${FONT_PROVIDER_SEPARATOR}${familyName}`; + +const CSS_FONT_FAMILY_PREFIX = "xf-"; +const CSS_FONT_FAMILY_SLUG_LENGTH = 40; + +/** per page, as it's asked for on every text measure & render */ +const cssFontFamilies = new Map(); + +/** 32-bit FNV-1a over UTF-16 code units, so lone surrogates stay distinct */ +const hashFontFamily = (fontFamily: string) => { + let hash = 0x811c9dc5; + for (let i = 0; i < fontFamily.length; i++) { + hash ^= fontFamily.charCodeAt(i); + hash = Math.imul(hash, 0x01000193); + } + return (hash >>> 0).toString(16).padStart(8, "0"); +}; + +/** + * The CSS family name a custom font is registered and referred to by, i.e. + * "google:Press Start 2P" -> "xf-press-start-2p-b5b3c1d0". + * + * The persisted id itself never reaches CSS, canvas or SVG. That is what lets + * its family part be any string (as `text` can): CSS matches family names + * case-insensitively and has its own escaping, so ids differing only by case + * would share a font, and control characters, quotes or a lone surrogate + * would match no font at all. The result is a plain CSS identifier - nothing + * to quote or escape anywhere it ends up. + * + * - prefix: keeps a bare name (i.e. "Nunito") from matching an installed or + * built-in font + * - slug: the family part, for readability only + * - hash: of the whole id, which is what makes the name unique + * + * WARN: one-way and never persisted, so the format is free to change - don't + * parse it back into an id, and don't store it. + */ +export const getCustomFontCSSFamily = (fontFamily: string): string => { + let cssFamily = cssFontFamilies.get(fontFamily); + + if (cssFamily === undefined) { + const familyName = + parseProviderFontFamily(fontFamily)?.familyName ?? fontFamily; + const slug = familyName + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .slice(0, CSS_FONT_FAMILY_SLUG_LENGTH) + .replace(/^-+|-+$/g, ""); + + cssFamily = `${CSS_FONT_FAMILY_PREFIX}${ + slug ? `${slug}-` : "" + }${hashFontFamily(fontFamily)}`; + cssFontFamilies.set(fontFamily, cssFamily); + } + + return cssFamily; +}; + // Segoe UI Emoji fails to properly fallback for some glyphs: ∞, ∫, ≠ // so we need to have generic font fallback before it export const SANS_SERIF_GENERIC_FONT = "sans-serif"; @@ -173,7 +295,7 @@ export const FONT_FAMILY_FALLBACKS = { }; export function getGenericFontFamilyFallback( - fontFamily: number, + fontFamily: FontFamily, ): keyof typeof FONT_FAMILY_GENERIC_FALLBACKS { switch (fontFamily) { case FONT_FAMILY.Cascadia: @@ -186,7 +308,7 @@ export function getGenericFontFamilyFallback( } export const getFontFamilyFallbacks = ( - fontFamily: number, + fontFamily: FontFamily, ): Array => { const genericFallbackFont = getGenericFontFamilyFallback(fontFamily); @@ -271,13 +393,34 @@ export const STICKY_NOTE_SHADOW_OFFSET = 3; export const STICKY_NOTE_SHADOW_OPACITY = 0.16; export const STICKY_NOTE_EDGE_SHADOW_WIDTH = 0.5; export const STICKY_NOTE_EDGE_SHADOW_OPACITY = 0.08; -export const DEFAULT_FONT_FAMILY: FontFamilyValues = FONT_FAMILY.Excalifont; +export const DEFAULT_FONT_FAMILY = FONT_FAMILY.Excalifont; /** number of slots in the font-picker top-picks strip — pick customization * (replace / reorder) preserves it. Must equal `DEFAULT_FONTS.length` in * `packages/excalidraw/components/FontPicker/FontPicker.tsx` (enforced by * `fontTopPicks.test.ts`) */ export const FONT_TOP_PICKS_SLOTS = 3; export const DEFAULT_TEXT_ALIGN = "left"; + +/** + * How a canvas shapes the text it measures or draws. + * + * Left on the default (`auto`), Chrome's canvas shapes a line word by word, + * where its text editor (the DOM) lays the line out as a whole. Two things + * then differ between the two, and the same text wraps at different words: + * + * - the kerning between a letter and a space is left out on canvas, so a + * line such as "A V A T A R" is several px wider there; + * - a font which picks a letter's shape by what's around it, across spaces + * too (i.e. Caveat), comes out several px a line wider or narrower. + * + * `optimizeLegibility` has the canvas shape the line as a whole as well. + * + * For the canvas only: the DOM, Firefox's canvas and skia-canvas shape whole + * lines as it is. Kerning itself (`font-kerning`) is left on the browser's + * default everywhere: set to `normal`, Firefox also closes up Japanese and + * Chinese text. + */ +export const TEXT_RENDERING = "optimizeLegibility"; export const DEFAULT_VERTICAL_ALIGN = "top"; export const DEFAULT_VERSION = "{version}"; export const DEFAULT_TRANSFORM_HANDLE_SPACING = 2; diff --git a/packages/common/src/font-metadata.ts b/packages/common/src/font-metadata.ts index 7382aa70f0..9c226e6b3c 100644 --- a/packages/common/src/font-metadata.ts +++ b/packages/common/src/font-metadata.ts @@ -1,9 +1,13 @@ -import type { - ExcalidrawTextElement, - FontFamilyValues, -} from "@excalidraw/element/types"; +import type { ExcalidrawTextElement } from "@excalidraw/element/types"; -import { FONT_FAMILY, FONT_FAMILY_FALLBACKS } from "./constants"; +import { + DEFAULT_FONT_FAMILY, + FONT_FAMILY, + FONT_FAMILY_FALLBACKS, + isCustomFontFamily, +} from "./constants"; + +import type { CustomFontFamily, FontFamily } from "./constants"; /** * Encapsulates font metrics with additional font metadata. @@ -11,8 +15,8 @@ import { FONT_FAMILY, FONT_FAMILY_FALLBACKS } from "./constants"; export interface FontMetadata { /** for head & hhea metrics read the woff2 with https://fontdrop.info/ */ metrics: { - /** head.unitsPerEm metric */ - unitsPerEm: 1000 | 1024 | 2048; + /** head.unitsPerEm metric - any positive value a font declares */ + unitsPerEm: number; /** hhea.ascender metric */ ascender: number; /** hhea.descender metric */ @@ -32,7 +36,12 @@ export interface FontMetadata { fallback?: true; } -export const FONT_METADATA: Record = { +/** + * Built-in font metadata, keyed by numeric family id. Frozen - runtime + * metadata for custom families goes through {@link setCustomFontMetadata}, + * never into this record. + */ +export const FONT_METADATA: Readonly> = { [FONT_FAMILY.Excalifont]: { metrics: { unitsPerEm: 1000, @@ -133,6 +142,39 @@ export const FONT_METADATA: Record = { }, }; +Object.freeze(FONT_METADATA); + +/** + * Metrics for custom (provider-qualified) families, registered at runtime by + * the editor's font registry - the single seam through which they reach the + * metric helpers below, keeping {@link FONT_METADATA} frozen. Those helpers + * must live in this package, as `@excalidraw/element` consumes them. + * + * Page-global, never per editor: a qualified family identifies exactly one + * definition, so its metrics are a fact about the family. + */ +const customFontMetadata = new Map(); + +export const setCustomFontMetadata = ( + family: CustomFontFamily, + metadata: FontMetadata, +) => { + customFontMetadata.set(family, metadata); +}; + +export const getFontMetadata = (fontFamily: FontFamily): FontMetadata => + (isCustomFontFamily(fontFamily) + ? customFontMetadata.get(fontFamily) + : FONT_METADATA[fontFamily]) ?? FONT_METADATA[DEFAULT_FONT_FAMILY]; + +/** + * Whether real metrics exist for the family. Built-ins always count - even an + * unknown numeric id falls back to Excalifont metrics (forward compat with + * newer clients); a custom family has none until its provider resolves it. + */ +export const isFontMetadataAvailable = (fontFamily: FontFamily): boolean => + !isCustomFontFamily(fontFamily) || customFontMetadata.has(fontFamily); + /** Unicode ranges defined by google fonts */ export const GOOGLE_FONTS_RANGES = { LATIN: @@ -158,8 +200,7 @@ export const getVerticalOffset = ( lineHeightPx: number, ) => { const { unitsPerEm, ascender, descender } = - FONT_METADATA[fontFamily]?.metrics || - FONT_METADATA[FONT_FAMILY.Excalifont].metrics; + getFontMetadata(fontFamily).metrics; const fontSizeEm = fontSize / unitsPerEm; const lineGap = @@ -172,10 +213,38 @@ export const getVerticalOffset = ( /** * Gets line height for a selected family. */ -export const getLineHeight = (fontFamily: FontFamilyValues) => { - const { lineHeight } = - FONT_METADATA[fontFamily]?.metrics || - FONT_METADATA[FONT_FAMILY.Excalifont].metrics; +export const getLineHeight = (fontFamily: FontFamily) => { + const { lineHeight } = getFontMetadata(fontFamily).metrics; return lineHeight as ExcalidrawTextElement["lineHeight"]; }; + +/** + * The correct `lineHeight` for the element's family, or `null` to leave the + * stored value alone. + * + * `lineHeight` is a snapshot of the family's metrics taken at write time, but + * a custom family's metrics only arrive once its provider resolves them - an + * element written before that carries the fallback's. This is the single place + * encoding when the snapshot may be corrected: custom families only (a + * built-in's value may be a legitimately divergent legacy `detectLineHeight`) + * and only once their real metrics are in. + * + * Callers scope the correction to just-loaded families, so it fires at most + * once per family. Two accepted consequences: a host-set value present while + * the faces are still arriving is corrected along with the baked-in ones, and + * a scene which never observes a load keeps its stored values. + */ +export const reconcileLineHeight = ( + element: Pick, +): ExcalidrawTextElement["lineHeight"] | null => { + if ( + !isCustomFontFamily(element.fontFamily) || + !isFontMetadataAvailable(element.fontFamily) + ) { + return null; + } + + const lineHeight = getLineHeight(element.fontFamily); + return element.lineHeight === lineHeight ? null : lineHeight; +}; diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.ts index be2e4b1384..fa21037db4 100644 --- a/packages/common/src/utils.ts +++ b/packages/common/src/utils.ts @@ -2,7 +2,7 @@ import { average } from "@excalidraw/math"; import type { GlobalCoord } from "@excalidraw/math"; -import type { FontFamilyValues, FontString } from "@excalidraw/element/types"; +import type { FontString } from "@excalidraw/element/types"; import type { ActiveTool, @@ -17,12 +17,14 @@ import { ENV, FONT_FAMILY, getFontFamilyFallbacks, + getCustomFontCSSFamily, + isCustomFontFamily, WINDOWS_EMOJI_FALLBACK_FONT, } from "./constants"; import type { MaybePromise, ResolutionType } from "./utility-types"; -import type { EVENT } from "./constants"; +import type { EVENT, FontFamily } from "./constants"; let mockDateTime: string | null = null; @@ -137,8 +139,20 @@ export const isWritableElement = ( export const getFontFamilyString = ({ fontFamily, }: { - fontFamily: FontFamilyValues; + fontFamily: FontFamily; }) => { + // Custom font - referred to by its generated CSS name, never by the id + // itself (see `getCustomFontCSSFamily`), plus the generic fallbacks. Also + // covers a string we can't resolve (i.e. a bare "Comic Sans MS" kept by + // `restore`): its generated name matches no font, so it renders in the + // fallbacks on every machine rather than in whatever happens to be installed + if (isCustomFontFamily(fontFamily)) { + const fallbacks = getFontFamilyFallbacks(fontFamily); + return `${getCustomFontCSSFamily(fontFamily)}${fallbacks + .map((x) => `, ${x}`) + .join("")}`; + } + for (const [fontFamilyString, id] of Object.entries(FONT_FAMILY)) { if (id === fontFamily) { return `${fontFamilyString}${getFontFamilyFallbacks(id) @@ -155,7 +169,7 @@ export const getFontString = ({ fontFamily, }: { fontSize: number; - fontFamily: FontFamilyValues; + fontFamily: FontFamily; }) => { return `${fontSize}px ${getFontFamilyString({ fontFamily })}` as FontString; }; diff --git a/packages/common/tests/fontFamily.test.ts b/packages/common/tests/fontFamily.test.ts new file mode 100644 index 0000000000..90e13f6fb5 --- /dev/null +++ b/packages/common/tests/fontFamily.test.ts @@ -0,0 +1,162 @@ +import { + FONT_FAMILY, + FONT_PROVIDER_SEPARATOR, + createProviderFontFamily, + getCustomFontCSSFamily, + getFontFamilyString, + parseProviderFontFamily, +} from "@excalidraw/common"; + +import type { FontFamily } from "@excalidraw/common"; + +describe("parseProviderFontFamily", () => { + it("should parse a provider-qualified family", () => { + expect(parseProviderFontFamily("google:Roboto")).toEqual({ + providerId: "google", + familyName: "Roboto", + }); + }); + + it("should preserve whitespace and casing in the family name", () => { + expect(parseProviderFontFamily("google:Lilita One")).toEqual({ + providerId: "google", + familyName: "Lilita One", + }); + }); + + it("should split on the first separator only", () => { + // so that family names may themselves contain a separator + expect(parseProviderFontFamily("a:b:c")).toEqual({ + providerId: "a", + familyName: "b:c", + }); + }); + + it("should return null when there is no separator", () => { + expect(parseProviderFontFamily("Roboto")).toBe(null); + expect(parseProviderFontFamily("")).toBe(null); + }); + + it("should return null for a leading separator (empty provider)", () => { + expect(parseProviderFontFamily(":Roboto")).toBe(null); + expect(parseProviderFontFamily(":")).toBe(null); + }); + + it("should return null for a trailing separator (empty family)", () => { + expect(parseProviderFontFamily("google:")).toBe(null); + }); +}); + +describe("createProviderFontFamily", () => { + it("should join the provider id and the family name", () => { + expect(createProviderFontFamily("google", "Roboto")).toBe("google:Roboto"); + }); + + it("should round-trip through parseProviderFontFamily", () => { + const family = createProviderFontFamily("google", "Lilita One"); + + expect(parseProviderFontFamily(family)).toEqual({ + providerId: "google", + familyName: "Lilita One", + }); + }); + + it("should round-trip a family name containing the separator", () => { + const family = createProviderFontFamily("google", "Foo:Bar"); + + expect(family).toBe(`google${FONT_PROVIDER_SEPARATOR}Foo:Bar`); + expect(parseProviderFontFamily(family)).toEqual({ + providerId: "google", + familyName: "Foo:Bar", + }); + }); +}); + +describe("getCustomFontCSSFamily", () => { + it("should generate a readable name from the family part", () => { + expect(getCustomFontCSSFamily("google:Press Start 2P")).toMatch( + /^xf-press-start-2p-[0-9a-f]{8}$/, + ); + }); + + it("should be stable for the same id", () => { + expect(getCustomFontCSSFamily("google:Roboto")).toBe( + getCustomFontCSSFamily("google:Roboto"), + ); + }); + + it("should tell apart ids which CSS or a slug alone would merge", () => { + const pairs = [ + // CSS matches family names case-insensitively + ["google:Abc", "google:aBC"], + ["google:Ä", "google:ä"], + // nothing of these survives into the slug + ["google:あいう", "google:かきく"], + ["google:Foo Bar", "google:Foo-Bar"], + // the same family name in two catalogs + ["google:Roboto", "com.acme.fonts:Roboto"], + // lone surrogates, which UTF-8 would turn into one character + ["google:\ud800", "google:\ud801"], + ]; + + for (const [a, b] of pairs) { + expect(getCustomFontCSSFamily(a)).not.toBe(getCustomFontCSSFamily(b)); + } + }); + + it("should always be a plain CSS identifier", () => { + const ids = [ + "google:Press Start 2P", + 'google:"quoted" \\ name', + "google:", + "google:a;b{c}d,e/*f*/", + "google:line\nbreak\ttab\u0000nul", + "google:nbsp\u00a0and\ufffe", + "google:\ud800", + "google:あいう", + "google:😀", + `google:${"x".repeat(10_000)}`, + // not provider-qualified, i.e. kept as is by `restore` + "Comic Sans MS", + "", + ]; + + for (const id of ids) { + const cssFamily = getCustomFontCSSFamily(id); + expect(cssFamily).toMatch(/^xf-[a-z0-9]+(-[a-z0-9]+)*$/); + expect(cssFamily.length).toBeLessThanOrEqual(60); + } + }); +}); + +describe("getFontFamilyString", () => { + it("should refer to a custom family by its generated name, with fallbacks", () => { + const fontFamily = "google:Roboto"; + + expect(getFontFamilyString({ fontFamily })).toBe( + `${getCustomFontCSSFamily(fontFamily)}, sans-serif, Segoe UI Emoji`, + ); + }); + + it("should never hand a bare name to CSS", () => { + // would otherwise render in the installed font on some machines only + const fontFamily = "Comic Sans MS" as FontFamily; + + expect(getFontFamilyString({ fontFamily })).not.toContain("Comic Sans MS"); + expect(getFontFamilyString({ fontFamily })).toMatch(/^xf-comic-sans-ms-/); + }); + + it("should fall back for values which aren't a family at all", () => { + for (const fontFamily of [9999, { family: "Roboto" }, true]) { + expect( + getFontFamilyString({ fontFamily: fontFamily as FontFamily }), + ).toBe("Segoe UI Emoji"); + } + }); + + it("should keep built-in families by name", () => { + expect(getFontFamilyString({ fontFamily: FONT_FAMILY.Nunito })).toMatch( + /^Nunito, /, + ); + }); +}); diff --git a/packages/element/src/newElement.ts b/packages/element/src/newElement.ts index 75b98c9ced..c4bfee8c8e 100644 --- a/packages/element/src/newElement.ts +++ b/packages/element/src/newElement.ts @@ -15,6 +15,8 @@ import { getLineHeight, } from "@excalidraw/common"; +import type { FontFamily } from "@excalidraw/common"; + import type { Radians } from "@excalidraw/math"; import type { MarkOptional, Merge } from "@excalidraw/common/utility-types"; @@ -47,7 +49,6 @@ import type { VerticalAlign, Arrowhead, ExcalidrawFreeDrawElement, - FontFamilyValues, ExcalidrawTextContainer, ExcalidrawFrameElement, ExcalidrawEmbeddableElement, @@ -339,7 +340,7 @@ export const newTextElement = ( text: string; originalText?: string; fontSize?: number; - fontFamily?: FontFamilyValues; + fontFamily?: FontFamily; textAlign?: TextAlign; verticalAlign?: VerticalAlign; containerId?: ExcalidrawTextContainer["id"] | null; diff --git a/packages/element/src/renderElement.ts b/packages/element/src/renderElement.ts index 97cf4bbf3a..c7e1d432b7 100644 --- a/packages/element/src/renderElement.ts +++ b/packages/element/src/renderElement.ts @@ -28,6 +28,7 @@ import { STICKY_NOTE_EDGE_SHADOW_OPACITY, STICKY_NOTE_EDGE_SHADOW_WIDTH, STICKY_NOTE_FOOTER, + TEXT_RENDERING, STICKY_NOTE_SHADOW_OPACITY, DEFAULT_ZOOM, } from "@excalidraw/common"; @@ -676,6 +677,7 @@ const drawElementOnCanvas = ( } withSavedContext(context, () => { context.font = getFontString(element); + context.textRendering = TEXT_RENDERING; context.fillStyle = applyDarkModeFilter( element.strokeColor, renderConfig.theme === THEME.DARK, @@ -1037,6 +1039,16 @@ export const renderElement = ( allElementsMap, ), ) => { + // its font is still loading - drawn once it arrives (or its block period + // runs out), instead of flashing in the fallback font first + if ( + isTextElement(element) && + !renderConfig.isExporting && + renderConfig.isFontBlocked?.(element.fontFamily) + ) { + return; + } + const reduceAlphaForSelection = appState.openDialog?.name === "elementLinkSelector" && !appState.selectedElementIds[element.id] && diff --git a/packages/element/src/textMeasurements.ts b/packages/element/src/textMeasurements.ts index f5081f3eab..2bcc481a4e 100644 --- a/packages/element/src/textMeasurements.ts +++ b/packages/element/src/textMeasurements.ts @@ -2,6 +2,7 @@ import { BOUND_TEXT_PADDING, DEFAULT_FONT_SIZE, DEFAULT_FONT_FAMILY, + TEXT_RENDERING, getFontString, isTestEnv, normalizeEOL, @@ -158,6 +159,7 @@ class CanvasTextMetricsProvider implements TextMetricsProvider { public getLineWidth(text: string, fontString: FontString): number { const context = this.canvas.getContext("2d")!; context.font = fontString; + context.textRendering = TEXT_RENDERING; const metrics = context.measureText(text); const advanceWidth = metrics.width; diff --git a/packages/element/src/textWrapping.ts b/packages/element/src/textWrapping.ts index 7f5064456c..84e87538d7 100644 --- a/packages/element/src/textWrapping.ts +++ b/packages/element/src/textWrapping.ts @@ -510,13 +510,28 @@ const wrapLine = ( const tokenEnd = tokenStart + token.length; const testLine = currentLine + token; + const isWhitespace = /\s/.test(token); + // cache single codepoint whitespace, CJK or emoji width calc. as kerning should not apply here - const testLineWidth = isSingleCharacter(token) + let testLineWidth = isSingleCharacter(token) ? currentLineWidth + charWidth.calculate(token, font, env) : getLineWidth(testLine, font, env); + // ...except where it does: a single letter kerns with its neighbours + // (i.e. "A V A"), which the sum above leaves out. So before the line + // breaks on such a token, measure it as a whole, as the text editor + // lays it out - else the two break at different words. + if ( + currentLine && + !isWhitespace && + testLineWidth > maxWidth && + isSingleCharacter(token) + ) { + testLineWidth = getLineWidth(testLine, font, env); + } + // build up the current line, skipping length check for possibly trailing whitespaces - if (/\s/.test(token) || testLineWidth <= maxWidth) { + if (isWhitespace || testLineWidth <= maxWidth) { if (!currentLine) { currentLineStart = tokenStart; } @@ -613,7 +628,13 @@ const wrapWord = ( const charStart = offset; const charEnd = charStart + char.length; const _charWidth = charWidth.calculate(char, font, env); - const testLineWidth = currentLineWidth + _charWidth; + let testLineWidth = currentLineWidth + _charWidth; + + // the sum leaves out the kerning between the letters, so before the word + // breaks here, measure the line as a whole (see `wrapLine`) + if (currentLine && testLineWidth > maxWidth) { + testLineWidth = getLineWidth(currentLine + char, font, env); + } if (testLineWidth <= maxWidth) { if (!currentLine) { diff --git a/packages/element/src/transform.ts b/packages/element/src/transform.ts index db58a7a9bf..2e5c5b930f 100644 --- a/packages/element/src/transform.ts +++ b/packages/element/src/transform.ts @@ -30,6 +30,8 @@ import { DEFAULT_ZOOM, } from "@excalidraw/common"; +import type { FontFamily } from "@excalidraw/common"; + import type { MarkOptional } from "@excalidraw/common/utility-types"; import type { Zoom } from "@excalidraw/excalidraw/types"; @@ -98,7 +100,6 @@ import type { ExcalidrawSelectionElement, ExcalidrawTextElement, FileId, - FontFamilyValues, NonDeleted, NonDeletedExcalidrawElement, NonDeletedSceneElementsMap, @@ -126,7 +127,7 @@ export type ValidLinearElement = { label?: { text: string; fontSize?: number; - fontFamily?: FontFamilyValues; + fontFamily?: FontFamily; textAlign?: TextAlign; verticalAlign?: VerticalAlign; /** where along an arrow's path (0-1) the label is centered */ @@ -225,7 +226,7 @@ export type ValidContainer = label?: { text: string; fontSize?: number; - fontFamily?: FontFamilyValues; + fontFamily?: FontFamily; textAlign?: TextAlign; verticalAlign?: VerticalAlign; } & FragmentConstructorOpts; diff --git a/packages/element/src/types.ts b/packages/element/src/types.ts index 68891be19f..ca9e730b4a 100644 --- a/packages/element/src/types.ts +++ b/packages/element/src/types.ts @@ -2,6 +2,7 @@ import type { LocalPoint, Radians } from "@excalidraw/math"; import type { FONT_FAMILY, + FontFamily, ROUNDNESS, TEXT_ALIGN, THEME, @@ -18,7 +19,6 @@ import type { export type ChartType = "bar" | "line" | "radar"; export type FillStyle = "hachure" | "cross-hatch" | "solid" | "zigzag"; export type FontFamilyKeys = keyof typeof FONT_FAMILY; -export type FontFamilyValues = typeof FONT_FAMILY[FontFamilyKeys]; export type Theme = typeof THEME[keyof typeof THEME]; export type FontString = string & { _brand: "fontString" }; export type GroupId = string; @@ -139,15 +139,14 @@ export type ExcalidrawIframeLikeElement = | ExcalidrawIframeElement | ExcalidrawEmbeddableElement; -export type IframeData = - | { - intrinsicSize: { w: number; h: number }; - error?: Error; - sandbox?: { allowSameOrigin?: boolean }; - } & ( - | { type: "video" | "generic"; link: string } - | { type: "document"; srcdoc: (theme: Theme) => string } - ); +export type IframeData = { + intrinsicSize: { w: number; h: number }; + error?: Error; + sandbox?: { allowSameOrigin?: boolean }; +} & ( + | { type: "video" | "generic"; link: string } + | { type: "document"; srcdoc: (theme: Theme) => string } +); export type ImageCrop = { x: number; @@ -254,7 +253,7 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{ type: "text"; fontSize: number; - fontFamily: FontFamilyValues; + fontFamily: FontFamily; /** * The font size the user picked, from which the layout derives `fontSize`. * Today only sticky note labels have one: the auto-fit shrinks below it diff --git a/packages/element/tests/textElement.test.ts b/packages/element/tests/textElement.test.ts index 986854b985..3d3d51858d 100644 --- a/packages/element/tests/textElement.test.ts +++ b/packages/element/tests/textElement.test.ts @@ -1,7 +1,12 @@ import { getLineHeight } from "@excalidraw/common"; import { API } from "@excalidraw/excalidraw/tests/helpers/api"; -import { FONT_FAMILY, TEXT_ALIGN, VERTICAL_ALIGN } from "@excalidraw/common"; +import { + FONT_FAMILY, + TEXT_ALIGN, + TEXT_RENDERING, + VERTICAL_ALIGN, +} from "@excalidraw/common"; import { computeContainerDimensionForBoundText, @@ -10,11 +15,47 @@ import { getBoundTextMaxHeight, computeBoundTextPosition, } from "../src/textElement"; -import { detectLineHeight, getLineHeightInPx } from "../src/textMeasurements"; +import { + detectLineHeight, + getLineHeightInPx, + getLineWidth, +} from "../src/textMeasurements"; -import type { ExcalidrawTextElementWithContainer } from "../src/types"; +import type { RenderEnvironment } from "../src/renderEnvironment"; +import type { + ExcalidrawTextElementWithContainer, + FontString, +} from "../src/types"; describe("Test measureText", () => { + it("should measure text as the text editor lays it out", () => { + // left on its default, Chrome's canvas shapes a line word by word (and + // so skips the kerning next to a space), while its text editor doesn't, + // so the two would wrap at different words + const renderingWhenMeasured: string[] = []; + const env: RenderEnvironment = { + createCanvas: () => + ({ + getContext: () => { + const context = { + font: "", + textRendering: "auto", + measureText: (text: string) => { + renderingWhenMeasured.push(context.textRendering); + return { width: text.length }; + }, + }; + return context; + }, + } as unknown as HTMLCanvasElement), + createImage: () => ({} as HTMLImageElement), + }; + + getLineWidth("A V A T A R", "20px Helvetica" as FontString, env); + + expect(renderingWhenMeasured).toEqual([TEXT_RENDERING]); + }); + describe("Test getContainerCoords", () => { const params = { width: 200, height: 100, x: 10, y: 20 }; @@ -207,6 +248,10 @@ describe("Test getDefaultLineHeight", () => { it("should return correct line height", () => { expect(getLineHeight(FONT_FAMILY.Cascadia)).toBe(1.2); }); + + it("should return line height using default font family for a custom font which isn't resolved yet", () => { + expect(getLineHeight("google:Unresolved")).toBe(1.25); + }); }); describe("Test computeBoundTextPosition", () => { diff --git a/packages/element/tests/textWrapping.test.ts b/packages/element/tests/textWrapping.test.ts index 2149dd5622..9c5dd94511 100644 --- a/packages/element/tests/textWrapping.test.ts +++ b/packages/element/tests/textWrapping.test.ts @@ -1,3 +1,7 @@ +import { + charWidth, + setCustomTextMetricsProvider, +} from "../src/textMeasurements"; import { getWrappedTextLines, parseTokens, @@ -457,6 +461,50 @@ describe("Test wrapText", () => { }); }); + describe("When letters kern", () => { + // a font which pulls a letter and a space 3px together, and "A" and "V" + // 2px: a line is narrower than its characters measured one by one + const kerningFont = "10px Kerning" as FontString; + const kerning = (a: string, b: string) => + (a === " ") !== (b === " ") + ? 3 + : a + b === "AV" || a + b === "VA" + ? 2 + : 0; + + beforeEach(() => { + charWidth.clearCache(kerningFont); + setCustomTextMetricsProvider({ + getLineWidth: (text) => + Array.from(text).reduce( + (width, char, index, chars) => + width + 10 - (index ? kerning(chars[index - 1], char) : 0), + 0, + ), + }); + }); + + afterEach(() => { + setCustomTextMetricsProvider(undefined); + charWidth.clearCache(kerningFont); + }); + + it("should break a line of single letters where the line as a whole stops fitting", () => { + // "A V A T A R A" is 13 characters and 94px wide: adding the letters' + // own widths up would break it after "A V A T A" + expect(wrapText("A V A T A R A V A T A R", kerningFont, 100)).toEqual( + "A V A T A R A\nV A T A R", + ); + }); + + it("should break a long word where the line as a whole stops fitting", () => { + // "AVAVAVAVAVAV" is 12 characters and 98px wide + expect(wrapText("AVAVAVAVAVAVAVAVAV", kerningFont, 100)).toEqual( + "AVAVAVAVAVAV\nAVAVAV", + ); + }); + }); + describe("Test parseTokens", () => { it("should tokenize latin", () => { let text = "Excalidraw is a virtual collaborative whiteboard"; diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md index 2fad134f98..22ad03d377 100644 --- a/packages/excalidraw/CHANGELOG.md +++ b/packages/excalidraw/CHANGELOG.md @@ -13,6 +13,20 @@ Please add the latest change on the top under the correct section. ## Unreleased +### Custom fonts: font providers, Google Fonts, and a font picker with search and favorites (2026-11-27) [#11601](https://github.com/excalidraw/excalidraw/pull/11601) + +- New `fontProviders` prop: fonts beyond the built-in ones, each supplied by a provider under its key. A text in such a font stores `":"` in `fontFamily`, i.e. `"google:Kalam"`, and the editor asks the provider's `resolve` for the font's files and metrics when it first needs them. A provider also says which fonts the font picker offers (`availableFonts`) and, optionally, answers the picker's search (`search`), pages through more of its fonts (`loadMore`, shown as "Browse more fonts" while there are any), tells what kind of font a family is (`getKind`: `"hand-drawn"`, `"normal"`, `"code"` or `"heading"`, which gives its row the icon our own fonts of that kind have) and a preview text in the family's own script (`getPreviewText`, i.e. `"あ"`, shown as the row's icon). New types: `FontProvider`, `FontProviders`, `FontResolver`, `FontResolvers`, `FontDefinition`, `ProvidedFont`, `FontSearchResult`, `FontKind`. +- A provider key is `google`, or for a host's own provider a lowercase reverse-DNS key with at least one dot, i.e. `com.acme.fonts`. Any other key throws (check with `isValidFontProviderKey`); keys without a dot are reserved. A key is saved into documents, so it must never change. +- New entry point `@excalidraw/excalidraw/fonts/google`: Google Fonts as a provider, loaded on demand and kept out of the main bundle. `createGoogleFontProvider()` returns the whole provider, to pass as `fontProviders={{ [GOOGLE_FONT_PROVIDER_KEY]: createGoogleFontProvider() }}`; with `offerInPicker: false` the picker offers none of the fonts, while a scene's Google fonts still render. `createGoogleFontResolver()` is the resolver alone, with a `source` or `fetch` of your own (i.e. to serve the files from elsewhere, or on a server). It resolves the families of a catalog shipped with the package and no other, 9 for now (Kalam, Patrick Hand, Pacifico, Open Sans, Literata, Fira Mono, Bevan, Zen Maru Gothic, Gowun Dodum), with the metrics from the catalog, so that every host lays the same text out the same way. The editor doesn't contact Google unless a host passes this provider. +- Exports render custom fonts when given the resolvers: per call in `config.fontResolvers` of `exportScene`, or once per page with `registerFontResolvers()` (also exported from `@excalidraw/utils`, which has its own registry). An export without a resolver for a font draws its text in a fallback font, and warns once on the console. Exports load their fonts into `config.environment.document` where that document has a font set, and run where there is no `document.fonts`, `FontFace` or `window` (an SVG with embedded fonts included). +- `Fonts.registerCustomFont(family, metadata, ...fontFaces)` registers a font the host already holds, without a resolver. `Fonts.loadElementsFonts(elements, fontsOrDocument?)` takes a `Fonts` instance in place of the document. +- New `fontFavorites` prop (`{ fonts, onChange }`): the font picker gets a "Favorites" section. A font is added by dragging it from the list onto the drop zone which takes the search's place during the drag, and removed the same way. Controlled: the host keeps the list. +- New `fontPickerTip` prop: replaces the hint at the bottom of the font picker ("Drag a font to pin"), i.e. to say where the offered fonts come from. `null` shows none. +- Escape closes the font picker, from its search as well. It used to take a hover preview back and leave the picker open. +- Taking a font hover preview back (leaving the list, closing the picker) restores only what the preview changed on the text and its container. Closing the picker used to restore every selected element from the copy taken when it opened, as a newer version, which overwrote what a collaborator had changed meanwhile. +- Text on canvas is drawn with `textRendering = "optimizeLegibility"`, which makes Chromium shape a whole line the way the text editor (the DOM) does. Without it a line with kerning across spaces, such as "A V A T A R", came out several px wider on canvas than in the editor, and the two wrapped it at different words. A text measured before keeps its size until it's edited. +- TypeScript: the `fontFamily` of a text element and `appState.currentItemFontFamily` are `FontFamily` (`number | ":"`) in place of `number`. The `FontFamilyValues` type is gone; narrow with `isBuiltInFontFamily()` and `isCustomFontFamily()`. + ### Minimap, zoom menu and `ui.disabled` (2026-11-12) [#12605](https://github.com/excalidraw/excalidraw/pull/12605), [#12606](https://github.com/excalidraw/excalidraw/pull/12606) - A toggleable minimap above the bottom-left canvas actions: drag its viewport (or press outside of it) to pan, wheel over it to zoom. Toggled from the footer button next to the zoom level, the Preferences menu, the command palette and the context menu; stored as `appState.minimapEnabled` (in the browser, not in exported files). Not shown on phones or in editors shorter than 500px. diff --git a/packages/excalidraw/actions/actionClipboard.tsx b/packages/excalidraw/actions/actionClipboard.tsx index 3c0a145c47..c08f313539 100644 --- a/packages/excalidraw/actions/actionClipboard.tsx +++ b/packages/excalidraw/actions/actionClipboard.tsx @@ -154,6 +154,7 @@ export const actionCopyAsSvg = register({ { exportingFrame, name: app.getName(), + fontResolvers: app.fonts.instance.fontResolvers, renderEnvironment: app.renderEnvironment, }, ); @@ -221,6 +222,7 @@ export const actionCopyAsPng = register({ await exportCanvas("clipboard", exportedElements, appState, app.files, { exportingFrame, name: app.getName(), + fontResolvers: app.fonts.instance.fontResolvers, renderEnvironment: app.renderEnvironment, }); return { diff --git a/packages/excalidraw/actions/actionDuplicateSelection.test.tsx b/packages/excalidraw/actions/actionDuplicateSelection.test.tsx index 71559fe47e..1281b3d2ba 100644 --- a/packages/excalidraw/actions/actionDuplicateSelection.test.tsx +++ b/packages/excalidraw/actions/actionDuplicateSelection.test.tsx @@ -1,10 +1,12 @@ import { ORIG_ID } from "@excalidraw/common"; import { Excalidraw } from "../index"; +import { Fonts } from "../fonts"; import { API } from "../tests/helpers/api"; import { act, assertElements, + cleanup, getCloneByOrigId, render, } from "../tests/test-utils"; @@ -528,4 +530,65 @@ describe("actionDuplicateSelection", () => { ]); }); }); + + describe("onDuplicate font swaps", () => { + it("leaves the geometry of host-swapped duplicates to the host", async () => { + // documents a deliberate contract (see the `onDuplicate` JSDoc in + // types.ts): replacing a duplicate's `fontFamily` in the hook leaves + // its measured geometry to the host - the editor loads the swapped + // family but does not re-measure the duplicate, even when the family + // was already processed by this editor + cleanup(); + await render( + { + const prevIds = new Set(prevElements.map(({ id }) => id)); + return nextElements.map((element) => + !prevIds.has(element.id) && element.type === "text" + ? { ...element, fontFamily: "test.dupcontract:Font" as const } + : element, + ); + }} + />, + ); + + Fonts.registerCustomFont( + "test.dupcontract:Font", + { + metrics: { + unitsPerEm: 1000, + ascender: 800, + descender: -200, + lineHeight: 2, + }, + }, + { uri: "https://example.com/font.woff2" }, + ); + // the family was fully processed by this editor long ago + const { fontFace } = Fonts.registered.get("test.dupcontract:Font")! + .fontFaces[0]; + act(() => { + window.h.app.fonts.instance.onLoaded([fontFace]); + }); + + const text = API.createElement({ type: "text", text: "swap me" }); + API.setElements([text]); + API.setSelectedElements([text]); + + act(() => { + h.app.actionManager.executeAction(actionDuplicateSelection); + }); + + // let the async font load & onLoaded pass settle + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + + const duplicate = h.elements.find( + (element) => element.type === "text" && element.id !== text.id, + ) as typeof text; + expect(duplicate.fontFamily).toBe("test.dupcontract:Font"); + // geometry stays the original family's - the host owns it + expect(duplicate.lineHeight).toBe(text.lineHeight); + expect(duplicate.height).toBe(text.height); + }); + }); }); diff --git a/packages/excalidraw/actions/actionDuplicateSelection.tsx b/packages/excalidraw/actions/actionDuplicateSelection.tsx index a77cd5da54..8e5fab5ff9 100644 --- a/packages/excalidraw/actions/actionDuplicateSelection.tsx +++ b/packages/excalidraw/actions/actionDuplicateSelection.tsx @@ -97,6 +97,7 @@ export const actionDuplicateSelection = register({ } } + app.fonts.onElementsDuplicated(duplicatedElements); app.duplicate.advanceListMarkers(duplicatedElements); return { diff --git a/packages/excalidraw/actions/actionExport.tsx b/packages/excalidraw/actions/actionExport.tsx index bee75d7a80..05105fa942 100644 --- a/packages/excalidraw/actions/actionExport.tsx +++ b/packages/excalidraw/actions/actionExport.tsx @@ -280,6 +280,7 @@ export const actionSaveToActiveFile = register({ exportedDataPromise, previousFileHandle, filename, + app.fonts.instance.fontResolvers, ) : await saveAsJSON({ data: exportedDataPromise, @@ -410,6 +411,7 @@ export const actionLoadScene = register({ elements: loadedElements, appState: loadedAppState, files, + loadFonts: true, captureUpdate: CaptureUpdateAction.IMMEDIATELY, }; } catch (error: any) { diff --git a/packages/excalidraw/actions/actionProperties.tsx b/packages/excalidraw/actions/actionProperties.tsx index 3ee482f45a..03805a0c46 100644 --- a/packages/excalidraw/actions/actionProperties.tsx +++ b/packages/excalidraw/actions/actionProperties.tsx @@ -1,6 +1,6 @@ import { pointFrom } from "@excalidraw/math"; -import { useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { BUCKET_FILL_BACKGROUND_PICKS, @@ -9,7 +9,6 @@ import { ARROW_TYPE, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, - FONT_FAMILY, ROUNDNESS, STROKE_WIDTH_KEYS, VERTICAL_ALIGN, @@ -77,7 +76,12 @@ import { toggleLinePolygonState, } from "@excalidraw/element"; -import { deriveStylesPanelMode } from "@excalidraw/common"; +import { + deriveStylesPanelMode, + isFontMetadataAvailable, +} from "@excalidraw/common"; + +import type { FontFamily } from "@excalidraw/common"; import type { LocalPoint, Radians } from "@excalidraw/math"; @@ -91,7 +95,6 @@ import type { ExcalidrawLinearElement, ExcalidrawTextElement, FixedPointBinding, - FontFamilyValues, StrokeVariability, NonDeleted, NonDeletedExcalidrawElement, @@ -158,7 +161,6 @@ import { strokeVariabilityVariableIcon, } from "../components/icons"; -import { Fonts } from "../fonts"; import { getLanguage, t } from "../i18n"; import { canHaveArrowheads, @@ -1165,6 +1167,55 @@ type ChangeFontFamilyData = Partial< resetAll?: true; /** flag to reset all containers to their cached versions */ resetContainers?: true; + /** + * re-snapshots the cache from the scene, once the elements have settled - + * called again after an async font load, whose redraw lands after the action. + * + * `activeHoveredFontFamily` is for callers knowing the hover state better + * than the (asynchronously committed) app state does. + */ + refreshCache?: (activeHoveredFontFamily?: FontFamily | null) => void; +}; + +/** + * What a font preview changes: the font of a text, and the layout which + * follows from it - of the text, and of its container. See + * `redrawTextBoundingBox`; a sticky note also fits its label's font size and + * keeps a base height. + */ +const FONT_PREVIEW_GEOMETRY_KEYS = ["x", "y", "width", "height"] as const; +const FONT_PREVIEW_CONTAINER_KEYS = [ + ...FONT_PREVIEW_GEOMETRY_KEYS, + "baseHeight", +] as const; +const FONT_PREVIEW_FONT_KEYS = ["fontFamily", "lineHeight"] as const; +const FONT_PREVIEW_TEXT_KEYS = [ + ...FONT_PREVIEW_FONT_KEYS, + "text", + "fontSize", + "baseFontSize", + ...FONT_PREVIEW_GEOMETRY_KEYS, +] as const; + +/** + * The cached values of the properties a font preview has changed. Taking a + * preview back restores these and nothing else: the rest of the element may + * have been changed meanwhile by someone else (a collaborator), for real. + */ +const getFontPreviewRevert = ( + element: T, + cachedElement: ExcalidrawElement, + keys: readonly string[], +) => { + const current = element as Record; + const cached = cachedElement as Record; + const update: Record = {}; + for (const key of keys) { + if (key in cached && current[key] !== cached[key]) { + update[key] = cached[key]; + } + } + return Object.keys(update).length ? (update as ElementUpdate) : null; }; export const actionChangeFontFamily = register<{ @@ -1175,34 +1226,88 @@ export const actionChangeFontFamily = register<{ label: "labels.fontFamily", trackEvent: false, perform: (elements, appState, value, app) => { - const { cachedElements, resetAll, resetContainers, ...nextAppState } = - value as ChangeFontFamilyData; + const { + cachedElements, + resetAll, + resetContainers, + refreshCache, + ...nextAppState + } = value as ChangeFontFamilyData; if (resetAll) { - const nextElements = changeProperty( - elements, - appState, - (element) => { - const cachedElement = cachedElements?.get(element.id); - if (cachedElement) { - const newElement = newElementWith(element, { - ...cachedElement, - } as ElementUpdate); + const resetAppState = { ...appState, ...nextAppState }; - return newElement; - } + // Only a live preview has something to take back. Without one (the + // picker got opened and closed, or the hover was reverted already) the + // elements are left alone: whatever changed since they were cached + // wasn't ours, and a restore would also be a newer version of each + if (appState.currentHoveredFontFamily == null) { + return { + appState: resetAppState, + captureUpdate: CaptureUpdateAction.NEVER, + }; + } + // a preview touches texts and their containers - whatever else is + // selected along with them (and so cached) isn't ours to restore + const containerIds = new Set(); + for (const cachedElement of cachedElements?.values() ?? []) { + if (isTextElement(cachedElement) && cachedElement.containerId) { + containerIds.add(cachedElement.containerId); + } + } + + // By id, not selection - a click outside the picker may have cleared it. + // A deleted one stays so, i.e. when deleted by a collaborator meanwhile. + // What gets restored is a newer version, or collab never syncs it + const nextElements = elements.map((element) => { + const cachedElement = cachedElements?.get(element.id); + if ( + !cachedElement || + element.isDeleted || + (!isTextElement(element) && !containerIds.has(element.id)) + ) { return element; - }, - true, - ); + } + + if ( + isTextElement(element) && + isTextElement(cachedElement) && + element.originalText !== cachedElement.originalText + ) { + // edited during the preview: the cached wrapping and geometry are + // another text's, so only the font goes back, and it's laid out anew + const update = getFontPreviewRevert( + element, + cachedElement, + FONT_PREVIEW_FONT_KEYS, + ); + if (!update) { + return element; + } + const nextElement = newElementWith(element, update); + redrawTextBoundingBox( + nextElement, + app.scene.getContainerElement(element), + app.scene, + app.renderEnvironment, + ); + return nextElement; + } + + const update = getFontPreviewRevert( + element, + cachedElement, + isTextElement(element) + ? FONT_PREVIEW_TEXT_KEYS + : FONT_PREVIEW_CONTAINER_KEYS, + ); + return update ? newElementWith(element, update) : element; + }); return { elements: nextElements, - appState: { - ...appState, - ...nextAppState, - }, + appState: resetAppState, captureUpdate: CaptureUpdateAction.NEVER, }; } @@ -1213,7 +1318,7 @@ export const actionChangeFontFamily = register<{ let nextCaptureUpdateAction: CaptureUpdateActionType = CaptureUpdateAction.EVENTUALLY; - let nextFontFamily: FontFamilyValues | undefined; + let nextFontFamily: FontFamily | undefined; let skipOnHoverRender = false; if (currentItemFontFamily) { @@ -1265,20 +1370,22 @@ export const actionChangeFontFamily = register<{ let uniqueChars = new Set(); let skipFontFaceCheck = false; - const fontsCache = Array.from(Fonts.loadedFontsCache.values()); - const fontFamily = Object.entries(FONT_FAMILY).find( - ([_, value]) => value === nextFontFamily, - )?.[0]; - - // skip `document.font.check` check on hover, if at least one font family has loaded as it's super slow (could result in slightly different bbox, which is fine) + // skip `document.fonts.check` on hover, if at least one font face of the + // family has loaded, as it's super slow (could result in slightly + // different bbox, which is fine) if ( currentHoveredFontFamily && - fontFamily && - fontsCache.some((sig) => sig.startsWith(fontFamily)) + app.fonts.instance.isFamilyLoaded(nextFontFamily) ) { skipFontFaceCheck = true; } + // a custom family only has metrics once resolved - substituting the + // fallback's line height would bake a wrong value in permanently, so + // it's converged once the family is in (`repairTextOnFontLoad` below) + const hasFontMetrics = + !nextFontFamily || isFontMetadataAvailable(nextFontFamily); + // following causes re-render so make sure we changed the family // otherwise it could cause unexpected issues, such as preventing opening the popover when in wysiwyg Object.assign(result, { @@ -1295,18 +1402,29 @@ export const actionChangeFontFamily = register<{ oldElement, { fontFamily: nextFontFamily, - lineHeight: getLineHeight(nextFontFamily!), + ...(hasFontMetrics + ? { lineHeight: getLineHeight(nextFontFamily!) } + : null), }, ); - const cachedContainer = - cachedElements?.get(oldElement.containerId || "") || {}; + const cachedContainer = cachedElements?.get( + oldElement.containerId || "", + ); const container = app.scene.getContainerElement(oldElement); if (resetContainers && container && cachedContainer) { - // reset the container back to it's cached version - app.scene.mutateElement(container, { ...cachedContainer }); + // back to the size it had before the previews, so that it + // doesn't keep the largest one's + const update = getFontPreviewRevert( + container, + cachedContainer, + FONT_PREVIEW_CONTAINER_KEYS, + ); + if (update) { + app.scene.mutateElement(container, update); + } } if (!skipFontFaceCheck) { @@ -1327,14 +1445,46 @@ export const actionChangeFontFamily = register<{ ), }); + if (!hasFontMetrics) { + // switched before the family resolved - the line height and the + // dimensions come out right only once it has + app.fonts.repairTextOnFontLoad( + Array.from(elementContainerMapping.keys()), + ); + } + // size is irrelevant, but necessary const fontString = `10px ${getFontFamilyString({ fontFamily: nextFontFamily, })}`; - const chars = Array.from(uniqueChars.values()).join(); - const ownerDocument = app.props.ownerDocument ?? document; + // a family committed with no text selected still needs loading - an + // empty string makes `check` pass vacuously, so probe with a glyph + const chars = Array.from(uniqueChars.values()).join() || " "; + const fontFaceSet = (app.props.ownerDocument ?? document).fonts; - if (skipFontFaceCheck || ownerDocument.fonts.check(fontString, chars)) { + if (!currentHoveredFontFamily) { + // picking a font again is how one whose file failed to download is + // retried - its faces would fail the load below for good otherwise + app.fonts.instance.retryFailedFontFaces(nextFontFamily); + } + + // WARN: `check()` can only be trusted when it says "unloaded" - Chrome + // reports any family whose name matches an *installed* system font as + // loaded, even with its web faces unloaded (i.e. anyone with Excalifont + // installed). A pass still gets the synchronous redraw below, but the + // faces get loaded regardless, repairing it if `check()` was wrong + const isLoaded = + skipFontFaceCheck || fontFaceSet.check(fontString, chars); + const loadedFacesBefore = + isLoaded && !skipFontFaceCheck + ? new Set( + Array.from(fontFaceSet).filter( + (fontFace) => fontFace.status === "loaded", + ), + ) + : null; + + if (isLoaded) { // we either skip the check (have at least one font face loaded) or do the check and find out all the font faces have loaded for (const [element, container] of elementContainerMapping) { // trigger synchronous redraw @@ -1345,30 +1495,71 @@ export const actionChangeFontFamily = register<{ app.renderEnvironment, ); } - } else { - // otherwise try to load all font faces for the given chars and redraw elements once our font faces loaded - ownerDocument.fonts.load(fontString, chars).then((fontFaces) => { - for (const [element, container] of elementContainerMapping) { - // use latest element state to ensure we don't have closure over an old instance in order to avoid possible race conditions (i.e. font faces load out-of-order while rapidly switching fonts) - const latestElement = app.scene.getElement(element.id); - const latestContainer = container - ? app.scene.getElement(container.id) - : null; + } - if (latestElement) { - // trigger async redraw - redrawTextBoundingBox( - latestElement as ExcalidrawTextElement, - latestContainer, - app.scene, - app.renderEnvironment, - ); + if (!skipFontFaceCheck) { + // load all font faces for the given chars and redraw elements once our font faces loaded + fontFaceSet + .load(fontString, chars) + .then((fontFaces) => { + // `check()` was right - the synchronous redraw above measured + // with the real faces already + if ( + loadedFacesBefore && + fontFaces.every((fontFace) => loadedFacesBefore.has(fontFace)) + ) { + return; } - } - // trigger update once we've mutated all the elements, which also updates our cache - app.fonts.onLoaded(fontFaces); - }); + if (elementContainerMapping.size) { + const redraw = () => { + for (const [element, container] of elementContainerMapping) { + // use latest element state to ensure we don't have closure over an old instance in order to avoid possible race conditions (i.e. font faces load out-of-order while rapidly switching fonts) + const latestElement = app.scene.getElement(element.id); + const latestContainer = container + ? app.scene.getElement(container.id) + : null; + + if ( + latestElement && + isTextElement(latestElement) && + latestElement.fontFamily === nextFontFamily + ) { + // trigger async redraw + redrawTextBoundingBox( + latestElement, + latestContainer, + app.scene, + app.renderEnvironment, + ); + } + } + }; + + if (app.state.currentHoveredFontFamily != null) { + // Still a preview: laid out again as part of it, uncaptured + // like the hover which made it. As a repair it would wait + // for the hover to end (see `AppFonts.isGestureInFlight`), + // the preview keeping the fallback font's layout meanwhile + redraw(); + } else { + app.fonts.instance.runSceneRepair(redraw); + } + } + + // trigger update once we've mutated all the elements, which also updates our cache + app.fonts.instance.onLoaded(fontFaces); + + // the redraw above happened after the action was applied, so the cache + // still holds the pre-redraw (fallback font) dimensions - re-snapshot it + refreshCache?.(); + }) + .catch((error) => { + // `load` rejects when any matched face fails to fetch - routine + // for custom families on host-resolver URLs, and it must not + // escape into the host page as an unhandled rejection + console.error(`Failed to load font "${fontString}"`, error); + }); } } @@ -1376,11 +1567,49 @@ export const actionChangeFontFamily = register<{ }, PanelComponent: ({ elements, appState, app, updateData }) => { const cachedElementsRef = useRef(new Map()); - const prevSelectedFontFamilyRef = useRef(null); + const prevSelectedFontFamilyRef = useRef(null); // relying on state batching as multiple `FontPicker` handlers could be called in rapid succession and we want to combine them const [batchedData, setBatchedData] = useState({}); const isUnmounted = useRef(true); - const { stylesPanelMode, isCompact } = getStylesPanelInfo(app); + const pendingRefreshRef = useRef(false); + /** a hover preview is applied to the scene, and not taken back yet */ + const isPreviewAppliedRef = useRef(false); + const { stylesPanelMode } = getStylesPanelInfo(app); + + const refreshCachedElements = useCallback( + (activeHoveredFontFamily?: FontFamily | null) => { + if (isUnmounted.current) { + return; + } + + // a live hover mutation must not leak into the snapshot: a font load + // settling mid-preview would make the later hover-leave reset + // "restore" the merely-hovered family permanently. Defer to the + // batched-data effect below, which runs once the hover clears. + // Committed app state lags the action by a React batch, so it's only + // a fallback for callers not passing the hover state + const hovered = + activeHoveredFontFamily !== undefined + ? activeHoveredFontFamily + : app.state.currentHoveredFontFamily; + if (hovered != null) { + pendingRefreshRef.current = true; + return; + } + + for (const id of cachedElementsRef.current.keys()) { + const element = app.scene.getElement(id); + if (element) { + cachedElementsRef.current.set( + id, + newElementWith(element, {}, true), + ); + } + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, + [app], + ); const selectedFontFamily = useMemo(() => { const getFontFamily = ( @@ -1409,6 +1638,10 @@ export const actionChangeFontFamily = register<{ : appState.currentItemFontFamily || DEFAULT_FONT_FAMILY, ); + if (batchedData.currentItemFontFamily) { + return batchedData.currentItemFontFamily; + } + // popup opened, use cached elements if ( batchedData.openPopup === "fontFamily" && @@ -1427,7 +1660,13 @@ export const actionChangeFontFamily = register<{ // popup props are not in sync, hence we are in the middle of an update, so keeping the previous value we've had return prevSelectedFontFamilyRef.current; - }, [batchedData.openPopup, appState, elements, app]); + }, [ + batchedData.openPopup, + batchedData.currentItemFontFamily, + appState, + elements, + app, + ]); useEffect(() => { prevSelectedFontFamilyRef.current = selectedFontFamily; @@ -1435,7 +1674,63 @@ export const actionChangeFontFamily = register<{ useEffect(() => { if (Object.keys(batchedData).length) { - updateData(batchedData); + let data = batchedData; + if (batchedData.resetAll || batchedData.currentItemFontFamily) { + isPreviewAppliedRef.current = false; + } else if ( + batchedData.currentHoveredFontFamily && + !isPreviewAppliedRef.current + ) { + // A preview starts here. What it's taken back to is the scene as + // it is now, not as it was when the picker opened - it may have + // been open for a while, with collaborators at work + isPreviewAppliedRef.current = true; + refreshCachedElements(null); + data = { + ...batchedData, + cachedElements: new Map(cachedElementsRef.current), + }; + } + updateData(data); + // the async font load path re-runs this from within the action once it + // settles. Hover is passed explicitly - committed app state still + // holds the pre-action value here + batchedData.refreshCache?.( + batchedData.currentHoveredFontFamily ?? null, + ); + + // a refresh deferred while a hover preview was live (see + // `refreshCachedElements`) runs now that it cleared: the hover-leave + // reset just restored pre-load geometry, so redraw with the (by now + // loaded) faces first, then re-snapshot + if ( + pendingRefreshRef.current && + batchedData.currentHoveredFontFamily === null + ) { + pendingRefreshRef.current = false; + + if (cachedElementsRef.current.size) { + // keep the repair out of the next action's undo delta. NOT via + // `runSceneRepair`: a hover-clear can't coincide with a gesture, + // and the re-snapshot below must follow synchronously + app.fonts.instance.onBeforeSceneMutation(); + + for (const id of cachedElementsRef.current.keys()) { + const element = app.scene.getElement(id); + if (element && isTextElement(element)) { + redrawTextBoundingBox( + element, + app.scene.getContainerElement(element), + app.scene, + app.renderEnvironment, + ); + } + } + } + + refreshCachedElements(null); + } + // reset the data after we've used the data setBatchedData({}); } @@ -1451,32 +1746,64 @@ export const actionChangeFontFamily = register<{ }; }, []); + const getResetData = (): ChangeFontFamilyData => ({ + currentHoveredFontFamily: null, + cachedElements: new Map(cachedElementsRef.current), + resetAll: true, + }); + + const updateDataRef = useRef(updateData); + updateDataRef.current = updateData; + const isOpened = appState.openPopup === "fontFamily"; + + // the cache lives while the popup is open - `onPopupChange(false)` also + // fires when it stays open (i.e. StrictMode, compact mode refocusing the + // editor). A close from outside the picker may unmount us before batched + // data applies, so revert a live preview right away + useEffect(() => { + if (!isOpened) { + return; + } + const cachedElements = cachedElementsRef.current; + return () => { + isPreviewAppliedRef.current = false; + if (cachedElements.size && app.state.currentHoveredFontFamily) { + updateDataRef.current(getResetData()); + // a batched reset would only repeat this + setBatchedData({}); + } + cachedElements.clear(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isOpened, app]); + return ( <> {stylesPanelMode === "full" && ( {t("labels.fontFamily")} )} updateData({ fontTopPicks })} - onSelect={(fontFamily) => { - withCaretPositionPreservation( - () => { - setBatchedData({ - openPopup: null, - currentHoveredFontFamily: null, - currentItemFontFamily: fontFamily, - }); - // defensive clear so immediate close won't abuse the cached elements - cachedElementsRef.current.clear(); - }, - isCompact, - !!appState.editingTextElement, - ); + onSelect={(fontFamily, { keepOpen } = {}) => { + // caret preservation is owned by the picker (`useFontResolution`'s + // `select`) - wrapping again here would schedule a competing + // restore + setBatchedData({ + openPopup: keepOpen ? "fontFamily" : null, + currentHoveredFontFamily: null, + currentItemFontFamily: fontFamily, + refreshCache: keepOpen ? refreshCachedElements : undefined, + }); + + if (!keepOpen) { + // defensive clear so immediate close won't abuse the cached elements + cachedElementsRef.current.clear(); + } }} onHover={(fontFamily) => { setBatchedData({ @@ -1486,18 +1813,18 @@ export const actionChangeFontFamily = register<{ }); }} onLeave={() => { - setBatchedData({ - currentHoveredFontFamily: null, - cachedElements: new Map(cachedElementsRef.current), - resetAll: true, - }); + setBatchedData(getResetData()); }} onPopupChange={(open) => { + // WARN: read state through the stable `app` handle, never the + // render-scoped `appState`/`elements` props - `FontPicker`'s memo + // skips re-renders, so this closure may be from an older render + // than the state it must act on if (open) { // open, populate the cache from scratch cachedElementsRef.current.clear(); - const { editingTextElement } = appState; + const { editingTextElement } = app.state; // still check type to be safe if (editingTextElement?.type === "text") { @@ -1517,8 +1844,8 @@ export const actionChangeFontFamily = register<{ ); } else { const selectedElements = getSelectedElements( - elements, - appState, + app.scene.getNonDeletedElements(), + app.state, { includeBoundTextElement: true, }, @@ -1532,24 +1859,18 @@ export const actionChangeFontFamily = register<{ } } - setBatchedData({ - ...batchedData, + setBatchedData((data) => ({ + ...data, openPopup: "fontFamily", - }); + })); } else { - const fontFamilyData = { - currentHoveredFontFamily: null, - cachedElements: new Map(cachedElementsRef.current), - resetAll: true, - } as ChangeFontFamilyData; - - setBatchedData({ - ...fontFamilyData, - }); - cachedElementsRef.current.clear(); + setBatchedData(getResetData()); // Refocus text editor when font picker closes if we were editing text - if (isCompact && appState.editingTextElement) { + if ( + getStylesPanelInfo(app).isCompact && + app.state.editingTextElement + ) { restoreCaretPosition(null, app.ownerDocument); // Just refocus without saved position } } diff --git a/packages/excalidraw/actions/types.ts b/packages/excalidraw/actions/types.ts index f918f30365..6ba839161b 100644 --- a/packages/excalidraw/actions/types.ts +++ b/packages/excalidraw/actions/types.ts @@ -29,6 +29,7 @@ export type ActionResult = files?: BinaryFiles | null; captureUpdate: CaptureUpdateActionType; replaceFiles?: boolean; + loadFonts?: boolean; } | false; diff --git a/packages/excalidraw/components/App.clipboard.ts b/packages/excalidraw/components/App.clipboard.ts index 0765ae3e9b..18e6f3583d 100644 --- a/packages/excalidraw/components/App.clipboard.ts +++ b/packages/excalidraw/components/App.clipboard.ts @@ -635,6 +635,8 @@ export class AppClipboard { } else { this.app.insertNewElements(textElements); } + // measured above, in the fallback font if their own is still on its way + this.app.fonts.repairTextOnFontLoad(textElements); this.app.store.scheduleCapture(); this.app.setState({ selectedElementIds: getSelectedElementIds() }); diff --git a/packages/excalidraw/components/App.duplicate.ts b/packages/excalidraw/components/App.duplicate.ts index 90f7ee2d26..7c91e6823e 100644 --- a/packages/excalidraw/components/App.duplicate.ts +++ b/packages/excalidraw/components/App.duplicate.ts @@ -542,5 +542,7 @@ export class AppDuplicate { this.app.maybeCacheVisibleGaps(event, selectedElements, true); this.app.maybeCacheReferenceSnapPoints(event, selectedElements, true); }); + + this.app.fonts.onElementsDuplicated(duplicatedElements); }; } diff --git a/packages/excalidraw/components/App.fonts.ts b/packages/excalidraw/components/App.fonts.ts new file mode 100644 index 0000000000..a1ae51b5c5 --- /dev/null +++ b/packages/excalidraw/components/App.fonts.ts @@ -0,0 +1,614 @@ +import throttle from "lodash.throttle"; + +import { + isCustomFontFamily, + isFontMetadataAvailable, + isSafari, + reconcileLineHeight, +} from "@excalidraw/common"; + +import { + getContainerElement, + isBoundToContainer, + isTextElement, + redrawTextBoundingBox, +} from "@excalidraw/element"; + +import type { FontFamily } from "@excalidraw/common"; +import type { + ExcalidrawElement, + ExcalidrawTextElement, +} from "@excalidraw/element/types"; + +import { Fonts } from "../fonts"; + +import type { FontResolvers } from "../fonts"; +import type { AppProps, AppState, FontProviders, SceneData } from "../types"; +import type App from "./App"; + +type AppFontsDependencies = { + /** + * Called right before a font reflow mutates the scene, so the mutation can + * be kept out of the next user action's undo delta. + */ + onBeforeSceneMutation: () => void; +}; + +/** + * Narrow the host-facing `FontProviders` down to what the font layer needs, + * keeping it free of UI concerns. + * + * Each resolver looks its provider up when called, rather than holding on to + * the callback it was built with: new callbacks under the same keys don't + * rebuild the `Fonts` instance (see `onPropsUpdated`), and a host's `resolve` + * may close over what its render had (i.e. a refreshed auth token). Called on + * the provider, as it may legitimately be a class instance resolving against + * its own `this`. + */ +const toFontResolvers = ( + getFontProviders: () => FontProviders | undefined, +): FontResolvers | undefined => { + const fontProviders = getFontProviders(); + + return ( + fontProviders && + Object.fromEntries( + Object.keys(fontProviders).map((id) => [ + id, + async (familyName: string) => { + const latestFontProviders = getFontProviders(); + if (!latestFontProviders || !Object.hasOwn(latestFontProviders, id)) { + throw new Error(`Font provider "${id}" is no longer available`); + } + return latestFontProviders[id].resolve(familyName); + }, + ]), + ) + ); +}; + +/** + * Owns the App-bound font workflows: the lifecycle of the editor's `Fonts` + * instance (including swapping it when `fontProviders` changes), loading the + * faces a scene needs as elements arrive, and the geometry repairs those loads + * trigger. + * + * The font machinery itself — resolution, registration, caching, the repair + * queue — lives in `../fonts` and knows nothing about `App`. + */ +export class AppFonts { + /** + * The editor's `Fonts` registry, read by actions and the picker as + * `app.fonts.instance`. Swapped wholesale when `fontProviders` changes, so + * work spanning an `await` must capture it up front rather than re-read it + * afterwards - otherwise it would settle against a different instance. + */ + public instance: Fonts; + + /** + * Families the scene walk alone would miss - i.e. an incoming default font + * no element uses yet - to pass along with the next throttled font load. + */ + private pendingSceneFontFamilies = new Set(); + + /** + * Per family: its block-period timer while its text is held back, `null` + * once settled - a family blocks at most once per editor, so text which got + * drawn (even in the fallback) never vanishes again. Lives here rather than + * on `Fonts`, so that a `fontProviders` swap doesn't restart it. + */ + private fontBlocks = new Map< + FontFamily, + ReturnType | null + >(); + + constructor(private app: App, private dependencies: AppFontsDependencies) { + this.instance = this.createFonts(); + } + + private createFonts = () => + new Fonts( + this.app.scene, + toFontResolvers(() => this.app.props.fontProviders), + undefined, + { + onBeforeSceneMutation: this.dependencies.onBeforeSceneMutation, + // a reflow must wait out any in-flight gesture or text edit: `NEVER` + // wins the commit over the gesture's `EVENTUALLY`, corrupting its undo + // entry (flushed by `onStateUpdated` once it ends) + shouldDeferSceneMutation: () => this.isGestureInFlight(this.app.state), + ownerDocument: this.app.ownerDocument, + getRenderEnvironment: () => this.app.renderEnvironment, + }, + ); + + /** + * Whether the scene holds changes which are yet to be captured: a pointer + * gesture, a text edit - typing writes to the element right away, while + * the edit is captured only once submitted - or a font hover preview, + * which is either taken back or captured once the font gets picked. A + * repair committed meanwhile would take the previewed font into the + * snapshot, and picking it would leave nothing to undo. + */ + private isGestureInFlight = (state: AppState) => + state.selectedElementsAreBeingDragged || + state.isResizing || + state.isRotating || + state.cursorButton === "down" || + !!state.editingTextElement || + state.currentHoveredFontFamily != null; + + /** + * Whether text in the family should stay undrawn for now, rather than be + * drawn in the fallback font - like CSS `font-display: block`, but short. + * + * A custom family still loading blocks for {@link Fonts.BLOCK_PERIOD} from + * its first render, then swaps to the fallback until its faces arrive - most + * fonts arrive within it, sparing a fallback flash and the reflow which + * follows. Built-ins never block - they're bundled and preloaded. + * + * Called per text element on every render - keep it cheap. + */ + public isFontBlocked = (family: FontFamily): boolean => { + const timer = this.fontBlocks.get(family); + if (timer === null) { + return false; + } + + if ( + Fonts.BLOCK_PERIOD <= 0 || + !isCustomFontFamily(family) || + this.instance.isFamilyLoaded(family) || + // unresolvable or failed - nothing to wait for + !this.instance.shouldLoadCustomFamily(family) + ) { + clearTimeout(timer); + this.fontBlocks.set(family, null); + return false; + } + + if (timer === undefined) { + // timer-driven rather than a deadline compared on render, so a timer + // firing a tick early can't leave the text blocked with no rerender left + this.fontBlocks.set( + family, + setTimeout(() => { + this.fontBlocks.set(family, null); + // rerender in the fallback - a load arriving first already + // rerendered through `onLoaded` + if (!this.instance.isFamilyLoaded(family)) { + this.app.scene.triggerUpdate(); + } + }, Fonts.BLOCK_PERIOD), + ); + } + + return true; + }; + + private loadSceneFontFamilies = (additionalFamilies: FontFamily[]) => { + // captured, as a `fontProviders` swap replaces the instance mid-flight + const fonts = this.instance; + + fonts.loadSceneFonts(additionalFamilies).then((fontFaces) => { + if (!this.app.unmounted) { + fonts.onLoaded(fontFaces); + } + }); + }; + + /** + * Load the faces the scene needs, plus `additionalFamily` - the current + * default font may not be used by any element yet, so the element walk alone + * wouldn't get it registered. + * + * Unlike `Fonts.loadSceneFonts`, this applies `onLoaded` itself - the caller + * has nothing left to await. + */ + public refreshSceneFonts = (additionalFamily?: FontFamily) => + this.loadSceneFontFamilies( + additionalFamily === undefined ? [] : [additionalFamily], + ); + + /** + * rerender text elements on font load to fix #637 && #1553 + */ + public onDocumentFontsLoaded = (event: Event) => { + this.instance.onLoaded((event as FontFaceSetLoadEvent).fontfaces); + }; + + /** + * A `fontProviders` change may make previously-unresolvable families + * resolvable, so the whole instance is rebuilt around the new resolvers. + */ + public onPropsUpdated = (prevProps: AppProps) => { + if (prevProps.fontProviders === this.app.props.fontProviders) { + return; + } + + // per the `FontProviders` contract a key always denotes the same font + // source, so only the key set matters - which also keeps an inline + // `fontProviders` object from churning the instance every render (its + // resolvers call whichever callbacks the props hold by then) + const prevProviders = prevProps.fontProviders ?? {}; + const nextProviders = this.app.props.fontProviders ?? {}; + const addedKeys = Object.keys(nextProviders).filter( + (key) => !Object.hasOwn(prevProviders, key), + ); + const removedKeys = Object.keys(prevProviders).filter( + (key) => !Object.hasOwn(nextProviders, key), + ); + + if (!addedKeys.length && !removedKeys.length) { + return; + } + + // the key set is captured by the instance, so swap the whole instance - + // the page-global registry & failure set are unaffected + this.instance = this.createFonts(); + + // an instance-field mutation - force a render so readers of + // `app.fonts.instance` (i.e. the picker) observe it + this.app.setState({}); + + if (addedKeys.length) { + // new providers may make previously-unsupported families resolvable; + // removals add nothing resolvable, so they need no pass + this.refreshSceneFonts(this.app.state.currentItemFontFamily); + } + }; + + /** + * Deferred font repairs run once the gesture fully ends - and only after the + * whole pointer-up chain, which schedules the gesture's capture *later* than + * the flags observed in `componentDidUpdate` flip. A repair's `NEVER` commit + * running first would eat the uncaptured gesture delta into the snapshot. + */ + public onStateUpdated = (prevState: AppState) => { + if ( + !this.isGestureInFlight(prevState) || + this.isGestureInFlight(this.app.state) || + // no timer per gesture end when nothing is pending - the common + // (no custom fonts) case must stay free + !this.instance.hasPendingSceneRepairs() + ) { + return; + } + + setTimeout(() => { + if (!this.app.unmounted) { + // no-ops if a new gesture started meanwhile - its end reschedules + this.instance.flushDeferredSceneRepairs(); + } + }); + }; + + /** + * Throttled, as `updateScene` runs on every remote collab increment and a + * scene using custom fonts would otherwise pay the character walk + + * `document.fonts.check` per family on each call. Leading edge keeps the + * first update immediate, trailing edge keeps the last one correct. + */ + private loadUpdatedSceneFontsThrottled = throttle(() => { + const additionalFamilies = Array.from(this.pendingSceneFontFamilies); + this.pendingSceneFontFamilies.clear(); + + this.loadSceneFontFamilies(additionalFamilies); + }, 1000); + + public onSceneUpdated = ( + elements: SceneData["elements"], + appState: Pick | null | undefined, + ) => { + // keeps `updateScene` (i.e. every collab increment) free of font work + // when no custom fonts can exist, matching master + if (!this.instance.mayHaveCustomFonts()) { + return; + } + + // Nothing of the family has arrived here yet. Once something has, there + // is nothing left for a pass to do on every update: the family's faces + // are installed, and the browser fetches whichever one later text needs + // (as it does for the built-in fonts) + // + // Not in Safari, which may not fire `loadingdone` for a face the canvas + // asked for (see `onElementsInserted`) - text needing one would stay in + // the fallback font. There the pass stays what loads and announces it + const needsLoading = (family: FontFamily) => + this.instance.shouldLoadCustomFamily(family) && + (isSafari || !this.instance.hasLoadedFamily(family)); + + // the incoming default font may not be used by any element yet + const currentItemFontFamily = appState?.currentItemFontFamily; + const additionalFamily = + currentItemFontFamily !== undefined && needsLoading(currentItemFontFamily) + ? currentItemFontFamily + : undefined; + + let shouldLoadFonts = additionalFamily !== undefined; + + if (!shouldLoadFonts && elements) { + // asked once per family rather than per element - this runs on every + // update, and a family can hold over a hundred faces + const families = new Set(); + for (const element of elements) { + if (isTextElement(element) && isCustomFontFamily(element.fontFamily)) { + families.add(element.fontFamily); + } + } + // unlike built-ins, custom families aren't lazily loadable by the + // browser until resolved + for (const family of families) { + if (needsLoading(family)) { + shouldLoadFonts = true; + break; + } + } + } + + if (shouldLoadFonts) { + if (additionalFamily !== undefined) { + // accumulated, so the next (possibly leading-edge) pass picks it up + this.pendingSceneFontFamilies.add(additionalFamily); + } + this.loadUpdatedSceneFontsThrottled(); + } + }; + + /** + * Why the text, measured right now, comes out in the fallback font's + * geometry, if it does: nothing of its custom `family` is in yet (neither + * its metrics nor a face), or only the `glyphs` this text needs aren't - a + * family arrives one face at a time, i.e. per `unicode-range` subset. + */ + private getPendingFont = ( + element: ExcalidrawTextElement, + ): "family" | "glyphs" | null => { + const family = element.fontFamily; + if (!isCustomFontFamily(family)) { + return null; + } + if ( + !isFontMetadataAvailable(family) || + !this.instance.isFamilyLoaded(family) + ) { + return "family"; + } + return this.instance.isTextLoaded(element) ? null : "glyphs"; + }; + + /** + * For text this session has just measured (created, edited, pasted as + * text, switched to a family) while its custom font was still on its way: + * once the font is in, measure again - and converge the line height on the + * family's, where the text got its line height before the family was in + * (so not for `keepLineHeight`: text which had one already). + * + * This is the only way a font load changes an element - text which was in + * the document already is never rewritten (see `Fonts.onLoaded`). + */ + public repairTextOnFontLoad = ( + elements: readonly ExcalidrawElement[], + { keepLineHeight = false }: { keepLineHeight?: boolean } = {}, + ) => { + const pending = new Map< + ExcalidrawElement["id"], + { fontFamily: FontFamily; shouldReconcileLineHeight: boolean } + >(); + for (const element of elements) { + const pendingFont = isTextElement(element) + ? this.getPendingFont(element) + : null; + if (pendingFont) { + pending.set(element.id, { + fontFamily: (element as ExcalidrawTextElement).fontFamily, + shouldReconcileLineHeight: + !keepLineHeight && pendingFont === "family", + }); + } + } + + if (!pending.size) { + return; + } + + // captured, as a `fontProviders` swap replaces the instance mid-flight + const fonts = this.instance; + Fonts.loadElementsFonts( + elements.filter((element) => pending.has(element.id)), + fonts, + ).then((fontFaces) => { + if (this.app.unmounted) { + return; + } + + fonts.onLoaded(fontFaces); + + fonts.runSceneRepair(() => { + const elementsMap = this.app.scene.getNonDeletedElementsMap(); + for (const [ + elementId, + { fontFamily, shouldReconcileLineHeight }, + ] of pending) { + // re-fetched - the repair may run late, after further edits + const latestElement = elementsMap.get(elementId); + if ( + !latestElement || + !isTextElement(latestElement) || + latestElement.fontFamily !== fontFamily + ) { + continue; + } + + const lineHeight = shouldReconcileLineHeight + ? reconcileLineHeight(latestElement) + : null; + if (lineHeight !== null) { + this.app.scene.mutateElement(latestElement, { lineHeight }); + } + redrawTextBoundingBox( + latestElement, + getContainerElement(latestElement, elementsMap), + this.app.scene, + this.app.renderEnvironment, + ); + } + }); + }); + }; + + /** + * Redraw the bound text of freshly inserted (pasted / library) elements, + * loading their fonts first where that is needed. + * + * Bound text in an unresolved custom family can't be measured yet - it would + * bake in the fallback font's metrics - so its redraw is deferred until the + * load below settles. + */ + public onElementsInserted = ( + insertedElements: readonly ExcalidrawElement[], + ) => { + const deferredBoundTextElements = new Map< + ExcalidrawElement["id"], + FontFamily + >(); + let hasCustomFontText = false; + + for (const element of insertedElements) { + if (!isTextElement(element)) { + continue; + } + + const isDeferred = isCustomFontFamily(element.fontFamily); + hasCustomFontText ||= isDeferred; + + if (!isBoundToContainer(element)) { + continue; + } + + if (isDeferred) { + deferredBoundTextElements.set(element.id, element.fontFamily); + } else { + const container = getContainerElement( + element, + this.app.scene.getElementsMapIncludingDeleted(), + ); + redrawTextBoundingBox( + element, + container, + this.app.scene, + this.app.renderEnvironment, + ); + } + } + + // paste event may not fire FontFace loadingdone event in Safari, hence loading font faces manually + // we also need to resolve & load custom fonts for pasted text elements, + // otherwise they would render with the fallback font indefinitely + if (!isSafari && !hasCustomFontText) { + return; + } + + const fonts = this.instance; + Fonts.loadElementsFonts(insertedElements, fonts).then((fontFaces) => { + // a `fontProviders` swap replaces `this.instance` but keeps the scene, so + // the deferred redraws stay valid - only unmount bails + if (this.app.unmounted) { + return; + } + + fonts.onLoaded(fontFaces); + + if (deferredBoundTextElements.size) { + fonts.runSceneRepair(() => { + const elementsMap = this.app.scene.getNonDeletedElementsMap(); + for (const [elementId, fontFamily] of deferredBoundTextElements) { + const latestElement = elementsMap.get(elementId); + // redraw whether or not the font resolved - the pasted + // dimensions came from the source scene, so leaving them be on + // a failure keeps the text overflowing indefinitely + if ( + !latestElement || + !isTextElement(latestElement) || + !isBoundToContainer(latestElement) || + latestElement.fontFamily !== fontFamily + ) { + continue; + } + + const container = getContainerElement(latestElement, elementsMap); + if (container) { + redrawTextBoundingBox( + latestElement, + container, + this.app.scene, + this.app.renderEnvironment, + ); + } + } + }); + } + }); + }; + + /** + * `onDuplicate` may have swapped a duplicate to a custom family the page + * hasn't loaded yet (mirrors the paste path). TRADE-OFF: load-only - a swap + * to an already-loaded family keeps the original geometry, which the host + * owns (`onDuplicate` JSDoc). + */ + public onElementsDuplicated = ( + insertedElements: readonly ExcalidrawElement[], + ) => { + if ( + !insertedElements.some( + (element) => + isTextElement(element) && isCustomFontFamily(element.fontFamily), + ) + ) { + return; + } + + const fonts = this.instance; + Fonts.loadElementsFonts(insertedElements, fonts).then((fontFaces) => + fonts.onLoaded(fontFaces), + ); + }; + + /** + * `destroy` isn't final: React StrictMode unmounts and remounts the same + * `App` instance, and the editor must not go on with the stand-in `Fonts` + * left behind there - it has none of the hooks keeping font repairs out of + * gestures and undo entries. + */ + public onMount = () => { + if (this.isDestroyed) { + this.isDestroyed = false; + this.instance = this.createFonts(); + } + }; + + private isDestroyed = false; + + public destroy = () => { + this.isDestroyed = true; + this.loadUpdatedSceneFontsThrottled.cancel(); + for (const timer of this.fontBlocks.values()) { + if (timer) { + clearTimeout(timer); + } + } + // cleared rather than settled, so a (StrictMode) remount blocks afresh + // instead of keeping a family blocked with its timer gone + this.fontBlocks.clear(); + // deliberately built without the options bag: this instance only exists so + // lingering references don't crash, and a repair running past unmount must + // not reach back into the store + this.instance = new Fonts( + this.app.scene, + toFontResolvers(() => this.app.props.fontProviders), + undefined, + { ownerDocument: this.app.ownerDocument }, + ); + }; +} diff --git a/packages/excalidraw/components/App.text.ts b/packages/excalidraw/components/App.text.ts index 4611554293..fa6b354afb 100644 --- a/packages/excalidraw/components/App.text.ts +++ b/packages/excalidraw/components/App.text.ts @@ -393,6 +393,14 @@ export class AppText { this.app.store.scheduleCapture(); } + if (!isDeleted) { + // measured just now - in the fallback font, if a font face for what + // got typed is still on its way + this.app.fonts.repairTextOnFontLoad([element], { + keepLineHeight: true, + }); + } + flushSync(() => { this.app.setState({ newElement: null, @@ -1127,6 +1135,8 @@ export class AppText { } else { this.app.insertNewElement(element); } + // typed in the fallback font for now, if its own is still on its way + this.app.fonts.repairTextOnFontLoad([element]); } if (arrowEndpoint && arrowEndpointBinding) { diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx index e75f6bf9b5..89c2718ce6 100644 --- a/packages/excalidraw/components/App.tsx +++ b/packages/excalidraw/components/App.tsx @@ -83,7 +83,6 @@ import { deriveStylesPanelMode, isIOS, isBrave, - isSafari, type EditorInterface, type StylesPanelMode, loadDesktopUIModePreference, @@ -152,11 +151,9 @@ import { updateImageCache as _updateImageCache, getBoundTextElement, getContainerCenter, - getContainerElement, getColorUpdate, getStickyNoteMinSize, isValidTextContainer, - redrawTextBoundingBox, hasBoundingBox, getFrameChildrenInsertionIndex, isCursorInFrame, @@ -345,7 +342,6 @@ import { Hyperlink, } from "../components/hyperlink/Hyperlink"; -import { Fonts } from "../fonts"; import { editorJotaiStore, type WritableAtom } from "../editor-jotai"; import { ImageSceneDataError } from "../errors"; import { @@ -393,6 +389,7 @@ import { AppCursor } from "./App.cursor"; import { AppDrawShape } from "./App.drawshape"; import { AppDuplicate } from "./App.duplicate"; import { AppFlowchart } from "./App.flowchart"; +import { AppFonts } from "./App.fonts"; import { AppModifiers } from "./App.modifiers"; import { AppPan } from "./App.pan"; import { AppViewport, RIGHT_SIDEBAR_WIDTH } from "./App.viewport"; @@ -631,7 +628,7 @@ class App extends React.Component { } public scene: Scene; - public fonts: Fonts; + public fonts: AppFonts; public renderer: Renderer; public visibleElements: readonly NonDeletedExcalidrawElement[]; /** whether the last render had any renderable elements (excludes e.g. the @@ -916,7 +913,12 @@ class App extends React.Component { id: this.id, }; - this.fonts = new Fonts(this.scene, this.ownerDocument); + this.fonts = new AppFonts(this, { + // font reflows must not get absorbed into the next user action's undo + // delta (same pattern as the image-cache error path) + onBeforeSceneMutation: () => + this.store.scheduleAction(CaptureUpdateAction.NEVER), + }); this.history = new History(this.store); this.actionManager.registerAll(actions); @@ -2671,6 +2673,7 @@ class App extends React.Component { pendingFlowchartNodes: this.flowchart.pendingNodes, theme: this.state.theme, + isFontBlocked: this.fonts.isFontBlocked, ...this.getRenderOverrideConfig(), }} /> @@ -2811,6 +2814,7 @@ class App extends React.Component { { name: this.getName(), exportingFrame: opts.exportingFrame, + fontResolvers: this.fonts.instance.fontResolvers, renderEnvironment: this.renderEnvironment, }, ) @@ -3160,6 +3164,12 @@ class App extends React.Component { didUpdate = true; } + if (actionResult.loadFonts) { + this.fonts.refreshSceneFonts( + actionResult.appState?.currentItemFontFamily, + ); + } + if (actionResult.files) { this.addMissingFiles(actionResult.files, actionResult.replaceFiles); this.addNewImagesToImageCache(); @@ -3722,16 +3732,8 @@ class App extends React.Component { // can be loaded fresh this.clearImageShapeCache(); - // manually loading the font faces seems faster even in browsers that do - // fire the loadingdone event. Prewarming the default font family, so that - // the first text element is not rendered with a fallback font. - // NOTE: reading from `restoredAppState` instead of `this.state`, as the - // `syncActionResult` above sets the state asynchronously - this.fonts - .loadSceneFonts(restoredAppState.currentItemFontFamily) - .then((fontFaces) => { - this.fonts.onLoaded(fontFaces); - }); + // manually loading the font faces seems faster even in browsers that do fire the loadingdone event + this.fonts.refreshSceneFonts(restoredAppState.currentItemFontFamily); if (isElementLink(this.ownerWindow.location.href)) { this.viewport.setViewport({ @@ -3823,6 +3825,7 @@ class App extends React.Component { public async componentDidMount() { this.unmounted = false; + this.fonts.onMount(); this.api = this.createExcalidrawAPI(); this.host.sync(); @@ -3858,7 +3861,7 @@ class App extends React.Component { }, fonts: { configurable: true, - value: this.fonts, + get: () => this.fonts.instance, }, }); } @@ -3946,7 +3949,7 @@ class App extends React.Component { this.renderer.destroy(this.canvas); this.scene.destroy(); this.scene = new Scene(); - this.fonts = new Fonts(this.scene, this.ownerDocument); + this.fonts.destroy(); this.renderer = new Renderer(this.scene); this.files = {}; this.imageCache.clear(); @@ -4037,14 +4040,10 @@ class App extends React.Component { passive: false, }, ), // #3553 - // rerender text elements on font load to fix #637 && #1553 addEventListener( this.ownerDocument.fonts, "loadingdone", - (event) => { - const fontFaces = (event as FontFaceSetLoadEvent).fontfaces; - this.fonts.onLoaded(fontFaces); - }, + this.fonts.onDocumentFontsLoaded, { passive: false }, ), addEventListener( @@ -4314,6 +4313,8 @@ class App extends React.Component { return; } + this.fonts.onPropsUpdated(prevProps); + // must be updated *before* state change listeners are triggered below if (!this._initialized && !this.state.isLoading) { this._initialized = true; @@ -4509,6 +4510,8 @@ class App extends React.Component { this.store.commit(elementsMap, this.state); + this.fonts.onStateUpdated(prevState); + // Do not notify consumers if we're still loading the scene. Among other // potential issues, this fixes a case where the tab isn't focused during // init, which would trigger onChange with empty elements, which would then @@ -4668,29 +4671,7 @@ class App extends React.Component { this.scene.replaceAllElements(nextElements); - duplicatedElements.forEach((newElement) => { - if (isTextElement(newElement) && isBoundToContainer(newElement)) { - const container = getContainerElement( - newElement, - this.scene.getElementsMapIncludingDeleted(), - ); - redrawTextBoundingBox( - newElement, - container, - this.scene, - this.renderEnvironment, - ); - } - }); - - // paste event may not fire FontFace loadingdone event in Safari, hence loading font faces manually - if (isSafari) { - Fonts.loadElementsFonts(duplicatedElements, this.ownerDocument).then( - (fontFaces) => { - this.fonts.onLoaded(fontFaces); - }, - ); - } + this.fonts.onElementsInserted(duplicatedElements); if (opts.files) { this.addMissingFiles(opts.files); @@ -4963,6 +4944,9 @@ class App extends React.Component { return { addedFiles }; }; + /** + * Update the scene with new elements, appState or collaborators. + */ public updateScene = withBatchedUpdates( (sceneData: { elements?: SceneData["elements"]; @@ -5007,6 +4991,11 @@ class App extends React.Component { this.scene.replaceAllElements(elements); } + this.fonts.onSceneUpdated( + elements, + appState as Pick | null, + ); + if (collaborators) { this.laserTrails.updateCollabTrails(collaborators); this.setState({ collaborators }); @@ -11035,6 +11024,8 @@ class App extends React.Component { isLoading: false, }, replaceFiles: true, + // a dropped scene's custom fonts are resolved by no one else + loadFonts: true, captureUpdate: CaptureUpdateAction.IMMEDIATELY, }); return true; diff --git a/packages/excalidraw/components/FontPicker/FontPicker.scss b/packages/excalidraw/components/FontPicker/FontPicker.scss index 1f182e0bc4..dd6f4dbcf8 100644 --- a/packages/excalidraw/components/FontPicker/FontPicker.scss +++ b/packages/excalidraw/components/FontPicker/FontPicker.scss @@ -18,6 +18,58 @@ } } + .FontPicker__font--failed, + .FontPicker__font--loading { + background: var(--color-danger-background); + + .dropdown-menu-item__text { + color: var(--color-danger); + } + } + + .FontPicker__font--unsupported { + cursor: not-allowed; + opacity: 0.5; + } + + // The list can get long ("Browse more fonts"). Every font which registers or + // arrives would lay all of it out again - this lets the browser skip the + // rows out of view. + .dropdown-menu.fonts .dropdown-menu-item { + content-visibility: auto; + contain-intrinsic-size: auto 2rem; + } + + .FontPicker__more-results { + padding: 0.25rem 0.5rem; + font-size: 0.75rem; + color: var(--color-gray-50); + } + + .FontPicker__retry-icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.5rem; + height: 1.5rem; + color: var(--color-danger); + + svg { + width: 1rem; + height: 1rem; + } + + &--loading svg { + animation: FontPicker-retry-spin 0.8s linear infinite; + } + } + + @keyframes FontPicker-retry-spin { + to { + transform: rotate(360deg); + } + } + .FontPicker__top-picks-slots { display: flex; // follow the .buttonList spacing @@ -36,9 +88,110 @@ line-height: 1; } + // a family's own-script sample standing in for its provider's icon, in the + // box an icon takes + .FontPicker__glyph-icon { + display: flex; + align-items: center; + justify-content: center; + width: 1rem; + height: 1rem; + font-size: 1rem; + line-height: 1; + } + .FontPicker__tip { margin-top: 0.5rem; } + + .FontPicker__tip-icon { + display: inline-flex; + margin-right: 0.25rem; + // sits on the text's line, without making it taller + vertical-align: -0.2em; + + svg { + width: 1.2em; + height: 1.2em; + } + } + + // anchor for the favorites drop zone, which covers the search for a drag + .FontPicker__search { + position: relative; + } + + .FontPicker__favorites-drop-zone { + position: absolute; + inset: 0; + // above the search's own icon + z-index: 1; + display: flex; + align-items: center; + justify-content: center; + border-radius: 6px; + background: var(--popup-bg-color); + font-size: 0.75rem; + color: var(--color-primary); + transition: background-color 0.14s ease; + + // the outline hugs the zone, rather than overhang it as on the strip + .top-picks-dnd__outline { + top: 0; + left: 0; + width: 100%; + height: 100%; + } + + &--over { + background: var(--color-surface-primary-container); + } + + &--remove { + color: var(--color-danger); + + .top-picks-dnd__outline rect { + stroke: var(--color-danger); + } + + &.FontPicker__favorites-drop-zone--over { + background: var(--color-danger-icon-background); + color: var(--color-danger-icon-color); + } + } + } + + // closes the available fonts once there are no more to load + .FontPicker__search-for-more { + margin-top: 0.25rem; + padding: 0.25rem 0.5rem; + font-size: 0.75rem; + text-align: center; + color: var(--color-gray-50); + } + + // "Browse more fonts", closing the available ones + .FontPicker__load-more { + display: block; + margin: 0.25rem auto 0; + padding: 0.25rem 0.5rem; + border: 0; + border-radius: var(--border-radius-md); + background: none; + font: inherit; + font-size: 0.75rem; + color: var(--color-primary); + cursor: pointer; + + &:hover:not(:disabled) { + text-decoration: underline; + } + + &:disabled { + color: var(--color-gray-50); + cursor: default; + } + } } // drag & drop ghost content (see TopPicksDnD.scss) — outside the .excalidraw diff --git a/packages/excalidraw/components/FontPicker/FontPicker.test.tsx b/packages/excalidraw/components/FontPicker/FontPicker.test.tsx index 0801f1b8e5..310088c41c 100644 --- a/packages/excalidraw/components/FontPicker/FontPicker.test.tsx +++ b/packages/excalidraw/components/FontPicker/FontPicker.test.tsx @@ -1,21 +1,100 @@ -import { FONT_FAMILY, KEYS } from "@excalidraw/common"; +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import React from "react"; -import { Excalidraw } from "../.."; +import { FONT_FAMILY, KEYS } from "@excalidraw/common"; +import { + CaptureUpdateAction, + Scene, + updateStickyNoteLayout, +} from "@excalidraw/element"; + +import type { FontMetadata } from "@excalidraw/common"; +import type { + ExcalidrawElement, + ExcalidrawTextElement, +} from "@excalidraw/element/types"; + +import { Excalidraw } from "../../index"; +import { Fonts } from "../../fonts"; import { API } from "../../tests/helpers/api"; -import { Keyboard } from "../../tests/helpers/ui"; -import { act, fireEvent, render, waitFor } from "../../tests/test-utils"; +import { muteExpectedFontErrors } from "../../tests/helpers/mocks"; +import { Keyboard, Pointer } from "../../tests/helpers/ui"; +import { act, cleanup, render } from "../../tests/test-utils"; + +import type { FontResolver } from "../../fonts"; +import type { ExcalidrawProps, FontProvider } from "../../types"; + +const metadata: FontMetadata = { + metrics: { + unitsPerEm: 1000, + ascender: 800, + descender: -200, + lineHeight: 2, + }, +}; + +const fontFaces = [{ uri: "https://example.com/font.woff2" }] as const; + +const createDeferredResolver = () => { + let resolve!: (font: Awaited>) => void; + const resolver: FontResolver = vi.fn( + () => + new Promise>>((resolvePromise) => { + resolve = resolvePromise; + }), + ); + + return { + resolver, + resolve: () => resolve({ fontFaces, metadata }), + }; +}; + +const mockVisibleIntersections = () => { + const originalIntersectionObserver = global.IntersectionObserver; + global.IntersectionObserver = class IntersectionObserver { + constructor(private readonly callback: IntersectionObserverCallback) {} + + observe(target: Element) { + this.callback( + [{ isIntersecting: true, target } as IntersectionObserverEntry], + this as unknown as globalThis.IntersectionObserver, + ); + } + + unobserve() {} + disconnect() {} + } as unknown as typeof IntersectionObserver; + + return () => { + global.IntersectionObserver = originalIntersectionObserver; + }; +}; const { h } = window; -(global as any).ResizeObserver = - (global as any).ResizeObserver || - class ResizeObserver { - observe() {} - unobserve() {} - disconnect() {} - }; - describe("FontPicker", () => { + let mutedConsoleError: ReturnType; + + afterEach(() => { + cleanup(); + mutedConsoleError.mockRestore(); + }); + + beforeEach(() => { + // several tests below reject on purpose - keep the expected log out of the + // test output + mutedConsoleError = muteExpectedFontErrors(); + + (global as any).ResizeObserver = + (global as any).ResizeObserver || + class ResizeObserver { + observe() {} + unobserve() {} + disconnect() {} + }; + }); + it("should be able to open font picker", async () => { const { queryByTestId } = await render( , @@ -32,6 +111,2019 @@ describe("FontPicker", () => { }); }); + it("only reacts to provider key changes, not resolver identity", async () => { + // per the `FontProviders` contract a provider key always denotes the same + // font source, so an inline (per-render) `fontProviders` object must not + // churn the fonts instance or reload scene fonts + const providers = (extraKey?: string) => ({ + "test.provider": { + icon: , + resolve: vi.fn(), + availableFonts: [], + }, + ...(extraKey + ? { + [extraKey]: { + icon: , + resolve: vi.fn(), + availableFonts: [], + }, + } + : null), + }); + + const { rerender } = await render( + , + ); + const fonts = window.h.app.fonts.instance; + + // fresh object, same keys - contractually interchangeable + rerender(); + expect(window.h.app.fonts.instance).toBe(fonts); + + // an added key is the one realistic change - swap + rerender(); + await waitFor(() => expect(window.h.app.fonts.instance).not.toBe(fonts)); + }); + + it("does not expose custom fonts cached by another editor", async () => { + const fonts = new Fonts(new Scene(), { + "test.hidden": vi.fn().mockResolvedValue({ fontFaces, metadata }), + }); + await fonts.registerCustomFamily("test.hidden:Global"); + + const { queryByTestId } = await render( + , + ); + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + + expect(screen.queryByText("Global")).toBeNull(); + }); + + it("creates no IntersectionObserver without font providers", async () => { + const constructed = vi.fn(); + const originalIntersectionObserver = global.IntersectionObserver; + global.IntersectionObserver = class { + constructor() { + constructed(); + } + observe() {} + unobserve() {} + disconnect() {} + } as unknown as typeof IntersectionObserver; + + try { + const { queryByTestId } = await render( + , + ); + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + await screen.findByText("Excalifont"); + + expect(constructed).not.toHaveBeenCalled(); + } finally { + global.IntersectionObserver = originalIntersectionObserver; + } + }); + + it("reverts a hover preview as a newer version, so collab syncs it", async () => { + const { queryByTestId } = await render(); + const [container, boundText] = API.createTextContainer(); + const text = boundText as ExcalidrawTextElement; + API.setElements([container, text]); + API.setSelectedElements([container]); + const initialFontFamily = API.getElement(text).fontFamily; + + const trigger = queryByTestId("font-family-show-fonts")!; + fireEvent.click(trigger); + + let textVersion = API.getElement(text).version; + const containerVersion = API.getElement(container).version; + for (const fontName of ["Nunito", "Comic Shanns"] as const) { + fireEvent.mouseMove( + (await screen.findByText(fontName)).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY[fontName]), + ); + expect(API.getElement(text).version).toBeGreaterThan(textVersion); + textVersion = API.getElement(text).version; + } + + fireEvent.click(trigger); + + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(initialFontFamily), + ); + expect(API.getElement(text).version).toBeGreaterThan(textVersion); + // the previews never changed its size, so there was nothing to restore + expect(API.getElement(container).version).toBe(containerVersion); + }); + + it("leaves the elements alone when the picker closes without a preview", async () => { + const { queryByTestId } = await render(); + const text = API.createElement({ type: "text", text: "Hello" }); + API.setElements([text]); + API.setSelectedElements([text]); + + const trigger = queryByTestId("font-family-show-fonts")!; + fireEvent.click(trigger); + await screen.findByText("Comic Shanns"); + + // i.e. by a collaborator, while the picker is open + API.updateElement(API.getElement(text) as ExcalidrawTextElement, { + originalText: "Hello there", + text: "Hello there", + x: 100, + }); + const { version } = API.getElement(text); + + fireEvent.click(trigger); + await waitFor(() => expect(h.state.openPopup).toBe(null)); + + expect(API.getElement(text)).toMatchObject({ + originalText: "Hello there", + x: 100, + version, + }); + }); + + it("takes a preview back to where it started, not to where the picker opened", async () => { + const { queryByTestId } = await render(); + const text = API.createElement({ type: "text", text: "Hello" }); + // selected along with the text, which is all it has to do with a font + const rectangle = API.createElement({ type: "rectangle", x: 200 }); + API.setElements([text, rectangle]); + API.setSelectedElements([text, rectangle]); + const initialFontFamily = API.getElement(text).fontFamily; + + const trigger = queryByTestId("font-family-show-fonts")!; + fireEvent.click(trigger); + const comicShanns = (await screen.findByText("Comic Shanns")).closest( + "button", + )!; + + // i.e. by a collaborator, with the picker open and nothing hovered yet + API.updateElement(API.getElement(text), { y: 300 }); + + fireEvent.mouseMove(comicShanns); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY["Comic Shanns"]), + ); + + // and during the preview + API.updateElement(API.getElement(rectangle), { x: 350 }); + + fireEvent.click(trigger); + + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(initialFontFamily), + ); + expect(API.getElement(text).y).toBe(300); + expect(API.getElement(rectangle).x).toBe(350); + }); + + it("restores the font size a preview refitted on a sticky note", async () => { + const { queryByTestId } = await render(); + const note = API.createElement({ + type: "stickynote", + id: "note", + width: 250, + height: 250, + baseHeight: 250, + boundElements: [{ type: "text", id: "label" }], + }); + const label = API.createElement({ + type: "text", + id: "label", + containerId: note.id, + text: "one\ntwo\nthree\nfour\nfive\nsix\nseven", + fontSize: 28, + textAlign: "center", + verticalAlign: "middle", + }); + API.setElements([note, label]); + act(() => { + updateStickyNoteLayout(API.getElement(note), h.app.scene, { + renderEnvironment: h.app.renderEnvironment, + }); + }); + API.setSelectedElements([API.getElement(note)]); + const { fontFamily, fontSize } = API.getElement(label); + + const trigger = queryByTestId("font-family-show-fonts")!; + fireEvent.click(trigger); + fireEvent.mouseMove( + (await screen.findByText("Lilita One")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(label).fontFamily).toBe(FONT_FAMILY["Lilita One"]), + ); + expect(API.getElement(label).fontSize).not.toBe(fontSize); + + fireEvent.click(trigger); + + await waitFor(() => + expect(API.getElement(label).fontFamily).toBe(fontFamily), + ); + expect(API.getElement(label).fontSize).toBe(fontSize); + }); + + it("lets a font be undone which was picked after a font repair landed on its preview", async () => { + const { queryByTestId } = await render( + , + ); + const text = API.createElement({ type: "text", text: "Hello" }); + const other = API.createElement({ type: "text", text: "other", y: 200 }); + API.updateScene({ + elements: [text, other], + captureUpdate: CaptureUpdateAction.IMMEDIATELY, + }); + API.setSelectedElements([text]); + const initialFontFamily = API.getElement(text).fontFamily; + const undoStackLength = API.getUndoStack().length; + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + const comicShanns = (await screen.findByText("Comic Shanns")).closest( + "button", + )!; + fireEvent.mouseMove(comicShanns); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY["Comic Shanns"]), + ); + + // Some font arrives during the hover, and text measured before it gets + // repaired. Committed right away (never captured), the repair would take + // the previewed font into the snapshot with it + act(() => { + h.app.fonts.instance.runSceneRepair(() => { + h.app.scene.mutateElement( + h.app.scene.getElement(other.id) as ExcalidrawTextElement, + { lineHeight: 2 as ExcalidrawTextElement["lineHeight"] }, + ); + }); + }); + act(() => { + h.app.scene.triggerUpdate(); + }); + expect( + (API.getElement(other) as ExcalidrawTextElement).lineHeight, + ).not.toBe(2); + + fireEvent.click(comicShanns); + await waitFor(() => expect(h.state.openPopup).toBe(null)); + expect(API.getUndoStack().length).toBe(undoStackLength + 1); + // the repair runs once the preview is over + await waitFor(() => + expect((API.getElement(other) as ExcalidrawTextElement).lineHeight).toBe( + 2, + ), + ); + + Keyboard.undo(); + expect(API.getElement(text).fontFamily).toBe(initialFontFamily); + }); + + it("takes back the font alone when the text was edited during the preview", async () => { + const { queryByTestId } = await render(); + const text = API.createElement({ type: "text", text: "Hello" }); + API.setElements([text]); + API.setSelectedElements([text]); + const initialFontFamily = API.getElement(text).fontFamily; + + const trigger = queryByTestId("font-family-show-fonts")!; + fireEvent.click(trigger); + fireEvent.mouseMove( + (await screen.findByText("Comic Shanns")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY["Comic Shanns"]), + ); + + // i.e. by a collaborator + API.updateElement(API.getElement(text) as ExcalidrawTextElement, { + originalText: "Hello there", + text: "Hello there", + strokeColor: "#ff0000", + }); + + fireEvent.click(trigger); + + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(initialFontFamily), + ); + expect(API.getElement(text)).toMatchObject({ + originalText: "Hello there", + text: "Hello there", + strokeColor: "#ff0000", + }); + }); + + it("reverts a hover preview when clicking outside the picker", async () => { + const { queryByTestId } = await render(); + const text = API.createElement({ type: "text", text: "Hello" }); + API.setElements([text]); + API.setSelectedElements([text]); + const initialFontFamily = API.getElement(text).fontFamily; + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.mouseMove( + (await screen.findByText("Comic Shanns")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY["Comic Shanns"]), + ); + + // deselects, unmounting the panel + new Pointer("mouse").clickAt(1000, 1000); + + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(initialFontFamily), + ); + expect(h.state.currentHoveredFontFamily).toBeNull(); + }); + + it("doesn't restore an element deleted during a hover preview", async () => { + const { queryByTestId } = await render(); + const text = API.createElement({ type: "text", text: "Hello" }); + API.setElements([text]); + API.setSelectedElements([text]); + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.mouseMove( + (await screen.findByText("Comic Shanns")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY["Comic Shanns"]), + ); + + // i.e. by a collaborator + API.updateElement(API.getElement(text) as ExcalidrawTextElement, { + isDeleted: true, + }); + + await waitFor(() => expect(h.state.currentHoveredFontFamily).toBeNull()); + expect(API.getElement(text).isDeleted).toBe(true); + }); + + it("reverts a hover preview after a close request which keeps the popup open", async () => { + const { queryByTestId } = await render(); + const text = API.createElement({ type: "text", text: "Hello" }); + API.setElements([text]); + API.setSelectedElements([text]); + const initialFontFamily = API.getElement(text).fontFamily; + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + const comicShanns = (await screen.findByText("Comic Shanns")).closest( + "button", + )!; + + // the focus moving out asks the popup to close, which it doesn't - as do + // compact mode refocusing the text editor, and StrictMode + act(() => { + document.querySelector(".excalidraw-container")!.focus(); + }); + expect(h.state.openPopup).toBe("fontFamily"); + + fireEvent.mouseMove(comicShanns); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY["Comic Shanns"]), + ); + + // closed by the app, keeping the selection (and the panel) + act(() => h.setState({ openPopup: null })); + + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(initialFontFamily), + ); + expect(h.state.currentHoveredFontFamily).toBeNull(); + }); + + it("closes on Escape, from the search too, taking a preview back", async () => { + const { queryByTestId } = await render(); + const text = API.createElement({ type: "text", text: "Hello" }); + API.setElements([text]); + API.setSelectedElements([text]); + const initialFontFamily = API.getElement(text).fontFamily; + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.mouseMove( + (await screen.findByText("Comic Shanns")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY["Comic Shanns"]), + ); + + fireEvent.keyDown( + document.querySelector(".properties-content .QuickSearch__input")!, + { key: KEYS.ESCAPE }, + ); + + await waitFor(() => expect(h.state.openPopup).toBe(null)); + expect(document.querySelector(".dropdown-menu.fonts")).toBe(null); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(initialFontFamily), + ); + // the text is still selected - Escape went to the picker alone + expect(h.state.selectedElementIds[text.id]).toBe(true); + }); + + it("lists a family by its preview text in place of the provider's icon", async () => { + let resolvePreviewText!: (text: string) => void; + const { queryByTestId } = await render( + , + resolve: createDeferredResolver().resolver, + availableFonts: ["Latin Row", "Kana Row"], + getPreviewText: (name) => + name === "Kana Row" + ? new Promise((resolve) => (resolvePreviewText = resolve)) + : "", + }, + }} + />, + ); + Keyboard.keyPress(KEYS.T); + act(() => { + queryByTestId("font-family-show-fonts")!.click(); + }); + + const getIcon = async (label: string) => + (await screen.findByText(label)) + .closest("button")! + .querySelector(".dropdown-menu-item__icon")!; + const hasProviderIcon = (icon: Element) => + !!icon.querySelector('[data-testid="provider-icon"]'); + + expect(hasProviderIcon(await getIcon("Kana Row"))).toBe(true); + await act(async () => resolvePreviewText("あ")); + + const kanaIcon = await getIcon("Kana Row"); + expect(kanaIcon.textContent).toBe("あ"); + expect(hasProviderIcon(kanaIcon)).toBe(false); + expect(hasProviderIcon(await getIcon("Latin Row"))).toBe(true); + }); + + it("lists a family by the icon our own fonts of its kind have", async () => { + const { queryByTestId } = await render( + + name === "Mono Row" ? Promise.resolve("code") : undefined, + }, + }} + />, + ); + Keyboard.keyPress(KEYS.T); + act(() => { + queryByTestId("font-family-show-fonts")!.click(); + }); + + // the icon's shape - its markup differs in the order of the attributes + const getIcon = async (label: string) => + Array.from( + (await screen.findByText(label)) + .closest("button")! + .querySelectorAll(".dropdown-menu-item__icon path"), + (path) => path.getAttribute("d"), + ).join(" "); + + await waitFor(async () => + expect(await getIcon("Mono Row")).toBe(await getIcon("Comic Shanns")), + ); + // no kind, and no icon of the provider's: a normal font's + expect(await getIcon("Plain Row")).toBe(await getIcon("Nunito")); + expect(await getIcon("Plain Row")).not.toBe(await getIcon("Mono Row")); + }); + + it("registers a visible available font before previewing it", async () => { + const restoreIntersectionObserver = mockVisibleIntersections(); + const deferred = createDeferredResolver(); + try { + const { queryByTestId } = await render( + , + resolve: deferred.resolver, + availableFonts: ["Kings"], + }, + }} + />, + ); + const text = API.createElement({ type: "text", text: "preview" }); + API.setElements([text]); + API.setSelectedElements([text]); + const initialFontFamily = text.fontFamily; + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + const fontButton = (await screen.findByText("Kings")).closest("button")!; + await waitFor(() => expect(deferred.resolver).toHaveBeenCalledTimes(1)); + fireEvent.mouseMove(fontButton); + expect(API.getElement(text).fontFamily).toBe(initialFontFamily); + + await act(async () => deferred.resolve()); + fireEvent.mouseMove( + (await screen.findByText("Kings")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe("test.provider:Kings"), + ); + } finally { + restoreIntersectionObserver(); + } + }); + + it("shows the retry state when registering a visible font fails", async () => { + const restoreIntersectionObserver = mockVisibleIntersections(); + const resolve = vi.fn().mockRejectedValue(new Error("failed")); + try { + const { queryByTestId } = await render( + , + resolve, + availableFonts: ["BrokenVisible"], + }, + }} + />, + ); + + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + await screen.findByText("BrokenVisible"); + + await waitFor(() => expect(resolve).toHaveBeenCalledTimes(1)); + await waitFor(() => + expect(screen.getByText("BrokenVisible").closest("button")).toHaveClass( + "FontPicker__font--failed", + ), + ); + expect( + screen + .getByText("BrokenVisible") + .closest("button") + ?.querySelector(".FontPicker__retry-icon"), + ).not.toBeNull(); + } finally { + restoreIntersectionObserver(); + } + }); + + it("ignores a resolution after the search query changes", async () => { + const deferred = createDeferredResolver(); + const { queryByTestId } = await render( + , + resolve: deferred.resolver, + availableFonts: ["SlowQuery"], + }, + }} + />, + ); + + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + const input = document.querySelector( + ".properties-content .QuickSearch__input", + )!; + + fireEvent.click((await screen.findByText("SlowQuery")).closest("button")!); + await waitFor(() => expect(deferred.resolver).toHaveBeenCalledTimes(1)); + + fireEvent.input(input, { target: { value: "New" } }); + await act(async () => deferred.resolve()); + + expect(input.value).toBe("New"); + expect(window.h.state.currentItemFontFamily).not.toBe( + "test.provider:SlowQuery", + ); + }); + + it("ignores a resolution after the picker closes", async () => { + const deferred = createDeferredResolver(); + const { queryByTestId } = await render( + , + resolve: deferred.resolver, + availableFonts: ["SlowClose"], + }, + }} + />, + ); + + Keyboard.keyPress(KEYS.T); + const fontPickerTrigger = queryByTestId("font-family-show-fonts")!; + fireEvent.click(fontPickerTrigger); + + fireEvent.click((await screen.findByText("SlowClose")).closest("button")!); + await waitFor(() => expect(deferred.resolver).toHaveBeenCalledTimes(1)); + + fireEvent.click(fontPickerTrigger); + await waitFor(() => + expect( + document.querySelector(".properties-content .QuickSearch__input"), + ).toBeNull(), + ); + await act(async () => deferred.resolve()); + expect(window.h.state.currentItemFontFamily).not.toBe( + "test.provider:SlowClose", + ); + }); + + it("moves keyboard navigation past a failed font", async () => { + const resolver = vi + .fn() + .mockImplementation(async (family) => { + if (family === "Broken") { + throw new Error("unavailable"); + } + return { fontFaces, metadata }; + }); + const { queryByTestId } = await render( + , + resolve: resolver, + availableFonts: ["Alpha", "Broken", "Charlie"], + }, + }} + />, + ); + + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.click((await screen.findByText("Broken")).closest("button")!); + await waitFor(() => expect(resolver).toHaveBeenCalledWith("Broken")); + + const failedButton = document.querySelector( + 'button[value="test.provider:Broken"]', + )!; + fireEvent.mouseMove(failedButton); + await waitFor(() => + expect( + document.querySelector('button[value="test.provider:Broken"]'), + ).toHaveClass("dropdown-menu-item--hovered"), + ); + + const buttons = Array.from( + document.querySelectorAll( + ".properties-content .dropdown-menu.fonts button[value]", + ), + ); + const failedIndex = buttons.findIndex( + (button) => button.value === "test.provider:Broken", + ); + const nextButton = buttons[(failedIndex + 1) % buttons.length]; + fireEvent.keyDown(document.querySelector(".properties-content")!, { + key: KEYS.ARROW_DOWN, + }); + + await waitFor(() => + expect( + document.querySelector(`button[value="${nextButton.value}"]`), + ).toHaveClass("dropdown-menu-item--hovered"), + ); + }); + + it("preserves recalculated geometry after a keep-open selection", async () => { + const resolver = vi + .fn() + .mockRejectedValueOnce(new Error("temporary")) + .mockResolvedValue({ fontFaces, metadata }); + const { queryByTestId } = await render( + , + resolve: resolver, + availableFonts: ["Tall"], + }, + }} + />, + ); + const text = API.createElement({ + type: "text", + text: "geometry", + width: 100, + height: 20, + }); + API.setElements([text]); + API.setSelectedElements([text]); + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.click((await screen.findByText("Tall")).closest("button")!); + await waitFor(() => expect(resolver).toHaveBeenCalledTimes(1)); + fireEvent.click((await screen.findByText("Tall")).closest("button")!); + + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe("test.provider:Tall"), + ); + const selectedText = API.getElement(text); + const selectedGeometry = { + width: selectedText.width, + height: selectedText.height, + }; + expect(selectedGeometry.height).not.toBe(20); + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + await waitFor(() => + expect( + document.querySelector(".properties-content .QuickSearch__input"), + ).toBeNull(), + ); + + expect(API.getElement(text).fontFamily).toBe("test.provider:Tall"); + expect(API.getElement(text).width).toBe(selectedGeometry.width); + expect(API.getElement(text).height).toBe(selectedGeometry.height); + }); + + it("repairs a font change measured while `document.fonts.check` lied", async () => { + const { queryByTestId } = await render(); + const text = API.createElement({ type: "text", text: "Hello" }); + API.setElements([text]); + API.setSelectedElements([text]); + + // Chrome's `check()` passes for any family matching an installed system + // font, with its web faces unloaded - the synchronous redraw measured the + // fallback, so the faces `load()` then brings in must trigger a repair + const check = vi.spyOn(document.fonts, "check").mockReturnValue(true); + const fontFace = new FontFace("Nunito", "url(nunito.woff2)"); + const load = vi.spyOn(document.fonts, "load").mockResolvedValue([fontFace]); + const onLoaded = vi.spyOn(window.h.app.fonts.instance, "onLoaded"); + + try { + fireEvent.click(queryByTestId("font-family-normal")!); + + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY.Nunito); + expect(load).toHaveBeenCalledWith( + expect.stringContaining("Nunito"), + expect.anything(), + ); + await waitFor(() => expect(onLoaded).toHaveBeenCalledWith([fontFace])); + } finally { + check.mockRestore(); + load.mockRestore(); + onLoaded.mockRestore(); + } + }); + + it("preserves geometry recalculated after a deferred font face load", async () => { + // font faces of a freshly resolved family are added but not yet loaded, so + // the redraw is deferred until `document.fonts.load` settles - only then is + // the cache holding the pre-redraw (fallback font) geometry + const check = vi.spyOn(document.fonts, "check").mockReturnValue(false); + const load = vi.spyOn(document.fonts, "load").mockResolvedValue([]); + + try { + const resolver = vi + .fn() + .mockRejectedValueOnce(new Error("temporary")) + .mockResolvedValue({ fontFaces, metadata }); + const { queryByTestId } = await render( + , + resolve: resolver, + availableFonts: ["Deferred"], + }, + }} + />, + ); + const text = API.createElement({ + type: "text", + text: "geometry", + width: 100, + height: 20, + }); + API.setElements([text]); + API.setSelectedElements([text]); + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.click((await screen.findByText("Deferred")).closest("button")!); + await waitFor(() => expect(resolver).toHaveBeenCalledTimes(1)); + // retry, which keeps the popup open and refreshes the cache + fireEvent.click((await screen.findByText("Deferred")).closest("button")!); + + await waitFor(() => expect(load).toHaveBeenCalled()); + await waitFor(() => expect(API.getElement(text).height).not.toBe(20)); + const redrawn = API.getElement(text); + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + await waitFor(() => + expect( + document.querySelector(".properties-content .QuickSearch__input"), + ).toBeNull(), + ); + + expect(API.getElement(text).fontFamily).toBe("test.provider:Deferred"); + expect(API.getElement(text).width).toBe(redrawn.width); + expect(API.getElement(text).height).toBe(redrawn.height); + } finally { + check.mockRestore(); + load.mockRestore(); + } + }); + + it("drops an in-flight selection when the providers change", async () => { + const check = vi.spyOn(document.fonts, "check").mockReturnValue(false); + const load = vi.spyOn(document.fonts, "load").mockResolvedValue([]); + let resolveSlow!: (font: Awaited>) => void; + const resolver = vi.fn( + () => + new Promise>>((resolve) => { + resolveSlow = resolve; + }), + ); + const providers = (extraKey?: string) => ({ + "test.provider": { + icon: , + resolve: resolver, + availableFonts: ["SwapStale"], + }, + ...(extraKey + ? { + [extraKey]: { + icon: , + resolve: vi.fn(), + availableFonts: [], + }, + } + : null), + }); + + try { + const { rerender, queryByTestId } = await render( + , + ); + const text = API.createElement({ type: "text", text: "swap" }); + API.setElements([text]); + API.setSelectedElements([text]); + const initialFontFamily = text.fontFamily; + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.click( + (await screen.findByText("SwapStale")).closest("button")!, + ); + await waitFor(() => expect(resolver).toHaveBeenCalledTimes(1)); + + // an added provider key swaps the fonts instance mid-resolution + const fontsBefore = window.h.app.fonts.instance; + rerender(); + await waitFor(() => + expect(window.h.app.fonts.instance).not.toBe(fontsBefore), + ); + + // the old instance's resolution settling must not apply its selection + await act(async () => { + resolveSlow({ fontFaces, metadata }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + + expect(API.getElement(text).fontFamily).toBe(initialFontFamily); + } finally { + check.mockRestore(); + load.mockRestore(); + } + }); + + it("refreshes scene groups when a custom family arrives while open", async () => { + const { queryByTestId } = await render( + , + resolve: vi.fn(), + availableFonts: [], + }, + }} + />, + ); + + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + expect(screen.queryByText("CollabArrived")).toBeNull(); + + // a collab-like update: the element lands in the scene and its family + // registers (which announces, refreshing the open picker's groups) + const text = API.createElement({ + type: "text", + text: "x", + fontFamily: "test.provider:CollabArrived", + }); + API.setElements([text]); + act(() => { + Fonts.registerCustomFont("test.provider:CollabArrived", metadata, { + uri: "https://example.com/font.woff2", + }); + }); + + expect(await screen.findByText("CollabArrived")).toBeInTheDocument(); + }); + + it("keeps scene groups free of a hover preview while fonts register", async () => { + const getSceneGroupFonts = () => + Array.from( + Array.from(document.querySelectorAll(".dropdown-menu-group-title")) + .find((title) => title.textContent === "In this scene")! + .parentElement!.querySelectorAll("button"), + ).map((button) => button.textContent); + + const { queryByTestId } = await render( + , + resolve: vi.fn(), + availableFonts: [], + }, + }} + />, + ); + const check = vi.spyOn(document.fonts, "check").mockReturnValue(true); + try { + const text = API.createElement({ + type: "text", + text: "Hello", + fontFamily: FONT_FAMILY.Nunito, + }); + API.setElements([text]); + API.setSelectedElements([text]); + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.mouseMove( + (await screen.findByText("Comic Shanns")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe( + FONT_FAMILY["Comic Shanns"], + ), + ); + + // i.e. a visible row registering its font for the preview + act(() => { + Fonts.registerCustomFont("test.provider:DuringPreview", metadata, { + uri: "https://example.com/font.woff2", + }); + }); + + expect(getSceneGroupFonts()).toEqual(["Nunito"]); + + fireEvent.pointerLeave(document.querySelector(".properties-content")!); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe(FONT_FAMILY.Nunito), + ); + expect(getSceneGroupFonts()).toEqual(["Nunito"]); + } finally { + check.mockRestore(); + } + }); + + it("lists the current default family even when no element uses it", async () => { + // a family searched & selected with nothing on canvas lives in no + // element - reopening the picker must still list it + const { queryByTestId } = await render( + , + resolve: vi.fn(), + availableFonts: [], + }, + }} + />, + ); + + API.setAppState({ currentItemFontFamily: "test.provider:Orphaned" }); + + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + + expect(await screen.findByText("Orphaned")).toBeInTheDocument(); + }); + + it("shows a scene font it doesn't offer by the label its resolver gave", async () => { + const { queryByTestId } = await render( + , + resolve: vi.fn().mockResolvedValue({ + fontFaces, + metadata, + label: "Brand Mono", + }), + availableFonts: [], + }, + }} + />, + ); + + API.setAppState({ currentItemFontFamily: "test.provider:9f8e7d" }); + await act(() => + window.h.app.fonts.instance.registerCustomFamily("test.provider:9f8e7d"), + ); + + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + + expect(await screen.findByText("Brand Mono")).toBeInTheDocument(); + expect(screen.queryByText("9f8e7d")).toBeNull(); + }); + + it("keeps a retried selection committed during a hover preview", async () => { + // the retry click lands while another family is hover-previewed - the + // cache refresh must not consult the not-yet-committed hover state, or + // the later hover-leave reset restores the pre-retry family + const check = vi.spyOn(document.fonts, "check").mockReturnValue(false); + const load = vi.spyOn(document.fonts, "load").mockResolvedValue([]); + + try { + const resolver = vi + .fn() + .mockRejectedValueOnce(new Error("temporary")) + .mockResolvedValue({ fontFaces, metadata }); + const { queryByTestId } = await render( + , + resolve: resolver, + availableFonts: ["StaleHover"], + }, + }} + />, + ); + const text = API.createElement({ type: "text", text: "stale" }); + API.setElements([text]); + API.setSelectedElements([text]); + const initialFontFamily = text.fontFamily; + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.click( + (await screen.findByText("StaleHover")).closest("button")!, + ); + await waitFor(() => expect(resolver).toHaveBeenCalledTimes(1)); + + // hover a registered built-in row, then retry the failed one while the + // hover preview is still live. Re-queried per hover - registration and + // selection regroup the list, detaching previously captured row nodes + const findBuiltinRow = () => + Array.from( + document.querySelectorAll( + ".dropdown-menu.fonts button", + ), + ).find( + (button) => + button.value && + !button.value.includes(":") && + Number(button.value) !== initialFontFamily, + )!; + fireEvent.mouseMove(findBuiltinRow()); + await waitFor(() => + expect(API.getElement(text).fontFamily).not.toBe(initialFontFamily), + ); + + fireEvent.click( + (await screen.findByText("StaleHover")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe( + "test.provider:StaleHover", + ), + ); + + // preview again and leave - the reset must restore the retried family, + // not the pre-retry snapshot + fireEvent.mouseMove(findBuiltinRow()); + await waitFor(() => + expect(API.getElement(text).fontFamily).not.toBe( + "test.provider:StaleHover", + ), + ); + fireEvent.pointerLeave(document.querySelector(".properties-content")!); + + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe( + "test.provider:StaleHover", + ), + ); + } finally { + check.mockRestore(); + load.mockRestore(); + } + }); + + it("lets a newer selection supersede an in-flight resolution", async () => { + const check = vi.spyOn(document.fonts, "check").mockReturnValue(false); + const load = vi.spyOn(document.fonts, "load").mockResolvedValue([]); + let resolveSlow!: (font: Awaited>) => void; + const resolver = vi.fn((familyName) => + familyName === "SupersededSlow" + ? new Promise>>((resolve) => { + resolveSlow = resolve; + }) + : Promise.resolve({ fontFaces, metadata }), + ); + + try { + const { queryByTestId } = await render( + , + resolve: resolver, + availableFonts: ["SupersededSlow", "SupersededFast"], + }, + }} + />, + ); + const text = API.createElement({ type: "text", text: "supersede" }); + API.setElements([text]); + API.setSelectedElements([text]); + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.click( + (await screen.findByText("SupersededSlow")).closest("button")!, + ); + await waitFor(() => + expect(resolver).toHaveBeenCalledWith("SupersededSlow"), + ); + + // a second selection while the first still resolves must win, not be + // swallowed + fireEvent.click( + (await screen.findByText("SupersededFast")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe( + "test.provider:SupersededFast", + ), + ); + + // the superseded resolution settling later cannot override it + await act(async () => { + resolveSlow({ fontFaces, metadata }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(API.getElement(text).fontFamily).toBe( + "test.provider:SupersededFast", + ); + } finally { + check.mockRestore(); + load.mockRestore(); + } + }); + + it("heals geometry when the font load settles during a hover preview", async () => { + // when `document.fonts.load` settles while another family is being + // hover-previewed, both the redraw and the cache refresh are (rightly) + // suppressed - the hover-leave reset then restores pre-load geometry, so + // the deferred refresh must redraw with the loaded faces (see the + // batched-data effect in `actionChangeFontFamily`) + let resolveHoverHealLoad!: (fontFaces: FontFace[]) => void; + const check = vi.spyOn(document.fonts, "check").mockReturnValue(false); + const load = vi + .spyOn(document.fonts, "load") + .mockImplementation((font: string) => + font.includes("hoverheal") + ? new Promise((resolve) => { + resolveHoverHealLoad = resolve; + }) + : Promise.resolve([]), + ); + + try { + const resolver = vi + .fn() + .mockRejectedValueOnce(new Error("temporary")) + .mockResolvedValue({ fontFaces, metadata }); + const { queryByTestId } = await render( + , + resolve: resolver, + availableFonts: ["HoverHeal"], + }, + }} + />, + ); + const text = API.createElement({ + type: "text", + text: "geometry", + width: 100, + height: 20, + }); + API.setElements([text]); + API.setSelectedElements([text]); + + fireEvent.click(queryByTestId("font-family-show-fonts")!); + fireEvent.click( + (await screen.findByText("HoverHeal")).closest("button")!, + ); + await waitFor(() => expect(resolver).toHaveBeenCalledTimes(1)); + // retry - the selection keeps the popup open and kicks off the load + fireEvent.click( + (await screen.findByText("HoverHeal")).closest("button")!, + ); + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe("test.provider:HoverHeal"), + ); + expect(resolveHoverHealLoad).toBeDefined(); + + // preview a built-in family while the load is still pending + const builtinRow = Array.from( + document.querySelectorAll( + ".dropdown-menu.fonts button", + ), + ).find((button) => button.value && !button.value.includes(":"))!; + fireEvent.mouseMove(builtinRow); + await waitFor(() => + expect(API.getElement(text).fontFamily).not.toBe( + "test.provider:HoverHeal", + ), + ); + + // the load settles mid-hover - redraw and refresh both get deferred + await act(async () => { + resolveHoverHealLoad([]); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + + fireEvent.pointerLeave(document.querySelector(".properties-content")!); + + // the leave reset restores the selected family; the deferred refresh + // must recompute its geometry (initial height of 20 was measured + // before the faces loaded) + await waitFor(() => + expect(API.getElement(text).fontFamily).toBe("test.provider:HoverHeal"), + ); + await waitFor(() => expect(API.getElement(text).height).not.toBe(20)); + } finally { + check.mockRestore(); + load.mockRestore(); + } + }); + + describe("provider search", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + const resolve: FontResolver = async () => ({ fontFaces, metadata }); + + const openAndSearch = async ( + providers: Record, + query: string, + elements?: ExcalidrawElement[], + ) => { + const { queryByTestId } = await render( + , + ); + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + const input = document.querySelector( + ".properties-content .QuickSearch__input", + )!; + fireEvent.input(input, { target: { value: query } }); + return input; + }; + + const rowValues = () => + Array.from( + document.querySelectorAll( + ".properties-content .dropdown-menu.fonts button[value]", + ), + (button) => button.value, + ); + + it("lists the first matches, selecting one applies it", async () => { + vi.spyOn(document.fonts, "check").mockReturnValue(false); + vi.spyOn(document.fonts, "load").mockResolvedValue([]); + const names = Array.from({ length: 12 }, (_, i) => `Sans ${i}`); + await openAndSearch( + { + "test.provider": { + icon: , + resolve, + availableFonts: ["Sans 0"], + search: async () => ({ kind: "match", fonts: names }), + }, + }, + "sans", + ); + + expect(await screen.findByText("Search results")).not.toBeNull(); + // "Sans 0" is listed already, so 11 left - 10 shown + expect(rowValues()).toEqual([ + "test.provider:Sans 0", + ...names.slice(1, 11).map((name) => `test.provider:${name}`), + ]); + expect(screen.getByText("+1 more, keep typing to narrow")).not.toBeNull(); + + await act(async () => { + fireEvent.click(screen.getByText("Sans 3").closest("button")!); + }); + + expect(window.h.state.currentItemFontFamily).toBe("test.provider:Sans 3"); + }); + + const pressEnter = () => + act(async () => { + fireEvent.keyDown(document.querySelector(".properties-content")!, { + key: KEYS.ENTER, + }); + }); + + it("suggests only when nothing matches, never on a bare Enter", async () => { + const fuzzyResolve = vi.fn(resolve); + await openAndSearch( + { + "test.fuzzy": { + icon: , + resolve: fuzzyResolve, + availableFonts: [], + search: async () => ({ kind: "suggestion", fonts: ["Roboto"] }), + }, + }, + "rovoto", + ); + + expect(await screen.findByText("Did you mean…")).not.toBeNull(); + expect(rowValues()).toEqual(["test.fuzzy:Roboto"]); + + // Enter with no row highlighted selects nothing + await pressEnter(); + + expect(fuzzyResolve).not.toHaveBeenCalled(); + }); + + it("never tries a typed name as a font of its own", async () => { + // neither for a provider that can't search nor for one whose search + // failed - ids aren't necessarily something a user could type + const plainResolve = vi.fn(resolve); + const brokenResolve = vi.fn(resolve); + vi.spyOn(console, "error").mockImplementation(() => {}); + await openAndSearch( + { + "test.plain": { + icon: , + resolve: plainResolve, + availableFonts: [], + }, + "test.broken": { + icon: , + resolve: brokenResolve, + availableFonts: [], + search: async () => { + throw new Error("offline"); + }, + }, + }, + "Roboto", + ); + + expect(await screen.findByText("No fonts found")).not.toBeNull(); + expect(rowValues()).toEqual([]); + + await pressEnter(); + + expect(plainResolve).not.toHaveBeenCalled(); + expect(brokenResolve).not.toHaveBeenCalled(); + }); + + it("shows a font by its label, and saves it by its id", async () => { + vi.spyOn(document.fonts, "check").mockReturnValue(false); + vi.spyOn(document.fonts, "load").mockResolvedValue([]); + const labelResolve = vi.fn(resolve); + await openAndSearch( + { + "test.provider": { + icon: , + resolve: labelResolve, + availableFonts: [{ id: "a1b2c3", label: "Brand Sans" }], + search: async () => ({ + kind: "match", + fonts: [{ id: "d4e5f6", label: "Brand Serif" }], + }), + }, + }, + "brand", + ); + + expect(await screen.findByText("Search results")).not.toBeNull(); + // the offered font is found by its label, and so is the search result + expect(rowValues()).toEqual([ + "test.provider:a1b2c3", + "test.provider:d4e5f6", + ]); + expect(screen.queryByText("a1b2c3")).toBeNull(); + + await act(async () => { + fireEvent.click(screen.getByText("Brand Serif").closest("button")!); + }); + + expect(labelResolve).toHaveBeenCalledWith("d4e5f6"); + expect(window.h.state.currentItemFontFamily).toBe("test.provider:d4e5f6"); + }); + + it("shows a pending search as such", async () => { + await openAndSearch( + { + "test.provider": { + icon: , + resolve, + availableFonts: [], + search: () => new Promise(() => {}), + }, + }, + "rovoto", + ); + + expect(screen.getByText("Searching…")).not.toBeNull(); + }); + + it("keeps focus in the popup after a keep-open selection while editing", async () => { + vi.spyOn(document.fonts, "check").mockReturnValue(false); + vi.spyOn(document.fonts, "load").mockResolvedValue([]); + vi.spyOn(console, "error").mockImplementation(() => {}); + // a retry is the selection which keeps the popup open + let isOffline = true; + const { queryByTestId } = await render( + , + resolve: async (familyName) => { + if (isOffline) { + throw new Error("offline"); + } + return resolve(familyName); + }, + availableFonts: ["Foo"], + }, + }} + />, + ); + const flushTimers = () => + act(() => new Promise((resolve) => setTimeout(resolve, 10))); + // as a real click, which the text editor tells apart from leaving it + const press = (target: Element) => { + fireEvent.pointerDown(target); + fireEvent.pointerUp(target); + fireEvent.click(target); + }; + Keyboard.keyPress(KEYS.T); + new Pointer("mouse").clickAt(100, 100); + await flushTimers(); + expect(h.state.editingTextElement).not.toBeNull(); + + press(queryByTestId("font-family-show-fonts")!); + const input = await waitFor(() => { + const input = document.querySelector( + ".properties-content .QuickSearch__input", + ); + expect(input).not.toBeNull(); + return input!; + }); + press(input); + input.focus(); + await flushTimers(); + fireEvent.input(input, { target: { value: "Foo" } }); + fireEvent.keyDown(document.querySelector(".properties-content")!, { + key: KEYS.ARROW_DOWN, + }); + await pressEnter(); + await waitFor(() => + expect( + document.querySelector(".FontPicker__font--failed"), + ).not.toBeNull(), + ); + + isOffline = false; + await pressEnter(); + + await waitFor(() => + expect(h.state.currentItemFontFamily).toBe("test.provider:Foo"), + ); + await flushTimers(); + expect(h.state.editingTextElement).not.toBeNull(); + expect(h.state.openPopup).toBe("fontFamily"); + expect(document.activeElement).toBe(input); + }); + + it("shares the result slots between providers", async () => { + const names = (prefix: string, count: number) => + Array.from({ length: count }, (_, i) => `${prefix} Sans ${i}`); + const provider = (familyNames: string[]): FontProvider => ({ + icon: , + resolve, + availableFonts: [], + search: async () => ({ kind: "match", fonts: familyNames }), + }); + await openAndSearch( + { + "test.big": provider(names("Big", 25)), + "test.small": provider(names("Small", 3)), + }, + "sans", + ); + + await screen.findByText("Search results"); + // the short list's unused slots go to the long one, order kept + expect(rowValues()).toEqual([ + ...names("Big", 7).map((name) => `test.big:${name}`), + ...names("Small", 3).map((name) => `test.small:${name}`), + ]); + expect( + screen.getByText("+18 more, keep typing to narrow"), + ).not.toBeNull(); + }); + + it("drops suggestions while another provider matches", async () => { + await openAndSearch( + { + "test.fuzzy": { + icon: , + resolve, + availableFonts: [], + search: async () => ({ kind: "suggestion", fonts: ["Lobster"] }), + }, + "test.exact": { + icon: , + resolve, + availableFonts: [], + search: async () => ({ kind: "match", fonts: ["Lobster Two"] }), + }, + }, + "lobster t", + ); + + await screen.findByText("Search results"); + expect(rowValues()).toEqual(["test.exact:Lobster Two"]); + expect(screen.queryByText("Did you mean…")).toBeNull(); + }); + + it("aborts a superseded search", async () => { + const signals: AbortSignal[] = []; + const input = await openAndSearch( + { + "test.provider": { + icon: , + resolve, + availableFonts: [], + search: (_query, { signal }) => { + signals.push(signal); + return new Promise(() => {}); + }, + }, + }, + "rob", + ); + + await waitFor(() => expect(signals).toHaveLength(1)); + fireEvent.input(input, { target: { value: "robo" } }); + + expect(signals[0].aborted).toBe(true); + await waitFor(() => expect(signals).toHaveLength(2)); + }); + }); + + describe("list", () => { + const resolve: FontResolver = async () => ({ fontFaces, metadata }); + + const open = async ( + props?: Pick, + /** what's on canvas as the picker opens */ + elements: readonly ExcalidrawElement[] = [], + ) => { + const { queryByTestId } = await render( + , + ); + API.setElements(elements); + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + await screen.findByText("Available fonts"); + }; + + const getGroupFamilies = (title: string) => + Array.from( + screen + .getByText(title) + .closest(".dropdown-menu-group")! + .querySelectorAll("button[value]"), + ).map((button) => button.title); + + it("leads the available fonts with our own, ahead of a provider's", async () => { + await open({ + fontProviders: { + "test.provider": { + icon: , + resolve, + // would sort first + availableFonts: ["Aardvark", "Zebra"], + }, + }, + }); + + expect(getGroupFamilies("Available fonts")).toEqual([ + "Excalifont", + "Nunito", + "Comic Shanns", + "Lilita One", + "Aardvark", + "Zebra", + ]); + }); + + it("counts a font as the scene's only once an element uses it", async () => { + await open(undefined, [ + API.createElement({ + type: "text", + text: "x", + fontFamily: FONT_FAMILY.Nunito, + }), + ]); + + // Excalifont is the current font (what the next text gets), in no + // element as yet + expect(getGroupFamilies("In this scene")).toEqual(["Nunito"]); + expect(getGroupFamilies("Available fonts")).toEqual([ + "Excalifont", + "Comic Shanns", + "Lilita One", + ]); + }); + + it("lists deprecated fonts of ours right below the current ones", async () => { + const { queryByTestId } = await render( + , + resolve, + availableFonts: ["Aardvark"], + }, + }} + />, + ); + Keyboard.keyPress(KEYS.T); + fireEvent.click(queryByTestId("font-family-show-fonts")!); + await screen.findByText("Available fonts"); + + expect(getGroupFamilies("Available fonts")).toEqual([ + "Excalifont", + "Nunito", + "Comic Shanns", + "Lilita One", + "Cascadia", + "Helvetica", + "Virgil", + "Aardvark", + ]); + }); + + describe("loading more", () => { + // jsdom has no layout: a list of 1000px in a 100px viewport, so that + // only a scroll gets to its end + beforeEach(() => { + vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue( + 1000, + ); + vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue( + 100, + ); + }); + + const page = (prefix: string, count: number) => + Array.from({ length: count }, (_, i) => `${prefix} ${i}`); + + it("appends a provider's fonts on demand, then as the list's end is reached", async () => { + const loadMore = vi + .fn>() + // not in alphabetical order, and holding a font listed already + .mockResolvedValueOnce(["Zulu", "Aardvark", ...page("First", 18)]) + .mockResolvedValueOnce(page("Second", 3)); + await open({ + fontProviders: { + "test.provider": { + icon: , + resolve, + availableFonts: ["Aardvark", "Mango"], + loadMore, + }, + }, + }); + const input = document.querySelector( + ".properties-content .QuickSearch__input", + )!; + input.focus(); + + fireEvent.click(screen.getByText("Browse more fonts")); + expect(loadMore).toHaveBeenCalledWith( + expect.objectContaining({ offset: 0, limit: 20 }), + ); + + // at the end, as they came - what was listed doesn't move + await waitFor(() => + expect(getGroupFamilies("Available fonts")).toEqual([ + "Excalifont", + "Nunito", + "Comic Shanns", + "Lilita One", + "Aardvark", + "Mango", + "Zulu", + ...page("First", 18), + ]), + ); + expect(document.activeElement).toBe(input); + expect(loadMore).toHaveBeenCalledTimes(1); + + // from now on, reaching the end of the list is enough + const list = document.querySelector( + ".properties-content .dropdown-menu.fonts", + )!; + list.scrollTop = 900; + fireEvent.scroll(list); + + await waitFor(() => + expect(getGroupFamilies("Available fonts").slice(-3)).toEqual( + page("Second", 3), + ), + ); + expect(loadMore).toHaveBeenLastCalledWith( + expect.objectContaining({ offset: 20 }), + ); + // a short page was the last one + expect(screen.queryByText("Browse more fonts")).toBe(null); + // nothing says the provider has more + expect(screen.queryByText("Use search for more")).toBe(null); + }); + + it("points at the search once a provider able to search has no more to load", async () => { + await open({ + fontProviders: { + "test.provider": { + icon: , + resolve, + availableFonts: ["Aardvark"], + loadMore: vi + .fn>() + .mockResolvedValueOnce(page("Only", 3)), + search: async () => ({ kind: "match", fonts: [] }), + }, + }, + }); + expect(screen.queryByText("Use search for more")).toBe(null); + + fireEvent.click(screen.getByText("Browse more fonts")); + + expect( + await screen.findByText("Use search for more"), + ).toBeInTheDocument(); + expect(screen.queryByText("Browse more fonts")).toBe(null); + }); + + it("keeps what got loaded, and loading at the list's end, when the picker reopens", async () => { + const loadMore = vi + .fn>() + .mockResolvedValueOnce(page("First", 20)) + .mockResolvedValueOnce(page("Second", 20)); + await open({ + fontProviders: { + "test.provider": { + icon: , + resolve, + availableFonts: ["Aardvark"], + loadMore, + }, + }, + }); + + fireEvent.click(screen.getByText("Browse more fonts")); + await screen.findByTitle("First 19"); + + // close (picking a font does), and open again + fireEvent.click(screen.getByTitle("Nunito")); + await waitFor(() => + expect(document.querySelector(".properties-content")).toBe(null), + ); + fireEvent.click(screen.getByTestId("font-family-show-fonts")); + await screen.findByText("Available fonts"); + + expect(getGroupFamilies("Available fonts").slice(-2)).toEqual([ + "First 18", + "First 19", + ]); + expect(loadMore).toHaveBeenCalledTimes(1); + + // no click needed this time + const list = document.querySelector( + ".properties-content .dropdown-menu.fonts", + )!; + list.scrollTop = 900; + fireEvent.scroll(list); + await screen.findByTitle("Second 19"); + // carrying on from where it was + expect(loadMore).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ offset: 20 }), + ); + }); + + it("lists nothing on a scroll before it was asked for, nor offers it while searching", async () => { + const loadMore = vi + .fn>() + .mockResolvedValue(["Zulu"]); + await open({ + fontProviders: { + "test.provider": { + icon: , + resolve, + availableFonts: ["Aardvark"], + loadMore, + }, + }, + }); + // the look ahead, which tells whether there is anything to offer + await screen.findByText("Browse more fonts"); + const list = document.querySelector( + ".properties-content .dropdown-menu.fonts", + )!; + list.scrollTop = 900; + fireEvent.scroll(list); + expect(loadMore).toHaveBeenCalledTimes(1); + expect(screen.queryByText("Zulu")).toBe(null); + + fireEvent.input( + document.querySelector(".properties-content .QuickSearch__input")!, + { target: { value: "aard" } }, + ); + await waitFor(() => + expect(screen.queryByText("Browse more fonts")).toBe(null), + ); + }); + + it("offers nothing more when a provider has no font beyond the listed ones", async () => { + const loadMore = vi + .fn>() + .mockResolvedValue(["Aardvark"]); + await open({ + fontProviders: { + "test.provider": { + icon: , + resolve, + availableFonts: ["Aardvark"], + loadMore, + }, + }, + }); + + await waitFor(() => expect(loadMore).toHaveBeenCalledTimes(1)); + await act(async () => {}); + expect(screen.queryByText("Browse more fonts")).toBe(null); + }); + + it("offers more also when the scene uses every available font", async () => { + await open( + { + fontProviders: { + "test.provider": { + resolve, + availableFonts: [], + loadMore: async () => ["Zulu"], + }, + }, + }, + [ + FONT_FAMILY.Excalifont, + FONT_FAMILY.Nunito, + FONT_FAMILY["Comic Shanns"], + FONT_FAMILY["Lilita One"], + ].map((fontFamily) => + API.createElement({ type: "text", text: "a", fontFamily }), + ), + ); + + expect(getGroupFamilies("Available fonts")).toEqual([]); + fireEvent.click(await screen.findByText("Browse more fonts")); + await screen.findByText("Zulu"); + }); + + it("offers nothing more without a provider able to page", async () => { + await open({ + fontProviders: { + "test.provider": { + icon: , + resolve, + availableFonts: ["Aardvark"], + search: async () => ({ kind: "match", fonts: [] }), + }, + }, + }); + + expect(screen.queryByText("Browse more fonts")).toBe(null); + }); + }); + + it("lists a favorite once, below the scene's fonts", async () => { + await open( + { + fontFavorites: { + // the scene's font stays with the scene + fonts: [FONT_FAMILY.Nunito, FONT_FAMILY.Excalifont], + onChange: vi.fn(), + }, + }, + [API.createElement({ type: "text", text: "x" })], + ); + + expect(getGroupFamilies("In this scene")).toEqual(["Excalifont"]); + expect(getGroupFamilies("Favorites")).toEqual(["Nunito"]); + expect(getGroupFamilies("Available fonts")).toEqual([ + "Comic Shanns", + "Lilita One", + ]); + expect( + Array.from( + document.querySelectorAll(".dropdown-menu-group-title"), + (title) => title.textContent, + ), + ).toEqual(["In this scene", "Favorites", "Available fonts"]); + }); + + it("scrolls to the highlighted font on open and on keyboard navigation only", async () => { + const scrollIntoView = vi.fn(); + const original = HTMLElement.prototype.scrollIntoView; + HTMLElement.prototype.scrollIntoView = scrollIntoView; + + try { + await open(); + const popup = document.querySelector(".properties-content")!; + const getRow = (title: string) => + document.querySelector( + `.dropdown-menu.fonts [title="${title}"]`, + )!; + + // the selected font, as the picker opens + expect(scrollIntoView).toHaveBeenCalledTimes(1); + expect(scrollIntoView.mock.contexts[0]).toBe(getRow("Excalifont")); + + // a hover preview, and its end - when the highlight falls back to the + // selected font - leave the list where it is + fireEvent.mouseMove(getRow("Lilita One")); + await waitFor(() => + expect(h.state.currentHoveredFontFamily).toBe( + FONT_FAMILY["Lilita One"], + ), + ); + fireEvent.pointerLeave(popup); + await waitFor(() => + expect(h.state.currentHoveredFontFamily).toBe(null), + ); + expect(scrollIntoView).toHaveBeenCalledTimes(1); + + // the keyboard moves the highlight where the pointer isn't + fireEvent.keyDown(popup, { key: KEYS.ARROW_DOWN }); + await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(2)); + expect(scrollIntoView.mock.contexts[1]).toBe(getRow("Nunito")); + } finally { + HTMLElement.prototype.scrollIntoView = original; + } + }); + }); + describe("top picks drag & drop", () => { const SLOT_SIZE = 32; const SLOT_SPAN = 40; @@ -55,6 +2147,9 @@ describe("FontPicker", () => { if (this.classList.contains("top-picks-dnd")) { return new DOMRect(0, 0, SLOT_SPAN * 2 + SLOT_SIZE, SLOT_SIZE); } + if (this.classList.contains("FontPicker__favorites-drop-zone")) { + return new DOMRect(0, 100, 200, 30); + } return new DOMRect(0, 300, SLOT_SIZE, SLOT_SIZE); }); }); @@ -89,8 +2184,12 @@ describe("FontPicker", () => { ), ).map((button) => button.title); - const openFontPicker = async () => { - const utils = await render(); + const openFontPicker = async ( + props?: Pick, + ) => { + const utils = await render( + , + ); Keyboard.keyPress(KEYS.T); act(() => { utils.queryByTestId("font-family-show-fonts")!.click(); @@ -127,6 +2226,56 @@ describe("FontPicker", () => { expect(h.state.currentItemFontFamily).not.toBe(FONT_FAMILY["Lilita One"]); }); + it("pins a custom font as its preview text, resolving it on select", async () => { + vi.spyOn(document.fonts, "check").mockReturnValue(false); + vi.spyOn(document.fonts, "load").mockResolvedValue([]); + const deferred = createDeferredResolver(); + let resolvePreviewText!: (text: string) => void; + const { container, queryByTestId } = await render( + , + resolve: deferred.resolver, + availableFonts: ["Pinned"], + getPreviewText: () => + new Promise((resolve) => (resolvePreviewText = resolve)), + }, + }} + />, + ); + Keyboard.keyPress(KEYS.T); + act(() => { + queryByTestId("font-family-show-fonts")!.click(); + }); + + const row = (await screen.findByText("Pinned")).closest("button")!; + await drag(row, { clientX: 16, clientY: 316 }, slotCenter(1)); + + await waitFor(() => + expect(h.state.fontTopPicks).toEqual([ + FONT_FAMILY.Excalifont, + "test.provider:Pinned", + FONT_FAMILY["Comic Shanns"], + ]), + ); + const pick = container.querySelector( + '.FontPicker__top-picks [data-top-pick-index="1"]', + )!; + expect(pick.querySelector("svg")).toBe(null); + expect(pick.textContent).toBe("Aa"); + await act(async () => resolvePreviewText("あ")); + expect(pick.textContent).toBe("あ"); + + fireEvent.click(pick); + expect(h.state.currentItemFontFamily).not.toBe("test.provider:Pinned"); + await act(async () => deferred.resolve()); + await waitFor(() => + expect(h.state.currentItemFontFamily).toBe("test.provider:Pinned"), + ); + }); + it("refuses pinning an already pinned font", async () => { await openFontPicker(); @@ -195,6 +2344,136 @@ describe("FontPicker", () => { ); }); + const getFavoritesDropZone = () => + document.querySelector(".FontPicker__favorites-drop-zone"); + + // the zone only mounts once a drag is in flight, so it takes a move to + // start the drag and another one to get onto it + const dragToFavorites = async (source: HTMLElement) => { + fireEvent.pointerDown(source, { + pointerId: 1, + button: 0, + clientX: 16, + clientY: 316, + }); + await new Promise((resolve) => setTimeout(resolve, 120)); + fireEvent.pointerMove(window, { + pointerId: 1, + clientX: 16, + clientY: 200, + }); + const label = getFavoritesDropZone()?.textContent ?? null; + fireEvent.pointerMove(window, { + pointerId: 1, + clientX: 100, + clientY: 115, + }); + fireEvent.pointerUp(window, { pointerId: 1, clientX: 100, clientY: 115 }); + await new Promise((resolve) => setTimeout(resolve, 120)); + return label; + }; + + const getGroupFamilies = (title: string) => + Array.from( + screen + .queryByText(title) + ?.closest(".dropdown-menu-group") + ?.querySelectorAll("button[value]") ?? [], + ).map((button) => button.title); + + it("adds a font dropped on the favorites zone, and removes it the same way", async () => { + const Host = () => { + const [fonts, setFonts] = React.useState< + NonNullable["fonts"] + >([]); + return ( + + ); + }; + const { queryByTestId } = await render(); + Keyboard.keyPress(KEYS.T); + act(() => { + queryByTestId("font-family-show-fonts")!.click(); + }); + const getRow = () => + document.querySelector( + '.dropdown-menu.fonts [title="Lilita One"]', + )!; + await waitFor(() => expect(getRow()).not.toBeNull()); + expect(getFavoritesDropZone()).toBe(null); + // the zone shows up only once a drag starts - the tip tells of it + expect( + document.querySelector(".FontPicker__tip")!.textContent, + ).toBe("Drag a font to pin"); + + const input = document.querySelector( + ".properties-content .QuickSearch__input", + )!; + input.blur(); + + expect(await dragToFavorites(getRow())).toBe("Drag to favorite"); + // the drag took the focus - the search has it back + expect(document.activeElement).toBe(input); + + // in a section of its own, and no longer among the available ones + await waitFor(() => + expect(getGroupFamilies("Favorites")).toEqual(["Lilita One"]), + ); + expect(getGroupFamilies("Available fonts")).not.toContain("Lilita One"); + expect(getFavoritesDropZone()).toBe(null); + // dropping is not selecting + expect(h.state.currentItemFontFamily).toBe(FONT_FAMILY.Excalifont); + + expect(await dragToFavorites(getRow())).toBe("Remove favorite"); + + await waitFor(() => expect(screen.queryByText("Favorites")).toBe(null)); + expect(getGroupFamilies("Available fonts")).toContain("Lilita One"); + }); + + it("offers no favorites zone unless the host keeps favorites", async () => { + await openFontPicker(); + const row = document.querySelector( + '.dropdown-menu.fonts [title="Lilita One"]', + )!; + + expect(await dragToFavorites(row)).toBe(null); + // a drag which went nowhere hands the focus back all the same + expect(document.activeElement).toBe( + document.querySelector(".properties-content .QuickSearch__input"), + ); + }); + + it("shows the host's tip in place of its own", async () => { + await openFontPicker({ + fontPickerTip: ( + Fonts are set by your team + ), + }); + const tip = document.querySelector(".FontPicker__tip")!; + + expect(tip.querySelector(".host-tip")).not.toBe(null); + expect(tip.textContent).not.toContain("drag any font"); + + // the editor's reset link stays next to it + act(() => { + API.setAppState({ fontTopPicks: [FONT_FAMILY.Nunito] }); + }); + await waitFor(() => + expect(tip.textContent).toBe("Fonts are set by your team · Reset"), + ); + }); + + it("shows no tip text when the host passes null", async () => { + await openFontPicker({ fontPickerTip: null }); + + expect( + document.querySelector(".FontPicker__tip")!.textContent, + ).toBe(""); + }); + it("resets customized picks from the tip's reset link", async () => { await openFontPicker(); diff --git a/packages/excalidraw/components/FontPicker/FontPicker.tsx b/packages/excalidraw/components/FontPicker/FontPicker.tsx index 66a4a3726b..6f9fb06579 100644 --- a/packages/excalidraw/components/FontPicker/FontPicker.tsx +++ b/packages/excalidraw/components/FontPicker/FontPicker.tsx @@ -1,17 +1,27 @@ import { Popover } from "radix-ui"; import clsx from "clsx"; -import React, { useCallback } from "react"; +import React, { + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useReducer, + useRef, +} from "react"; import { FONT_FAMILY, FONT_TOP_PICKS_SLOTS, getFontFamilyString, + isCustomFontFamily, + parseProviderFontFamily, } from "@excalidraw/common"; -import type { FontFamilyValues } from "@excalidraw/element/types"; +import type { FontFamily } from "@excalidraw/common"; import { Fonts } from "../../fonts"; import { t } from "../../i18n"; +import { useApp, useAppProps } from "../App"; import { ButtonSeparator } from "../ButtonSeparator"; import { FontFamilyCodeIcon, @@ -24,17 +34,15 @@ import { TopPicksDnDOutline, } from "../TopPicksDnD/topPicksDnD"; -import { - FontPickerList, - getFontFamilyIcon, - getFontFamilyLabel, -} from "./FontPickerList"; +import { FontPickerList, type FontSelectionOptions } from "./FontPickerList"; import { FontPickerTrigger } from "./FontPickerTrigger"; +import { getFontPreviewText, loadFontPreviewText } from "./fontProviderInfo"; import { FontPickerDnDContext, useFontPickerDnD, useFontTopPicksDnD, } from "./fontTopPicksDnD"; +import { getFontFamilyIcon, getFontFamilyLabel } from "./useFontCatalog"; import "./FontPicker.scss"; @@ -65,8 +73,8 @@ const DEFAULT_FONT_TOP_PICKS = DEFAULT_FONTS.map((font) => font.value); const defaultFontFamilies = new Set(DEFAULT_FONT_TOP_PICKS); const getFontTopPicks = ( - topPicks: readonly FontFamilyValues[], -): readonly FontFamilyValues[] => { + topPicks: readonly FontFamily[], +): readonly FontFamily[] => { const picks = [...new Set(topPicks)].slice(0, FONT_TOP_PICKS_SLOTS); for (const fontFamily of DEFAULT_FONT_TOP_PICKS) { if (picks.length >= FONT_TOP_PICKS_SLOTS) { @@ -79,30 +87,30 @@ const getFontTopPicks = ( return picks; }; -export const isDefaultFont = (fontFamily: number | null) => { +export const isDefaultFont = (fontFamily: FontFamily | null) => { if (!fontFamily) { return false; } - return defaultFontFamilies.has(fontFamily); + return defaultFontFamilies.has(fontFamily as number); }; -const getTopPickFont = (fontFamily: FontFamilyValues) => +const getTopPickFont = (fontFamily: FontFamily) => DEFAULT_FONTS.find((font) => font.value === fontFamily) ?? { value: fontFamily, icon: getFontFamilyIcon(fontFamily), - text: getFontFamilyLabel( - fontFamily, - Fonts.registered.get(fontFamily)?.fontFaces ?? [], - ), + text: getFontFamilyLabel(fontFamily, Fonts.registered.get(fontFamily)), testId: `font-family-${fontFamily}`, }; const needsGlyphSample = ( - fontFamily: FontFamilyValues, - picks: readonly FontFamilyValues[], + fontFamily: FontFamily, + picks: readonly FontFamily[], ) => { - if (defaultFontFamilies.has(fontFamily)) { + if (isCustomFontFamily(fontFamily)) { + return true; + } + if (defaultFontFamilies.has(fontFamily as number)) { return false; } const icon = getFontFamilyIcon(fontFamily); @@ -118,15 +126,80 @@ const FontTopPicks = ({ onReset, isCustomized, }: { - picks: readonly FontFamilyValues[]; - selectedFontFamily: FontFamilyValues | null; - onSelect: (fontFamily: FontFamilyValues) => void; + picks: readonly FontFamily[]; + selectedFontFamily: FontFamily | null; + onSelect: (fontFamily: FontFamily) => void; /** present when the strip is user-customizable */ onReset?: () => void; isCustomized: boolean; }) => { const dnd = useFontPickerDnD(); const dragState = dnd?.dragState ?? null; + const fonts = useApp().fonts.instance; + const { fontProviders } = useAppProps(); + const selectRequestIdRef = useRef(0); + const [, rerender] = useReducer((count: number) => count + 1, 0); + + // layout effect: a synchronous answer lands before paint, without flashing + // the default first + useLayoutEffect(() => { + let isCurrent = true; + const onSettled = () => isCurrent && rerender(); + let hasSyncAnswer = false; + for (const fontFamily of picks) { + const previousText = getFontPreviewText(fontFamily); + const pending = loadFontPreviewText(fontFamily, fontProviders); + if (pending) { + pending.then(onSettled); + } else if (getFontPreviewText(fontFamily) !== previousText) { + hasSyncAnswer = true; + } + } + if (hasSyncAnswer) { + rerender(); + } + return () => { + isCurrent = false; + }; + }, [picks, fontProviders]); + + // custom picks render their sample in their own typeface + useEffect(() => { + void fonts.registerCustomFamilies( + picks.filter( + (fontFamily) => + isCustomFontFamily(fontFamily) && + fonts.getResolutionStatus(fontFamily) === "initial", + ), + ); + }, [fonts, picks]); + + const isUnsupported = (fontFamily: FontFamily) => { + if (!isCustomFontFamily(fontFamily)) { + return false; + } + const parsed = parseProviderFontFamily(fontFamily); + return ( + !parsed || + !fontProviders || + !Object.hasOwn(fontProviders, parsed.providerId) + ); + }; + + // last click wins, as in the list + const selectPick = async (fontFamily: FontFamily) => { + const requestId = ++selectRequestIdRef.current; + if (isCustomFontFamily(fontFamily) && !fonts.registered.has(fontFamily)) { + const result = await fonts.registerCustomFamily(fontFamily); + if ( + result.status !== "success" || + selectRequestIdRef.current !== requestId + ) { + return; + } + } + onSelect(fontFamily); + }; return ( onSelect(fontFamily)} + disabled={isUnsupported(fontFamily)} + onClick={() => selectPick(fontFamily)} onPointerDown={ dnd ? (event) => dnd.startPickDrag(event, index, fontFamily) @@ -181,7 +255,7 @@ const FontTopPicks = ({ className="FontPicker__top-pick-sample" style={{ fontFamily: getFontFamilyString({ fontFamily }) }} > - Aa + {getFontPreviewText(fontFamily)} ) : ( font.icon @@ -197,13 +271,13 @@ const FontTopPicks = ({ interface FontPickerProps { isOpened: boolean; - selectedFontFamily: FontFamilyValues | null; - hoveredFontFamily: FontFamilyValues | null; + selectedFontFamily: FontFamily | null; + hoveredFontFamily: FontFamily | null; /** user-customized top picks (`appState.fontTopPicks`) */ - topPicks: readonly FontFamilyValues[] | null; - onSelect: (fontFamily: FontFamilyValues) => void; - onTopPicksChange: (fontTopPicks: FontFamilyValues[] | null) => void; - onHover: (fontFamily: FontFamilyValues) => void; + topPicks: readonly FontFamily[] | null; + onSelect: (fontFamily: FontFamily, options?: FontSelectionOptions) => void; + onTopPicksChange: (fontTopPicks: FontFamily[] | null) => void; + onHover: (fontFamily: FontFamily) => void; onLeave: () => void; onPopupChange: (open: boolean) => void; compactMode?: boolean; @@ -223,7 +297,7 @@ export const FontPicker = React.memo( compactMode = false, }: FontPickerProps) => { const onSelectCallback = useCallback( - (value: number | false) => { + (value: FontFamily | false) => { if (value) { onSelect(value); } @@ -234,16 +308,30 @@ export const FontPicker = React.memo( // the strip (and thus its customization) is hidden in compact mode const isTopPicksCustomizable = !compactMode; const isCustomized = !!topPicks?.length; - const picks = topPicks?.length - ? getFontTopPicks(topPicks) - : DEFAULT_FONT_TOP_PICKS; + const picks = useMemo( + () => + topPicks?.length ? getFontTopPicks(topPicks) : DEFAULT_FONT_TOP_PICKS, + [topPicks], + ); const resetTopPicks = () => onTopPicksChange(null); + const { fontFavorites } = useAppProps(); + const dnd = useFontTopPicksDnD({ enabled: isTopPicksCustomizable, picks, onPicksChange: onTopPicksChange, + onFavoriteToggle: fontFavorites + ? (fontFamily) => { + const { fonts, onChange } = fontFavorites; + onChange( + fonts.includes(fontFamily) + ? fonts.filter((favorite) => favorite !== fontFamily) + : [...fonts, fontFamily], + ); + } + : undefined, }); return ( @@ -277,7 +365,7 @@ export const FontPicker = React.memo( onPopupChange(true)} @@ -294,6 +382,11 @@ export const FontPicker = React.memo( ); }, + // deliberately narrow: the parent re-renders on every canvas interaction, + // and only these props change what the picker shows. The price is that the + // callback props may be closures from an older render - they must read live + // state through stable handles (`app`, refs, setters), never render-scoped + // props. See `onPopupChange` in `actionChangeFontFamily` (prev, next) => prev.isOpened === next.isOpened && prev.selectedFontFamily === next.selectedFontFamily && diff --git a/packages/excalidraw/components/FontPicker/FontPickerList.tsx b/packages/excalidraw/components/FontPicker/FontPickerList.tsx index f24eee02fd..cf0ad53fb7 100644 --- a/packages/excalidraw/components/FontPicker/FontPickerList.tsx +++ b/packages/excalidraw/components/FontPicker/FontPickerList.tsx @@ -1,71 +1,55 @@ +import clsx from "clsx"; import React, { useMemo, - useState, useRef, + useState, useEffect, useCallback, type KeyboardEventHandler, } from "react"; -import { type FontFamilyValues } from "@excalidraw/element/types"; +import { isCustomFontFamily, KEYS } from "@excalidraw/common"; -import { - arrayToList, - debounce, - FONT_FAMILY, - getFontFamilyString, -} from "@excalidraw/common"; +import type { FontFamily } from "@excalidraw/common"; -import type { ValueOf } from "@excalidraw/common/utility-types"; - -import { Fonts } from "../../fonts"; +import { useStableCallback } from "../../hooks/useStableCallback"; +import { useSyncExternalStore } from "../../hooks/useSyncExternalStore"; import { t } from "../../i18n"; import { useApp, useAppProps, useExcalidrawContainer, + useExcalidrawSetAppState, useStylesPanelMode, } from "../App"; import { PropertiesPopover } from "../PropertiesPopover"; import { QuickSearch } from "../QuickSearch"; import { ScrollableList } from "../ScrollableList"; import { TopPicksTip } from "../TopPicksDnD/TopPicksTip"; +import { TopPicksDnDOutline } from "../TopPicksDnD/topPicksDnD"; import DropdownMenuGroup from "../dropdownMenu/DropdownMenuGroup"; -import { - DropDownMenuItemBadgeType, - DropDownMenuItemBadge, -} from "../dropdownMenu/DropdownMenuItem"; -import MenuItemContent from "../dropdownMenu/DropdownMenuItemContent"; -import { getDropdownMenuItemClassName } from "../dropdownMenu/common"; -import { - FontFamilyCodeIcon, - FontFamilyHeadingIcon, - FontFamilyNormalIcon, - FreedrawIcon, -} from "../icons"; +import { DragDropIcon } from "../icons"; import { useFontPickerDnD } from "./fontTopPicksDnD"; import { fontPickerKeyHandler } from "./keyboardNavHandlers"; +import { FontPickerListItem } from "./FontPickerListItem"; +import { useFontCatalog, type FontDescriptor } from "./useFontCatalog"; +import { + useFontResolution, + type FontSelectionOptions, +} from "./useFontResolution"; +import { useFontSearch } from "./useFontSearch"; +import { useMoreFonts } from "./useMoreFonts"; +import { useVisibleFontRegistration } from "./useVisibleFontRegistration"; -import type { JSX } from "react"; -import type { ExcalidrawFontFace } from "../../fonts/ExcalidrawFontFace"; - -export interface FontDescriptor { - value: number; - icon: JSX.Element; - text: string; - deprecated?: true; - badge?: { - type: ValueOf; - placeholder: string; - }; -} +export type { FontSelectionOptions } from "./useFontResolution"; +export type { FontDescriptor } from "./useFontCatalog"; interface FontPickerListProps { - selectedFontFamily: FontFamilyValues | null; - hoveredFontFamily: FontFamilyValues | null; - onSelect: (value: number) => void; - onHover: (value: number) => void; + selectedFontFamily: FontFamily | null; + hoveredFontFamily: FontFamily | null; + onSelect: (value: FontFamily, options?: FontSelectionOptions) => void; + onHover: (value: FontFamily) => void; onLeave: () => void; onOpen: () => void; onClose: () => void; @@ -73,34 +57,8 @@ interface FontPickerListProps { onResetTopPicks?: () => void; } -export const getFontFamilyIcon = ( - fontFamily: FontFamilyValues, -): JSX.Element => { - switch (fontFamily) { - case FONT_FAMILY.Excalifont: - case FONT_FAMILY.Virgil: - return FreedrawIcon; - case FONT_FAMILY.Nunito: - case FONT_FAMILY.Helvetica: - return FontFamilyNormalIcon; - case FONT_FAMILY["Lilita One"]: - return FontFamilyHeadingIcon; - case FONT_FAMILY["Comic Shanns"]: - case FONT_FAMILY.Cascadia: - return FontFamilyCodeIcon; - default: - return FontFamilyNormalIcon; - } -}; - -export const getFontFamilyLabel = ( - fontFamily: FontFamilyValues, - fontFaces: ExcalidrawFontFace[], -) => - // prefer our config as the browser resolved names may be wrapped in quotes and such - Object.entries(FONT_FAMILY).find(([, id]) => id === fontFamily)?.[0] ?? - fontFaces[0]?.fontFace?.family ?? - "Unknown"; +/** how close (px) to the end of the list the next batch of fonts loads */ +const LOAD_MORE_DISTANCE = 40; export const FontPickerList = React.memo( ({ @@ -115,152 +73,338 @@ export const FontPickerList = React.memo( }: FontPickerListProps) => { const { container } = useExcalidrawContainer(); const app = useApp(); - const { fonts } = app; - const { showDeprecatedFonts } = useAppProps(); + const setAppState = useExcalidrawSetAppState(); + const fonts = app.fonts.instance; + const { showDeprecatedFonts, fontProviders, fontPickerTip, fontFavorites } = + useAppProps(); const stylesPanelMode = useStylesPanelMode(); + const hasFontProviders = useMemo( + () => !!Object.keys(fontProviders ?? {}).length, + [fontProviders], + ); + const favoriteFamilies = useMemo( + () => + new Set( + (fontFavorites?.fonts ?? []).filter( + (fontFamily) => + typeof fontFamily === "number" || typeof fontFamily === "string", + ), + ), + [fontFavorites?.fonts], + ); // present only when the top picks are customizable const dnd = useFontPickerDnD(); - const [searchTerm, setSearchTerm] = useState(""); - const inputRef = useRef(null); - const allFonts = useMemo( - () => - Array.from(Fonts.registered.entries()) - .filter( - ([_, { metadata }]) => !metadata.private && !metadata.fallback, - ) - .map(([familyId, { metadata, fontFaces }]) => { - const fontDescriptor = { - value: familyId, - icon: getFontFamilyIcon(familyId), - text: getFontFamilyLabel(familyId, fontFaces), - }; + const [localHoveredFontFamily, setLocalHoveredFontFamily] = + useState(null); + // useSyncExternalStore rather than subscribe-in-effect: an emit landing + // between this render's snapshot and the effect's subscription would + // otherwise be lost until the *next* emit. Both getters return + // identity-stable maps that only change on an announcement (the lone + // unannounced reassignment - the registry's lazy built-in init - runs on + // first access, before any subscriber exists), as the contract requires + const failedResolutions = useSyncExternalStore( + useCallback( + (onStoreChange: () => void) => + fonts.onFailedResolutionsChangeEmitter.on(onStoreChange), + [fonts], + ), + () => fonts.failedResolutions, + ); + const registeredFonts = useSyncExternalStore( + useCallback( + (onStoreChange: () => void) => + fonts.onRegisteredFontsChangeEmitter.on(onStoreChange), + [fonts], + ), + () => fonts.registered, + ); + const { + inputRef, + searchTerm, + resolvingFamily, + selectFontFamily, + onSearchChange, + cancelResolution, + } = useFontResolution({ + fonts, + registeredFonts, + failedResolutions, + isEditingText: !!app.state.editingTextElement, + onSelect, + }); + const { results: searchResults, isSearching } = useFontSearch({ + fonts, + fontProviders, + searchTerm, + }); + const listedFamiliesRef = useRef>(new Set()); + const { + moreFonts, + hasMore: hasMoreFonts, + isAtEnd: isAtMoreFontsEnd, + isLoading: isLoadingMoreFonts, + isActive: isLoadingMoreOnScroll, + loadMore: loadMoreFonts, + } = useMoreFonts({ fonts, fontProviders, listedFamiliesRef }); + const { + listedFamilies, + selectableFonts, + sceneFilteredFonts, + favoriteFilteredFonts, + availableFilteredFonts, + searchMatches, + hiddenSearchMatchCount, + searchSuggestions, + } = useFontCatalog({ + fonts, + fontProviders, + registeredFonts, + failedResolutions, + selectedFontFamily, + hoveredFontFamily, + favoriteFamilies, + moreFonts, + resolvingFamily, + searchTerm, + searchResults, + showDeprecatedFonts: !!showDeprecatedFonts, + }); + listedFamiliesRef.current = listedFamilies; - if (metadata.deprecated) { - Object.assign(fontDescriptor, { - deprecated: metadata.deprecated, - badge: { - type: DropDownMenuItemBadgeType.RED, - placeholder: t("fontList.badge.old"), - }, - }); - } + // more is on offer at the end of the list, unless it's being searched + const isSearchShown = stylesPanelMode === "full"; + const canLoadMoreFonts = hasMoreFonts && !searchTerm.trim(); + // what a provider pages through may be a part of what it has (i.e. its + // most popular fonts) - the rest is found by searching + const hasSearchForMore = + isAtMoreFontsEnd && + isSearchShown && + !searchTerm.trim() && + Object.values(fontProviders ?? {}).some( + (provider) => provider.loadMore && provider.search, + ); - return fontDescriptor as FontDescriptor; - }) - .sort((a, b) => - a.text.toLowerCase() > b.text.toLowerCase() ? 1 : -1, - ), - [], + // Once the user has asked for more, reaching the end of the list - by + // scrolling, or by moving the highlight there with the keyboard, which + // scrolls - loads the next batch by itself. + const loadMoreFontsAtListEnd = useCallback(() => { + const scrollContainer = scrollContainerRef.current; + if ( + scrollContainer && + scrollContainer.scrollTop + scrollContainer.clientHeight >= + scrollContainer.scrollHeight - LOAD_MORE_DISTANCE + ) { + loadMoreFonts(); + } + }, [loadMoreFonts]); + const isLoadingMoreAtListEnd = + isLoadingMoreOnScroll && canLoadMoreFonts && !isLoadingMoreFonts; + useEffect(() => { + const scrollContainer = scrollContainerRef.current; + if (!isLoadingMoreAtListEnd || !scrollContainer) { + return; + } + // a batch may not have been enough to push the end out of view + loadMoreFontsAtListEnd(); + scrollContainer.addEventListener("scroll", loadMoreFontsAtListEnd, { + passive: true, + }); + return () => + scrollContainer.removeEventListener("scroll", loadMoreFontsAtListEnd); + }, [isLoadingMoreAtListEnd, loadMoreFontsAtListEnd, moreFonts]); + + // dragging a font takes the focus along - hand it back to the search + // once the drag is over, wherever the font got dropped (if anywhere) + const isDragging = !!dnd?.dragState; + const wasDraggingRef = useRef(false); + useEffect(() => { + if (wasDraggingRef.current && !isDragging) { + inputRef.current?.focus(); + } + wasDraggingRef.current = isDragging; + }, [isDragging, inputRef]); + + const hoverFontFamily = useCallback( + (fontFamily: FontFamily) => { + if ( + isCustomFontFamily(fontFamily) && + !registeredFonts.has(fontFamily) + ) { + // an unregistered family has no metrics yet, so its hover stays + // picker-local until it registers (see the effect below) - but + // clear the previous row's canvas preview, or the canvas would keep + // showing it under this row's highlight + setLocalHoveredFontFamily(fontFamily); + onLeave(); + return; + } + + setLocalHoveredFontFamily(null); + onHover(fontFamily); + }, + [onHover, onLeave, registeredFonts], ); - const sceneFamilies = useMemo( - () => new Set(fonts.getSceneFamilies()), - // cache per selected font family, so hover re-render won't mess it up - // eslint-disable-next-line react-hooks/exhaustive-deps - [selectedFontFamily], + // stable for the rows, which re-render only when what they show changes + const selectRowFontFamily = useStableCallback((fontFamily: FontFamily) => + selectFontFamily(fontFamily), ); + const hoverRowFontFamily = useStableCallback(hoverFontFamily); - const sceneFonts = useMemo( - () => allFonts.filter((font) => sceneFamilies.has(font.value)), // always show all the fonts in the scene, even those that were deprecated - [allFonts, sceneFamilies], - ); + const leaveFontFamily = useCallback(() => { + setLocalHoveredFontFamily(null); + onLeave(); + }, [onLeave]); - const availableFonts = useMemo( - () => - allFonts.filter( - (font) => - !sceneFamilies.has(font.value) && - (showDeprecatedFonts || !font.deprecated), // skip deprecated fonts - ), - [allFonts, sceneFamilies, showDeprecatedFonts], - ); + // Once the family has registered, its hover moves on to the canvas + // preview. The picker's own hover is dropped only when that has caught up + // (it takes a few renders): in between, the highlight would fall back to + // the selected font, and a key pressed right then would carry on from + // there - back at the top of the list. + const promotedHoverRef = useRef(null); + useEffect(() => { + if (localHoveredFontFamily === null) { + promotedHoverRef.current = null; + } else if (hoveredFontFamily === localHoveredFontFamily) { + setLocalHoveredFontFamily(null); + } else if ( + isCustomFontFamily(localHoveredFontFamily) && + registeredFonts.has(localHoveredFontFamily) && + promotedHoverRef.current !== localHoveredFontFamily + ) { + promotedHoverRef.current = localHoveredFontFamily; + onHover(localHoveredFontFamily); + } + }, [localHoveredFontFamily, hoveredFontFamily, onHover, registeredFonts]); - const filteredFonts = useMemo( - () => - arrayToList( - [...sceneFonts, ...availableFonts].filter((font) => - font.text?.toLowerCase().includes(searchTerm), - ), - ), - [sceneFonts, availableFonts, searchTerm], + const { + setScrollContainerRef: setRegistrationScrollContainerRef, + setFontItemRef, + } = useVisibleFontRegistration({ + fonts, + registeredFonts, + failedResolutions, + enabled: hasFontProviders, + }); + const scrollContainerRef = useRef(null); + const setScrollContainerRef = useCallback( + (node: HTMLDivElement | null) => { + scrollContainerRef.current = node; + setRegistrationScrollContainerRef(node); + }, + [setRegistrationScrollContainerRef], ); const hoveredFont = useMemo(() => { - let font; - - if (hoveredFontFamily) { - font = filteredFonts.find((font) => font.value === hoveredFontFamily); - } else if (selectedFontFamily) { - font = filteredFonts.find((font) => font.value === selectedFontFamily); + const activeHoveredFontFamily = + localHoveredFontFamily ?? hoveredFontFamily; + if (activeHoveredFontFamily) { + return selectableFonts.find( + (font) => font.value === activeHoveredFontFamily, + ); } - if (!font && searchTerm) { - if (filteredFonts[0]?.value) { - // hover first element on search - onHover(filteredFonts[0].value); - } else { - // re-render cache on no results - onLeave(); - } + if (selectedFontFamily) { + return selectableFonts.find( + (font) => font.value === selectedFontFamily, + ); } - return font; + return undefined; }, [ hoveredFontFamily, + localHoveredFontFamily, selectedFontFamily, - searchTerm, - filteredFonts, - onHover, - onLeave, + selectableFonts, ]); - // Create a wrapped onSelect function that preserves caret position - const wrappedOnSelect = useCallback( - (fontFamily: FontFamilyValues) => { - // Save caret position before font selection if editing text - let savedSelection: { start: number; end: number } | null = null; - if (app.state.editingTextElement) { - const textEditor = document.querySelector( - ".excalidraw-wysiwyg", - ) as HTMLTextAreaElement; - if (textEditor) { - savedSelection = { - start: textEditor.selectionStart, - end: textEditor.selectionEnd, - }; - } - } + useEffect(() => { + if (hoveredFont || !searchTerm) { + return; + } - onSelect(fontFamily); + const firstFont = selectableFonts[0]; + // a typo correction is picked deliberately, never by a bare Enter + if (firstFont && !searchSuggestions.length) { + hoverFontFamily(firstFont.value); + } else if (hoveredFontFamily || localHoveredFontFamily) { + leaveFontFamily(); + } + }, [ + hoveredFont, + hoveredFontFamily, + localHoveredFontFamily, + searchTerm, + searchSuggestions, + selectableFonts, + hoverFontFamily, + leaveFontFamily, + ]); - // Restore caret position after font selection if editing text - if (app.state.editingTextElement && savedSelection) { - setTimeout(() => { - const textEditor = document.querySelector( - ".excalidraw-wysiwyg", - ) as HTMLTextAreaElement; - if (textEditor && savedSelection) { - textEditor.focus(); - textEditor.selectionStart = savedSelection.start; - textEditor.selectionEnd = savedSelection.end; - } - }, 0); - } - }, - [onSelect, app.state.editingTextElement], - ); + // The highlighted row is scrolled into view on two occasions only: as the + // picker opens (the selected font), and when the highlight moves by + // keyboard. Never when it moves for another reason - a hover preview + // ending (the highlight falls back to the selected font), a font getting + // selected, the pointer - as the list would jump away from under it. + const shouldRevealHoveredFontRef = useRef(true); + const hoveredFontValue = hoveredFont?.value; + const isFirstFontHovered = selectableFonts[0]?.value === hoveredFontValue; + useEffect(() => { + if (!shouldRevealHoveredFontRef.current) { + return; + } + shouldRevealHoveredFontRef.current = false; + if (hoveredFontValue === undefined) { + return; + } + const row = Array.from( + scrollContainerRef.current?.querySelectorAll( + "button[value]", + ) ?? [], + ).find((button) => button.value === String(hoveredFontValue)); + // the first row differently, so that what's above (its group's title) + // shows as well + row?.scrollIntoView?.({ block: isFirstFontHovered ? "end" : "nearest" }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [hoveredFontValue]); const onKeyDown = useCallback>( (event) => { + if (event.key === KEYS.ARROW_DOWN || event.key === KEYS.ARROW_UP) { + shouldRevealHoveredFontRef.current = true; + } + if ( + event.key === KEYS.ARROW_DOWN && + isLoadingMoreOnScroll && + canLoadMoreFonts && + hoveredFont && + !hoveredFont.next + ) { + // on the last font, with more to come: load it rather than wrap + // around to the first one + loadMoreFonts(); + event.preventDefault(); + event.stopPropagation(); + return; + } const handled = fontPickerKeyHandler({ event, inputRef, hoveredFont, - filteredFonts, - onSelect: wrappedOnSelect, - onHover, - onClose, + filteredFonts: selectableFonts, + onSelect: selectFontFamily, + onHover: hoverFontFamily, + // Escape, wherever the focus is in the popup. `onClose` alone takes + // a preview back and leaves the popup open - it is also what a + // focus moving out reports, which doesn't close it + onClose: () => { + onClose(); + setAppState((state) => ({ + openPopup: + state.openPopup === "fontFamily" ? null : state.openPopup, + })); + }, }); if (handled) { @@ -268,117 +412,107 @@ export const FontPickerList = React.memo( event.stopPropagation(); } }, - [hoveredFont, filteredFonts, wrappedOnSelect, onHover, onClose], + [ + hoveredFont, + selectableFonts, + selectFontFamily, + hoverFontFamily, + onClose, + setAppState, + inputRef, + isLoadingMoreOnScroll, + canLoadMoreFonts, + loadMoreFonts, + ], ); useEffect(() => { onOpen(); return () => { + cancelResolution(); onClose(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - const sceneFilteredFonts = useMemo( - () => filteredFonts.filter((font) => sceneFamilies.has(font.value)), - [filteredFonts, sceneFamilies], - ); - - const availableFilteredFonts = useMemo( - () => filteredFonts.filter((font) => !sceneFamilies.has(font.value)), - [filteredFonts, sceneFamilies], - ); - - const FontPickerListItem = ({ - font, - order, - }: { - font: FontDescriptor; - order: number; - }) => { - const ref = useRef(null); - const isHovered = font.value === hoveredFont?.value; - const isSelected = font.value === selectedFontFamily; - - useEffect(() => { - if (!isHovered) { - return; - } - if (order === 0) { - // scroll into the first item differently, so it's visible what is above (i.e. group title) - ref.current?.scrollIntoView?.({ block: "end" }); - } else { - ref.current?.scrollIntoView?.({ block: "nearest" }); - } - }, [isHovered, order]); - - return ( - - ); - }; - - const groups = []; - - if (sceneFilteredFonts.length) { + const groups: React.ReactNode[] = []; + const pushGroup = ( + title: string, + key: string, + groupFonts: readonly FontDescriptor[], + footer?: React.ReactNode, + ) => { + // a footer is shown also on its own, i.e. "Browse more fonts" when the + // scene uses every available font + if (!groupFonts.length && !footer) { + return; + } groups.push( - - {sceneFilteredFonts.map((font, index) => ( - - ))} - , - ); - } - - if (availableFilteredFonts.length) { - groups.push( - - {availableFilteredFonts.map((font, index) => ( + + {groupFonts.map((font) => ( ))} + {footer} , ); - } + }; + + pushGroup(t("fontList.sceneFonts"), "group_1", sceneFilteredFonts); + pushGroup( + t("fontList.favoriteFonts"), + "group_favorites", + favoriteFilteredFonts, + ); + pushGroup( + t("fontList.availableFonts"), + "group_2", + availableFilteredFonts, + canLoadMoreFonts ? ( + + ) : ( + hasSearchForMore && ( +
+ {t("fontList.searchForMore")} +
+ ) + ), + ); + pushGroup( + t("fontList.searchResults"), + "group_search", + searchMatches, + hiddenSearchMatchCount > 0 && ( +
+ {t("fontList.moreResults", { count: hiddenSearchMatchCount })} +
+ ), + ); + pushGroup(t("fontList.didYouMean"), "group_suggestions", searchSuggestions); return ( - {stylesPanelMode === "full" && ( - + {isSearchShown && ( +
+ { + setLocalHoveredFontFamily(null); + onSearchChange(term); + }} + /> + {/* takes the search's place for the drag - on top of it rather + than instead of it, so that the query and the focus survive */} + {fontFavorites && dnd?.dragState && ( +
+ + {t( + favoriteFamilies.has(dnd.dragState.value) + ? "fontList.removeFromFavorites" + : "fontList.addToFavorites", + )} +
+ )} +
)} - {groups.length ? groups : null} + {groups} {dnd && ( + + {t("fontList.topPicksTip")} + + ) : ( + fontPickerTip + ) + } onReset={onResetTopPicks} resetTitle={t("fontList.resetTopPicks")} /> diff --git a/packages/excalidraw/components/FontPicker/FontPickerListItem.tsx b/packages/excalidraw/components/FontPicker/FontPickerListItem.tsx new file mode 100644 index 0000000000..fee00f5d45 --- /dev/null +++ b/packages/excalidraw/components/FontPicker/FontPickerListItem.tsx @@ -0,0 +1,130 @@ +import { memo, useCallback } from "react"; + +import { getFontFamilyString } from "@excalidraw/common"; + +import type { FontFamily } from "@excalidraw/common"; + +import { DropDownMenuItemBadge } from "../dropdownMenu/DropdownMenuItem"; + +import MenuItemContent from "../dropdownMenu/DropdownMenuItemContent"; +import { getDropdownMenuItemClassName } from "../dropdownMenu/common"; +import { RetryIcon } from "../icons"; + +import { useFontPickerDnD } from "./fontTopPicksDnD"; + +import type { FontDescriptor } from "./useFontCatalog"; + +interface FontPickerListItemProps { + font: FontDescriptor; + isHovered: boolean; + isSelected: boolean; + /** the callbacks must be stable - a changed one re-renders every row */ + onSelect: (fontFamily: FontFamily) => void; + onHover: (fontFamily: FontFamily) => void; + setItemRef: (fontFamily: FontFamily, node: HTMLButtonElement | null) => void; +} + +const FONT_DESCRIPTOR_KEYS: readonly (keyof FontDescriptor)[] = [ + "value", + "text", + "icon", + "status", + "deprecated", +]; + +const getFontStatusClassName = (status: FontDescriptor["status"]) => + status ? ` FontPicker__font--${status}` : ""; + +const renderRetryIcon = (isLoading: boolean) => ( + +); + +const FontPickerListItemComponent = ({ + font, + isHovered, + isSelected, + onSelect, + onHover, + setItemRef, +}: FontPickerListItemProps) => { + const dnd = useFontPickerDnD(); + const isUnsupported = font.status === "unsupported"; + + const setRef = useCallback( + (node: HTMLButtonElement | null) => setItemRef(font.value, node), + [font.value, setItemRef], + ); + + return ( + + ); +}; + +/** + * A row re-renders only when what it shows changed. The list can get long + * ("Browse more fonts"), and it re-renders on every move of the highlight and + * on every font which registers. + */ +export const FontPickerListItem = memo( + FontPickerListItemComponent, + (prev, next) => + prev.isHovered === next.isHovered && + prev.isSelected === next.isSelected && + prev.onSelect === next.onSelect && + prev.onHover === next.onHover && + prev.setItemRef === next.setItemRef && + // the descriptors are rebuilt along with the list (the badge follows + // `deprecated`) + FONT_DESCRIPTOR_KEYS.every((key) => prev.font[key] === next.font[key]), +); diff --git a/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx b/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx index 9000b1fb23..2b1f67bf0d 100644 --- a/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx +++ b/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx @@ -2,7 +2,7 @@ import { Popover } from "radix-ui"; import { MOBILE_ACTION_BUTTON_BG } from "@excalidraw/common"; -import type { FontFamilyValues } from "@excalidraw/element/types"; +import type { FontFamily } from "@excalidraw/common"; import { t } from "../../i18n"; import { IconButton } from "../IconButton"; @@ -11,7 +11,7 @@ import { TextIcon } from "../icons"; import { useExcalidrawSetAppState } from "../App"; interface FontPickerTriggerProps { - selectedFontFamily: FontFamilyValues | null; + selectedFontFamily: FontFamily | null; isOpened?: boolean; compactMode?: boolean; } diff --git a/packages/excalidraw/components/FontPicker/fontProviderInfo.test.tsx b/packages/excalidraw/components/FontPicker/fontProviderInfo.test.tsx new file mode 100644 index 0000000000..a87309bc39 --- /dev/null +++ b/packages/excalidraw/components/FontPicker/fontProviderInfo.test.tsx @@ -0,0 +1,119 @@ +import { FONT_FAMILY } from "@excalidraw/common"; + +import { + getFontPreviewText, + getProvidedFontKind, + loadFontKind, + loadFontPreviewText, +} from "./fontProviderInfo"; + +import type { FontProviders } from "../../types"; + +// the cache is module-wide - each test uses its own families +const providers = ( + getPreviewText?: (familyName: string) => string | Promise, +): FontProviders => ({ + google: { + icon: , + resolve: vi.fn(), + availableFonts: [], + getPreviewText, + }, +}); + +describe("font preview text", () => { + it("caches a synchronous answer right away", () => { + const getPreviewText = vi.fn(() => "あ"); + expect( + loadFontPreviewText("google:Sync JP", providers(getPreviewText)), + ).toBe(null); + expect(getFontPreviewText("google:Sync JP")).toBe("あ"); + expect(getPreviewText).toHaveBeenCalledWith("Sync JP"); + + // asked once + loadFontPreviewText("google:Sync JP", providers(getPreviewText)); + expect(getPreviewText).toHaveBeenCalledTimes(1); + }); + + it("shows Aa until an async answer settles, asking once", async () => { + let resolve!: (text: string) => void; + const getPreviewText = vi.fn( + () => new Promise((r) => (resolve = r)), + ); + const first = loadFontPreviewText( + "google:Async KR", + providers(getPreviewText), + ); + const second = loadFontPreviewText( + "google:Async KR", + providers(getPreviewText), + ); + expect(second).toBe(first); + expect(getPreviewText).toHaveBeenCalledTimes(1); + expect(getFontPreviewText("google:Async KR")).toBe("Aa"); + + resolve("한"); + await first; + expect(getFontPreviewText("google:Async KR")).toBe("한"); + }); + + it("falls back to Aa", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + + expect( + loadFontPreviewText( + FONT_FAMILY.Nunito, + providers(() => "x"), + ), + ).toBe(null); + expect(getFontPreviewText(FONT_FAMILY.Nunito)).toBe("Aa"); + + loadFontPreviewText( + "google:Empty", + providers(() => ""), + ); + expect(getFontPreviewText("google:Empty")).toBe("Aa"); + + loadFontPreviewText( + "other:Unknown", + providers(() => "x"), + ); + expect(getFontPreviewText("other:Unknown")).toBe("Aa"); + + loadFontPreviewText( + "google:Throws", + providers(() => { + throw new Error("boom"); + }), + ); + expect(getFontPreviewText("google:Throws")).toBe("Aa"); + + await loadFontPreviewText( + "google:Rejects", + providers(() => Promise.reject(new Error("boom"))), + ); + expect(getFontPreviewText("google:Rejects")).toBe("Aa"); + + expect(error).toHaveBeenCalledTimes(2); + error.mockRestore(); + }); +}); + +describe("font kind", () => { + it("keeps a kind we have an icon for, and no other", () => { + const fontProviders = { + google: { + resolve: vi.fn(), + availableFonts: [], + // a host's answer isn't necessarily one of ours + getKind: (familyName: string) => familyName.toLowerCase() as "code", + }, + }; + + loadFontKind("google:Code", fontProviders); + loadFontKind("google:Serif", fontProviders); + + expect(getProvidedFontKind("google:Code")).toBe("code"); + expect(getProvidedFontKind("google:Serif")).toBe(null); + }); +}); diff --git a/packages/excalidraw/components/FontPicker/fontProviderInfo.ts b/packages/excalidraw/components/FontPicker/fontProviderInfo.ts new file mode 100644 index 0000000000..d4fd0f0cbc --- /dev/null +++ b/packages/excalidraw/components/FontPicker/fontProviderInfo.ts @@ -0,0 +1,141 @@ +import { + isCustomFontFamily, + parseProviderFontFamily, +} from "@excalidraw/common"; + +import type { CustomFontFamily, FontFamily } from "@excalidraw/common"; + +import type { FontKind, FontProvider, FontProviders } from "../../types"; + +const DEFAULT_PREVIEW_TEXT = "Aa"; + +const FONT_KINDS: ReadonlySet = new Set([ + "hand-drawn", + "normal", + "code", + "heading", +]); + +/** + * What a provider says about a family, asked once per family and kept for the + * session - per qualified family, as a provider key always denotes the same + * font source. + */ +const createProviderAnswers = ({ + name, + getMethod, + normalize, +}: { + /** the provider's method, for the error message */ + name: string; + getMethod: ( + provider: FontProvider, + ) => ((familyName: string) => unknown) | undefined; + /** the answer to keep - `null` for none, and for one that can't be used */ + normalize: (answer: unknown) => T | null; +}) => { + const answers = new Map(); + const pendingAnswers = new Map>(); + + /** `null` where the provider gave none, or hasn't answered yet */ + const get = (fontFamily: FontFamily): T | null => + (isCustomFontFamily(fontFamily) && answers.get(fontFamily)) || null; + + /** + * Ask the family's provider. A synchronous answer is cached before this + * returns; a failed one caches none, so a broken provider isn't asked (and + * doesn't log) on every render. + * + * @returns `null` when there's nothing to wait for + */ + const load = ( + fontFamily: FontFamily, + fontProviders: FontProviders | undefined, + ): Promise | null => { + if (!isCustomFontFamily(fontFamily) || answers.has(fontFamily)) { + return null; + } + const pending = pendingAnswers.get(fontFamily); + if (pending) { + return pending; + } + + const parsed = parseProviderFontFamily(fontFamily); + // own-property check: "toString:Foo" must not match an inherited member + const provider = + parsed && fontProviders && Object.hasOwn(fontProviders, parsed.providerId) + ? fontProviders[parsed.providerId] + : undefined; + const method = provider && getMethod(provider); + if (!parsed || !provider || !method) { + // not cached - the provider may be configured later + return null; + } + + const onError = (error: unknown) => { + console.error(`${name} failed for "${fontFamily}"`, error); + answers.set(fontFamily, null); + }; + + let result: unknown; + try { + result = method.call(provider, parsed.familyName); + } catch (error) { + onError(error); + return null; + } + if (typeof (result as PromiseLike | null)?.then !== "function") { + answers.set(fontFamily, normalize(result)); + return null; + } + + const promise = Promise.resolve(result) + .then((answer) => { + answers.set(fontFamily, normalize(answer)); + }, onError) + .finally(() => pendingAnswers.delete(fontFamily)); + pendingAnswers.set(fontFamily, promise); + return promise; + }; + + return { get, load }; +}; + +const previewTexts = createProviderAnswers({ + name: "getPreviewText", + getMethod: (provider) => provider.getPreviewText, + normalize: (text) => + typeof text === "string" && text && text !== DEFAULT_PREVIEW_TEXT + ? text + : null, +}); + +const kinds = createProviderAnswers({ + name: "getKind", + getMethod: (provider) => provider.getKind, + normalize: (kind) => (FONT_KINDS.has(kind) ? (kind as FontKind) : null), +}); + +/** + * The preview text a family's provider gave it - `null` where it gave none + * (or hasn't answered yet). Stands in for an icon in the font list: a family + * named in Latin letters shows that it writes another script. + */ +export const getProvidedFontPreviewText = previewTexts.get; + +/** see `FontProvider.getPreviewText` */ +export const loadFontPreviewText = previewTexts.load; + +/** the glyph sample a font is previewed with in the top-picks strip - "Aa" + * until {@link loadFontPreviewText} settles */ +export const getFontPreviewText = (fontFamily: FontFamily) => + previewTexts.get(fontFamily) ?? DEFAULT_PREVIEW_TEXT; + +/** + * The kind a family's provider gave it - `null` where it gave none (or hasn't + * answered yet) + */ +export const getProvidedFontKind = kinds.get; + +/** see `FontProvider.getKind` */ +export const loadFontKind = kinds.load; diff --git a/packages/excalidraw/components/FontPicker/fontTopPicksDnD.ts b/packages/excalidraw/components/FontPicker/fontTopPicksDnD.ts index 4273ec5466..66753ab96b 100644 --- a/packages/excalidraw/components/FontPicker/fontTopPicksDnD.ts +++ b/packages/excalidraw/components/FontPicker/fontTopPicksDnD.ts @@ -1,9 +1,13 @@ import { createContext, useContext } from "react"; -import type { FontFamilyValues } from "@excalidraw/element/types"; +import { getFontFamilyString, isCustomFontFamily } from "@excalidraw/common"; + +import type { FontFamily } from "@excalidraw/common"; import { useTopPicksDnD } from "../TopPicksDnD/topPicksDnD"; +import { getFontPreviewText } from "./fontProviderInfo"; + import type { CreateTopPicksGhost, TopPicksDnD, @@ -16,7 +20,8 @@ import type { * The ghost lives outside the editor's CSS scope — the tile look is sampled * from a rendered strip button instead. */ -const createFontGhost: CreateTopPicksGhost = ({ +const createFontGhost: CreateTopPicksGhost = ({ + value, sourceEl, stripEl, }) => { @@ -43,7 +48,20 @@ const createFontGhost: CreateTopPicksGhost = ({ tile.style.borderRadius = templateStyle.borderTopLeftRadius; const icon = sourceEl.querySelector("svg"); - if (icon) { + // picks with a glyph sample, and custom fonts (pinned as a sample) dragged + // from the list + const hasSample = isPick + ? !!sourceEl.querySelector(".FontPicker__top-pick-sample") + : isCustomFontFamily(value); + if (hasSample) { + const sample = ownerDocument.createElement("span"); + sample.textContent = getFontPreviewText(value); + // the ghost is outside the editor's CSS scope + sample.style.fontFamily = getFontFamilyString({ fontFamily: value }); + sample.style.fontSize = "1rem"; + sample.style.lineHeight = "1"; + tile.appendChild(sample); + } else if (icon) { const templateIconRect = template .querySelector("svg") ?.getBoundingClientRect(); @@ -53,19 +71,6 @@ const createFontGhost: CreateTopPicksGhost = ({ iconClone.style.height = `${templateIconRect.height}px`; } tile.appendChild(iconClone); - } else { - // a pick rendering a glyph sample instead of an icon - const sample = sourceEl.querySelector( - ".FontPicker__top-pick-sample", - ); - if (sample) { - const sampleClone = sample.cloneNode(true) as HTMLElement; - // the ghost is outside the editor's CSS scope - sampleClone.style.fontSize = - ownerWindow.getComputedStyle(sample).fontSize; - sampleClone.style.lineHeight = "1"; - tile.appendChild(sampleClone); - } } if (isPick) { @@ -85,26 +90,30 @@ const createFontGhost: CreateTopPicksGhost = ({ }; }; -export type FontPickerDnD = TopPicksDnD; +export type FontPickerDnD = TopPicksDnD; export const FontPickerDnDContext = createContext(null); export const useFontPickerDnD = () => useContext(FontPickerDnDContext); -/** pinning fonts from the font picker list to the top-picks strip, and - * reordering the strip */ +/** pinning fonts from the font picker list to the top-picks strip, + * reordering the strip, and dropping fonts onto the favorites drop zone */ export const useFontTopPicksDnD = ({ enabled, picks, onPicksChange, + onFavoriteToggle, }: { enabled: boolean; - picks: readonly FontFamilyValues[]; - onPicksChange: (picks: FontFamilyValues[]) => void; + picks: readonly FontFamily[]; + onPicksChange: (picks: FontFamily[]) => void; + /** a font got dropped on the favorites drop zone */ + onFavoriteToggle?: (fontFamily: FontFamily) => void; }): FontPickerDnD => useTopPicksDnD({ enabled, picks, onPicksChange, createGhost: createFontGhost, + onDropZoneDrop: onFavoriteToggle, }); diff --git a/packages/excalidraw/components/FontPicker/keyboardNavHandlers.ts b/packages/excalidraw/components/FontPicker/keyboardNavHandlers.ts index 16ffa7c45f..17a503c815 100644 --- a/packages/excalidraw/components/FontPicker/keyboardNavHandlers.ts +++ b/packages/excalidraw/components/FontPicker/keyboardNavHandlers.ts @@ -1,5 +1,6 @@ import { KEYS } from "@excalidraw/common"; +import type { FontFamily } from "@excalidraw/common"; import type { Node } from "@excalidraw/common"; import { type FontDescriptor } from "./FontPickerList"; @@ -10,8 +11,8 @@ interface FontPickerKeyNavHandlerProps { hoveredFont: Node | undefined; filteredFonts: Node[]; onClose: () => void; - onSelect: (value: number) => void; - onHover: (value: number) => void; + onSelect: (value: FontFamily) => void; + onHover: (value: FontFamily) => void; } export const fontPickerKeyHandler = ({ diff --git a/packages/excalidraw/components/FontPicker/useFontCatalog.tsx b/packages/excalidraw/components/FontPicker/useFontCatalog.tsx new file mode 100644 index 0000000000..45486e7568 --- /dev/null +++ b/packages/excalidraw/components/FontPicker/useFontCatalog.tsx @@ -0,0 +1,588 @@ +import { + useCallback, + useLayoutEffect, + useMemo, + useReducer, + useState, + type JSX, +} from "react"; + +import { + arrayToList, + createProviderFontFamily, + FONT_FAMILY, + getFontFamilyString, + isCustomFontFamily, + parseProviderFontFamily, +} from "@excalidraw/common"; + +import type { CustomFontFamily, FontFamily } from "@excalidraw/common"; + +import type { ValueOf } from "@excalidraw/common/utility-types"; + +import { t } from "../../i18n"; +import { DropDownMenuItemBadgeType } from "../dropdownMenu/DropdownMenuItem"; +import { + FontFamilyCodeIcon, + FontFamilyHeadingIcon, + FontFamilyNormalIcon, + FreedrawIcon, +} from "../icons"; + +import { + getProvidedFontKind, + getProvidedFontPreviewText, + loadFontKind, + loadFontPreviewText, +} from "./fontProviderInfo"; + +import type { Fonts } from "../../fonts"; + +import type { FontKind, FontProviders, ProvidedFont } from "../../types"; +import type { RegisteredFont } from "../../fonts"; + +import type { ProviderSearchResult } from "./useFontSearch"; +import type { MoreFont } from "./useMoreFonts"; + +/** + * Our own fonts lead the available ones, in this order - what a host's + * providers offer comes after them. + */ +const LEADING_FONT_FAMILIES: readonly FontFamily[] = [ + FONT_FAMILY.Excalifont, + FONT_FAMILY.Nunito, + FONT_FAMILY["Comic Shanns"], + FONT_FAMILY["Lilita One"], +]; + +/** shared by all providers, the rest is left to narrowing down the search */ +const SEARCH_MATCHES_LIMIT = 10; +const SEARCH_SUGGESTIONS_LIMIT = 5; + +/** + * Up to `total` items, slots dealt round-robin so every list gets an equal + * share - one running short passes its slots on to the rest. Each list keeps + * its own order and stays contiguous. + */ +const takeFairShare = (lists: readonly (readonly T[])[], total: number) => { + const slots = lists.map(() => 0); + for (let remaining = total, dealt = true; remaining > 0 && dealt; ) { + dealt = false; + for (let i = 0; i < lists.length && remaining > 0; i++) { + if (slots[i] < lists[i].length) { + slots[i]++; + remaining--; + dealt = true; + } + } + } + return lists.flatMap((list, i) => list.slice(0, slots[i])); +}; + +export interface FontDescriptor { + value: FontFamily; + icon: JSX.Element; + text: string; + status?: "failed" | "loading" | "unsupported"; + deprecated?: true; + badge?: { + type: ValueOf; + placeholder: string; + }; +} + +// one element per family and text: a row re-renders when its icon changes +const glyphIcons = new Map(); + +/** the family's preview text, written in the family - see `getPreviewText` */ +const getGlyphIcon = (fontFamily: CustomFontFamily, text: string) => { + const key = `${fontFamily}\n${text}`; + let icon = glyphIcons.get(key); + if (!icon) { + icon = ( + + {text} + + ); + glyphIcons.set(key, icon); + } + return icon; +}; + +/** the icons our own fonts have, for a provider's family of the same kind */ +const FONT_KIND_ICONS: Record = { + "hand-drawn": FreedrawIcon, + normal: FontFamilyNormalIcon, + code: FontFamilyCodeIcon, + heading: FontFamilyHeadingIcon, +}; + +/** + * A custom family goes by what its provider says about it: a sample of its + * script, else the icon of its kind, else the provider's own icon. + */ +export const getFontFamilyIcon = ( + fontFamily: FontFamily, + icons?: Record, +): JSX.Element => { + if (isCustomFontFamily(fontFamily)) { + const previewText = getProvidedFontPreviewText(fontFamily); + if (previewText) { + return getGlyphIcon(fontFamily, previewText); + } + const kind = getProvidedFontKind(fontFamily); + if (kind) { + return FONT_KIND_ICONS[kind]; + } + const parsed = parseProviderFontFamily(fontFamily); + const icon = parsed ? icons?.[parsed.providerId]?.icon : undefined; + if (icon) { + return icon; + } + } + + switch (fontFamily) { + case FONT_FAMILY.Excalifont: + case FONT_FAMILY.Virgil: + return FreedrawIcon; + case FONT_FAMILY.Nunito: + case FONT_FAMILY.Helvetica: + return FontFamilyNormalIcon; + case FONT_FAMILY["Lilita One"]: + return FontFamilyHeadingIcon; + case FONT_FAMILY["Comic Shanns"]: + case FONT_FAMILY.Cascadia: + return FontFamilyCodeIcon; + default: + return FontFamilyNormalIcon; + } +}; + +/** `{ id, label }` for both forms a provider may give - see `ProvidedFont` */ +export const toProvidedFont = (font: ProvidedFont) => + typeof font === "string" ? { id: font, label: font } : font; + +/** whether a provider's (host-supplied) entry is usable at all */ +const isProvidedFont = (font: unknown): font is ProvidedFont => + (typeof font === "string" && !!font) || + (typeof font === "object" && + font !== null && + typeof (font as { id?: unknown }).id === "string" && + !!(font as { id: string }).id && + typeof (font as { label?: unknown }).label === "string"); + +/** the provider's entries as `{ id, label }`, dropping malformed ones */ +export const getProvidedFonts = (fonts: readonly unknown[]) => + fonts.filter(isProvidedFont).map(toProvidedFont); + +/** + * The name to show for a family. A custom one goes by the label its resolver + * gave (see `FontDefinition.label`), else by the family part of its id. + */ +export const getFontFamilyLabel = ( + fontFamily: FontFamily, + registeredFont: RegisteredFont | undefined, +) => { + if (isCustomFontFamily(fontFamily)) { + return ( + registeredFont?.label ?? + parseProviderFontFamily(fontFamily)?.familyName ?? + fontFamily + ); + } + + return ( + Object.entries(FONT_FAMILY).find(([, id]) => id === fontFamily)?.[0] ?? + registeredFont?.fontFaces[0]?.family ?? + "Unknown" + ); +}; + +interface FontCatalogOptions { + fonts: Fonts; + fontProviders?: FontProviders; + registeredFonts: Fonts["registered"]; + failedResolutions: ReadonlyMap; + selectedFontFamily: FontFamily | null; + hoveredFontFamily: FontFamily | null; + /** the user's favorites - see `ExcalidrawProps.fontFavorites` */ + favoriteFamilies: ReadonlySet; + /** fonts loaded on demand, in the order they arrived - see `useMoreFonts` */ + moreFonts: readonly MoreFont[]; + resolvingFamily: CustomFontFamily | null; + searchTerm: string; + searchResults: readonly ProviderSearchResult[]; + showDeprecatedFonts: boolean; +} + +export const useFontCatalog = ({ + fonts, + fontProviders, + registeredFonts, + failedResolutions, + selectedFontFamily, + hoveredFontFamily, + favoriteFamilies, + moreFonts, + resolvingFamily, + searchTerm, + searchResults, + showDeprecatedFonts, +}: FontCatalogOptions) => { + // a hover preview rewrites the selection's family, so the scene groups follow + // the registry only while there is none (and catch up once it ends) + const [sceneRegisteredFonts, setSceneRegisteredFonts] = + useState(registeredFonts); + if (hoveredFontFamily == null && sceneRegisteredFonts !== registeredFonts) { + setSceneRegisteredFonts(registeredFonts); + } + + // the families of the elements on canvas - the current one (what the next + // text gets) isn't the scene's until an element uses it + const sceneFamilies = useMemo( + () => new Set(fonts.getSceneFamilies()), + // refresh after selection without recalculating on hover. `registeredFonts` + // additionally refreshes the groups when a scene-only custom family arrives + // while the picker is open (i.e. collab, paste), registering on load + // eslint-disable-next-line react-hooks/exhaustive-deps + [selectedFontFamily, sceneRegisteredFonts], + ); + + const getCustomFontStatus = useCallback( + (family: CustomFontFamily) => { + if (resolvingFamily === family) { + return "loading" as const; + } + const parsed = parseProviderFontFamily(family); + // own-property check: "toString:Foo" must not match an inherited + // `Object.prototype` member as a provider + if ( + !parsed || + !fontProviders || + !Object.hasOwn(fontProviders, parsed.providerId) + ) { + return "unsupported" as const; + } + return failedResolutions.has(family) ? ("failed" as const) : undefined; + }, + [fontProviders, failedResolutions, resolvingFamily], + ); + + const resultFamilies = useMemo( + () => + new Set( + searchResults.flatMap(({ providerId, fonts }) => + getProvidedFonts(fonts).map(({ id }) => + createProviderFontFamily(providerId, id), + ), + ), + ), + [searchResults], + ); + + // what a provider says about a family arrives after the row it changes the + // icon of + const [providerInfoVersion, onProviderInfoChange] = useReducer( + (version: number) => version + 1, + 0, + ); + const getIcon = useMemo(() => { + // a new function per version: the lists below rebuild with the new icons + void providerInfoVersion; + return (fontFamily: FontFamily) => + getFontFamilyIcon(fontFamily, fontProviders); + }, [fontProviders, providerInfoVersion]); + + const { allFonts, moreOnlyFamilies } = useMemo(() => { + const descriptors = new Map(); + // loaded on demand, and listed for no other reason + const moreOnlyFamilies = new Set(); + + for (const [providerId, provider] of Object.entries(fontProviders ?? {})) { + for (const { id, label } of getProvidedFonts(provider.availableFonts)) { + const familyId = createProviderFontFamily(providerId, id); + descriptors.set(familyId, { + value: familyId, + icon: getIcon(familyId), + text: label, + status: getCustomFontStatus(familyId), + }); + } + } + + for (const familyId of [ + ...sceneFamilies, + // listed whether or not their provider (still) offers them + ...favoriteFamilies, + // the current family may be in no element yet (i.e. found by search + // and picked with nothing on canvas) - it must still be listed. One + // loaded on demand is, and keeps its place there + ...(selectedFontFamily != null && + !moreFonts.some((font) => font.value === selectedFontFamily) + ? [selectedFontFamily] + : []), + // a search result resolves in place rather than jumping into the list + ...(resolvingFamily && !resultFamilies.has(resolvingFamily) + ? [resolvingFamily] + : []), + ]) { + if (!isCustomFontFamily(familyId) || descriptors.has(familyId)) { + continue; + } + descriptors.set(familyId, { + value: familyId, + icon: getIcon(familyId), + text: getFontFamilyLabel(familyId, registeredFonts.get(familyId)), + status: getCustomFontStatus(familyId), + }); + } + + for (const { value, text } of moreFonts) { + if (!descriptors.has(value)) { + moreOnlyFamilies.add(value); + descriptors.set(value, { + value, + icon: getIcon(value), + text, + status: getCustomFontStatus(value), + }); + } + } + + for (const [familyId, registeredFont] of registeredFonts) { + const { metadata } = registeredFont; + if (metadata.private || metadata.fallback) { + continue; + } + // registration alone does not earn a custom family a place in the list - + // it gets one from `availableFonts` or from being used in the scene. + // Listing whatever is registered would instead grow the list with every + // previewed or searched family, and permanently so - the registry is + // page-global and never evicts. + if (isCustomFontFamily(familyId) && !descriptors.has(familyId)) { + continue; + } + + const fontDescriptor: FontDescriptor = { + value: familyId, + icon: getIcon(familyId), + // an offered custom font keeps the label its provider offered it by + text: + descriptors.get(familyId)?.text ?? + getFontFamilyLabel(familyId, registeredFont), + }; + + if (metadata.deprecated) { + fontDescriptor.deprecated = metadata.deprecated; + fontDescriptor.badge = { + type: DropDownMenuItemBadgeType.RED, + placeholder: t("fontList.badge.old"), + }; + } + + descriptors.set(familyId, fontDescriptor); + } + + return { + allFonts: Array.from(descriptors.values()).sort((a, b) => + a.text.toLowerCase() > b.text.toLowerCase() ? 1 : -1, + ), + moreOnlyFamilies, + }; + }, [ + moreFonts, + registeredFonts, + fontProviders, + getCustomFontStatus, + resolvingFamily, + resultFamilies, + sceneFamilies, + favoriteFamilies, + selectedFontFamily, + getIcon, + ]); + + // a font is listed once: with the scene's, else among the favorites, else + // among the available ones + const sceneFonts = useMemo( + () => allFonts.filter((font) => sceneFamilies.has(font.value)), + [allFonts, sceneFamilies], + ); + const favoriteFonts = useMemo( + () => + allFonts.filter( + (font) => + favoriteFamilies.has(font.value) && !sceneFamilies.has(font.value), + ), + [allFonts, favoriteFamilies, sceneFamilies], + ); + // Ours lead (the current ones, then the deprecated ones), a host's follow + // by name, and what got loaded on demand comes last in the order it + // arrived - so that loading more never moves a font listed before. + const availableFonts = useMemo(() => { + const available = allFonts.filter( + (font) => + !sceneFamilies.has(font.value) && + !favoriteFamilies.has(font.value) && + // the current font is listed even when deprecated + (showDeprecatedFonts || + !font.deprecated || + font.value === selectedFontFamily), + ); + const byValue = new Map(available.map((font) => [font.value, font])); + const leading = LEADING_FONT_FAMILIES.flatMap( + (fontFamily) => byValue.get(fontFamily) ?? [], + ); + const deprecated = available.filter( + (font) => font.deprecated && !leading.includes(font), + ); + const more = moreFonts.flatMap(({ value }) => + moreOnlyFamilies.has(value) ? byValue.get(value) ?? [] : [], + ); + const placed = new Set([...leading, ...deprecated, ...more]); + + return [ + ...leading, + ...deprecated, + ...available.filter((font) => !placed.has(font)), + ...more, + ]; + }, [ + allFonts, + moreFonts, + moreOnlyFamilies, + sceneFamilies, + favoriteFamilies, + showDeprecatedFonts, + selectedFontFamily, + ]); + const filteredFontDescriptors = useMemo( + () => + [...sceneFonts, ...favoriteFonts, ...availableFonts].filter((font) => + font.text.toLowerCase().includes(searchTerm.toLowerCase()), + ), + [sceneFonts, favoriteFonts, availableFonts, searchTerm], + ); + const { searchMatches, hiddenSearchMatchCount, searchSuggestions } = + useMemo(() => { + const listed = new Set(filteredFontDescriptors.map((font) => font.value)); + const getDescriptors = (kind: ProviderSearchResult["kind"]) => + searchResults + .filter((result) => result.kind === kind) + .map(({ providerId, fonts }) => { + const descriptors: FontDescriptor[] = []; + for (const { id, label } of getProvidedFonts(fonts)) { + const familyId = createProviderFontFamily(providerId, id); + if (listed.has(familyId)) { + continue; + } + listed.add(familyId); + descriptors.push({ + value: familyId, + icon: getIcon(familyId), + text: label, + status: getCustomFontStatus(familyId), + }); + } + return descriptors; + }); + + const matches = getDescriptors("match"); + const searchMatches = takeFairShare(matches, SEARCH_MATCHES_LIMIT); + + return { + searchMatches, + hiddenSearchMatchCount: matches.flat().length - searchMatches.length, + searchSuggestions: + filteredFontDescriptors.length || searchMatches.length + ? [] + : takeFairShare( + getDescriptors("suggestion"), + SEARCH_SUGGESTIONS_LIMIT, + ), + }; + }, [filteredFontDescriptors, searchResults, getCustomFontStatus, getIcon]); + + // layout effect: a synchronous answer lands before paint, without flashing + // another icon first + useLayoutEffect(() => { + let isCurrent = true; + const getIconSource = (fontFamily: FontFamily) => + getProvidedFontPreviewText(fontFamily) ?? getProvidedFontKind(fontFamily); + /** @returns whether an answer came synchronously, and changed the icon */ + const load = (fontFamily: FontFamily) => { + const previous = getIconSource(fontFamily); + const hasChanged = () => getIconSource(fontFamily) !== previous; + const onSettled = () => { + if (isCurrent && hasChanged()) { + onProviderInfoChange(); + } + }; + loadFontPreviewText(fontFamily, fontProviders)?.then(onSettled); + loadFontKind(fontFamily, fontProviders)?.then(onSettled); + return hasChanged(); + }; + // `map`, not `some`: every family gets asked + const hasSyncAnswer = [...allFonts, ...searchMatches, ...searchSuggestions] + .map((font) => load(font.value)) + .includes(true); + if (hasSyncAnswer) { + onProviderInfoChange(); + } + return () => { + isCurrent = false; + }; + }, [allFonts, searchMatches, searchSuggestions, fontProviders]); + + const selectableFonts = useMemo( + () => + arrayToList( + [ + ...filteredFontDescriptors, + ...searchMatches, + ...searchSuggestions, + ].filter((font) => font.status !== "unsupported"), + ), + [filteredFontDescriptors, searchMatches, searchSuggestions], + ); + const sceneFilteredFonts = useMemo( + () => + filteredFontDescriptors.filter((font) => sceneFamilies.has(font.value)), + [filteredFontDescriptors, sceneFamilies], + ); + const favoriteFilteredFonts = useMemo( + () => + filteredFontDescriptors.filter( + (font) => + favoriteFamilies.has(font.value) && !sceneFamilies.has(font.value), + ), + [filteredFontDescriptors, favoriteFamilies, sceneFamilies], + ); + const availableFilteredFonts = useMemo( + () => + filteredFontDescriptors.filter( + (font) => + !sceneFamilies.has(font.value) && !favoriteFamilies.has(font.value), + ), + [filteredFontDescriptors, sceneFamilies, favoriteFamilies], + ); + + const listedFamilies = useMemo( + () => new Set(allFonts.map((font) => font.value)), + [allFonts], + ); + + return { + listedFamilies, + selectableFonts, + sceneFilteredFonts, + favoriteFilteredFonts, + availableFilteredFonts, + searchMatches, + hiddenSearchMatchCount, + searchSuggestions, + }; +}; diff --git a/packages/excalidraw/components/FontPicker/useFontResolution.ts b/packages/excalidraw/components/FontPicker/useFontResolution.ts new file mode 100644 index 0000000000..7478d73b1b --- /dev/null +++ b/packages/excalidraw/components/FontPicker/useFontResolution.ts @@ -0,0 +1,139 @@ +import { useCallback, useEffect, useRef, useState } from "react"; + +import { isCustomFontFamily } from "@excalidraw/common"; + +import type { CustomFontFamily, FontFamily } from "@excalidraw/common"; + +import { + restoreCaretPosition, + saveCaretPosition, +} from "../../hooks/useTextEditorFocus"; + +import type { Fonts } from "../../fonts"; + +/** + * Minimum time a retry stays in the loading state. A resolution served from the + * host's cache returns near-instantly, which would otherwise read as the retry + * never having run. + */ +const RETRY_FEEDBACK_DURATION = 500; + +const retryFeedbackDelay = (isRetry: boolean) => + isRetry + ? new Promise((resolve) => + setTimeout(resolve, RETRY_FEEDBACK_DURATION), + ) + : null; + +export type FontSelectionOptions = { + keepOpen?: boolean; +}; + +type FontResolution = { type: "family"; family: CustomFontFamily } | null; + +interface FontResolutionOptions { + fonts: Fonts; + registeredFonts: Fonts["registered"]; + failedResolutions: ReadonlyMap; + isEditingText: boolean; + onSelect: (fontFamily: FontFamily, options?: FontSelectionOptions) => void; +} + +export const useFontResolution = ({ + fonts, + registeredFonts, + failedResolutions, + isEditingText, + onSelect, +}: FontResolutionOptions) => { + const [searchTerm, setSearchTerm] = useState(""); + const [fontResolution, setFontResolution] = useState(null); + const inputRef = useRef(null); + const requestIdRef = useRef(0); + const resolvingFamily = + fontResolution?.type === "family" ? fontResolution.family : null; + + const select = useCallback( + (fontFamily: FontFamily, options?: FontSelectionOptions) => { + // an open popup keeps the focus + const savedCaret = + isEditingText && !options?.keepOpen ? saveCaretPosition() : null; + + onSelect(fontFamily, options); + + if (savedCaret) { + restoreCaretPosition(savedCaret); + } + }, + [isEditingText, onSelect], + ); + + const cancelResolution = useCallback(() => { + requestIdRef.current += 1; + setFontResolution(null); + }, []); + + // a `fontProviders` change swaps the `fonts` instance (see + // `AppFonts.onPropsUpdated`) - an in-flight resolution belongs to the old + // provider set and must not apply its selection (or call its provider + // callbacks) under the new one + useEffect(() => { + cancelResolution(); + }, [fonts, cancelResolution]); + + /** @returns whether the family got selected */ + const selectFontFamily = useCallback( + async (fontFamily: FontFamily) => { + const isRetry = + isCustomFontFamily(fontFamily) && failedResolutions.has(fontFamily); + + if (!isCustomFontFamily(fontFamily) || registeredFonts.has(fontFamily)) { + // applies right away - drop any in-flight resolution, so that its later + // result cannot override this (more recent) selection + cancelResolution(); + select(fontFamily, isRetry ? { keepOpen: true } : undefined); + return true; + } + + // last click wins, exactly as it does for registered families above - + // bumping the request id invalidates any in-flight resolution's + // selection, and the loading indicator moves to this row. The + // superseded resolver still settles registry-side (a resolution is a + // fact about the family, not about this click) + const requestId = ++requestIdRef.current; + const retryDelay = retryFeedbackDelay(isRetry); + setFontResolution({ type: "family", family: fontFamily }); + try { + const result = await fonts.registerCustomFamily(fontFamily); + await retryDelay; + + if (requestIdRef.current !== requestId || result.status !== "success") { + return false; + } + } finally { + if (requestIdRef.current === requestId) { + setFontResolution(null); + } + } + + select(fontFamily, isRetry ? { keepOpen: true } : undefined); + return true; + }, + [cancelResolution, failedResolutions, fonts, registeredFonts, select], + ); + + const onSearchChange = useCallback((term: string) => { + requestIdRef.current += 1; + setFontResolution(null); + setSearchTerm(term); + }, []); + + return { + inputRef, + searchTerm, + resolvingFamily, + selectFontFamily, + onSearchChange, + cancelResolution, + }; +}; diff --git a/packages/excalidraw/components/FontPicker/useFontSearch.ts b/packages/excalidraw/components/FontPicker/useFontSearch.ts new file mode 100644 index 0000000000..3b1de843a8 --- /dev/null +++ b/packages/excalidraw/components/FontPicker/useFontSearch.ts @@ -0,0 +1,102 @@ +import { useEffect, useMemo, useRef, useState } from "react"; + +import type { Fonts } from "../../fonts"; + +import type { FontProviders, FontSearchResult } from "../../types"; + +const SEARCH_DEBOUNCE = 200; + +export type ProviderSearchResult = FontSearchResult & { providerId: string }; + +interface FontSearchOptions { + fonts: Fonts; + fontProviders?: FontProviders; + searchTerm: string; +} + +/** the providers' `search` results for the current term, in provider order */ +export const useFontSearch = ({ + fonts, + fontProviders, + searchTerm, +}: FontSearchOptions) => { + // `null` marks a failed search + const [search, setSearch] = useState<{ + query: string; + results: Map; + } | null>(null); + // hosts may pass `fontProviders` inline - re-run on the provider set + // (`fonts`, see `AppFonts.onPropsUpdated`), not on every new object + const fontProvidersRef = useRef(fontProviders); + fontProvidersRef.current = fontProviders; + const query = searchTerm.trim(); + + useEffect(() => { + const providers = Object.entries(fontProvidersRef.current ?? {}).filter( + ([, provider]) => provider.search, + ); + if (!query || !providers.length) { + return; + } + + const controller = new AbortController(); + const settle = (providerId: string, result: FontSearchResult | null) => + setSearch((prev) => ({ + query, + results: new Map(prev?.query === query ? prev.results : undefined).set( + providerId, + result, + ), + })); + + const timeout = setTimeout(() => { + for (const [providerId, provider] of providers) { + Promise.resolve() + .then(() => provider.search!(query, { signal: controller.signal })) + .then((result) => { + if (!Array.isArray(result?.fonts)) { + throw new Error("expected { kind, fonts }"); + } + if (!controller.signal.aborted) { + settle(providerId, result); + } + }) + .catch((error) => { + if (!controller.signal.aborted) { + console.error( + `font search failed for provider "${providerId}"`, + error, + ); + settle(providerId, null); + } + }); + } + }, SEARCH_DEBOUNCE); + + return () => { + clearTimeout(timeout); + controller.abort(); + }; + }, [query, fonts]); + + return useMemo(() => { + const results: ProviderSearchResult[] = []; + let isSearching = false; + + for (const [providerId, provider] of Object.entries(fontProviders ?? {})) { + if (!provider.search) { + continue; + } + const result = + search?.query === query ? search.results.get(providerId) : undefined; + if (result) { + results.push({ ...result, providerId }); + } else if (result === undefined && query) { + // `null` is a failed search, which leaves nothing to wait for + isSearching = true; + } + } + + return { results, isSearching }; + }, [search, query, fontProviders]); +}; diff --git a/packages/excalidraw/components/FontPicker/useMoreFonts.ts b/packages/excalidraw/components/FontPicker/useMoreFonts.ts new file mode 100644 index 0000000000..fe38c03e4c --- /dev/null +++ b/packages/excalidraw/components/FontPicker/useMoreFonts.ts @@ -0,0 +1,244 @@ +import { + useCallback, + useEffect, + useMemo, + useReducer, + useRef, + useState, +} from "react"; + +import { createProviderFontFamily } from "@excalidraw/common"; + +import type { CustomFontFamily, FontFamily } from "@excalidraw/common"; + +import { getProvidedFonts } from "./useFontCatalog"; + +import type { Fonts } from "../../fonts"; +import type { FontProviders } from "../../types"; + +/** fonts asked for at a time - see `FontProvider.loadMore` */ +const PAGE_SIZE = 20; +/** pages asked for in a row while they bring nothing which isn't listed */ +const MAX_PAGES_PER_LOAD = 5; + +export type MoreFont = { value: CustomFontFamily; text: string }; + +interface MoreFontsOptions { + fonts: Fonts; + fontProviders?: FontProviders; + /** the fonts the picker lists as of now - loading skips them */ + listedFamiliesRef: React.RefObject>; +} + +/** what got loaded so far, and where each provider's paging stands */ +interface MoreFontsState { + moreFonts: readonly MoreFont[]; + /** + * fetched ahead and not listed yet: what tells whether there is anything to + * browse, and what the first "Browse more fonts" lists + */ + peeked: readonly MoreFont[]; + /** the look ahead is done - until then nothing is offered */ + isProbed: boolean; + /** + * the user asked for more at least once - from then on more gets loaded + * as they reach the end of the list + */ + isActive: boolean; + offsets: Map; + exhausted: ReadonlySet; + loaded: Set; +} + +/** + * Kept per `Fonts` instance, so that the fonts are still listed when the + * picker reopens - for as long as the editor and its set of providers live + * (a `fontProviders` change swaps the instance). + */ +const statesByFonts = new WeakMap(); + +const getMoreFontsState = (fonts: Fonts) => { + let state = statesByFonts.get(fonts); + if (!state) { + state = { + moreFonts: [], + peeked: [], + isProbed: false, + isActive: false, + offsets: new Map(), + exhausted: new Set(), + loaded: new Set(), + }; + statesByFonts.set(fonts, state); + } + return state; +}; + +/** + * Fonts loaded on demand from the providers able to page through what they + * have (`FontProvider.loadMore`), in the order they arrived - appended, never + * re-sorted, so that loading doesn't move the fonts listed before. + * + * Kept when the picker closes - see `statesByFonts`. + */ +export const useMoreFonts = ({ + fonts, + fontProviders, + listedFamiliesRef, +}: MoreFontsOptions) => { + const state = getMoreFontsState(fonts); + // the state lives outside of React + const [, rerender] = useReducer((count: number) => count + 1, 0); + const [isLoading, setIsLoading] = useState(false); + + const fontProvidersRef = useRef(fontProviders); + fontProvidersRef.current = fontProviders; + const controllerRef = useRef(null); + + // a page still on its way as the picker closes (or the `fonts` instance + // gets swapped) is dropped, and asked for again next time + useEffect( + () => () => { + controllerRef.current?.abort(); + controllerRef.current = null; + setIsLoading(false); + }, + [fonts], + ); + + const { exhausted, peeked, isProbed } = state; + const hasUnexhausted = useMemo( + () => + Object.entries(fontProviders ?? {}).some( + ([providerId, provider]) => + provider.loadMore && !exhausted.has(providerId), + ), + [fontProviders, exhausted], + ); + // offered only once we know there is a font to show for it + const hasMore = peeked.length > 0 || (isProbed && hasUnexhausted); + + /** + * The next fonts which aren't listed yet, paging on while a page holds + * nothing but listed ones (i.e. the most popular ones, which a host tends + * to offer up front). + * + * @returns `null` once aborted + */ + const fetchUnlisted = useCallback( + async (signal: AbortSignal) => { + const added: MoreFont[] = []; + const exhausted = new Set(state.exhausted); + for (let page = 0; page < MAX_PAGES_PER_LOAD && !added.length; page++) { + const next = Object.entries(fontProvidersRef.current ?? {}).find( + ([providerId, provider]) => + provider.loadMore && !exhausted.has(providerId), + ); + if (!next) { + break; + } + const [providerId, provider] = next; + const offset = state.offsets.get(providerId) ?? 0; + + let provided: readonly unknown[] = []; + try { + const result = await provider.loadMore!({ + offset, + limit: PAGE_SIZE, + signal, + }); + provided = Array.isArray(result) ? result : []; + } catch (error) { + if (!signal.aborted) { + // not asked again for as long as the list is kept + console.error( + `loading more fonts failed for provider "${providerId}"`, + error, + ); + } + } + if (signal.aborted) { + return null; + } + + state.offsets.set(providerId, offset + provided.length); + if (provided.length < PAGE_SIZE) { + exhausted.add(providerId); + } + for (const { id, label } of getProvidedFonts(provided)) { + const value = createProviderFontFamily(providerId, id); + if ( + !state.loaded.has(value) && + !listedFamiliesRef.current?.has(value) + ) { + state.loaded.add(value); + added.push({ value, text: label }); + } + } + } + if (exhausted.size !== state.exhausted.size) { + state.exhausted = exhausted; + } + return added; + }, + [state, listedFamiliesRef], + ); + + // Look ahead once, as the picker opens: a provider may have nothing beyond + // what's listed (i.e. it offers all of its fonts up front), and "Browse + // more fonts" would then bring nothing. + useEffect(() => { + if (state.isProbed || !hasUnexhausted || controllerRef.current) { + return; + } + const controller = new AbortController(); + controllerRef.current = controller; + fetchUnlisted(controller.signal).then((added) => { + if (controllerRef.current === controller) { + controllerRef.current = null; + if (added) { + state.peeked = added; + state.isProbed = true; + rerender(); + } + } + }); + }, [state, hasUnexhausted, fetchUnlisted]); + + const loadMore = useCallback(async () => { + if (controllerRef.current) { + return; + } + state.isActive = true; + // what the look ahead found comes first + if (state.peeked.length) { + state.moreFonts = [...state.moreFonts, ...state.peeked]; + state.peeked = []; + rerender(); + return; + } + + const controller = new AbortController(); + controllerRef.current = controller; + setIsLoading(true); + const added = await fetchUnlisted(controller.signal); + if (controllerRef.current === controller) { + controllerRef.current = null; + if (added?.length) { + state.moreFonts = [...state.moreFonts, ...added]; + } + setIsLoading(false); + rerender(); + } + }, [state, fetchUnlisted]); + + return { + moreFonts: state.moreFonts, + hasMore, + /** fonts got loaded on demand, and there are no more to load */ + isAtEnd: !hasMore && state.moreFonts.length > 0, + isLoading, + isActive: state.isActive, + loadMore, + }; +}; diff --git a/packages/excalidraw/components/FontPicker/useVisibleFontRegistration.ts b/packages/excalidraw/components/FontPicker/useVisibleFontRegistration.ts new file mode 100644 index 0000000000..f102bdee00 --- /dev/null +++ b/packages/excalidraw/components/FontPicker/useVisibleFontRegistration.ts @@ -0,0 +1,155 @@ +import { useCallback, useEffect, useRef } from "react"; + +import { isCustomFontFamily } from "@excalidraw/common"; + +import type { CustomFontFamily, FontFamily } from "@excalidraw/common"; + +import { type Fonts } from "../../fonts"; + +interface VisibleFontRegistrationOptions { + fonts: Fonts; + registeredFonts: Fonts["registered"]; + failedResolutions: ReadonlyMap; + /** + * without providers nothing is resolvable, so observing rows would only + * dispatch guaranteed-`unsupported` registrations - disabled, the hook + * costs nothing + */ + enabled: boolean; +} + +const noopRef = () => {}; + +/** + * Resolve custom fonts lazily, as their rows scroll into view, so each renders + * in its own typeface - resolving the whole catalog on open would fire one + * provider request per available font. + */ +export const useVisibleFontRegistration = ({ + fonts, + registeredFonts, + failedResolutions, + enabled, +}: VisibleFontRegistrationOptions) => { + const observerRef = useRef(null); + const fontItemRefs = useRef(new Map()); + const familiesByElement = useRef(new Map()); + + const shouldObserve = useCallback( + (family: FontFamily): family is CustomFontFamily => { + if (!isCustomFontFamily(family)) { + return false; + } + + // "registered" needs nothing and "failed" has its retry affordance. + // "loading" is still dispatched: the in-flight resolution may be a + // silent one (a probe or export, which never record failures), and + // joining it attaches the user-visible failure semantics this row needs + const status = fonts.getResolutionStatus(family); + return status !== "registered" && status !== "failed"; + }, + [fonts], + ); + + const setScrollContainerRef = useCallback( + (node: HTMLDivElement | null) => { + observerRef.current?.disconnect(); + observerRef.current = null; + + if (!node || typeof IntersectionObserver === "undefined") { + return; + } + + const observer = new IntersectionObserver( + (entries) => { + const visibleFamilies: CustomFontFamily[] = []; + for (const entry of entries) { + if (!entry.isIntersecting) { + continue; + } + + const family = familiesByElement.current.get(entry.target); + if (family && shouldObserve(family)) { + visibleFamilies.push(family); + } + } + + if (!visibleFamilies.length) { + return; + } + + // a repeat dispatch joins the pending resolution rather than + // re-running the resolver, so racing callbacks are cheap + void fonts.registerCustomFamilies(visibleFamilies).then((results) => { + for (const { family } of results) { + const element = fontItemRefs.current.get(family); + if (element) { + observerRef.current?.unobserve(element); + } + } + }); + }, + { + root: node, + rootMargin: "50px 0px", + }, + ); + observerRef.current = observer; + + for (const [family, element] of fontItemRefs.current) { + if (shouldObserve(family)) { + observer.observe(element); + } + } + }, + [fonts, shouldObserve], + ); + + const setFontItemRef = useCallback( + (family: FontFamily, node: HTMLButtonElement | null) => { + const previousNode = fontItemRefs.current.get(family); + if (previousNode) { + observerRef.current?.unobserve(previousNode); + familiesByElement.current.delete(previousNode); + fontItemRefs.current.delete(family); + } + + if (!node) { + return; + } + + fontItemRefs.current.set(family, node); + if (isCustomFontFamily(family)) { + familiesByElement.current.set(node, family); + } + if (shouldObserve(family)) { + observerRef.current?.observe(node); + } + }, + [shouldObserve], + ); + + useEffect(() => { + for (const [family, element] of fontItemRefs.current) { + if ( + isCustomFontFamily(family) && + (registeredFonts.has(family) || failedResolutions.has(family)) + ) { + observerRef.current?.unobserve(element); + } + } + }, [failedResolutions, registeredFonts]); + + useEffect( + () => () => { + observerRef.current?.disconnect(); + }, + [], + ); + + if (!enabled) { + return { setScrollContainerRef: noopRef, setFontItemRef: noopRef }; + } + + return { setScrollContainerRef, setFontItemRef }; +}; diff --git a/packages/excalidraw/components/ImageExportDialog.tsx b/packages/excalidraw/components/ImageExportDialog.tsx index 5d0e2bc137..2d4743ff7a 100644 --- a/packages/excalidraw/components/ImageExportDialog.tsx +++ b/packages/excalidraw/components/ImageExportDialog.tsx @@ -38,6 +38,7 @@ import "./ImageExportDialog.scss"; import type { ActionManager } from "../actions/manager"; +import type { FontResolvers } from "../fonts"; import type { AppClassProperties, BinaryFiles, UIAppState } from "../types"; export const ErrorCanvasPreview = () => { @@ -60,6 +61,7 @@ type ImageExportModalProps = { onExportImage: AppClassProperties["onExportImage"]; name: string; exportWithDarkMode: boolean; + fontResolvers: FontResolvers; }; const ImageExportModal = ({ @@ -70,6 +72,7 @@ const ImageExportModal = ({ onExportImage, name, exportWithDarkMode, + fontResolvers, }: ImageExportModalProps) => { const hasSelection = isSomeElementSelected( elementsSnapshot, @@ -145,6 +148,7 @@ const ImageExportModal = ({ padding: DEFAULT_EXPORT_PADDING, maxWidthOrHeight: Math.max(maxWidth, maxHeight), exportingFrame, + fontResolvers, }, }) .then(async (canvas) => { @@ -192,6 +196,7 @@ const ImageExportModal = ({ exportWithDarkMode, exportScale, embedScene, + fontResolvers, ]); return ( @@ -397,6 +402,7 @@ export const ImageExportDialog = ({ onExportImage, onCloseRequest, name, + fontResolvers, }: { appState: UIAppState; elements: readonly NonDeletedExcalidrawElement[]; @@ -405,6 +411,7 @@ export const ImageExportDialog = ({ onExportImage: AppClassProperties["onExportImage"]; onCloseRequest: () => void; name: string; + fontResolvers: FontResolvers; }) => { // we need to take a snapshot so that the exported state can't be modified // while the dialog is open @@ -425,6 +432,7 @@ export const ImageExportDialog = ({ onExportImage={onExportImage} name={name} exportWithDarkMode={appState.exportWithDarkMode} + fontResolvers={fontResolvers} /> ); diff --git a/packages/excalidraw/components/LayerUI.tsx b/packages/excalidraw/components/LayerUI.tsx index f3ce2ec58a..a36976fa3c 100644 --- a/packages/excalidraw/components/LayerUI.tsx +++ b/packages/excalidraw/components/LayerUI.tsx @@ -239,6 +239,7 @@ const LayerUI = ({ onExportImage={onExportImage} onCloseRequest={() => setAppState({ openDialog: null })} name={app.getName()} + fontResolvers={app.fonts.instance.fontResolvers} /> ); }; diff --git a/packages/excalidraw/components/QuickSearch.tsx b/packages/excalidraw/components/QuickSearch.tsx index 83b65183fe..ac056ba594 100644 --- a/packages/excalidraw/components/QuickSearch.tsx +++ b/packages/excalidraw/components/QuickSearch.tsx @@ -21,7 +21,7 @@ export const QuickSearch = React.forwardRef( className="QuickSearch__input" type="text" placeholder={placeholder} - onChange={(e) => onChange(e.target.value.trim().toLowerCase())} + onChange={(e) => onChange(e.target.value.trim())} /> ); diff --git a/packages/excalidraw/components/ScrollableList.tsx b/packages/excalidraw/components/ScrollableList.tsx index 60ca1ad6c0..76ca164199 100644 --- a/packages/excalidraw/components/ScrollableList.tsx +++ b/packages/excalidraw/components/ScrollableList.tsx @@ -1,5 +1,5 @@ import clsx from "clsx"; -import { Children } from "react"; +import { Children, forwardRef } from "react"; import "./ScrollableList.scss"; @@ -9,16 +9,18 @@ interface ScrollableListProps { children: React.ReactNode; } -export const ScrollableList = ({ - className, - placeholder, - children, -}: ScrollableListProps) => { - const isEmpty = !Children.count(children); +export const ScrollableList = forwardRef( + ({ className, placeholder, children }, ref) => { + const isEmpty = !Children.count(children); - return ( -
- {isEmpty ?
{placeholder}
: children} -
- ); -}; + return ( +
+ {isEmpty ?
{placeholder}
: children} +
+ ); + }, +); diff --git a/packages/excalidraw/components/TopPicksDnD/TopPicksTip.tsx b/packages/excalidraw/components/TopPicksDnD/TopPicksTip.tsx index 8958ebeae5..be674bbdd2 100644 --- a/packages/excalidraw/components/TopPicksDnD/TopPicksTip.tsx +++ b/packages/excalidraw/components/TopPicksDnD/TopPicksTip.tsx @@ -6,7 +6,8 @@ import { t } from "../../i18n"; /** * "drag to pin" hint shown in a picker popup whose top picks are - * customizable — with a reset link while the picks are customized + * customizable — with a reset link while the picks are customized. A host may + * put its own text in place of the hint (see `fontPickerTip`), or none. */ export const TopPicksTip = ({ className, @@ -15,7 +16,7 @@ export const TopPicksTip = ({ resetTitle, }: { className?: string; - tip: string; + tip: React.ReactNode; /** present only while the top picks are customized */ onReset?: () => void; resetTitle: string; @@ -24,7 +25,7 @@ export const TopPicksTip = ({ {tip} {onReset && ( <> - {" · "} + {tip != null && tip !== false && tip !== "" && " · "}