feat(packages/excalidraw): Extended fonts support (#11601)

* 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 <noreply@anthropic.com>

* 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 `<provider>:<family>`. 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-<slug>-<hash>`), 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-<hash>.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 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 12:42:28 +00:00
1 parent 4a12effe9a
commit ea74995af2
90 files changed
+12796 -916

No files matched your search

+2
View File
@@ -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 = () => {
})}
>
<Excalidraw
fontProviders={fontProviders}
viewportStatusFrame={viewportStatusFrame}
userToFollow={userToFollow}
onChange={onChange}
+28
View File
@@ -0,0 +1,28 @@
/**
* Google Fonts on excalidraw.com: the resolver alone.
*
* The font picker offers no Google fonts. But a text using one - from an
* `.excalidraw` file, a shared link, or a paste from another app such as
* Excalidraw+ - renders in that font, and the picker lists it for as long as
* the scene uses it.
*/
import {
createGoogleFontProvider,
GOOGLE_FONT_PROVIDER_KEY,
registerFontResolvers,
} from "@excalidraw/excalidraw/fonts/google";
import type { FontProviders } from "@excalidraw/excalidraw";
const provider = createGoogleFontProvider({ offerInPicker: false });
export const resolveGoogleFont = provider.resolve;
// for the image exports made outside of the editor, which doesn't share its
// `fontProviders` with them
registerFontResolvers({ [GOOGLE_FONT_PROVIDER_KEY]: resolveGoogleFont });
/** `fontProviders` for `<Excalidraw>` */
export const fontProviders: FontProviders = {
[GOOGLE_FONT_PROVIDER_KEY]: provider,
};
+26
View File
@@ -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",
+1
View File
@@ -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",
+150 -7
View File
@@ -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<string, string>();
/** 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<keyof typeof FONT_FAMILY_FALLBACKS> => {
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;
+83 -14
View File
@@ -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<number, FontMetadata> = {
/**
* 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<Record<number, FontMetadata>> = {
[FONT_FAMILY.Excalifont]: {
metrics: {
unitsPerEm: 1000,
@@ -133,6 +142,39 @@ export const FONT_METADATA: Record<number, FontMetadata> = {
},
};
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<CustomFontFamily, FontMetadata>();
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, "fontFamily" | "lineHeight">,
): ExcalidrawTextElement["lineHeight"] | null => {
if (
!isCustomFontFamily(element.fontFamily) ||
!isFontMetadataAvailable(element.fontFamily)
) {
return null;
}
const lineHeight = getLineHeight(element.fontFamily);
return element.lineHeight === lineHeight ? null : lineHeight;
};
+18 -4
View File
@@ -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;
};
+162
View File
@@ -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:</style><x>",
"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, /,
);
});
});
+3 -2
View File
@@ -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;
+12
View File
@@ -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] &&
+2
View File
@@ -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;
+24 -3
View File
@@ -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) {
+4 -3
View File
@@ -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;
+10 -11
View File
@@ -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
+48 -3
View File
@@ -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", () => {
@@ -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";
+14
View File
@@ -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 `"<provider key>:<font id>"` 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 | "<provider key>:<font id>"`) 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.
@@ -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 {
@@ -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(
<Excalidraw
onDuplicate={(nextElements, prevElements) => {
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);
});
});
});
@@ -97,6 +97,7 @@ export const actionDuplicateSelection = register({
}
}
app.fonts.onElementsDuplicated(duplicatedElements);
app.duplicate.advanceListMarkers(duplicatedElements);
return {
@@ -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) {
+425 -104
View File
@@ -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 = <T extends ExcalidrawElement>(
element: T,
cachedElement: ExcalidrawElement,
keys: readonly string[],
) => {
const current = element as Record<string, unknown>;
const cached = cachedElement as Record<string, unknown>;
const update: Record<string, unknown> = {};
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<T>) : 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<NonDeletedExcalidrawElement>);
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<string>();
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<string>();
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<ElementsMap>(new Map());
const prevSelectedFontFamilyRef = useRef<number | null>(null);
const prevSelectedFontFamilyRef = useRef<FontFamily | null>(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<ChangeFontFamilyData>({});
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" && (
<legend>{t("labels.fontFamily")}</legend>
)}
<FontPicker
isOpened={appState.openPopup === "fontFamily"}
isOpened={isOpened}
selectedFontFamily={selectedFontFamily}
hoveredFontFamily={appState.currentHoveredFontFamily}
topPicks={appState.fontTopPicks}
compactMode={stylesPanelMode !== "full"}
onTopPicksChange={(fontTopPicks) => 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
}
}
+1
View File
@@ -29,6 +29,7 @@ export type ActionResult =
files?: BinaryFiles | null;
captureUpdate: CaptureUpdateActionType;
replaceFiles?: boolean;
loadFonts?: boolean;
}
| false;
@@ -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() });
@@ -542,5 +542,7 @@ export class AppDuplicate {
this.app.maybeCacheVisibleGaps(event, selectedElements, true);
this.app.maybeCacheReferenceSnapPoints(event, selectedElements, true);
});
this.app.fonts.onElementsDuplicated(duplicatedElements);
};
}
+614
View File
@@ -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<FontFamily>();
/**
* 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<typeof setTimeout> | 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<AppState, "currentItemFontFamily"> | 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<FontFamily>();
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 },
);
};
}
@@ -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) {
+37 -46
View File
@@ -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<AppProps, AppState> {
}
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<AppProps, AppState> {
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<AppProps, AppState> {
pendingFlowchartNodes:
this.flowchart.pendingNodes,
theme: this.state.theme,
isFontBlocked: this.fonts.isFontBlocked,
...this.getRenderOverrideConfig(),
}}
/>
@@ -2811,6 +2814,7 @@ class App extends React.Component<AppProps, AppState> {
{
name: this.getName(),
exportingFrame: opts.exportingFrame,
fontResolvers: this.fonts.instance.fontResolvers,
renderEnvironment: this.renderEnvironment,
},
)
@@ -3160,6 +3164,12 @@ class App extends React.Component<AppProps, AppState> {
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<AppProps, AppState> {
// 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<AppProps, AppState> {
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<AppProps, AppState> {
},
fonts: {
configurable: true,
value: this.fonts,
get: () => this.fonts.instance,
},
});
}
@@ -3946,7 +3949,7 @@ class App extends React.Component<AppProps, AppState> {
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<AppProps, AppState> {
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<AppProps, AppState> {
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<AppProps, AppState> {
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<AppProps, AppState> {
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<AppProps, AppState> {
return { addedFiles };
};
/**
* Update the scene with new elements, appState or collaborators.
*/
public updateScene = withBatchedUpdates(
<K extends keyof AppState>(sceneData: {
elements?: SceneData["elements"];
@@ -5007,6 +4991,11 @@ class App extends React.Component<AppProps, AppState> {
this.scene.replaceAllElements(elements);
}
this.fonts.onSceneUpdated(
elements,
appState as Pick<AppState, "currentItemFontFamily"> | null,
);
if (collaborators) {
this.laserTrails.updateCollabTrails(collaborators);
this.setState({ collaborators });
@@ -11035,6 +11024,8 @@ class App extends React.Component<AppProps, AppState> {
isLoading: false,
},
replaceFiles: true,
// a dropped scene's custom fonts are resolved by no one else
loadFonts: true,
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
});
return true;
@@ -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
File diff suppressed because it is too large. Load diff
@@ -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 (
<TopPicksContextMenu
@@ -168,7 +241,8 @@ const FontTopPicks = ({
? { transform: `translateX(${reorderOffset}px)` }
: undefined
}
onClick={() => 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)}
</span>
) : (
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(
<FontPickerList
selectedFontFamily={selectedFontFamily}
hoveredFontFamily={hoveredFontFamily}
onSelect={onSelectCallback}
onSelect={onSelect}
onHover={onHover}
onLeave={onLeave}
onOpen={() => onPopupChange(true)}
@@ -294,6 +382,11 @@ export const FontPicker = React.memo(
</FontPickerDnDContext.Provider>
);
},
// 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 &&
@@ -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<typeof DropDownMenuItemBadgeType>;
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<HTMLInputElement>(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<FontFamily | null>(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<ReadonlySet<FontFamily>>(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<FontFamily | null>(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<HTMLDivElement | null>(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<HTMLButtonElement>(
"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<KeyboardEventHandler<HTMLDivElement>>(
(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<HTMLButtonElement>(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 (
<button
ref={ref}
type="button"
value={font.value}
className={getDropdownMenuItemClassName("", isSelected, isHovered)}
title={font.text}
// allow to tab between search and selected font
tabIndex={isSelected ? 0 : -1}
onClick={(e) => {
wrappedOnSelect(Number(e.currentTarget.value));
}}
onMouseMove={() => {
// don't live-preview fonts the dragged one merely passes over
if (!dnd?.dragState && hoveredFont?.value !== font.value) {
onHover(font.value);
}
}}
onPointerDown={
dnd ? (event) => dnd.startSourceDrag(event, font.value) : undefined
}
>
<MenuItemContent
icon={font.icon}
badge={
font.badge && (
<DropDownMenuItemBadge type={font.badge.type}>
{font.badge.placeholder}
</DropDownMenuItemBadge>
)
}
textStyle={{
fontFamily: getFontFamilyString({ fontFamily: font.value }),
}}
>
{font.text}
</MenuItemContent>
</button>
);
};
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(
<DropdownMenuGroup title={t("fontList.sceneFonts")} key="group_1">
{sceneFilteredFonts.map((font, index) => (
<FontPickerListItem key={font.value} font={font} order={index} />
))}
</DropdownMenuGroup>,
);
}
if (availableFilteredFonts.length) {
groups.push(
<DropdownMenuGroup title={t("fontList.availableFonts")} key="group_2">
{availableFilteredFonts.map((font, index) => (
<DropdownMenuGroup title={title} key={key}>
{groupFonts.map((font) => (
<FontPickerListItem
key={font.value}
font={font}
order={index + sceneFilteredFonts.length}
isHovered={font.value === hoveredFont?.value}
isSelected={font.value === selectedFontFamily}
onSelect={selectRowFontFamily}
onHover={hoverRowFontFamily}
setItemRef={setFontItemRef}
/>
))}
{footer}
</DropdownMenuGroup>,
);
}
};
pushGroup(t("fontList.sceneFonts"), "group_1", sceneFilteredFonts);
pushGroup(
t("fontList.favoriteFonts"),
"group_favorites",
favoriteFilteredFonts,
);
pushGroup(
t("fontList.availableFonts"),
"group_2",
availableFilteredFonts,
canLoadMoreFonts ? (
<button
type="button"
className="FontPicker__load-more"
disabled={isLoadingMoreFonts}
// keeps the focus where it is (the search), and with it the
// picker's keyboard handling
onMouseDown={(event) => event.preventDefault()}
onClick={() => loadMoreFonts()}
onKeyDown={(event) => {
// the picker acts on these (Enter picks the highlighted font)
if (event.key === KEYS.ENTER || event.key === KEYS.SPACE) {
event.stopPropagation();
}
}}
>
{t(isLoadingMoreFonts ? "fontList.loadingMore" : "fontList.loadMore")}
</button>
) : (
hasSearchForMore && (
<div className="FontPicker__search-for-more">
{t("fontList.searchForMore")}
</div>
)
),
);
pushGroup(
t("fontList.searchResults"),
"group_search",
searchMatches,
hiddenSearchMatchCount > 0 && (
<div className="FontPicker__more-results">
{t("fontList.moreResults", { count: hiddenSearchMatchCount })}
</div>
),
);
pushGroup(t("fontList.didYouMean"), "group_suggestions", searchSuggestions);
return (
<PropertiesPopover
@@ -400,27 +534,64 @@ export const FontPickerList = React.memo(
}, 0);
}
}}
onPointerLeave={onLeave}
onPointerLeave={leaveFontFamily}
onKeyDown={onKeyDown}
preventAutoFocusOnTouch={!!app.state.editingTextElement}
>
{stylesPanelMode === "full" && (
<QuickSearch
ref={inputRef}
placeholder={t("quickSearch.placeholder")}
onChange={debounce(setSearchTerm, 20)}
/>
{isSearchShown && (
<div className="FontPicker__search">
<QuickSearch
ref={inputRef}
placeholder={t("quickSearch.placeholder")}
onChange={(term) => {
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 && (
<div
ref={dnd.setDropZoneEl}
className={clsx("FontPicker__favorites-drop-zone", {
"FontPicker__favorites-drop-zone--over":
dnd.dragState.isOverDropZone,
"FontPicker__favorites-drop-zone--remove":
favoriteFamilies.has(dnd.dragState.value),
})}
>
<TopPicksDnDOutline />
{t(
favoriteFamilies.has(dnd.dragState.value)
? "fontList.removeFromFavorites"
: "fontList.addToFavorites",
)}
</div>
)}
</div>
)}
<ScrollableList
ref={setScrollContainerRef}
className="dropdown-menu fonts manual-hover"
placeholder={t("fontList.empty")}
placeholder={t(isSearching ? "fontList.searching" : "fontList.empty")}
>
{groups.length ? groups : null}
{groups}
</ScrollableList>
{dnd && (
<TopPicksTip
className="FontPicker__tip"
tip={t("fontList.topPicksTip")}
tip={
fontPickerTip === undefined ? (
<>
<span className="FontPicker__tip-icon" aria-hidden="true">
{DragDropIcon}
</span>
{t("fontList.topPicksTip")}
</>
) : (
fontPickerTip
)
}
onReset={onResetTopPicks}
resetTitle={t("fontList.resetTopPicks")}
/>
@@ -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) => (
<span
className={`FontPicker__retry-icon${
isLoading ? " FontPicker__retry-icon--loading" : ""
}`}
aria-hidden="true"
>
{RetryIcon}
</span>
);
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 (
<button
ref={setRef}
type="button"
value={font.value}
className={`${getDropdownMenuItemClassName(
"",
isSelected,
isHovered,
)}${getFontStatusClassName(font.status)}`}
title={font.text}
disabled={isUnsupported}
aria-busy={font.status === "loading"}
// allow to tab between search and selected font
tabIndex={isSelected ? 0 : -1}
onClick={() => onSelect(font.value)}
onMouseMove={() => {
// don't live-preview fonts the dragged one merely passes over
if (!dnd?.dragState && !isHovered) {
onHover(font.value);
}
}}
onPointerDown={
dnd && !isUnsupported
? (event) => dnd.startSourceDrag(event, font.value)
: undefined
}
>
<MenuItemContent
icon={font.icon}
badge={
font.status === "failed" || font.status === "loading" ? (
renderRetryIcon(font.status === "loading")
) : font.badge ? (
<DropDownMenuItemBadge type={font.badge.type}>
{font.badge.placeholder}
</DropDownMenuItemBadge>
) : null
}
textStyle={{
fontFamily: getFontFamilyString({ fontFamily: font.value }),
}}
>
{font.text}
</MenuItemContent>
</button>
);
};
/**
* 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]),
);
@@ -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;
}
@@ -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<string>,
): FontProviders => ({
google: {
icon: <span />,
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<string>((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);
});
});
@@ -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<unknown> = new Set<FontKind>([
"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 = <T>({
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<CustomFontFamily, T | null>();
const pendingAnswers = new Map<CustomFontFamily, Promise<void>>();
/** `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<void> | 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<unknown> | 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<string>({
name: "getPreviewText",
getMethod: (provider) => provider.getPreviewText,
normalize: (text) =>
typeof text === "string" && text && text !== DEFAULT_PREVIEW_TEXT
? text
: null,
});
const kinds = createProviderAnswers<FontKind>({
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;
@@ -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<FontFamilyValues> = ({
const createFontGhost: CreateTopPicksGhost<FontFamily> = ({
value,
sourceEl,
stripEl,
}) => {
@@ -43,7 +48,20 @@ const createFontGhost: CreateTopPicksGhost<FontFamilyValues> = ({
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<FontFamilyValues> = ({
iconClone.style.height = `${templateIconRect.height}px`;
}
tile.appendChild(iconClone);
} else {
// a pick rendering a glyph sample instead of an icon
const sample = sourceEl.querySelector<HTMLElement>(
".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<FontFamilyValues> = ({
};
};
export type FontPickerDnD = TopPicksDnD<FontFamilyValues>;
export type FontPickerDnD = TopPicksDnD<FontFamily>;
export const FontPickerDnDContext = createContext<FontPickerDnD | null>(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,
});
@@ -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<FontDescriptor> | undefined;
filteredFonts: Node<FontDescriptor>[];
onClose: () => void;
onSelect: (value: number) => void;
onHover: (value: number) => void;
onSelect: (value: FontFamily) => void;
onHover: (value: FontFamily) => void;
}
export const fontPickerKeyHandler = ({
@@ -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 = <T,>(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<typeof DropDownMenuItemBadgeType>;
placeholder: string;
};
}
// one element per family and text: a row re-renders when its icon changes
const glyphIcons = new Map<string, JSX.Element>();
/** 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 = (
<span
className="FontPicker__glyph-icon"
style={{ fontFamily: getFontFamilyString({ fontFamily }) }}
>
{text}
</span>
);
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<FontKind, JSX.Element> = {
"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<string, { icon?: JSX.Element }>,
): 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<string, unknown>;
selectedFontFamily: FontFamily | null;
hoveredFontFamily: FontFamily | null;
/** the user's favorites - see `ExcalidrawProps.fontFavorites` */
favoriteFamilies: ReadonlySet<FontFamily>;
/** 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<FontFamily, FontDescriptor>();
// loaded on demand, and listed for no other reason
const moreOnlyFamilies = new Set<FontFamily>();
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,
};
};
@@ -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<void>((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<string, unknown>;
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<FontResolution>(null);
const inputRef = useRef<HTMLInputElement>(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,
};
};
@@ -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<string, FontSearchResult | null>;
} | 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]);
};
@@ -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<ReadonlySet<FontFamily>>;
}
/** 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<string, number>;
exhausted: ReadonlySet<string>;
loaded: Set<FontFamily>;
}
/**
* 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<Fonts, MoreFontsState>();
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<AbortController | null>(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,
};
};
@@ -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<string, unknown>;
/**
* 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<IntersectionObserver | null>(null);
const fontItemRefs = useRef(new Map<FontFamily, HTMLButtonElement>());
const familiesByElement = useRef(new Map<Element, CustomFontFamily>());
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 };
};
@@ -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}
/>
</Dialog>
);
@@ -239,6 +239,7 @@ const LayerUI = ({
onExportImage={onExportImage}
onCloseRequest={() => setAppState({ openDialog: null })}
name={app.getName()}
fontResolvers={app.fonts.instance.fontResolvers}
/>
);
};
@@ -21,7 +21,7 @@ export const QuickSearch = React.forwardRef<HTMLInputElement, QuickSearchProps>(
className="QuickSearch__input"
type="text"
placeholder={placeholder}
onChange={(e) => onChange(e.target.value.trim().toLowerCase())}
onChange={(e) => onChange(e.target.value.trim())}
/>
</div>
);
@@ -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<HTMLDivElement, ScrollableListProps>(
({ className, placeholder, children }, ref) => {
const isEmpty = !Children.count(children);
return (
<div className={clsx("ScrollableList__wrapper", className)} role="menu">
{isEmpty ? <div className="empty">{placeholder}</div> : children}
</div>
);
};
return (
<div
ref={ref}
className={clsx("ScrollableList__wrapper", className)}
role="menu"
>
{isEmpty ? <div className="empty">{placeholder}</div> : children}
</div>
);
},
);
@@ -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 !== "" && " · "}
<button
type="button"
className="top-picks-dnd__tip-reset"
@@ -12,6 +12,10 @@ import "./TopPicksDnD.scss";
*
* The strip must be registered via `setStripEl`, and render its picks with
* `data-top-pick-index` (hit-testing and the drop animation measure these).
*
* A picker may register one more drop target beside the strip, via
* `setDropZoneEl` (e.g. the font picker's favorites) - a dragged value
* dropped there is handed to `onDropZoneDrop`, leaving the picks alone.
*/
const GHOST_CLASS = "excalidraw-top-picks-dnd-ghost";
@@ -38,6 +42,8 @@ export type TopPicksDragState<T> = {
duplicateIndex: number | null;
/** signed distance between strip slot centers (for reorder preview) */
slotSpan: number;
/** the pointer is over the extra drop zone (see `setDropZoneEl`) */
isOverDropZone: boolean;
} | null;
export type TopPicksGhost = {
@@ -86,6 +92,7 @@ type DragSession<T> = {
hitRect: { left: number; right: number; top: number; bottom: number } | null;
overIndex: number | null;
duplicateIndex: number | null;
isOverDropZone: boolean;
};
export type TopPicksDnD<T> = {
@@ -93,6 +100,11 @@ export type TopPicksDnD<T> = {
startSourceDrag: (event: React.PointerEvent, value: T | null) => void;
startPickDrag: (event: React.PointerEvent, index: number, value: T) => void;
setStripEl: (el: HTMLDivElement | null) => void;
/**
* An extra drop target beside the strip. May mount only once a drag is in
* flight (it's measured on every move), i.e. to replace other UI meanwhile.
*/
setDropZoneEl: (el: HTMLElement | null) => void;
};
/**
@@ -143,6 +155,7 @@ export const useTopPicksDnD = <T,>({
onPicksChange,
isSamePick = (a, b) => a === b,
createGhost,
onDropZoneDrop,
}: {
enabled: boolean;
picks: readonly T[];
@@ -150,9 +163,12 @@ export const useTopPicksDnD = <T,>({
/** value-equality — pins identical to an existing pick are refused */
isSamePick?: (a: T, b: T) => boolean;
createGhost: CreateTopPicksGhost<T>;
/** a value got dropped on the extra drop zone (see `setDropZoneEl`) */
onDropZoneDrop?: (value: T) => void;
}): TopPicksDnD<T> => {
const [dragState, setDragState] = useState<TopPicksDragState<T>>(null);
const stripRef = useRef<HTMLDivElement | null>(null);
const dropZoneRef = useRef<HTMLElement | null>(null);
const latestRef = useRef({
enabled,
@@ -160,6 +176,7 @@ export const useTopPicksDnD = <T,>({
onPicksChange,
isSamePick,
createGhost,
onDropZoneDrop,
});
latestRef.current = {
enabled,
@@ -167,6 +184,7 @@ export const useTopPicksDnD = <T,>({
onPicksChange,
isSamePick,
createGhost,
onDropZoneDrop,
};
const controller = useMemo(() => {
@@ -180,6 +198,7 @@ export const useTopPicksDnD = <T,>({
overIndex: session.overIndex,
duplicateIndex: session.duplicateIndex,
slotSpan: session.slotSpan,
isOverDropZone: session.isOverDropZone,
});
} else {
setDragState(null);
@@ -318,16 +337,37 @@ export const useTopPicksDnD = <T,>({
}
}
// the extra drop zone - measured live, as it may mount mid-drag
let isOverDropZone = false;
const dropZoneRect =
overIndex === null && duplicateIndex === null
? dropZoneRef.current?.getBoundingClientRect()
: null;
if (
dropZoneRect &&
x >= dropZoneRect.left &&
x <= dropZoneRect.right &&
y >= dropZoneRect.top &&
y <= dropZoneRect.bottom
) {
isOverDropZone = true;
}
if (
overIndex !== session.overIndex ||
duplicateIndex !== session.duplicateIndex
duplicateIndex !== session.duplicateIndex ||
isOverDropZone !== session.isOverDropZone
) {
session.overIndex = overIndex;
session.duplicateIndex = duplicateIndex;
session.isOverDropZone = isOverDropZone;
const { ghost } = session;
if (ghost) {
ghost.classList.toggle(`${GHOST_CLASS}--over`, overIndex !== null);
ghost.classList.toggle(
`${GHOST_CLASS}--over`,
overIndex !== null || isOverDropZone,
);
ghost.classList.toggle(
`${GHOST_CLASS}--blocked`,
duplicateIndex !== null,
@@ -535,8 +575,12 @@ export const useTopPicksDnD = <T,>({
event.stopPropagation();
suppressNextClick();
const { overIndex, origin, value, slotRects } = session;
const { picks, onPicksChange, isSamePick } = latestRef.current;
const { overIndex, origin, value, slotRects, isOverDropZone } = session;
const { picks, onPicksChange, isSamePick, onDropZoneDrop } =
latestRef.current;
const dropZoneRect = isOverDropZone
? dropZoneRef.current?.getBoundingClientRect()
: null;
settleStripInstantly();
@@ -554,6 +598,17 @@ export const useTopPicksDnD = <T,>({
onPicksChange(next);
}
releaseGhost({ rect: slotRects[overIndex] });
} else if (dropZoneRect && onDropZoneDrop) {
onDropZoneDrop(value);
// lands in the middle of the zone, at its own size
releaseGhost({
rect: new DOMRect(
dropZoneRect.left + (dropZoneRect.width - session.ghostW) / 2,
dropZoneRect.top + (dropZoneRect.height - session.ghostH) / 2,
session.ghostW,
session.ghostH,
),
});
} else {
releaseGhost({ rect: session.homeRect });
}
@@ -631,6 +686,7 @@ export const useTopPicksDnD = <T,>({
hitRect: null,
overIndex: null,
duplicateIndex: null,
isOverDropZone: false,
};
ownerWindow.addEventListener("pointermove", onPointerMove, true);
ownerWindow.addEventListener("pointerup", onPointerUp, true);
@@ -658,6 +714,9 @@ export const useTopPicksDnD = <T,>({
setStripEl: (el) => {
stripRef.current = el;
},
setDropZoneEl: (el) => {
dropZoneRef.current = el;
},
}),
[dragState, controller],
);
+1 -1
View File
@@ -147,7 +147,7 @@ export const UserList = React.memo(
const [searchTerm, setSearchTerm] = React.useState("");
const filteredCollaborators = collaboratorsArray.filter((collaborator) =>
collaborator.username?.toLowerCase().includes(searchTerm),
collaborator.username?.toLowerCase().includes(searchTerm.toLowerCase()),
);
const userListWrapper = React.useRef<HTMLDivElement | null>(null);
+17
View File
@@ -2601,3 +2601,20 @@ export const settingsIcon = createIcon(
</g>,
tablerIconProps,
);
// tabler-icons: drag-drop
export const DragDropIcon = createIcon(
<g strokeWidth="1.5">
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M19 11v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2" />
<path d="M13 13l9 3l-4 2l-2 4l-3 -9" />
<path d="M3 3l0 .01" />
<path d="M7 3l0 .01" />
<path d="M11 3l0 .01" />
<path d="M15 3l0 .01" />
<path d="M3 7l0 .01" />
<path d="M3 11l0 .01" />
<path d="M3 15l0 .01" />
</g>,
tablerIconProps,
);
+11 -3
View File
@@ -30,12 +30,17 @@ import {
import { t } from "../i18n";
import { getSelectedElements, isSomeElementSelected } from "../scene";
import { exportScene, getExportConfigFromAppState } from "../scene/export";
import {
exportScene,
getExportConfigFromAppState,
serializeSvg,
} from "../scene/export";
import { canvasToBlob } from "./blob";
import { fileSave } from "./filesystem";
import { serializeAsJSON } from "./json";
import type { FontResolvers } from "../fonts";
import type { ExportType } from "../scene/types";
import type { AppState, BinaryFiles } from "../types";
@@ -107,6 +112,7 @@ export const exportCanvas = async (
fileHandle = null,
exportingFrame = null,
renderEnvironment,
fontResolvers,
}: {
exportPadding?: number;
/** filename, if applicable */
@@ -114,6 +120,7 @@ export const exportCanvas = async (
fileHandle?: FileSystemFileHandle | null;
exportingFrame: NonDeleted<ExcalidrawFrameLikeElement> | null;
renderEnvironment?: RenderEnvironment;
fontResolvers?: FontResolvers;
},
) => {
if (elements.length === 0) {
@@ -124,6 +131,7 @@ export const exportCanvas = async (
...getExportConfigFromAppState(appState),
padding: exportPadding,
exportingFrame,
fontResolvers,
};
if (type === "svg" || type === "clipboard-svg") {
@@ -146,7 +154,7 @@ export const exportCanvas = async (
svgPromise.then((svg) => {
// adding SVG preamble so that older software parse the SVG file
// properly
return new Blob([SVG_DOCUMENT_PREAMBLE + svg.outerHTML], {
return new Blob([SVG_DOCUMENT_PREAMBLE + serializeSvg(svg)], {
type: MIME_TYPES.svg,
});
}),
@@ -159,7 +167,7 @@ export const exportCanvas = async (
},
);
} else if (type === "clipboard-svg") {
const svg = await svgPromise.then((svg) => svg.outerHTML);
const svg = await svgPromise.then(serializeSvg);
try {
await copyTextToSystemClipboard(svg);
} catch (e) {
+3
View File
@@ -7,6 +7,7 @@ import { getFileHandleType, isImageFileHandleType } from "./blob";
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
import { exportCanvas, prepareElementsForExport } from ".";
import type { FontResolvers } from "../fonts";
import type { AppState, BinaryFiles } from "../types";
export const resaveAsImageWithScene = async (
@@ -17,6 +18,7 @@ export const resaveAsImageWithScene = async (
}>,
fileHandle: FileSystemFileHandle,
filename: string,
fontResolvers: FontResolvers,
) => {
const fileHandleType = getFileHandleType(fileHandle);
@@ -43,6 +45,7 @@ export const resaveAsImageWithScene = async (
name: filename,
fileHandle,
exportingFrame,
fontResolvers,
});
return { fileHandle };
+53 -11
View File
@@ -29,12 +29,14 @@ import {
getSizeFromPoints,
normalizeLink,
getLineHeight,
isProviderQualifiedFontFamily,
STROKE_WIDTH,
STROKE_WIDTH_KEYS,
type StrokeWidthKey,
isTransparent,
DEFAULT_ZOOM,
} from "@excalidraw/common";
import {
calculateFixedPointForNonElbowArrowBinding,
getNonDeletedElements,
@@ -84,6 +86,8 @@ import { getNormalizedDimensions } from "@excalidraw/element";
import { isInvisiblySmallElement } from "@excalidraw/element";
import type { FontFamily } from "@excalidraw/common";
import type { LocalPoint, Radians } from "@excalidraw/math";
import type {
@@ -97,7 +101,6 @@ import type {
ExcalidrawSelectionElement,
ExcalidrawTextElement,
FixedPointBinding,
FontFamilyValues,
NonDeleted,
NonDeletedSceneElementsMap,
OrderedExcalidrawElement,
@@ -286,15 +289,46 @@ const restoreFreedrawStrokeOptions = (
};
};
const getFontFamilyByName = (fontFamilyName: string): FontFamilyValues => {
/** for the legacy `font` property only, i.e. "20px Virgil" */
const getFontFamilyByName = (fontFamilyName: string): FontFamily => {
if (Object.keys(FONT_FAMILY).includes(fontFamilyName)) {
return FONT_FAMILY[
fontFamilyName as keyof typeof FONT_FAMILY
] as FontFamilyValues;
] as FontFamily;
}
return DEFAULT_FONT_FAMILY;
};
/**
* Keeps whatever the document holds, as master always has - only a missing
* value gets the default.
*
* WARN: don't normalize here. Restore runs on every path a document takes
* (files, collab, library, paste) and its output gets saved, so a value this
* version rewrites is a value no later version can ever introduce: a future
* `fontFamily` shape would be turned into the default font by every deployed
* client and synced back. Values we can't interpret are instead dealt with
* where they are *read* - see `getFontFamilyString`.
*/
const restoreFontFamily = (fontFamily: unknown): FontFamily =>
fontFamily == null ? DEFAULT_FONT_FAMILY : (fontFamily as FontFamily);
/**
* Unlike element families, the default for *new* text is normalized - it's
* browser-only state, and a value we can't interpret must not be written into
* every text element created from now on.
*/
const restoreCurrentItemFontFamily = (fontFamily: unknown): FontFamily => {
if (typeof fontFamily === "string") {
return isProviderQualifiedFontFamily(fontFamily)
? fontFamily
: DEFAULT_FONT_FAMILY;
}
return isFiniteNumber(fontFamily) ? fontFamily : DEFAULT_FONT_FAMILY;
};
/**
* Line-height might not be specified either when creating elements
* programmatically, or when importing old diagrams. For the latter we want to
@@ -558,7 +592,7 @@ export const restoreElement = (
delete (element as any).rawText;
let fontSize = element.fontSize;
let fontFamily = element.fontFamily;
let fontFamily = restoreFontFamily(element.fontFamily);
if ("font" in element) {
const [fontPx, _fontFamily]: [string, string] = (
element as any
@@ -1243,21 +1277,24 @@ const restoreColorTopPicksList = (value: unknown): readonly string[] | null => {
return colors.size ? [...colors.values()] : null;
};
const restoreFontTopPicks = (
value: unknown,
): readonly FontFamilyValues[] | null => {
const restoreFontTopPicks = (value: unknown): readonly FontFamily[] | null => {
if (!Array.isArray(value)) {
return null;
}
const fontFamilies = new Set<FontFamilyValues>();
const fontFamilies = new Set<FontFamily>();
for (const fontFamily of value) {
const metadata =
typeof fontFamily === "number" ? FONT_METADATA[fontFamily] : undefined;
// only families the font picker lists (no internal or fallback fonts)
if (!metadata || metadata.private || metadata.fallback) {
// only families the font picker lists (custom, or built-ins that are not
// internal or fallback fonts)
const isPickable =
typeof fontFamily === "string"
? isProviderQualifiedFontFamily(fontFamily)
: !!metadata && !metadata.private && !metadata.fallback;
if (!isPickable) {
continue;
}
fontFamilies.add(fontFamily as FontFamilyValues);
fontFamilies.add(fontFamily as FontFamily);
if (fontFamilies.size >= FONT_TOP_PICKS_SLOTS) {
break;
}
@@ -1340,6 +1377,11 @@ export const restoreAppState = (
return {
...nextAppState,
// or a bare name from persisted data leaks into every newly created
// text element
currentItemFontFamily: restoreCurrentItemFontFamily(
nextAppState.currentItemFontFamily,
),
cursorButton: localAppState?.cursorButton || "up",
// reset on fresh restore so as to hide the UI button if penMode not active
penDetected:
+121 -28
View File
@@ -6,7 +6,49 @@ type DataURL = string;
export class ExcalidrawFontFace {
public readonly urls: URL[] | DataURL[];
public readonly fontFace: FontFace;
/**
* Built when first asked for: an export running where there is no
* `FontFace` (Node, a worker without one) registers fonts as well - for
* their metrics, and to inline their files into an SVG - and never gets
* here, having no font set to put a face into.
*/
public get fontFace(): FontFace {
if (!this._fontFace) {
const sources = this.urls
.map((url) => `url(${url}) ${ExcalidrawFontFace.getFormat(url)}`)
.join(", ");
// WARN: the bare name, unquoted - it takes the name itself, so a
// pre-quoted value double-quotes and matches nothing
this._fontFace = new FontFace(this.cssFamily, sources, {
display: "swap",
style: "normal",
weight: "400",
...this.descriptors,
});
}
return this._fontFace;
}
private _fontFace: FontFace | undefined;
/**
* The family as we know it, i.e. "Excalifont" or "google:Roboto" - our
* source of truth, for lookups and messages.
*/
public readonly family: string;
/**
* The name the browser knows the family by: the same as `family` for the
* built-ins, a generated one for custom fonts (`getCustomFontCSSFamily`),
* whose id must never reach CSS. What `getFontFamilyString` refers to.
*/
public readonly cssFamily: string;
private readonly descriptors?: FontFaceDescriptors;
private readonly uri: string;
private static readonly ASSETS_FALLBACK_URL = `https://esm.sh/${
import.meta.env.PKG_NAME
@@ -14,19 +56,27 @@ export class ExcalidrawFontFace {
: "@excalidraw/excalidraw" // fallback to the latest package version (i.e. for app)
}/dist/prod/`;
constructor(family: string, uri: string, descriptors?: FontFaceDescriptors) {
constructor(
family: string,
uri: string,
descriptors?: FontFaceDescriptors,
cssFamily: string = family,
) {
this.uri = uri;
this.urls = ExcalidrawFontFace.createUrls(uri);
this.family = family;
this.cssFamily = cssFamily;
this.descriptors = descriptors;
}
const sources = this.urls
.map((url) => `url(${url}) ${ExcalidrawFontFace.getFormat(url)}`)
.join(", ");
this.fontFace = new FontFace(family, sources, {
display: "swap",
style: "normal",
weight: "400",
...descriptors,
});
/** the same face again, with a `FontFace` which hasn't been loaded yet */
public clone(): ExcalidrawFontFace {
return new (this.constructor as typeof ExcalidrawFontFace)(
this.family,
this.uri,
this.descriptors,
this.cssFamily,
);
}
/**
@@ -44,9 +94,31 @@ export class ExcalidrawFontFace {
(char) => char.codePointAt(0)!,
);
// carry the face's distinguishing descriptors into the declaration, or a
// multi-weight / italic / unicode-ranged family collapses into one bucket
// and viewers match the wrong face. From our own descriptors, as browser
// `FontFace` serialization differs per engine; defaults are omitted
const cssDescriptors = [
this.descriptors?.style &&
this.descriptors.style !== "normal" &&
`font-style: ${this.descriptors.style};`,
this.descriptors?.weight &&
this.descriptors.weight !== "400" &&
`font-weight: ${this.descriptors.weight};`,
this.descriptors?.unicodeRange &&
`unicode-range: ${this.descriptors.unicodeRange};`,
]
.filter(Boolean)
.join(" ");
return this.getContent(codepoints).then(
(content) =>
`@font-face { font-family: ${this.fontFace.family}; src: url(${content}); }`,
// quoted, as not every built-in name is a valid ident sequence
`@font-face { font-family: ${JSON.stringify(
this.cssFamily,
)}; src: url(${content});${
cssDescriptors ? ` ${cssDescriptors}` : ""
} }`,
);
}
@@ -78,7 +150,7 @@ export class ExcalidrawFontFace {
}
console.error(
`Failed to fetch font family "${this.fontFace.family}"`,
`Failed to fetch font family "${this.family}"`,
JSON.stringify(errorMessages, undefined, 2),
);
@@ -112,22 +184,41 @@ export class ExcalidrawFontFace {
}
private getUnicodeRangeRegex() {
// From our own descriptor, not from `fontFace.unicodeRange`: that is the
// browser's serialization of it, and takes a `FontFace`, which an export
// running headless hasn't got. A face without one covers every character
// (the default in CSS, and what the browser says for it too). A real gate
// here also keeps non-intersecting faces out of exports entirely
const unicodeRange = this.descriptors?.unicodeRange ?? "U+0-10FFFF";
// using \u{h} or \u{hhhhh} to match any number of hex digits,
// otherwise we would get an "Invalid Unicode escape" error
// e.g. U+0-1007F -> \u{0}-\u{1007F}
const unicodeRangeRegex = this.fontFace.unicodeRange
.split(/,\s*/)
const unicodeRangeRegex = unicodeRange
.split(",")
.map((range) => {
const [start, end] = range.replace("U+", "").split("-");
if (end) {
return `\\u{${start}}-\\u{${end}}`;
// a descriptor is the host's own text, so every form CSS takes:
// `U+26`, `u+0025-00ff`, and the wildcard `U+4??` (= U+400-4FF)
const match = range
.trim()
.match(/^u\+([0-9a-f]*)(\?*)(?:-([0-9a-f]+))?$/i);
if (!match || !(match[1] + match[2])) {
return "";
}
return `\\u{${start}}`;
const [, digits, wildcards, end] = match;
const first = `${digits}${"0".repeat(wildcards.length)}`;
const last = wildcards
? `${digits}${"F".repeat(wildcards.length)}`
: end;
return last ? `\\u{${first}}-\\u{${last}}` : `\\u{${first}}`;
})
.join("");
return new RegExp(`[${unicodeRangeRegex}]`, "u");
// (an empty class would be a syntax error - nothing valid matches nothing)
return new RegExp(
unicodeRangeRegex ? `[${unicodeRangeRegex}]` : "(?!)",
"u",
);
}
private static createUrls(uri: string): URL[] | DataURL[] {
@@ -149,15 +240,17 @@ export class ExcalidrawFontFace {
// absolute assets paths, which are found in tests and excalidraw-app build, won't work with base url, so we are stripping initial slash away
const assetUrl: string = uri.replace(/^\/+/, "");
const urls: URL[] = [];
// no `window` where an export runs headless (i.e. Node) - the bundled
// fonts come from the fallback url there
const assetPath =
typeof window !== "undefined" ? window.EXCALIDRAW_ASSET_PATH : undefined;
if (typeof window.EXCALIDRAW_ASSET_PATH === "string") {
const normalizedBaseUrl = this.normalizeBaseUrl(
window.EXCALIDRAW_ASSET_PATH,
);
if (typeof assetPath === "string") {
const normalizedBaseUrl = this.normalizeBaseUrl(assetPath);
urls.push(new URL(assetUrl, normalizedBaseUrl));
} else if (Array.isArray(window.EXCALIDRAW_ASSET_PATH)) {
window.EXCALIDRAW_ASSET_PATH.forEach((path) => {
} else if (Array.isArray(assetPath)) {
assetPath.forEach((path) => {
const normalizedBaseUrl = this.normalizeBaseUrl(path);
urls.push(new URL(assetUrl, normalizedBaseUrl));
});
+280
View File
@@ -0,0 +1,280 @@
import {
FONT_FAMILY,
FONT_FAMILY_FALLBACKS,
CJK_HAND_DRAWN_FALLBACK_FONT,
WINDOWS_EMOJI_FALLBACK_FONT,
getFontMetadata,
getCustomFontCSSFamily,
isCustomFontFamily,
Emitter,
} from "@excalidraw/common";
import type {
CustomFontFamily,
FontFamily,
FontMetadata,
} from "@excalidraw/common";
import { CascadiaFontFaces } from "./Cascadia";
import { ComicShannsFontFaces } from "./ComicShanns";
import { EmojiFontFaces } from "./Emoji";
import { ExcalidrawFontFace } from "./ExcalidrawFontFace";
import { ExcalifontFontFaces } from "./Excalifont";
import { FontsCache } from "./FontsCache";
import { HelveticaFontFaces } from "./Helvetica";
import { LiberationFontFaces } from "./Liberation";
import { LilitaFontFaces } from "./Lilita";
import { NunitoFontFaces } from "./Nunito";
import { VirgilFontFaces } from "./Virgil";
import { XiaolaiFontFaces } from "./Xiaolai";
import type { ExcalidrawFontFaceDescriptor } from "./Fonts";
/**
* The font set faces are installed & loaded into: the document's, or in a
* worker its own (`self.fonts`, what an `OffscreenCanvas` there measures
* with). `null` where there is neither, e.g. Node or `linkedom`.
*/
export const getFontFaceSet = (ownerDocument?: Document): FontFaceSet | null =>
(ownerDocument ?? (typeof document !== "undefined" ? document : null))
?.fonts ??
(typeof self !== "undefined" && "fonts" in self
? (self as unknown as { fonts: FontFaceSet }).fonts
: null);
/**
* Font faces for a family registered under `key`. A custom family (keyed by
* its id) goes by a generated CSS name - the id itself never reaches CSS.
*/
export const createFontFaces = (
key: FontFamily,
family: string,
fontFaceDescriptors: readonly ExcalidrawFontFaceDescriptor[],
): ExcalidrawFontFace[] => {
const cssFamily = isCustomFontFamily(key)
? getCustomFontCSSFamily(key)
: family;
return fontFaceDescriptors.map(
({ uri, descriptors }) =>
new ExcalidrawFontFace(family, uri, descriptors, cssFamily),
);
};
/** a registered font, as held by {@link Fonts.registered} */
export type RegisteredFont = {
metadata: FontMetadata;
fontFaces: ExcalidrawFontFace[];
/** custom fonts only - see `FontDefinition.label` */
label?: string;
};
/**
* Owns the page-global font state: resolved definitions, the resolution cache
* (in-flight attempts + verdicts), loaded-face tracking and change events.
*
* One instance ({@link defaultFontRegistry}) is shared by every editor on the
* page - a resolved font face is a document-level browser resource, and the
* `FontProviders` contract makes definitions editor-independent. Constructing
* `Fonts` with an own registry opts out (i.e. tests); custom font *metrics*
* stay page-global even then, being contract-stable per family.
*/
export class FontRegistry {
/** resolution state: in-flight attempts + verdicts - see {@link FontsCache} */
public readonly cache = new FontsCache(this);
// tracked by instance rather than by name, as `fontFace.family` is the
// browser's serialization, quoted or bare per engine. A WeakSet, as
// `loadingdone` also delivers the host page's own font faces - pinning
// those would keep them alive past their stylesheet
public readonly loadedFaces = new WeakSet<FontFace>();
public readonly onChangeEmitter = new Emitter<
[ReadonlyMap<FontFamily, RegisteredFont>]
>();
private _registered: Map<FontFamily, RegisteredFont> | undefined;
private initializedBuiltIns = false;
public get registered() {
// lazy load the built-in font registration
if (!this._registered) {
this._registered = this.initBuiltIns();
} else if (!this.initializedBuiltIns) {
// case when a host registered custom fonts before the built-ins were
// lazily initialized - don't override what has been registered already
this._registered = new Map([
...this.initBuiltIns().entries(),
...this._registered.entries(),
]);
}
return this._registered;
}
/**
* Whether any custom family has ever been registered - the gate letting
* no-provider editors skip custom-font work wholesale, so it stays cheap:
* monotonic (never unregistered), so `true` is cached, and `false` scans
* only the ~10 built-in keys. Reads the backing map directly, to avoid
* forcing the lazy built-in init.
*/
private _hasCustomFamilies = false;
public get hasCustomFamilies(): boolean {
if (!this._hasCustomFamilies && this._registered) {
for (const key of this._registered.keys()) {
if (typeof key === "string") {
this._hasCustomFamilies = true;
break;
}
}
}
return this._hasCustomFamilies;
}
/**
* Whether a custom family is registered. Reads the backing map directly,
* as {@link hasCustomFamilies} does: the lazy built-in init builds font
* faces, which a headless export has no `FontFace` for.
*/
public hasCustomFamily(family: CustomFontFamily): boolean {
return !!this._registered?.has(family);
}
/**
* Announce registry changes at most once per microtask - registrations
* arrive in bursts, and each emit hands React a fresh map identity.
*
* Per registration rather than per batch: gating emits on batch completion
* would let one slow resolver mute its already-registered batch-mates.
*/
private emitScheduled = false;
public scheduleEmit() {
if (this.emitScheduled) {
return;
}
this.emitScheduled = true;
queueMicrotask(() => {
this.emitScheduled = false;
this._registered = new Map(this.registered);
this.onChangeEmitter.trigger(this._registered);
});
}
/** announce immediately - for synchronous registration APIs */
public emitNow() {
this._registered = new Map(this.registered);
this.onChangeEmitter.trigger(this._registered);
}
/**
* Register a font under `key`, unless something is registered there already.
*
* `key` and `family` come apart for the built-ins, which are keyed by their
* numeric id but whose font faces (and so CSS) go by name.
*/
public add(
key: FontFamily,
family: string,
metadata: FontMetadata,
fontFaceDescriptors: ExcalidrawFontFaceDescriptor[],
) {
FontRegistry.addTo(
this.registered,
key,
family,
metadata,
fontFaceDescriptors,
);
}
/**
* add the given font faces into the font set (if not added already) - see
* {@link getFontFaceSet}
*/
public installFontFaces(
fontFaces: readonly ExcalidrawFontFace[],
fontFaceSet: FontFaceSet | null = getFontFaceSet(),
) {
// nothing to install into (i.e. a headless export) - and no reason to
// build the faces' `FontFace`s, which such an environment may not have
if (!fontFaceSet) {
return;
}
for (const { fontFace } of fontFaces) {
if (!fontFaceSet.has(fontFace)) {
fontFaceSet.add(fontFace);
}
}
}
/**
* Whether at least one font face of the family has already loaded - by our
* own instances, not the browser-serialized `fontFace.family`. A face the
* host loaded itself stays invisible here, which errs safely: callers fall
* back to the (slow, but correct) `document.fonts.check`.
*/
public isFamilyLoaded = (family: FontFamily): boolean =>
this.registered
.get(family)
?.fontFaces.some(({ fontFace }) => this.loadedFaces.has(fontFace)) ??
false;
private static addTo(
registered: Map<FontFamily, RegisteredFont>,
key: FontFamily,
family: string,
metadata: FontMetadata,
fontFaceDescriptors: ExcalidrawFontFaceDescriptor[],
) {
if (!registered.has(key)) {
registered.set(key, {
metadata,
fontFaces: createFontFaces(key, family, fontFaceDescriptors),
});
}
}
private initBuiltIns() {
const registered = new Map<FontFamily, RegisteredFont>();
const init = (
family: keyof typeof FONT_FAMILY | keyof typeof FONT_FAMILY_FALLBACKS,
...fontFacesDescriptors: ExcalidrawFontFaceDescriptor[]
) => {
const fontFamily =
FONT_FAMILY[family as keyof typeof FONT_FAMILY] ??
FONT_FAMILY_FALLBACKS[family as keyof typeof FONT_FAMILY_FALLBACKS];
FontRegistry.addTo(
registered,
fontFamily,
family,
getFontMetadata(fontFamily),
fontFacesDescriptors,
);
};
init("Cascadia", ...CascadiaFontFaces);
init("Comic Shanns", ...ComicShannsFontFaces);
init("Excalifont", ...ExcalifontFontFaces);
// keeping for backwards compatibility reasons, uses system font (Helvetica on MacOS, Arial on Win)
init("Helvetica", ...HelveticaFontFaces);
// used for server-side pdf & png export instead of helvetica (technically does not need metrics, but kept in for consistency)
init("Liberation Sans", ...LiberationFontFaces);
init("Lilita One", ...LilitaFontFaces);
init("Nunito", ...NunitoFontFaces);
init("Virgil", ...VirgilFontFaces);
// fallback font faces
init(CJK_HAND_DRAWN_FALLBACK_FONT, ...XiaolaiFontFaces);
init(WINDOWS_EMOJI_FALLBACK_FONT, ...EmojiFontFaces);
this.initializedBuiltIns = true;
return registered;
}
}
/** the page-wide default registry - see {@link FontRegistry} */
export const defaultFontRegistry = new FontRegistry();
File diff suppressed because it is too large. Load diff
+170
View File
@@ -0,0 +1,170 @@
import { Emitter } from "@excalidraw/common";
import type { CustomFontFamily } from "@excalidraw/common";
import type { FontDefinition, FontResolver } from "./Fonts";
import type { FontRegistry } from "./FontRegistry";
/**
* `initial` - never handed to a resolver; `loading` - resolution in flight;
* `failed` - the resolver rejected (and the attempt was user-visible);
* `registered` - definition available, in {@link Fonts.registered}.
*/
export type FontResolutionStatus =
| "initial"
| "loading"
| "failed"
| "registered";
/**
* A {@link FontRegistry}'s custom font resolution state, in two separate
* layers:
*
* - the *dedup* layer (`pending`) tracks in-flight resolutions, so concurrent
* callers hand a family to its resolver once. Shared unconditionally.
* - the *verdict* layer (`failures`) records rejections, but only from
* attempts whose outcome the user sees (see `recordFailure`).
*
* Keeping them apart is what makes `recordFailure` expressible: a
* non-recording attempt still dedupes while `failures` stays untouched.
* Failures are advisory - they exclude a family from automatic loading and
* paint its picker row, never block a deliberate re-attempt - and clear as
* soon as the family resolves anywhere.
*
* Scoped to its registry, and so shared by every editor on it: a resolution is
* a fact about the family, not about the editor that asked.
*/
export class FontsCache {
constructor(private readonly registry: FontRegistry) {}
/** dedup layer: in-flight resolutions, keyed by qualified family */
private readonly pending = new Map<string, Promise<FontDefinition>>();
/** verdict layer: families whose resolver rejected, with the rejection */
private failures: ReadonlyMap<string, unknown> = new Map();
public readonly onFailuresChangeEmitter = new Emitter<
[ReadonlyMap<string, unknown>]
>();
public get failedResolutions(): ReadonlyMap<string, unknown> {
return this.failures;
}
public getStatus(family: CustomFontFamily): FontResolutionStatus {
if (this.registry.registered.has(family)) {
return "registered";
}
if (this.pending.has(family)) {
return "loading";
}
if (this.failures.has(family)) {
return "failed";
}
return "initial";
}
/**
* How long a resolver may stay pending before the attempt is abandoned - a
* hanging one would otherwise poison `pending` forever, every retry joining
* the dead promise. The entry clears on timeout, so the next attempt runs
* afresh. Measured from invocation, not from time spent queued.
*/
private static readonly RESOLUTION_TIMEOUT = 30_000;
/**
* At most this many resolvers run at once, registry-wide - scrolling a large
* catalog dispatches many *distinct* families (`useVisibleFontRegistration`)
* and resolvers are arbitrary network code.
*
* Best-effort: a timed-out resolver keeps running (promises can't be
* cancelled) while its slot is released, so a wave of timeouts can
* transiently exceed the cap - better than letting it starve the queue.
*/
private static readonly RESOLVER_CONCURRENCY = 6;
private activeResolvers = 0;
private readonly resolverQueue: Array<() => void> = [];
private acquireResolverSlot(): Promise<void> {
if (this.activeResolvers < FontsCache.RESOLVER_CONCURRENCY) {
this.activeResolvers++;
return Promise.resolve();
}
return new Promise((resolve) => this.resolverQueue.push(resolve));
}
private releaseResolverSlot() {
const next = this.resolverQueue.shift();
if (next) {
// hand the slot over directly - `activeResolvers` stays constant
next();
} else {
this.activeResolvers--;
}
}
/** join an in-flight resolution, or start one */
public resolve(
family: string,
familyName: string,
resolver: FontResolver,
): Promise<FontDefinition> {
const pendingResolution = this.pending.get(family);
if (pendingResolution) {
return pendingResolution;
}
let timeoutId!: ReturnType<typeof setTimeout>;
const resolution = this.acquireResolverSlot()
.then(() =>
Promise.race([
Promise.resolve().then(() => resolver(familyName)),
new Promise<never>((_, reject) => {
timeoutId = setTimeout(
() =>
reject(
new Error(`Timed out resolving custom font "${family}"`),
),
FontsCache.RESOLUTION_TIMEOUT,
);
}),
]),
)
.finally(() => {
clearTimeout(timeoutId);
this.releaseResolverSlot();
if (this.pending.get(family) === resolution) {
this.pending.delete(family);
}
});
this.pending.set(family, resolution);
return resolution;
}
/**
* Record a rejection. Only call from settle paths of user-visible attempts -
* see `RegistrationOptions.recordFailure`.
*/
public setFailed(family: string, error: unknown) {
if (this.failures.has(family)) {
return;
}
const failures = new Map(this.failures);
failures.set(family, error);
this.failures = failures;
this.onFailuresChangeEmitter.trigger(this.failures);
}
/** Only call from success paths - a resolved family has nothing to fail. */
public clearFailed(family: string) {
if (!this.failures.has(family)) {
return;
}
const failures = new Map(this.failures);
failures.delete(family);
this.failures = failures;
this.onFailuresChangeEmitter.trigger(this.failures);
}
}
@@ -0,0 +1,11 @@
[
["Kalam", 1000, 1063, -531, 0, "hand-drawn"],
["Patrick Hand", 1000, 1042, -312, 0, "hand-drawn"],
["Pacifico", 1000, 1303, -453, 0, "hand-drawn"],
["Open Sans", 2048, 2189, -600, 0, "normal"],
["Literata", 1000, 1177, -308, 0, "normal"],
["Fira Mono", 1000, 935, -265, 0, "code"],
["Bevan", 2048, 2366, -925, 0, "heading"],
["Zen Maru Gothic", 1000, 1160, -288, 0, "normal", "Jpan"],
["Gowun Dodum", 1000, 1160, -288, 0, "normal", "Kore"]
]
+529
View File
@@ -0,0 +1,529 @@
/**
* Google Fonts for the editor: the catalog of families, and a resolver
* turning a family name into the font faces and metrics the editor loads.
*
* ```tsx
* import {
* GOOGLE_FONT_PROVIDER_KEY,
* createGoogleFontResolver,
* } from "@excalidraw/excalidraw/fonts/google";
*
* // renders Google fonts found in documents, offers none in the font picker
* <Excalidraw
* fontProviders={{
* [GOOGLE_FONT_PROVIDER_KEY]: {
* icon,
* availableFonts: [],
* resolve: createGoogleFontResolver(),
* },
* }}
* />
* ```
*
* Opt-in, as resolving a family requests it from Google's servers. Sharing
* one catalog is what makes text carry over between hosts: each uses the same
* family names as ids, and lays text out with the same metrics.
*
* WARN: nothing here may import editor code at runtime (types are fine) - it
* has to load in a worker and on a server, and stay out of the main bundle.
*/
import type { FontDefinition, FontResolver } from "../Fonts";
import type { FontKind, FontProvider, FontSearchResult } from "../../types";
/** the provider key of every Google font id, i.e. "google:Open Sans" */
export { GOOGLE_FONT_PROVIDER_KEY } from "../providerKey";
/**
* Also exported by the main entry. Here, so that a host can register its
* resolvers at startup without loading the editor.
*/
export { registerFontResolvers } from "../resolvers";
export type GoogleFont = {
/**
* The family name, exactly as Google publishes it - the family part of the
* font id, i.e. "Roboto" in "google:Roboto".
*/
name: string;
/** read from the font files when the catalog is generated */
metrics: FontDefinition["metadata"]["metrics"];
/** set by hand - Google's categories file i.e. a display face as a serif */
kind: FontKind;
/**
* Text previewing the family where "Aa" would misrepresent it: CJK
* families, and families with no Latin glyphs.
*/
previewText?: string;
};
export type GoogleFontCatalog = {
/** every family, most popular first */
fonts: readonly GoogleFont[];
/** by exact name */
get(name: string): GoogleFont | undefined;
};
/**
* [name, unitsPerEm, ascender, descender, lineGap, kind, script?] - see
* `scripts/buildGoogleFontsCatalog.mjs`
*/
type CatalogEntry = [string, number, number, number, number, FontKind, string?];
const PREVIEW_TEXT_BY_SCRIPT: Record<string, string> = {
Jpan: "あ",
Hira: "あ",
Kore: "한",
Hans: "汉",
Hant: "漢",
Khmr: "ក",
Taml: "அ",
Laoo: "ກ",
};
let catalogPromise: Promise<GoogleFontCatalog> | null = null;
/**
* The catalog: the Google font families the editor offers. A small,
* hand-picked set - each one looked at on the canvas and in the text editor,
* in Chrome, Firefox and Safari - and not Google's whole list. A chunk of
* its own, loaded on first use and kept for the session.
*
* Append-only across releases, as font ids are saved into documents. A family
* added in a later version of the package isn't in it.
*/
export const loadGoogleFontCatalog = (): Promise<GoogleFontCatalog> => {
if (!catalogPromise) {
catalogPromise = import("./catalog.json").then((module) => {
const fonts = (module.default as CatalogEntry[]).map(
([name, unitsPerEm, ascender, descender, lineGap, kind, script]) => {
const font: GoogleFont = {
name,
metrics: {
unitsPerEm,
ascender,
descender,
// the font's own default line spacing, over the em
lineHeight: (ascender - descender + lineGap) / unitsPerEm,
},
kind,
};
const previewText = script && PREVIEW_TEXT_BY_SCRIPT[script];
if (previewText) {
font.previewText = previewText;
}
return font;
},
);
const byName = new Map(fonts.map((font) => [font.name, font]));
return { fonts, get: (name: string) => byName.get(name) };
});
// i.e. the chunk failed to load - let the next call try again
catalogPromise.catch(() => {
catalogPromise = null;
});
}
return catalogPromise;
};
/**
* Why a family couldn't be resolved. The two aren't interchangeable for a
* caller deciding whether to try again:
*
* - `unknown-family` - not in the catalog. Trying again won't help.
* - `unavailable` - its files couldn't be listed (network, or the source is
* down), after the resolver's own retries.
*/
export class GoogleFontError extends Error {
constructor(
public readonly reason: "unknown-family" | "unavailable",
message: string,
options?: ErrorOptions,
) {
super(message, options);
this.name = "GoogleFontError";
}
}
type FontFaces = FontDefinition["fontFaces"];
/**
* Where a family's font files are: given a catalog family, the faces to
* load. The default asks Google ({@link googleFontsCss2Source}); a host
* mirroring the files can list its own urls instead, for the same families.
*/
export type GoogleFontSource = (
font: GoogleFont,
options: { fetch: typeof fetch },
) => Promise<FontFaces>;
const CSS2_URL = "https://fonts.googleapis.com/css2";
const ATTEMPTS = 3;
const RETRY_DELAY = 300;
const REQUEST_TIMEOUT = 10_000;
/** distinct families resolved against the source at once */
const CONCURRENCY = 4;
/** `url(…)` paired with its `format(…)`; either may be quoted */
const SRC_ENTRY_REGEX =
/url\(\s*(['"]?)(.+?)\1\s*\)\s*format\(\s*(['"]?)([^'")]+)\3\s*\)/g;
const getDeclaration = (block: string, property: string) =>
new RegExp(`(?:^|;)\\s*${property}\\s*:\\s*([^;]+)`, "i")
.exec(block)?.[1]
.trim();
/** the woff2 faces of a `css2` stylesheet, one per `unicode-range` subset */
const parseFontFaces = (css: string) => {
const fontFaces: FontFaces[number][] = [];
let blocks = 0;
for (const [, block] of css.matchAll(/@font-face\s*\{([^}]*)\}/g)) {
blocks++;
const uri = Array.from(
(getDeclaration(block, "src") ?? "").matchAll(SRC_ENTRY_REGEX),
).find(([, , , , format]) => format.toLowerCase() === "woff2")?.[2];
if (!uri) {
continue;
}
const unicodeRange = getDeclaration(block, "unicode-range");
// the catalog holds the regular face only, so weight & style are the
// defaults - the range is all that tells a family's faces apart
fontFaces.push(
unicodeRange ? { uri, descriptors: { unicodeRange } } : { uri },
);
}
return { fontFaces, blocks };
};
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
/**
* Asks Google's `css2` API for the family's regular face. Its answer is a
* stylesheet listing one woff2 file per `unicode-range` subset, on
* `fonts.gstatic.com`.
*
* WARN: `css2` answers by User-Agent, and only a browser's gets woff2. On a
* server, pass a `fetch` which sends one (a browser must not: it can't set
* that header, and trying turns the request into a preflighted one).
*/
export const googleFontsCss2Source: GoogleFontSource = async (
font,
{ fetch },
) => {
const url = `${CSS2_URL}?${new URLSearchParams({
family: font.name,
display: "swap",
})}`;
let failure: unknown;
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
if (attempt) {
await sleep(RETRY_DELAY * 3 ** (attempt - 1));
}
try {
const response = await fetch(url, {
signal:
typeof AbortSignal !== "undefined" && "timeout" in AbortSignal
? AbortSignal.timeout(REQUEST_TIMEOUT)
: undefined,
});
if (response.ok) {
const { fontFaces, blocks } = parseFontFaces(await response.text());
const [first, ...rest] = fontFaces;
if (!first) {
throw new GoogleFontError(
"unavailable",
blocks
? `Google Fonts listed no woff2 files for "${font.name}" - on a server, pass a \`fetch\` which sends a browser User-Agent`
: `Google Fonts listed no font files for "${font.name}"`,
);
}
return [first, ...rest];
}
failure = new Error(`${response.status} ${response.statusText}`);
// anything but "try later" is an answer - asking again won't change it
if (response.status < 500 && response.status !== 429) {
break;
}
} catch (error) {
if (error instanceof GoogleFontError) {
throw error;
}
failure = error;
}
}
throw new GoogleFontError(
"unavailable",
`Couldn't load the font files of "${font.name}" from Google Fonts`,
{ cause: failure },
);
};
/**
* A resolver for Google fonts, to pass as a font provider's `resolve` or
* among an export's `fontResolvers` under {@link GOOGLE_FONT_PROVIDER_KEY}.
*
* - Resolves catalog families only, by exact name. Anything else rejects, so
* that text keeps its font id and renders in a fallback font.
* - Metrics come from the catalog, never from the files, so every host and
* every renderer lays out the same text the same way.
* - Transient failures are retried here - the editor doesn't retry a family
* which failed to resolve until the user asks it to.
* - Concurrent calls for a family share one request. Results aren't kept:
* the editor caches definitions itself, and a long-lived server process
* would otherwise hold on to file urls Google has since replaced.
*/
export const createGoogleFontResolver = ({
fetch: fetchOption,
source = googleFontsCss2Source,
}: {
/** defaults to the global `fetch` - see {@link googleFontsCss2Source} */
fetch?: typeof fetch;
/** where the font files are - defaults to Google */
source?: GoogleFontSource;
} = {}): FontResolver => {
const inFlight = new Map<string, Promise<FontDefinition>>();
let active = 0;
const waiting: (() => void)[] = [];
const withSlot = async <T>(task: () => Promise<T>): Promise<T> => {
if (active >= CONCURRENCY) {
await new Promise<void>((resolve) => waiting.push(resolve));
}
active++;
try {
return await task();
} finally {
active--;
waiting.shift()?.();
}
};
return (familyName) => {
let resolving = inFlight.get(familyName);
if (!resolving) {
resolving = (async () => {
const font = (await loadGoogleFontCatalog()).get(familyName);
if (!font) {
throw new GoogleFontError(
"unknown-family",
`"${familyName}" isn't a Google font this version knows`,
);
}
const fontFaces = await withSlot(() =>
source(font, {
// looked up late, so that a `fetch` patched after creating the
// resolver (i.e. by a test, or instrumentation) is honored
fetch: fetchOption ?? ((...args) => globalThis.fetch(...args)),
}),
);
return { fontFaces, metadata: { metrics: font.metrics } };
})();
inFlight.set(familyName, resolving);
const forget = () => inFlight.delete(familyName);
resolving.then(forget, forget);
}
return resolving;
};
};
const SUGGESTIONS_LIMIT = 24;
const getEditDistance = (a: string, b: string) => {
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
for (let i = 1; i <= a.length; i++) {
let previous = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const current = row[j];
row[j] = Math.min(
row[j] + 1,
row[j - 1] + 1,
previous + (a[i - 1] === b[j - 1] ? 0 : 1),
);
previous = current;
}
}
return row[b.length];
};
/**
* A font provider's `search`, over the catalog: the families whose name
* contains the query, in the catalog's order. Only when none does, the
* families a typo away ("literrata").
*/
export const searchGoogleFonts = async (
query: string,
options?: { signal?: AbortSignal },
): Promise<FontSearchResult> => {
const { fonts } = await loadGoogleFontCatalog();
options?.signal?.throwIfAborted();
const needle = query.trim().toLowerCase();
if (!needle) {
return { kind: "match", fonts: [] };
}
const matches = fonts
.filter((font) => font.name.toLowerCase().includes(needle))
.map((font) => font.name);
if (matches.length) {
return { kind: "match", fonts: matches };
}
// against the name's start too, as a typo usually comes with a query
// which is only the beginning of the name
const maxDistance = Math.max(1, Math.floor(needle.length / 4));
const suggestions: { name: string; distance: number }[] = [];
for (const { name } of fonts) {
const lowerCased = name.toLowerCase();
const distance = Math.min(
getEditDistance(needle, lowerCased.slice(0, needle.length)),
getEditDistance(needle, lowerCased),
);
if (distance <= maxDistance) {
suggestions.push({ name, distance });
}
}
return {
kind: "suggestion",
// stable, so equally close families stay in the catalog's order
fonts: suggestions
.sort((a, b) => a.distance - b.distance)
.slice(0, SUGGESTIONS_LIMIT)
.map((suggestion) => suggestion.name),
};
};
/**
* How many of the catalog's families `loadMoreGoogleFonts` pages through at
* most: its first ones. The rest is found by `searchGoogleFonts`, which
* covers the whole catalog. (The catalog is smaller than this today.)
*
* A font picker draws each family's name in its own font, so browsing costs
* a download per family (about 20 KB) and the memory of a loaded font, which
* the page keeps until it's reloaded.
*/
export const GOOGLE_FONT_BROWSE_LIMIT = 100;
/**
* A font provider's `loadMore`, over the catalog: its families (the first
* `GOOGLE_FONT_BROWSE_LIMIT` of them) a page at a time, in its order.
*/
export const loadMoreGoogleFonts = async ({
offset,
limit,
signal,
}: {
offset: number;
limit: number;
signal?: AbortSignal;
}): Promise<string[]> => {
const { fonts } = await loadGoogleFontCatalog();
signal?.throwIfAborted();
return fonts
.slice(offset, Math.min(offset + limit, GOOGLE_FONT_BROWSE_LIMIT))
.map((font) => font.name);
};
/**
* A font provider's `getPreviewText`: a sample in the family's own script
* where it has one, "" otherwise (which the editor previews as "Aa").
*/
export const getGoogleFontPreviewText = async (
familyName: string,
): Promise<string> =>
(await loadGoogleFontCatalog()).get(familyName)?.previewText ?? "";
/**
* A font provider's `getKind`: what kind of font the family is, for the icon
* of its row in the font list.
*/
export const getGoogleFontKind = async (
familyName: string,
): Promise<FontKind | undefined> =>
(await loadGoogleFontCatalog()).get(familyName)?.kind;
/**
* The catalog's families by name and in its order, for a font picker's
* `availableFonts`: a few of each kind. Here as well, so that a host can list
* them without loading the catalog.
*/
export const GOOGLE_FONT_DEFAULT_PICKS: readonly string[] = [
// handwriting
"Kalam",
"Patrick Hand",
"Pacifico",
// sans
"Open Sans",
// serif
"Literata",
// monospace
"Fira Mono",
// display
"Bevan",
// Japanese
"Zen Maru Gothic",
// Korean
"Gowun Dodum",
];
/**
* The Google fonts as a font provider, for `<Excalidraw fontProviders>`
* under {@link GOOGLE_FONT_PROVIDER_KEY}:
*
* ```ts
* const google = createGoogleFontProvider();
* // image exports made outside of the editor don't get its `fontProviders`
* registerFontResolvers({ [GOOGLE_FONT_PROVIDER_KEY]: google.resolve });
*
* <Excalidraw fontProviders={{ [GOOGLE_FONT_PROVIDER_KEY]: google }} />
* ```
*
* Whatever the catalog and the font picker come to need from a provider is
* wired up here, so a host needn't follow along. Spread it to change a part,
* i.e. `availableFonts` for a list of your own.
*/
export const createGoogleFontProvider = ({
resolve = createGoogleFontResolver(),
offerInPicker = true,
}: {
/**
* Defaults to `createGoogleFontResolver()`. Pass your own for another
* `source` of the font files, or to share one you've created already.
*/
resolve?: FontResolver;
/**
* `false` keeps the fonts out of the font picker: none is listed up front,
* found by its search or browsed to. A scene's Google fonts still render,
* and are listed for as long as the scene uses them.
*
* @default true
*/
offerInPicker?: boolean;
} = {}): FontProvider => ({
resolve,
availableFonts: offerInPicker ? GOOGLE_FONT_DEFAULT_PICKS : [],
getKind: getGoogleFontKind,
getPreviewText: getGoogleFontPreviewText,
...(offerInPicker
? { search: searchGoogleFonts, loadMore: loadMoreGoogleFonts }
: null),
});
+4
View File
@@ -1 +1,5 @@
export * from "./Fonts";
export * from "./FontRegistry";
export * from "./FontsCache";
export * from "./providerKey";
export * from "./resolvers";
+48
View File
@@ -0,0 +1,48 @@
/**
* The rule for font provider keys.
*
* WARN: no imports here - this is also loaded on its own, without the editor
* (see `./resolvers`).
*/
/**
* The provider key of Google Fonts, i.e. "google:Roboto" - the one key we
* define ourselves. It names the catalog rather than whoever serves the
* files: the family of that exact name, in its regular face.
*/
export const GOOGLE_FONT_PROVIDER_KEY = "google";
/** provider keys without a dot are reserved for us - hosts can't register others */
const RESERVED_FONT_PROVIDER_KEYS: ReadonlySet<string> = new Set([
GOOGLE_FONT_PROVIDER_KEY,
]);
/** reverse DNS, i.e. "com.acme.fonts" - lowercase, at least one dot */
const HOST_FONT_PROVIDER_KEY_REGEX = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/;
/**
* Whether the key can be registered as a font provider. A key is persisted
* into every `fontFamily` it resolves (i.e. "com.acme.fonts:Brand Sans") and
* travels with the document, so it can never change and has to mean the same
* thing everywhere:
*
* - {@link GOOGLE_FONT_PROVIDER_KEY}, or
* - a reverse-DNS key under a domain the host owns, i.e. "com.acme.fonts".
* Requiring the dot is what keeps the rest of the dotless namespace free
* for us to define later.
*
* Lowercase only: provider keys are compared verbatim, and "Google" next to
* "google" would be two providers for what reads as one.
*/
export const isValidFontProviderKey = (providerKey: string): boolean =>
RESERVED_FONT_PROVIDER_KEYS.has(providerKey) ||
HOST_FONT_PROVIDER_KEY_REGEX.test(providerKey);
/** throws for a key which can't be registered - see `isValidFontProviderKey` */
export const validateFontProviderKey = (providerKey: string) => {
if (!isValidFontProviderKey(providerKey)) {
throw new Error(
`Invalid font provider key "${providerKey}": expected "${GOOGLE_FONT_PROVIDER_KEY}", or a lowercase reverse-DNS key containing a dot, i.e. "com.example.fonts"`,
);
}
};
+64
View File
@@ -0,0 +1,64 @@
/**
* Font resolvers registered for image exports.
*
* WARN: no runtime imports of editor code here - a host registers its
* resolvers at startup, and that must not load the editor along.
*/
import { validateFontProviderKey } from "./providerKey";
import type { FontResolvers } from "./Fonts";
/**
* Kept on the global object rather than in this module, so that every copy of
* the package in the realm (a page, a worker, a server process) reads the
* same registrations: the editor, `@excalidraw/utils`, a second bundle of
* either. Whichever copy an export runs in, and whenever that copy got
* loaded, it finds what the host registered.
*/
const REGISTRY_KEY = Symbol.for("excalidraw.fontResolvers");
const getRegisteredFontResolvers = (): FontResolvers =>
((globalThis as { [REGISTRY_KEY]?: FontResolvers })[REGISTRY_KEY] ??= {});
/**
* Register font resolvers for every image export, so that no export call has
* to remember `config.fontResolvers` - without a resolver, text in a custom
* font is exported in a fallback font.
*
* Call it once in each realm which exports - a page, a worker, a server
* process - as early as its code starts. It doesn't need the editor loaded
* (import it from `@excalidraw/excalidraw/fonts/google` to keep it that
* way), and an export only looks the resolvers up when it runs, so nothing
* depends on what else got loaded first.
*
* - A resolver passed to an export in `config.fontResolvers` wins over a
* registered one for the same provider.
* - The editor's own exports already use its `fontProviders`. Those aren't
* registered here on mount: an export elsewhere on the page would then
* work or not depending on whether an editor happened to mount first.
*
* @returns a function taking back what this call registered
*/
export const registerFontResolvers = (
resolvers: FontResolvers,
): (() => void) => {
for (const provider of Object.keys(resolvers)) {
validateFontProviderKey(provider);
}
const registered = getRegisteredFontResolvers();
Object.assign(registered, resolvers);
return () => {
for (const [provider, resolver] of Object.entries(resolvers)) {
// unless registered over since
if (registered[provider] === resolver) {
delete registered[provider];
}
}
};
};
/** the resolvers an export goes by: the registered ones, overridden per call */
export const getExportFontResolvers = (
resolvers?: FontResolvers,
): FontResolvers => ({ ...getRegisteredFontResolvers(), ...resolvers });
@@ -0,0 +1,34 @@
import { act, render } from "@testing-library/react";
import { useSyncExternalStorePolyfill } from "./useSyncExternalStore";
describe("useSyncExternalStore for React 17", () => {
it("follows the store, also a change landing before it subscribed", () => {
let value = "a";
const listeners = new Set<() => void>();
const subscribe = (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const Reader = () => {
const snapshot = useSyncExternalStorePolyfill(subscribe, () => value);
// changes after this render, before the effect subscribes
if (value === "a") {
value = "b";
}
return <span>{snapshot}</span>;
};
const { container, unmount } = render(<Reader />);
expect(container.textContent).toBe("b");
act(() => {
value = "c";
listeners.forEach((listener) => listener());
});
expect(container.textContent).toBe("c");
unmount();
expect(listeners.size).toBe(0);
});
});
@@ -0,0 +1,34 @@
import React, { useEffect, useReducer, useRef } from "react";
/**
* For React 17, which has none. Subscribes in an effect, and reads again
* once subscribed: a change landing between the render and the subscription
* would otherwise go unnoticed until the next one.
*/
export const useSyncExternalStorePolyfill = <T>(
subscribe: (onStoreChange: () => void) => () => void,
getSnapshot: () => T,
): T => {
const [, rerender] = useReducer((count: number) => count + 1, 0);
const snapshot = getSnapshot();
const getSnapshotRef = useRef(getSnapshot);
getSnapshotRef.current = getSnapshot;
const renderedSnapshotRef = useRef(snapshot);
renderedSnapshotRef.current = snapshot;
useEffect(() => {
const onStoreChange = () => {
if (getSnapshotRef.current() !== renderedSnapshotRef.current) {
rerender();
}
};
const unsubscribe = subscribe(onStoreChange);
onStoreChange();
return unsubscribe;
}, [subscribe]);
return snapshot;
};
export const useSyncExternalStore: typeof useSyncExternalStorePolyfill =
React.useSyncExternalStore || useSyncExternalStorePolyfill;
+33
View File
@@ -114,6 +114,9 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
renderEmbeddable,
aiEnabled,
showDeprecatedFonts,
fontProviders,
fontPickerTip,
fontFavorites,
renderScrollbars,
viewportStatusFrame,
currentUserControls,
@@ -257,6 +260,9 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
renderEmbeddable={renderEmbeddable}
aiEnabled={aiEnabled !== false}
showDeprecatedFonts={showDeprecatedFonts}
fontProviders={fontProviders}
fontPickerTip={fontPickerTip}
fontFavorites={fontFavorites}
renderScrollbars={renderScrollbars}
viewportStatusFrame={viewportStatusFrame}
currentUserControls={currentUserControls}
@@ -517,6 +523,32 @@ export type {
export { zoomToFitBounds, DEFAULT_OVERSCROLL } from "./viewport";
export type {
FontKind,
FontProvider,
FontProviders,
FontSearchResult,
ProvidedFont,
} from "./types";
export type { CustomFontFamily, FontFamily } from "@excalidraw/common";
export {
isCustomFontFamily,
isBuiltInFontFamily,
isProviderQualifiedFontFamily,
} from "@excalidraw/common";
export {
GOOGLE_FONT_PROVIDER_KEY,
isValidFontProviderKey,
} from "./fonts/providerKey";
export type {
FontDefinition,
FontRegistrationResult,
FontResolutionStatus,
FontResolver,
FontResolvers,
ExcalidrawFontFaceDescriptor,
} from "./fonts";
export {
getCommonBounds,
getVisibleSceneBounds,
@@ -530,6 +562,7 @@ export { getDataURL } from "./data/blob";
export { isElementLink } from "@excalidraw/element";
export { Fonts } from "./fonts/Fonts";
export { registerFontResolvers } from "./fonts/resolvers";
export { setCustomTextMetricsProvider } from "@excalidraw/element";
export type { RenderEnvironment } from "@excalidraw/element";
+11 -1
View File
@@ -749,9 +749,19 @@
"old": "old"
},
"sceneFonts": "In this scene",
"favoriteFonts": "Favorites",
"availableFonts": "Available fonts",
"loadMore": "Browse more fonts",
"loadingMore": "Loading…",
"searchForMore": "Use search for more",
"addToFavorites": "Drag to favorite",
"removeFromFavorites": "Remove favorite",
"searchResults": "Search results",
"moreResults": "+{{count}} more, keep typing to narrow",
"didYouMean": "Did you mean…",
"empty": "No fonts found",
"topPicksTip": "Tip: drag any font onto your top picks to pin it",
"searching": "Searching…",
"topPicksTip": "Drag a font to pin",
"resetTopPicks": "Reset to default top picks"
},
"userList": {
+6
View File
@@ -18,6 +18,12 @@
"./utils/*": {
"types": "./dist/types/utils/src/*.d.ts"
},
"./fonts/google": {
"types": "./dist/types/excalidraw/fonts/google/index.d.ts",
"development": "./dist/dev/fonts-google.js",
"production": "./dist/prod/fonts-google.js",
"default": "./dist/prod/fonts-google.js"
},
"./*": {
"types": "./dist/types/excalidraw/*.d.ts"
},
+83 -5
View File
@@ -17,7 +17,11 @@ import {
removeDarkModeFilter,
} from "@excalidraw/common";
import { getCommonBounds, getElementAbsoluteCoords } from "@excalidraw/element";
import {
getCommonBounds,
getElementAbsoluteCoords,
Scene,
} from "@excalidraw/element";
import {
getInitializedImageElements,
@@ -61,7 +65,7 @@ import { serializeAsJSON } from "../data/json";
import { restoreAppState, restoreElements } from "../data/restore";
import { encodePngMetadata } from "../data/image";
import { Fonts } from "../fonts";
import { Fonts, getExportFontResolvers } from "../fonts";
import { renderStaticScene } from "../renderer/staticScene";
import { renderSceneToSvg } from "../renderer/staticSvgScene";
@@ -72,6 +76,8 @@ import {
copyToClipboard,
} from "../clipboard";
import type { FontResolvers } from "../fonts";
import type { RenderableElementsMap } from "./types";
import type { AppState, BinaryFiles, NormalizedZoomValue } from "../types";
@@ -346,6 +352,23 @@ type ExportSceneBaseConfig = {
* Host environment overrides, e.g. for test environments or Node.js.
*/
environment?: ExportEnvironment;
/**
* Resolvers for custom (provider-qualified) font families, keyed by provider
* id - without the matching resolver that text falls back to a generic font.
* Pass the same resolvers given to `fontProviders`.
*
* Rather than passing them to every export, register them once with
* `registerFontResolvers()`. What is passed here wins over a registered
* resolver for the same provider.
*
* Needed even when an editor on the page has the fonts registered, if
* exporting through `@excalidraw/utils` - it ships its own copy of the font
* registry (and of the registered resolvers).
*
* Exports render persisted geometry as-is - text measured before its font
* loaded keeps those (fallback-derived) measurements.
*/
fontResolvers?: FontResolvers;
exportingFrame?: NonDeleted<ExcalidrawFrameLikeElement> | null;
/**
@@ -564,6 +587,35 @@ const configExportDimension = async ({
const { exportingFrame } = cfg;
// exports never record resolution failures - a transient one must not mark
// the family failed for a live editor sharing the page-scoped failure set
const fontResolvers = getExportFontResolvers(cfg.fontResolvers);
// The fonts go into the document the export draws in: a canvas can't use
// the faces of another one (i.e. an editor in a popout window, whose
// exports would otherwise load them into the opener's). A document without
// a font set (a DOM implementation's) is left to the defaults.
const fontsDocument = renderEnvironment.document?.fonts
? renderEnvironment.document
: undefined;
const fonts = new Fonts(new Scene(), fontResolvers, undefined, {
ownerDocument: fontsDocument,
});
// resolve custom families before `restore` - a programmatic text element
// (one without `lineHeight`/`height`) derives its line height from the
// family metrics, which only exist once registered
// (not for what won't be exported: `data.elements` may hold deleted ones)
const exportedElements = data.elements.filter(
(element) => !element.isDeleted,
);
if (Object.keys(fontResolvers).length) {
await Fonts.registerElementsFonts(exportedElements, fonts, {
recordFailure: false,
});
}
// nothing else would tell: the text just comes out in another font
Fonts.warnAboutUnresolvableFonts(exportedElements, fonts);
// restore elements (normalizes & drops invisible elements) and filter out
// deleted ones. The type contract requires non-deleted elements already,
// but types alone don't protect JS consumers passing raw scene data.
@@ -673,7 +725,7 @@ const configExportDimension = async ({
if (cfg.environment?.loadFonts) {
await cfg.environment.loadFonts();
} else {
await Fonts.loadElementsFonts(elements);
await Fonts.loadElementsFonts(elements, fonts, { recordFailure: false });
}
// value used to scale the canvas context. By default, we use this to
@@ -828,6 +880,7 @@ const configExportDimension = async ({
backgroundColor,
paintedBackgroundColor,
theme,
fonts,
};
};
@@ -944,6 +997,7 @@ type ExportToSvgConfig = Pick<
| "scale"
| "frames"
| "environment"
| "fontResolvers"
> &
ExportSizeConfig & {
/**
@@ -1001,6 +1055,7 @@ const exportToSvg = async ({
backgroundColor,
paintedBackgroundColor,
theme,
fonts,
} = await configExportDimension({ data, config, renderEnvironment });
const offsetX = -(x - normalizedPadding);
@@ -1107,7 +1162,9 @@ const exportToSvg = async ({
const fontFaces =
config?.skipInliningFonts !== true
? await Fonts.generateFontFaceDeclarations(elements)
? await Fonts.generateFontFaceDeclarations(elements, fonts, {
recordFailure: false,
})
: [];
const delimiter = "\n "; // 6 spaces
@@ -1377,6 +1434,27 @@ export function exportScene(
}
}
// ---------------------------------------------------------------------------
// serializeSvg
// ---------------------------------------------------------------------------
/**
* The SVG as markup, for anything which leaves the page (a file, the
* clipboard).
*
* `outerHTML` is *HTML* serialization, which writes a non-breaking space as
* `&nbsp;` - an entity XML doesn't define, so the result fails to parse
* everywhere but inside an HTML document. It's the only such entity: the
* others it writes (`&amp;`, `&lt;`, `&gt;`, `&quot;`) are XML's own, and a
* literal "&nbsp;" in the text comes out as `&amp;nbsp;`, so replacing it is
* exact.
*
* Not `XMLSerializer`, as engines disagree on our `xmlns` attribute - jsdom
* declares the namespace twice, which is no more parseable.
*/
export const serializeSvg = (svg: SVGSVGElement): string =>
svg.outerHTML.replace(/&nbsp;/g, "&#160;");
// ---------------------------------------------------------------------------
// exportToClipboard
// ---------------------------------------------------------------------------
@@ -1390,7 +1468,7 @@ export const exportToClipboard = async (
) => {
if (opts.type === "svg") {
const svg = await exportScene(opts);
await copyTextToSystemClipboard(svg.outerHTML);
await copyTextToSystemClipboard(serializeSvg(svg));
} else if (opts.type === "png") {
await copyBlobToClipboardAsPng(exportScene(opts));
} else if (opts.type === "json") {
+10 -1
View File
@@ -1,4 +1,8 @@
import type { UserIdleState, EditorInterface } from "@excalidraw/common";
import type {
UserIdleState,
EditorInterface,
FontFamily,
} from "@excalidraw/common";
import type {
ExcalidrawElement,
ExcalidrawFrameLikeElement,
@@ -59,6 +63,11 @@ export type StaticCanvasRenderConfig = {
pendingFlowchartNodes: PendingExcalidrawElements | null;
theme: AppState["theme"];
elementRenderOverrides?: ElementRenderOverrides;
/**
* editor only: text in a family this returns true for is left undrawn,
* rather than drawn in the fallback font - see `AppFonts.isFontBlocked`
*/
isFontBlocked?: (fontFamily: FontFamily) => boolean;
};
export type SVGRenderConfig = {
@@ -149,6 +149,10 @@ describe("Test <MermaidToExcalidraw/>", () => {
expect(dialog.querySelector('[data-testid="mermaid-error"]')).toBeNull();
// the sample definition is populated asynchronously after the editor
// mounts - asserting straight away races it (and under `--update` a lost
// race silently rewrites the snapshot to the empty interim state)
await waitFor(() => expect(editor.textContent).not.toBe(""));
expect(editor.textContent).toMatchSnapshot();
updateTextEditor(editor, "flowchart TD1");
@@ -12677,6 +12677,524 @@ exports[`history > multiplayer undo/redo > should update history entries after r
]
`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a drag out of the drag's undo entry > [end of test] appState 1`] = `
{
"activeEmbeddable": null,
"activeLockedId": null,
"activeTool": {
"customType": null,
"fromSelection": false,
"lastActiveTool": null,
"locked": false,
"type": "selection",
},
"bindMode": "orbit",
"bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {},
"colorTopPicks": {
"bucketFill": null,
"elementBackground": null,
"elementStroke": null,
"stickyNoteBackground": null,
"stickyNoteStroke": null,
},
"contextMenu": null,
"croppingElementId": null,
"currentHoveredFontFamily": null,
"currentItemArrowType": "round",
"currentItemBackgroundColor": "transparent",
"currentItemEndArrowhead": "arrow",
"currentItemFillStyle": "solid",
"currentItemFontFamily": 5,
"currentItemFontSize": 20,
"currentItemOpacity": 100,
"currentItemRoughness": 1,
"currentItemRoundness": "sharp",
"currentItemStartArrowhead": null,
"currentItemStickynoteBackgroundColor": "#ffdf6b",
"currentItemStickynoteStrokeColor": "#1e1e1e",
"currentItemStrokeColor": "#1e1e1e",
"currentItemStrokeStyle": "solid",
"currentItemStrokeVariability": "constant",
"currentItemStrokeWidthKey": "medium",
"currentItemTextAlign": "left",
"cursorButton": "up",
"defaultSidebarDockedPreference": false,
"editingFrame": null,
"editingGroupId": null,
"editingTextElement": null,
"elementsToHighlight": null,
"errorMessage": null,
"exportBackground": true,
"exportEmbedScene": false,
"exportScale": 1,
"exportWithDarkMode": false,
"fileHandle": null,
"fontTopPicks": null,
"frameRendering": {
"clip": true,
"enabled": true,
"name": true,
"outline": true,
},
"frameToHighlight": null,
"gridModeEnabled": false,
"gridSize": 20,
"gridStep": 5,
"height": 0,
"hoveredElementIds": {},
"inputDevice": "auto",
"isBindingEnabled": true,
"isCropping": false,
"isLoading": false,
"isMidpointSnappingEnabled": true,
"isResizing": false,
"isRotating": false,
"lastPointerDownWith": "mouse",
"lockedMultiSelections": {},
"minimapEnabled": false,
"multiElement": null,
"newElement": null,
"objectsSnapModeEnabled": false,
"offsetLeft": 0,
"offsetTop": 0,
"openDialog": null,
"openMenu": null,
"openPopup": null,
"openSidebar": null,
"originSnapOffset": null,
"penDetected": false,
"penMode": false,
"preferredSelectionTool": {
"initialized": true,
"type": "selection",
},
"previousSelectedElementIds": {
"id0": true,
},
"resizingElement": null,
"scrollConstraints": null,
"scrollX": 0,
"scrollY": 0,
"searchMatches": null,
"selectedElementIds": {},
"selectedElementsAreBeingDragged": false,
"selectedGroupIds": {},
"selectionElement": null,
"shouldCacheIgnoreZoom": false,
"showHints": true,
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"splitOnPaste": false,
"stats": {
"open": false,
"panels": 3,
},
"suggestedBinding": null,
"textToolHover": null,
"theme": "light",
"toast": null,
"viewBackgroundColor": "#ffffff",
"viewModeEnabled": false,
"width": 0,
"zenModeEnabled": false,
"zoom": {
"value": 1,
},
}
`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a drag out of the drag's undo entry > [end of test] element 0 1`] = `
{
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": "test.historyrepair:Font",
"fontSize": 20,
"frameId": null,
"groupIds": [],
"height": 100,
"id": "id0",
"index": "a0",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 2,
"link": null,
"locked": false,
"opacity": 100,
"originalText": "drag me",
"roughness": 1,
"roundness": null,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"text": "drag me",
"textAlign": "left",
"type": "text",
"updated": 1,
"version": 5,
"verticalAlign": "top",
"width": 100,
"x": 10,
"y": 10,
}
`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a drag out of the drag's undo entry > [end of test] number of elements 1`] = `1`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a drag out of the drag's undo entry > [end of test] number of renders 1`] = `9`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a drag out of the drag's undo entry > [end of test] redo stack 1`] = `
[
{
"appState": AppStateDelta {
"delta": Delta {
"deleted": {
"selectedElementIds": {},
},
"inserted": {
"selectedElementIds": {
"id0": true,
},
},
},
},
"elements": {
"added": {},
"removed": {},
"updated": {
"id0": {
"deleted": {
"version": 5,
"x": 10,
},
"inserted": {
"version": 4,
"x": 40,
},
},
},
},
"id": "id6",
},
]
`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a drag out of the drag's undo entry > [end of test] undo stack 1`] = `
[
{
"appState": AppStateDelta {
"delta": Delta {
"deleted": {},
"inserted": {},
},
},
"elements": {
"added": {},
"removed": {
"id0": {
"deleted": {
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": "test.historyrepair:Font",
"fontSize": 20,
"frameId": null,
"groupIds": [],
"height": 100,
"index": "a0",
"isDeleted": false,
"labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
"opacity": 100,
"originalText": "drag me",
"roughness": 1,
"roundness": null,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"text": "drag me",
"textAlign": "left",
"type": "text",
"version": 2,
"verticalAlign": "top",
"width": 100,
"x": 10,
"y": 10,
},
"inserted": {
"isDeleted": true,
"version": 1,
},
},
},
"updated": {},
},
"id": "id2",
},
]
`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a text edit out of the edit's undo entry > [end of test] appState 1`] = `
{
"activeEmbeddable": null,
"activeLockedId": null,
"activeTool": {
"customType": null,
"fromSelection": false,
"lastActiveTool": null,
"locked": false,
"type": "selection",
},
"bindMode": "orbit",
"bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {},
"colorTopPicks": {
"bucketFill": null,
"elementBackground": null,
"elementStroke": null,
"stickyNoteBackground": null,
"stickyNoteStroke": null,
},
"contextMenu": null,
"croppingElementId": null,
"currentHoveredFontFamily": null,
"currentItemArrowType": "round",
"currentItemBackgroundColor": "transparent",
"currentItemEndArrowhead": "arrow",
"currentItemFillStyle": "solid",
"currentItemFontFamily": 5,
"currentItemFontSize": 20,
"currentItemOpacity": 100,
"currentItemRoughness": 1,
"currentItemRoundness": "sharp",
"currentItemStartArrowhead": null,
"currentItemStickynoteBackgroundColor": "#ffdf6b",
"currentItemStickynoteStrokeColor": "#1e1e1e",
"currentItemStrokeColor": "#1e1e1e",
"currentItemStrokeStyle": "solid",
"currentItemStrokeVariability": "constant",
"currentItemStrokeWidthKey": "medium",
"currentItemTextAlign": "left",
"cursorButton": "up",
"defaultSidebarDockedPreference": false,
"editingFrame": null,
"editingGroupId": null,
"editingTextElement": null,
"elementsToHighlight": null,
"errorMessage": null,
"exportBackground": true,
"exportEmbedScene": false,
"exportScale": 1,
"exportWithDarkMode": false,
"fileHandle": null,
"fontTopPicks": null,
"frameRendering": {
"clip": true,
"enabled": true,
"name": true,
"outline": true,
},
"frameToHighlight": null,
"gridModeEnabled": false,
"gridSize": 20,
"gridStep": 5,
"height": 0,
"hoveredElementIds": {},
"inputDevice": "auto",
"isBindingEnabled": true,
"isCropping": false,
"isLoading": false,
"isMidpointSnappingEnabled": true,
"isResizing": false,
"isRotating": false,
"lastPointerDownWith": "mouse",
"lockedMultiSelections": {},
"minimapEnabled": false,
"multiElement": null,
"newElement": null,
"objectsSnapModeEnabled": false,
"offsetLeft": 0,
"offsetTop": 0,
"openDialog": null,
"openMenu": null,
"openPopup": null,
"openSidebar": null,
"originSnapOffset": null,
"penDetected": false,
"penMode": false,
"preferredSelectionTool": {
"initialized": true,
"type": "selection",
},
"previousSelectedElementIds": {},
"resizingElement": null,
"scrollConstraints": null,
"scrollX": 0,
"scrollY": 0,
"searchMatches": null,
"selectedElementIds": {},
"selectedElementsAreBeingDragged": false,
"selectedGroupIds": {},
"selectionElement": null,
"shouldCacheIgnoreZoom": false,
"showHints": true,
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"splitOnPaste": false,
"stats": {
"open": false,
"panels": 3,
},
"suggestedBinding": null,
"textToolHover": null,
"theme": "light",
"toast": null,
"viewBackgroundColor": "#ffffff",
"viewModeEnabled": false,
"width": 0,
"zenModeEnabled": false,
"zoom": {
"value": 1,
},
}
`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a text edit out of the edit's undo entry > [end of test] element 0 1`] = `
{
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
"fontSize": 20,
"frameId": null,
"groupIds": [],
"height": 25,
"id": "id0",
"index": "a0",
"isDeleted": true,
"labelPosition": null,
"lineHeight": 2,
"link": null,
"locked": false,
"opacity": 100,
"originalText": "hello",
"roughness": 1,
"roundness": null,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"text": "hello",
"textAlign": "left",
"type": "text",
"updated": 1,
"version": 5,
"verticalAlign": "top",
"width": 50,
"x": 100,
"y": "87.50000",
}
`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a text edit out of the edit's undo entry > [end of test] number of elements 1`] = `1`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a text edit out of the edit's undo entry > [end of test] number of renders 1`] = `11`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a text edit out of the edit's undo entry > [end of test] redo stack 1`] = `
[
{
"appState": AppStateDelta {
"delta": Delta {
"deleted": {
"selectedElementIds": {},
},
"inserted": {
"selectedElementIds": {
"id0": true,
},
},
},
},
"elements": {
"added": {
"id0": {
"deleted": {
"isDeleted": true,
"version": 5,
},
"inserted": {
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
"fontSize": 20,
"frameId": null,
"groupIds": [],
"height": 25,
"index": "a0",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 2,
"link": null,
"locked": false,
"opacity": 100,
"originalText": "hello",
"roughness": 1,
"roundness": null,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"text": "hello",
"textAlign": "left",
"type": "text",
"version": 4,
"verticalAlign": "top",
"width": 50,
"x": 100,
"y": "87.50000",
},
},
},
"removed": {},
"updated": {},
},
"id": "id3",
},
]
`;
exports[`history > singleplayer undo/redo > keeps a font repair deferred during a text edit out of the edit's undo entry > [end of test] undo stack 1`] = `[]`;
exports[`history > singleplayer undo/redo > remounting undo/redo buttons should initialize undo/redo state correctly > [end of test] appState 1`] = `
{
"activeEmbeddable": null,
@@ -29,6 +29,7 @@ import { API } from "./helpers/api";
import { mockMermaidToExcalidraw } from "./helpers/mocks";
import { Pointer, Keyboard } from "./helpers/ui";
import {
act,
fireEvent,
render,
waitFor,
@@ -36,6 +37,7 @@ import {
unmountComponent,
} from "./test-utils";
import type { FontResolver } from "../fonts";
import type { NormalizedZoomValue } from "../types";
const { h } = window;
@@ -752,6 +754,76 @@ describe("Paste bound text container", () => {
expect(container.width).toBe(166);
});
});
it("should preserve custom-font geometry until the font loads", async () => {
unmountComponent();
let resolveFont!: (font: Awaited<ReturnType<FontResolver>>) => void;
const resolve: FontResolver = vi.fn(
() =>
new Promise<Awaited<ReturnType<FontResolver>>>((resolvePromise) => {
resolveFont = resolvePromise;
}),
);
const check = vi.spyOn(document.fonts, "check").mockReturnValue(true);
try {
await render(
<Excalidraw
autoFocus={true}
handleKeyboardGlobally={true}
initialData={{
appState: { zoom: { value: 1 as NormalizedZoomValue } },
}}
fontProviders={{
"test.paste": {
icon: <span />,
availableFonts: ["Deferred"],
resolve,
},
}}
/>,
);
Object.assign(document, {
elementFromPoint: () => GlobalTestState.canvas,
});
pasteWithCtrlCmdShiftV(
JSON.stringify({
type: "excalidraw/clipboard",
elements: [
container,
{ ...textElement, fontFamily: "test.paste:Deferred" },
],
}),
);
await waitFor(() => {
expect(resolve).toHaveBeenCalledWith("Deferred");
expect(h.elements).toHaveLength(2);
});
expect(h.elements[0].height).toBe(187.01953125);
expect(h.elements[1].width).toBe(154);
expect(h.elements[1].height).toBe(175);
await act(async () => {
resolveFont({
fontFaces: [{ uri: "https://example.com/font.woff2" }],
metadata: {
metrics: {
unitsPerEm: 1000,
ascender: 800,
descender: -200,
lineHeight: 1.2,
},
},
});
});
await waitFor(() => expect(h.elements[0].height).toBe(368));
} finally {
check.mockRestore();
}
});
});
describe("pasting & frames", () => {
@@ -9,14 +9,14 @@ import { vi } from "vitest";
import { COLOR_PALETTE, FONT_FAMILY } from "@excalidraw/common";
import type { FontFamilyValues } from "@excalidraw/element/types";
import type { FontFamily } from "@excalidraw/common";
import { Excalidraw } from "../index";
import { useColorTopPicksDnD } from "../components/ColorPicker/colorTopPicksDnD";
import type { ExcalidrawImperativeAPI } from "../types";
const mountEditorInOwnDocument = (currentItemFontFamily?: FontFamilyValues) => {
const mountEditorInOwnDocument = (currentItemFontFamily?: FontFamily) => {
const iframe = document.createElement("iframe");
document.body.append(iframe);
@@ -3,6 +3,7 @@ import { vi } from "vitest";
import {
COLOR_PALETTE,
DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE,
DEFAULT_SIDEBAR,
FONT_FAMILY,
@@ -174,6 +175,92 @@ describe("restoreElements", () => {
});
});
describe("fontFamily", () => {
const restoreFontFamily = (
// wider than `FontFamily` on purpose - documents hold values the type
// doesn't admit (i.e. "Random Font")
fontFamily: unknown,
) => {
// assigned post-creation - `API.createElement` would default it away
const textElement = {
...API.createElement({ type: "text", text: "text" }),
fontFamily,
};
return (
restore.restoreElements(
[textElement as ExcalidrawTextElement],
null,
)[0] as ExcalidrawTextElement
).fontFamily;
};
it("should preserve built-in (numeric) families", () => {
expect(restoreFontFamily(FONT_FAMILY.Virgil)).toBe(FONT_FAMILY.Virgil);
expect(restoreFontFamily(FONT_FAMILY.Excalifont)).toBe(
FONT_FAMILY.Excalifont,
);
});
it("should preserve unknown numeric families for forward compatibility", () => {
// a file written by a newer version may reference a family we don't know
expect(restoreFontFamily(9999)).toBe(9999);
});
it("should preserve provider-qualified custom families", () => {
expect(restoreFontFamily("google:Roboto")).toBe("google:Roboto");
expect(restoreFontFamily("google:Lilita One")).toBe("google:Lilita One");
});
it("should keep values it can't interpret, as master does", () => {
// rewriting them here would be saved & synced, so no later version
// could ever introduce a new shape - they're handled at render instead
expect(restoreFontFamily("Comic Sans MS")).toBe("Comic Sans MS");
expect(restoreFontFamily(":Roboto")).toBe(":Roboto");
expect(restoreFontFamily("google:")).toBe("google:");
expect(restoreFontFamily("")).toBe("");
const futureShape = { family: "Roboto", weight: 700 };
expect(restoreFontFamily(futureShape)).toBe(futureShape);
});
it("should default a missing family", () => {
expect(restoreFontFamily(undefined)).toBe(DEFAULT_FONT_FAMILY);
expect(restoreFontFamily(null)).toBe(DEFAULT_FONT_FAMILY);
});
it("should map legacy `font` names to built-in families", () => {
const legacyElement = {
...API.createElement({ type: "text", text: "text" }),
font: "20px Virgil",
};
expect(
(
restore.restoreElements(
[legacyElement as any],
null,
)[0] as ExcalidrawTextElement
).fontFamily,
).toBe(FONT_FAMILY.Virgil);
});
it("should default unknown legacy `font` names", () => {
const legacyElement = {
...API.createElement({ type: "text", text: "text" }),
font: "20px Random",
};
expect(
(
restore.restoreElements(
[legacyElement as any],
null,
)[0] as ExcalidrawTextElement
).fontFamily,
).toBe(DEFAULT_FONT_FAMILY);
});
});
it("should not delete empty text element when opts.deleteInvisibleElements is not defined", () => {
const textElement = API.createElement({
type: "text",
@@ -1034,6 +1121,32 @@ describe("restoreElements", () => {
});
describe("restoreAppState", () => {
it("should normalize currentItemFontFamily, unlike element fontFamily", () => {
// valid values pass through untouched
expect(
restore.restoreAppState({ currentItemFontFamily: "google:Roboto" }, null)
.currentItemFontFamily,
).toBe("google:Roboto");
expect(
restore.restoreAppState({ currentItemFontFamily: 9999 }, null)
.currentItemFontFamily,
).toBe(9999);
// persisted data isn't bound by our types - a bare font name defaults,
// whichever source it comes from
expect(
restore.restoreAppState(
{ currentItemFontFamily: "Random Font" as any },
null,
).currentItemFontFamily,
).toBe(DEFAULT_FONT_FAMILY);
expect(
restore.restoreAppState(null, {
currentItemFontFamily: "Random Font" as any,
}).currentItemFontFamily,
).toBe(DEFAULT_FONT_FAMILY);
});
it("should restore freedraw mode app state values", () => {
expect(
restore.restoreAppState(
@@ -270,6 +270,50 @@ describe("dropping scenes", () => {
);
});
describe("dropping a scene with a custom font", () => {
it("resolves the font", async () => {
const resolve = vi.fn(async () => ({
fontFaces: [{ uri: "https://example.com/font.woff2" }] as const,
metadata: {
metrics: {
unitsPerEm: 1000,
ascender: 800,
descender: -200,
lineHeight: 1.2,
},
},
}));
await render(
<Excalidraw
handleKeyboardGlobally
fontProviders={{ "test.drop": { resolve, availableFonts: [] } }}
/>,
);
const file = new h.app.ownerWindow.File(
[
serializeAsJSON(
[
API.createElement({
type: "text",
text: "a",
fontFamily: "test.drop:Font",
}),
],
h.state,
{},
"local",
),
],
"scene.excalidraw",
{ type: MIME_TYPES.json },
);
drag(GlobalTestState.interactiveCanvas, "drop", { files: [file] });
await waitFor(() => expect(resolve).toHaveBeenCalledWith("Font"));
});
});
describe("ignoring drops", () => {
it.each([
["in view mode", { viewModeEnabled: true }],
@@ -25,6 +25,7 @@ describe("restore appState.fontTopPicks", () => {
FONT_FAMILY.Assistant, // private
FONT_FAMILY_FALLBACKS.Xiaolai,
FONT_FAMILY.Virgil, // deprecated, but still pickable
"google:Roboto",
],
} as any,
null,
@@ -32,6 +33,7 @@ describe("restore appState.fontTopPicks", () => {
expect(restored.fontTopPicks).toEqual([
FONT_FAMILY["Lilita One"],
FONT_FAMILY.Virgil,
"google:Roboto",
]);
});
@@ -50,7 +52,8 @@ describe("restore appState.fontTopPicks", () => {
restoreAppState({ fontTopPicks: "junk" } as any, null).fontTopPicks,
).toBe(null);
expect(
restoreAppState({ fontTopPicks: [4, "5"] } as any, null).fontTopPicks,
restoreAppState({ fontTopPicks: [4, "5", ":Roboto"] } as any, null)
.fontTopPicks,
).toBe(null);
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,261 @@
import { isValidFontProviderKey } from "../fonts";
import {
createGoogleFontProvider,
createGoogleFontResolver,
getGoogleFontKind,
getGoogleFontPreviewText,
loadMoreGoogleFonts,
GOOGLE_FONT_DEFAULT_PICKS,
GOOGLE_FONT_PROVIDER_KEY,
GoogleFontError,
loadGoogleFontCatalog,
searchGoogleFonts,
} from "../fonts/google";
import type { GoogleFontSource } from "../fonts/google";
const css = (
faces: { url: string; format?: string; unicodeRange?: string }[],
) =>
faces
.map(
({ url, format = "woff2", unicodeRange }) => `/* subset */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(${url}) format('${format}');${
unicodeRange ? `\n unicode-range: ${unicodeRange};` : ""
}
}`,
)
.join("\n");
const ok = (body: string) => new Response(body, { status: 200 });
describe("Google Fonts catalog", () => {
it("uses the provider key the editor accepts", () => {
expect(GOOGLE_FONT_PROVIDER_KEY).toBe("google");
expect(isValidFontProviderKey(GOOGLE_FONT_PROVIDER_KEY)).toBe(true);
});
it("holds each family once, with usable metrics", async () => {
const { fonts } = await loadGoogleFontCatalog();
expect(new Set(fonts.map((font) => font.name)).size).toBe(fonts.length);
for (const { metrics } of fonts) {
expect(metrics.unitsPerEm).toBeGreaterThan(0);
expect(metrics.lineHeight).toBeGreaterThan(0);
}
});
it("holds the families we offer and no other, in the order they're listed", async () => {
const { fonts } = await loadGoogleFontCatalog();
expect(fonts.map((font) => font.name)).toEqual(GOOGLE_FONT_DEFAULT_PICKS);
});
it("previews a family in its own script where it has one", async () => {
expect(await getGoogleFontPreviewText("Zen Maru Gothic")).toBe("あ");
expect(await getGoogleFontPreviewText("Open Sans")).toBe("");
expect(await getGoogleFontPreviewText("Not A Font")).toBe("");
});
it("tells what kind of font a family is", async () => {
expect(await getGoogleFontKind("Kalam")).toBe("hand-drawn");
expect(await getGoogleFontKind("Fira Mono")).toBe("code");
expect(await getGoogleFontKind("Not A Font")).toBe(undefined);
});
});
describe("createGoogleFontProvider", () => {
it("offers the catalog in the font picker, with the resolver it's given", async () => {
const resolve = vi.fn();
const provider = createGoogleFontProvider({ resolve });
expect(provider.resolve).toBe(resolve);
expect(provider.availableFonts).toEqual(GOOGLE_FONT_DEFAULT_PICKS);
expect(await provider.getKind!("Kalam")).toBe("hand-drawn");
expect(await provider.getPreviewText!("Zen Maru Gothic")).toBe("あ");
expect(provider.search).toBe(searchGoogleFonts);
expect(provider.loadMore).toBe(loadMoreGoogleFonts);
});
it("offers nothing in the picker when told so, and still tells of a scene's fonts", async () => {
const provider = createGoogleFontProvider({ offerInPicker: false });
expect(provider.availableFonts).toEqual([]);
expect(provider.search).toBe(undefined);
expect(provider.loadMore).toBe(undefined);
expect(await provider.getKind!("Kalam")).toBe("hand-drawn");
});
});
describe("createGoogleFontResolver", () => {
it("resolves a family into its faces, with the catalog's metrics", async () => {
const fetch = vi.fn(async (_input: RequestInfo | URL) =>
ok(
css([
{ url: "https://fonts.gstatic.com/a.woff2", unicodeRange: "U+0-FF" },
{ url: "https://fonts.gstatic.com/b.woff2" },
]),
),
);
const definition = await createGoogleFontResolver({ fetch })("Open Sans");
expect(fetch).toHaveBeenCalledTimes(1);
expect(String(fetch.mock.calls[0][0])).toBe(
"https://fonts.googleapis.com/css2?family=Open+Sans&display=swap",
);
expect(definition.fontFaces).toEqual([
{
uri: "https://fonts.gstatic.com/a.woff2",
descriptors: { unicodeRange: "U+0-FF" },
},
{ uri: "https://fonts.gstatic.com/b.woff2" },
]);
expect(definition.metadata.metrics).toEqual(
(await loadGoogleFontCatalog()).get("Open Sans")!.metrics,
);
});
it("rejects a name which isn't in the catalog, without asking Google", async () => {
const fetch = vi.fn();
const resolve = createGoogleFontResolver({ fetch });
// ids are exact - a differently cased name is a different id
for (const name of ["open sans", "Material Icons Round", "Roboto"]) {
await expect(resolve(name)).rejects.toMatchObject({
name: "GoogleFontError",
reason: "unknown-family",
});
}
expect(fetch).not.toHaveBeenCalled();
});
it("retries a transient failure", async () => {
const fetch = vi
.fn()
.mockResolvedValueOnce(new Response("", { status: 503 }))
.mockRejectedValueOnce(new TypeError("Failed to fetch"))
.mockResolvedValueOnce(
ok(css([{ url: "https://fonts.gstatic.com/a.woff2" }])),
);
const definition = await createGoogleFontResolver({ fetch })("Open Sans");
expect(fetch).toHaveBeenCalledTimes(3);
expect(definition.fontFaces).toHaveLength(1);
});
it("doesn't retry an answer which won't change", async () => {
const fetch = vi.fn(async () => new Response("", { status: 400 }));
await expect(
createGoogleFontResolver({ fetch })("Open Sans"),
).rejects.toMatchObject({ reason: "unavailable" });
expect(fetch).toHaveBeenCalledTimes(1);
});
it("explains a stylesheet without woff2 files", async () => {
// what `css2` serves to anything but a browser's User-Agent
const fetch = vi.fn(async () =>
ok(css([{ url: "https://fonts.gstatic.com/a.ttf", format: "truetype" }])),
);
const error = await createGoogleFontResolver({ fetch })("Open Sans").catch(
(error) => error,
);
expect(error).toBeInstanceOf(GoogleFontError);
expect(error.message).toContain("User-Agent");
expect(fetch).toHaveBeenCalledTimes(1);
});
it("shares one request among concurrent calls, and keeps no result", async () => {
const fetch = vi.fn(async () =>
ok(css([{ url: "https://fonts.gstatic.com/a.woff2" }])),
);
const resolve = createGoogleFontResolver({ fetch });
const [first, second] = await Promise.all([
resolve("Open Sans"),
resolve("Open Sans"),
]);
expect(first).toBe(second);
expect(fetch).toHaveBeenCalledTimes(1);
await resolve("Open Sans");
expect(fetch).toHaveBeenCalledTimes(2);
});
it("takes its font files from another source", async () => {
const source = vi.fn<GoogleFontSource>(async () => [
{ uri: "https://mirror.example/roboto.woff2" },
]);
const resolve = createGoogleFontResolver({ source, fetch: vi.fn() });
const definition = await resolve("Open Sans");
expect(source.mock.calls[0][0]).toMatchObject({ name: "Open Sans" });
expect(definition.fontFaces).toEqual([
{ uri: "https://mirror.example/roboto.woff2" },
]);
});
});
describe("searchGoogleFonts", () => {
it("lists the families containing the query, in the catalog's order", async () => {
const { fonts } = await loadGoogleFontCatalog();
const result = await searchGoogleFonts(" An ");
expect(result.kind).toBe("match");
expect(result.fonts.length).toBeGreaterThan(1);
expect(result.fonts).toEqual(
fonts
.filter((font) => font.name.toLowerCase().includes("an"))
.map((font) => font.name),
);
});
it("suggests the families a typo away when nothing matches", async () => {
expect(await searchGoogleFonts("literrata")).toEqual({
kind: "suggestion",
fonts: ["Literata"],
});
});
it("finds nothing for an empty query", async () => {
expect(await searchGoogleFonts(" ")).toEqual({ kind: "match", fonts: [] });
});
it("honors an aborted signal", async () => {
const controller = new AbortController();
controller.abort();
await expect(
searchGoogleFonts("zen", { signal: controller.signal }),
).rejects.toThrow();
});
});
describe("loadMoreGoogleFonts", () => {
it("pages through the catalog, to its end", async () => {
const { fonts } = await loadGoogleFontCatalog();
const names = fonts.map((font) => font.name);
expect(names.length).toBeGreaterThan(5);
expect(await loadMoreGoogleFonts({ offset: 0, limit: 5 })).toEqual(
names.slice(0, 5),
);
// fewer than asked for: the end
expect(await loadMoreGoogleFonts({ offset: 5, limit: 5 })).toEqual(
names.slice(5),
);
expect(
await loadMoreGoogleFonts({ offset: names.length, limit: 5 }),
).toEqual([]);
});
});
@@ -51,6 +51,36 @@ export const mockMermaidToExcalidraw = (opts: {
}
};
/** logged on purpose by tests exercising the font failure paths */
const EXPECTED_FONT_ERRORS = [
"Failed to resolve custom font", // the resolver rejected
"Failed to load font", // the font file didn't fetch
"font search failed", // the provider's search rejected
];
/**
* Keep the errors above out of the test output, so that a passing run doesn't
* read as a broken one. Scoped to them - anything else (i.e. React's act()
* warning) still surfaces.
*
* Returns the spy, which records the muted calls too, so a test can still
* assert the failure was reported.
*/
export const muteExpectedFontErrors = () => {
const consoleError = console.error;
return vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => {
const [message] = args;
if (
typeof message === "string" &&
EXPECTED_FONT_ERRORS.some((expected) => message.startsWith(expected))
) {
return;
}
consoleError(...args);
});
};
// Mock for HTMLImageElement (use with `vi.unstubAllGlobals()`)
// as jsdom.resources: "usable" throws an error on image load
export const mockHTMLImageElement = (
+101
View File
@@ -66,6 +66,7 @@ import {
} from "./fixtures/constants";
import { API } from "./helpers/api";
import { Keyboard, Pointer, UI } from "./helpers/ui";
import { getTextEditor } from "./queries/dom";
import { INITIALIZED_IMAGE_PROPS } from "./helpers/constants";
import {
GlobalTestState,
@@ -145,6 +146,106 @@ describe("history", () => {
});
describe("singleplayer undo/redo", () => {
it("keeps a font repair deferred during a drag out of the drag's undo entry", async () => {
await render(<Excalidraw handleKeyboardGlobally={true} />);
// created before its family is in - bakes in the fallback metrics
const text = API.createElement({
type: "text",
text: "drag me",
x: 10,
y: 10,
fontFamily: "test.historyrepair:Font",
});
API.updateScene({
elements: [text],
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
});
API.setSelectedElements([text]);
const originalLineHeight = text.lineHeight;
expect(originalLineHeight).not.toBe(2);
// drag the element...
mouse.downAt(text.x + text.width / 2, text.y + text.height / 2);
mouse.moveTo(text.x + text.width / 2 + 30, text.y + text.height / 2);
// ...and let its font settle mid-drag - the repair of text measured
// before that (see `AppFonts.repairTextOnFontLoad`) must defer, as
// mutating mid-gesture would corrupt the gesture's undo entry
// (`CaptureUpdateAction.NEVER` outranks the gesture's `EVENTUALLY`)
act(() => {
h.app.fonts.instance.runSceneRepair(() => {
h.app.scene.mutateElement(
h.app.scene.getElement(text.id) as ExcalidrawTextElement,
{ lineHeight: 2 as ExcalidrawTextElement["lineHeight"] },
);
});
});
expect((h.elements[0] as ExcalidrawTextElement).lineHeight).toBe(
originalLineHeight,
);
mouse.up();
// the gesture got captured, then the repair ran in its own
// non-capturable pass
await waitFor(() =>
expect((h.elements[0] as ExcalidrawTextElement).lineHeight).toBe(2),
);
expect(h.elements[0].x).not.toBe(10);
// creation baseline + the drag
expect(API.getUndoStack().length).toBe(2);
Keyboard.undo();
// undo reverts the drag - and only the drag; the repair is not part
// of its entry
expect(h.elements[0].x).toBe(10);
expect((h.elements[0] as ExcalidrawTextElement).lineHeight).toBe(2);
});
it("keeps a font repair deferred during a text edit out of the edit's undo entry", async () => {
await render(<Excalidraw handleKeyboardGlobally={true} />);
UI.clickTool("text");
mouse.clickAt(100, 100);
const editor = await getTextEditor();
fireEvent.input(editor, { target: { value: "hello" } });
const text = h.elements[0] as ExcalidrawTextElement;
expect(text.text).toBe("hello");
// its font settles while typing - the repair must defer, as typing
// isn't captured until submitted: a `CaptureUpdateAction.NEVER` commit
// would take what's been typed into the snapshot, out of undo's reach
act(() => {
h.app.fonts.instance.runSceneRepair(() => {
h.app.scene.mutateElement(
h.app.scene.getElement(text.id) as ExcalidrawTextElement,
{ lineHeight: 2 as ExcalidrawTextElement["lineHeight"] },
);
});
});
// (and something commits meanwhile, i.e. the font load's rerender)
act(() => {
h.app.scene.triggerUpdate();
});
expect((h.elements[0] as ExcalidrawTextElement).lineHeight).not.toBe(2);
Keyboard.exitTextEditor(editor);
// the edit got captured, then the repair ran in its own
// non-capturable pass
await waitFor(() =>
expect((h.elements[0] as ExcalidrawTextElement).lineHeight).toBe(2),
);
expect(API.getUndoStack().length).toBe(1);
Keyboard.undo();
expect(h.elements[0].isDeleted).toBe(true);
});
it("should not collapse when applying corrupted history entry", async () => {
await render(<Excalidraw handleKeyboardGlobally={true} />);
const rect = API.createElement({ type: "rectangle" });
@@ -15,31 +15,25 @@ exports[`exportToSvg > with a CJK font 1`] = `
class="style-fonts"
>
@font-face { font-family: Xiaolai; src: url(data:font/woff2;base64,d09GMgABAAAAAAM0ABEAAAAACzgAAALeAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhQbHhweBmAABAgKCY4uERAKACoLBAABNgIkAwQEIAWCXgcgDBQbNQrIHoVxw13yP14ojTKEaM1QThFEa2X1zD6gAgRNQZKAQm5cJIKwaMzJFzIynkDG/ty7111blluK97oujDnzP3PlZLtT5hYmqg9h0LjgDmEQdkzh6nAwbBu0VTWm4+n/f+8edt9rio0t1vvn35ZoInvhWJaOCTQpDCjgNF7W8TExw4AT7w+6mxSsux9EoBMQCCHQbkSA59iJ+XUoUkEpMLA750+RBUqSEHWibcATRW0pmuVwhdieuzy1BWPlPLkuNci17O28ePvzQmpKB5iQD5r0oB/ZAFbOMuXS5ceIN8RRHjO8o08U+dbNZgZXEB0tbdxeZWiFwSXRzPAKujbPuquqktBMmNNxM+FiOhK31Wzibz0pYa60ovVd1mj9l4U9RH5nLEE00MzIFqzqMVfQxcxilvGTe/43M7oyhzbPLasVZe9Jvz0kyS8EOnZ/Wdl96RdEzYxd0p9UbnX5dYHn2RJJCRvE15iflMm8qOQqBewzxm+myVrJgSoOFdnszjzrcNxbbm/eqxR+dEylqBTkFySbmbgyt6YcKTSC4tLneiYoBE4GhcnOVwlaw+siDDCpobJkhzhC9/7Le/M2wuFc8JjrfJ+gA3woIoKYRlJNAJ8iMi6HguXOLwm6wtciGmhpI9UO8D1i4EaY2Oj8maAX/Cpig51uUj2A/fkdALJWyQBPKTIIkLgulfMG8kj9/ancv1vF279FHfknfP6YqwJ8WZ69K1/LYvWX74DtwwtC/3iu+j+gP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Ja1vs32DFTXoGd0WUSOqi1fJVagXIzZ385YCz7Utr84eHv16Lm6v3prigqlIn69YTQZ7Tq8PvW1nOl3v+ULqc+AcCjvb+mAPC2TbomMq2sX00FSiMBEPBLKVn/DGj/bQMCN4YmUTvYs0kpvwItMBP5jjLmnlaK/hTCKgO09qSwCqq7bpVUxFgVbXnLrWFrgDmqpqPMx0GxkGEmm2CYkDxxCo0yzXQhk02iddJWBx30Em+UEUaZaDgc1zoLskZH7YMQzCZOH58hzjSYHpZhckPrsEG+fdDoqGsjrZOtdeYYLmTGJbKar68nT+fCxhgzJ645bVmYGyebYq5zyBhjzVh++KLbaumKJSmicINFpmivaxSThAcFVAVoAwAA); }
@font-face { font-family: Xiaolai; src: url(data:font/woff2;base64,d09GMgABAAAAAARMABEAAAAADKAAAAPxAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKgiyCFgsGAAE2AiQDCAQgBYJeByAMFBtXC1GUDE6U7OeBbetIH0CFoo4NofKHy4LoNHigvN43M9kPMF9QRZyaQluQR/FEMIiD2+3koQQeGDVsG5FWxPiMp5vLGQs7ueoeHt0+cyXMJTxy/kDp4IIX/P/3q49z/5sUixabN+ffKdER6aaOzdQE2SVcKq4EaWySQtw/qldpsPLvfAjACQAQgETAFOBA0HciKqsbtMAODcA0AQaOVuqimIsFJBIQQxL5PjJjN0EKG5RwASvBnAZb05rSb4DHqCHmEETnYG4XTax5cAOkRf4H9C09ZLECvChEYqihA00gGpcamCbOJe9evWBhWOC9SgUkNhSjCX2F+LAK865A5X8Y4M5Lq8BEAH9xIrpYBSUqMB6tghMhEBUV9MkwhHpYtw/1AM6bvWhRiav1RoewbQmEjy4g/IRSyllnwYG5bBWyBdGSYVuYg+ticnWR0H/ErWhiA0RFd6lHYqislDrOIoKXY10KVrssMluFXdKVFG+X1HWBp1g8iYoNQgPmIgUOrZWkQTgjDPMwgq0dVUBFpRll9mQV5VUY3faaYTCLkgbFXpxFdlaRiY0JS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lj5y2LM9i+k3j8uhbKiNEJFYpFXB74fjtpcpt5ak9Wi4hZ2H82YDLXZESrVoSz4z6h69RPdycal/Cx2vJjlq8888X3KaC+pTMHrc2cbV92f68L1Vxo+OInv+rsm7i/UU623XZH5+tgVJsZWDyfkNfcsYvZ6QVNR8VDi6e11xJxrYVV8bWL5Y8vvTKm+7bOZW9Rj7d8byzX1E/7iXJKyuVyZmoRzmka1918rGTflLNc1pueE7clyb9E3MsbZbk0vQO1bPzGiSK7kIjmiK9v3nEqFQx7YXq/SPKBQYPbJDUZc+ybp9vCJy51izZqciH7lFtEkwBvDdjWSh5aGZzMdMJKyDkfPqn5trPJ+urflWSxBeA3+PfJQHwl5m87f9Jr/7JBQC6Cgj+nvnqv8f8b+YI2FJZm18wNTfDzHwG5vbaq/K1VCXY3wMFfKrjASEqFbDmbu4M4950FmNqZ9oiXK/6nS0fTIm28XXgDmeqeWabijOokZvPQotw5pkLK5QjX75KTXym85ljGtzEimSxVoE8v1WpZfzmYo0WosTUFPNaWP4KmTy/VaCklsDx44pkm4az+BQpzO9XwRMDsOW3ZOSdC+cJbp1nvhXeHL9hi6+fPelarItXKw+CE6sZytOvIW1dIg4WqIuwDg==); }
@font-face { font-family: Xiaolai; src: url(data:font/woff2;base64,d09GMgABAAAAAARsABEAAAAADIQAAAQSAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKghCBeQsGAAE2AiQDCAQgBYJeByAMFBs6C8g+DdADNv0nCQmZKD22SR70ylVVNZPdZj6OHe5K/0hhMiqn7umclEGZzimAaDtIVghBKcMPWGWVkN95NraHe3fvrzXagFFaFFGYhRoP0L17f4Flg//kLFsTzwrwA54HEmhgBxRQpHEJMJCjk9PTE44wSCVqJVHKIbTu/n2XngQFEdWWF3EWBlp68MgyDLQkaGPPFcrRBKBzTzj///wnL/z7U4N5+V1asLHF+nN5l4pXaE8a22IdC2iCtITV8hqAE6tc8Ya9g+4mBevvKwEBTAcAAAFwCC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BSdUKko15UeR1XF1EsowAMlAxsAAA==); }
@font-face { font-family: Xiaolai; src: url(data:font/woff2;base64,d09GMgABAAAAAARoABEAAAAADMQAAAQOAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKglCCKAsGAAE2AiQDCAQgBYJeByAMFBtpC8gehU2ZezT6/jg5OeRRMpYk8fDffu2+mUVM8t9BI5nmUSzTRE8nZUL+oWzodAiVPJc1dZVzGM/tSDYH8AocAFKIL2WyW1YKDJei0hcgPRFeoWHbKCtjTK9L58D//8sc3Dt/q1jpYvv3zNsmuiK9U+1pHaSCJITRcGsYqxjliGdYMqpXabDy71ciMAoIJCEEhq1SQ4fJmYXgoAO1wsDVOT9Eq4AhSYjHRN/CHQ7rUthBDhfgFXYdX6SUQGwvla4SxvU+gugesKpGhXZ+eAFSn00PNreMkIMZswSROKpsAh1FDHqpvRXXDjpWb/SZ9X5kC6AccZDPS9sRWkE56l3I4VnrAFm+rwrjAAvGSXKigmrCOKDCATYkjAMuOFkR9Mn5pVqKGWZpDQwn45baBkWlT0KtL2pkNAIr8F3IWIH/giixVHT2NVI6OIwD2YKpiozCGm5dzFpDJNU94r2YkoEVwZBbmleqWBJFJTaRioTgJOVibqlyMVEklIZxYC8ZSpqz5YDrgiuxDcnyG6QKWIg0KGOVopbAbYyJTEutczkCqoqtcJi9UdAncWTJbe9ZtEREt9ESLaEioYlhHISSUVCalCh0hKbEz/UPvIrnJMhM8rwikFW6JkGHIeoaUxHLgSvL34L35i2CzTlwmeN5TyD79EBCiEgM5RoDPiGkXIacZZ4vBHJJryTUaMRari3gO0LPDRjZ4PlJIM/0RcKKTVzlugPn474AskHJIlR7ZZC4uY7EK74g30necE2r9WxmhnOGA8+DdiDriKMpB53b+p19Zr4HloBNT028lh3x2yFYxY1usPX1geufwfr1+52fgWXTPqcNTmwTUJ91DcxvA9qIrM/7bglXO7f5rm8vesZLKTfy8v7NvRPpadONF6QTvMFwYfy/r+NAA5+ZhvgmLE3Jio19/HdQ8vLjEXdF/xQpuU9UTl2AtEiKP52WusE1d/h66ViO4d7VgYD3JiFh+apfcQMZArFf2EmsjupteauX7GiFWQ/XHX2cfZybFuscA7Vu8zf4uI9fYhc/NG6NWr/YCWLiq+nSWJXTx9VSiiGs7f32OonQL0PF14Y8AAjkVXMl/byw2n3o/0Fn4RMAP3t/6AD4DdGv6f3rNau68ngAg5KM/nqKnf8Bbc+3s4IbQXP5G142T+krGDGL3L6MulcNuCKIjiPQeF1YwqzrlmRca8m2scOdYUufT16pfvN94IKs1lij1JIVSFCs0QQTycYaA4sRLkqUIRI1qtdotDo4xSShrB4tMqgPkTx9OkmCCShVm2FsHYvaIBcZ1KP1b6RwcjFJmDqySZfIYH66wTyVD+vNJk88ccKyEDeMNc50R1mzFpMOH77opVimUilKCNxA9VGkTgt9VyKFDbEMugAA); }
@font-face { font-family: Xiaolai; src: url(data:font/woff2;base64,d09GMgABAAAAAAQQABEAAAAADCgAAAO4AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKgTSBLwsGAAE2AiQDCAQgBYJeByAMFBvwCsi+DG+MoX6W2WQkaA6TTA8WW+jOLYyHNVxaQ79SPHw/9u3c91Y8mWb1qpJMqkHcytA0VDKhfapmIkMVTdpW/s+/tzuBOBO5Fd7/ISfyC4B2AmuSLGbX3bpTyVLdlnu+UWvbe3HDvREaVAjdpn82QvIjDm4RBBRhIAfCuIbDBfqfK6OkeVXF3v8+/oWTvOL//793D7vvNUTHFut2/m2JJrI3jWXZGkATKMI0XhbFE1NOvC+KuSFO3KvyKxGoAgSSEAIVWrWKmbnkbNBRBHcHGDme83sSsCQJcT/VFmBbZQMpSuTwgFuYWUlcHkT9gdyj3noHxO80U6aBnn/9AqTidAs6FSMho1YWqFWkE0WKBK9WDarcXpvXitXyRx6gZwUoG9s3CD2jAqmWez8CRT469BdAejBWyBJHZb0CqB4BpIv4C6B7sJKruysz810pZpglVDGsxHXlVVzDPQ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UZCvxZ0ITZco+h+FZ/4AyPK52J0C3MM4ti5GRqXuFNAeBbjDu1PAezhOZuzjskRbCRNMEisJjsO1ZZUya49jrS+qIpInluG9qcMyfDe8rJA4Z1eVJIW4UyBbMLZCJNjE9YtZfYy85193CsxeMpYZhwwxU5RHYzhZESNxPI9j5eMZonw8huMlyZ0Ce8lY0hmqM78uuCq7Qwr8BiKbxUhbIqRSseXhJkI4YitZJ1IEVKeoU5i9lrGPpWg0o304astzqGLLexWJo2fFuFMQ9pKzxdiYSpTGoBA/NzzwOp6TIDMp8IpEVumaAh2GrBtMjYIDX6N/C96btwg258BlTuA9iezTAwUhIjlUawz4hJByGXKWBb6QyCW9UlCjkWu1toDvCD03YGRD4CeJPNMXBSs2eVXrDryPOwFI/YopqAUJaC1UuOUF+AYMwx1z3dpWIKbz56OxLfciTwlLuLsO603hG5bs17pzxmQe0LlLzW/fzjnfRCwX5921ziMOPcvMFmwQhHtRVss7Y8oq+K3miiRv/pyzUy7f1lyP0IL0e8KKJQMx8j/YZHIn947zPKDGcxd8V/XdXWCut2giY/EnLrc74jnK3GUqaKjdF5c3oTnmg6pMwJL+yW09M4diOfdA88I8lIbyimKRwvSIjtag+K2HRY1Mw+FlxpmscUlra3a/Ch+0pPP/CoO53RVehost1Jb+GopXU+Yunp05h1XlIkyyh7KSPf/0aBn9aAcF4L1dzqgwehDIOefEORo7SvTCvqprMS8A+F3zzg6AP1f72f/Huf7JNgD9b9gOfjqV+o+Nf3NccBNoTv5AP5sr5TU4YhbFE5l0r+pzhxFVA9jxsHCEMWcdxajGkQ6QvXXY0eOVoeg13wdu1CnTolGZOtmi5anSrkOdFs0wXx68eQsVo0qFKk3K4Qzmx421fHgFUZiPmz7TKVo7FGUZWlqY9wZFr6DlI6AhcHI6P+7K1em8RB7zo4VwkQVbNbomHtq+LMYtLVr1edapUatz76aLXoqlEMUTMNxIbYeXfgP9rkQKG2IN7AIA); }
@font-face { font-family: Xiaolai; src: url(data:font/woff2;base64,d09GMgABA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NCf6Yc99cj//92OwJOEC8F/WIFWoJSrOeGb6ALjUsHDwg5lwlkokgsAmB0OzcSbo4bORwcMVJW09Zy+4087VzifOP7gHQVCtSpVqBCkklSlWjUpEKdWnKDWAUJMopdiSIlahTCfnKDmckFY3yfkQwdP9ZskkaIF6RQ15QLWiHN+M1gQ2txeby3wSwKVWg+RVIutjZSxBOhWaZl5KaN8/xCW6deh3WFMuWa12496b5y0dKFSUM53th6jN4j0A99CAA3EBdgAgAAAA==); }
@font-face { font-family: Xiaolai; src: url(data:font/woff2;base64,d09GMgABAAAAAAXIABEAAAAADrwAAAVvAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAAPAgKCY4uERAKhjyFFQsIAAE2AiQDCgQgBYJeByAMFBvgDFGUUM50ZD8PbGPag0X0IGi0GXhhW4zg1rvWFOETxTM8oG/x0LdW/urq3WMOk4tDlIBCroxcHRI2xuWNjJCAjlDH3ty3X5u7w5ol3jubRVT3f9R2Md9DPeqCl0Zb2hAKoVoJNNrJUF6WaZssskJKpIZ+ABc+ljpRT7IBsDra+v8/p5G9+QXbCgdsXH9PXgfGzqif4U8GBUA5QKFQqCk5B5pQTldOTYlJvxgt9xBvdZCtgzECo1AvwtCN32fYKg/HKbt7GOJUaCOAhSsyX8YzmBL1iR56G85B3FKiKyOEaYMmdKm2MWh6190713ZkG2QPnu9HgWefviidso5NolGQmOUS4ImyC91KKGz9Hgu48/X5fj44hLWOWe1bNqB9FwnlmniPeHqDor1sIHgfKPLedD4B+xAtxU3czydq+wjYw/KJ+j60TW63B0WqRL1Jn1/Um2xcnVs0dTuK0Xct6RuFaCSl0EiOmWPSHRxZkrImn2jswWpK34A8BtgsIFQZWlGC93XhQ3NHvxgQps/d5hiXbsbQMi/6RTLmbiYlYQO5pSjqFyr5viCkkT3qKnEHOaQLtSb1w04qlcEerd16q/QupKA5jmWJ9PbcblH0r42v9MFwKw9LZalMupnk+YS0r2tIWNzNNOFL8u/OjuggcigoDJ16qkKm0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ebAYFpBiWAP4cxQhA13zDwEPBOZBQOLo1+dAOdA4v/wq2oVFX5CrplDGdBb6vZXwBTYECkKEnweDMdgcaj6QTIIZmOIUdsItmcTsE6KqTVpwPoFzXbUovMFtWlRq+IFVaKWmoJTqEc+fKVCIqYK2KxObSNU8THVxTIcypK1HZvW6XGCsDZESyt4OSP4MpzKgpMLCAX7KyI3xxRq1YhcMLMigXspBWDVnecfgUOa0BaZj2P0U44HzZyLqxU4jRj/Or0wWAWlF4mT20SsmcHrKABsQheAA==); }
@font-face { font-family: Excalifont; src: url(data:font/woff2;base64,d09GMgABAAAAAAi8AA4AAAAADzAAAAhnAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbgygcNAZgAIEEEQgKkVSMfgseAAE2AiQDOAQgBYMYByAbywtRlHFSDdnPhEzuD8sFIqcVVQPGX5YIb+bD42nvJ+naVdw6ZZALDjfzBJj4b9f+F3jESULNBBIk8YHo9T+Af/9523zpFU77LwmVb2Lza2Xqp+0kSjeH096SUBOgohN1ZP7395rmplSqgM8DnC4eC1hpZ26alkadStPk07d4xALYGmWrbUdaMFnbWYLVgF0Ri7yEFwZBAAgBUCLRxJhFIF8D8BFBhzFZsgqhPT07tYH2dmraGtpX16UdtBjg49EEad20UxU8yUwBLYq4wiEjHngcH+v5I35zA1yIgPn/b/jkDVnvv+n/ETziK+6UPaTRTcAFA07Q4YEPwTXqpyCEIzhJnoagAAfazAUfpAmOLKOZMU6OK6JyD07HBwEXhGfag8BkMiYKpjnmFKP3yB4lypV7BcB9imYXqUIyARzwqFFUKYDMaBlSjSi/wJ/goGlZm+AAWD1at3+jwAn6SDcWmN+Jh82TZe8/aA/KgElkZtCh5USKJm/zFKZOU8211EZ7nXTRY2dytlHb7vv8/5AhLSEuJiIsKIBEgA75DxSrEpOrQtZPPQZoC9gKGICpuxcNdOSpJEAij1YGKou1rr5GZ/fYioqSZYtcZl9f7DI/er3HdDho5mtmr/adPvUlZmKm0xznOYVXXF2VCzbbit0ietgc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57sKa8nptnDnWeO5cQNOImqKb1NcoDA0E+v8vDgAAAA==); }
@font-face { font-family: Excalifont; src: url(data:font/woff2;base64,d09GMgABAAAAAAHcAA0AAAAAA9gAAAGMAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cNAZgAAQRCAoAKgsEAAE2AiQDBAQgBYMYByAbHQPIrgp4MjSeIQLqpl4jnPFQwveqm205gmrZevZ2/8kKGaJ6ictBuCwMMnsKo8hC4RwaLBrJ7dXaFrFk0Re1e/Dk3t9wCUVrYAiZkgiZ5rGDVFdY04wBF4APOCzXHr/ljrNIDqLAY/slkQf0SyjxLNBaAq8Z1AJqYW5j0GjbckRLQhoJCgwYoyfY3q33QS5DrSAwYB4hFruNve4WoN2On4P29GEFWsC+nVM/UvSlVwIcsWycI/5gbqfUhE/9Q2P7UppTOAVeIR4TYIocELVKIEACZJgXCJ5GXl0o+esbFP3g+763DcDPx6/60MrnBaBPAsGPUDRC/8+FGIqGUSBA+NIJOwTWe13HRCIrgEvfRhj1RjLiE42eG7I5DIpVNuqkNNhxwaItTI2srRz4dfHGjhZoO0O8nb2pilFYQKhenFaycLUxsYcoAQRyoRBEnPvcgfysPq+npClt8UxLyvHWjaudqbGJA+TCckNECBGBGFforuTs0M4CUMbCAvp+P4in4o864XECREBtFQAAAAA=); }
@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAIsAA4AAAAABLQAAAHYAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQDBAQgBYQkByAb5wPIrgp4Mt6IIcJZFNCfWmZY6KzqazTt6AiVHCFawzJ7V0CQBKoSQQEpFKrCVxiSFbqqqsaTevKs/q7s6uBYmujMyA9wxb6a7XnEOcNnDLgG4nW8PoPzHzYpS2uqp51pL3eB/xZoxIllCQc80B9o4j/4xMbxQB+j+SC3hsm6JmI8RMaHj+aJApW6ZbkXlg4vXSE5FECg0og6LzxP9pOarug4tF1RLp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u32bGxtjOs0w8O+gFG9obdhkj7ZHgJXvyi9V1VWUUeciDjE+P07FJBxPiCij0EiQBmINBFCV4aukhKBBImYd0UfgKZEAIBAxeEBHTKU6I9yhpVChXUCAAAA); }
@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAIsAA4AAAAABLQAAAHYAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQDBAQgBYQkByAb5wPILgps9xRFkFEihAtyRcm3sWFhmEeo5Dz8tx/rvpmPqESTBE0lkSBySERCJxSLhLR5U7Uk2jzt3GfnB66lLWNU8Qd04uTtzX70HcgYcA3E63iUZs1n9bQz7eUu8N8CjTixwAIOeKA/0MR/8IlNNx7oYzQf5NYwWddEjIfI+PDR3FGg0bAs9+b23pkrpIJSQKDRjCovPE/2jZqu6Di0XVEulttVWotfakj36YLLQQ0bl7KZpEiOueu9/Jf8839UqzEzzv0A8SF9YJxXCPUSunkwzXN3raIbN+dMdwjdfLKQYoILgYCoiV+AEKVoAwESscqBAvl55Pju68dV2/rv+py/wJu+4f2SMlM2UqnaudRKIPgl5Qwg9QWdJuKXJW6EE163fAIAZIEm97KoGvDi38iw4F8mrV7LbNNzvWJZY9CdqDWnXgiaTQYM2gtraOOVJkRwDlg4tn0SkYaxbEMck0ZwSaJRqNABxqZBYOkVojh71KwZ7AsSyrkLbERHXV9Tu92JA4cOLMs0w5N1BWPi0Fs3SZ8sz4GNN5Tea2tq6SLOqCTE+P1HKKCTCBAxxSAVoBxEkQqhDcdYQ4NCg1QMr04ALA0KABQmiQzYkKPBfpRLvBQqrwwDAA==); }
@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAIoAA4AAAAABLQAAAHVAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQDBAQgBYQkByAb5wMRFZQHZF8mb0PNXjkIbeHQ4UpbWDTlYMn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Od7V9pq41qZGQFXRVcPs6apZghHh7PZ+uIldD5Wa2OIgt57txjsGMpiWV5wQD3S2m6Y+NzCEiuBoMIz2PiuQOTovQYAoChpJEc3hLvy/eG9eJiicCo2p3tcFskE3JViwRUuuDuBdgsf5CJjv/VAgR/RYQoJUTOSaAT4nFFyJipXerwVyQ28ldOjFTq4D4DrsAcq+naQ2EYECQAJgZelUhiFAZV1Mdq0+eVmh96DwFEtqbW1xsNzSh+W+4oBm+7n0/N4UsJfjCffF5Qg/Za+FheHtu9f367y5DPsKvEnjI6xXcP+4Wv/7jmRd9LfKs1IVK06r+FeDWnXbFJTITX3zlKpSbfTpOQ2qJJbbIy+oGZ2iR8iSoTOFnaJa1vs32DFTXoGd0WUSOqi1fJVagXIzZ385YCz7Utr84eHv16Lm6v3prigqlIn69YTQZ7Tq8PvW1nOl3v+ULqc+AcCjvb+mAPC2TbomMq2sX00FSiMBEPBLKVn/DGj/bQMCN4YmUTvYs0kpvwItMBP5jjLmnlaK/hTCKgO09qSwCqq7bpVUxFgVbXnLrWFrgDmqpqPMx0GxkGEmm2CYkDxxCo0yzXQhk02iddJWBx30Em+UEUaZaDgc1zoLskZH7YMQzCZOH58hzjSYHpZhckPrsEG+fdDoqGsjrZOtdeYYLmTGJbKar68nT+fCxhgzJ645bVmYGyebYq5zyBhjzVh++KLbaumKJSmicINFpmivaxSThAcFVAVoAwAA); unicode-range: U+d265-d34d; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAARMABEAAAAADKAAAAPxAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKgiyCFgsGAAE2AiQDCAQgBYJeByAMFBtXC1GUDE6U7OeBbetIH0CFoo4NofKHy4LoNHigvN43M9kPMF9QRZyaQluQR/FEMIiD2+3koQQeGDVsG5FWxPiMp5vLGQs7ueoeHt0+cyXMJTxy/kDp4IIX/P/3q49z/5sUixabN+ffKdER6aaOzdQE2SVcKq4EaWyS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lN0J6srtMSbrpa8QlIjrfWj4PNYP53kZO3HTYMhdXDDbEWMO+eutjxNptFz1U10AbNVpTuI7MIVJV9hE7EkLACxzSJAAAAAA=); unicode-range: U+d093-d17b; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAAXgABEAAAAADpwAAAWIAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAARAgKCY4uERAKhgyFHQsKAAE2AiQDEAQgBYJeByAMFBv2DMgeg+NuaWWyxBATxvPTnlMRxF++s2/v9yRUC5YKWouVDvYxFpEYnIYCGg9w+H7+3fTPJXgwT+Wmph4gE2c0nVvY8zBxYZ2lT0SBiX0+Eev/Qn/y/v9f2mDu/FQcwJRmAczPmZcmGqFvKbVs7UAVKELLSym8xRa04YosyKLvuO+guwnBvMtLYARSxW6liBt98+5vgg5auoZAqYKmAfQczfw4toBsKZRKDPFmDUWhbNkKOWQ4gLDwRRd3rR6o+6l76wli/v/zQQ5hyxQpOvzoFkBpSf7DMhkKEuMIgRSpnZ90dRV+6t5a/NYT/+MPln2XbSpbu1G7Zdz9ljXAxrkImhvvFYQ2sSL6vxqaFsZAI18nZYuANjBu5ppCaEq2CJINEdAanS0CsYFbQkRyy4A3kcUCFtpnCLgFD0+dEZImY9H4Jp/A5uIQDN5xOARDd3SojqXsKz6WrcgWQboGk+YFFlbwyGw2Ikji3wF12UYnei2R0uft94b4JipU18RSNI2bQy/3ef3NJopm2RE5+SlF3FnDOc4LRUG+RtLKFRKDTJA2KwilfCINzwgCJSSy5lwRATXUlUSYfJxIbhYR39c85BNpCuUTabGIpWi2KVsE1UbniHxzE7TQbEL9utFBaVByJDSMDL1WIuvoehUGGGWDyaSr4yAQ/7fguXkzwcJZYWPW0NslsoPuVOECJbu0GgP4WEIcFw/M4kNPS+QEeqKKJCTLSVpNAXwqIY1LRwZLD32mRM6iZ6vIQa6co9U84J8/ApDf65VpqAHJUSrWdzFC9ECcQMhA78XUWjCbTJTNeedYo9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D2YKpiozCGm5dzFpDJNU94r2YkoEVwZBbmleqWBJFJTaRioTgJOVibqlyMVEklIZxYC8ZSpqz5YDrgiuxDcnyG6QKWIg0KGOVopbAbYyJTEutczkCqoqtcJi9UdAncWTJbe9ZtEREt9ESLaEioYlhHISSUVCalCh0hKbEz/UPvIrnJMhM8rwikFW6JkGHIeoaUxHLgSvL34L35i2CzTlwmeN5TyD79EBCiEgM5RoDPiGkXIacZZ4vBHJJryTUaMRari3gO0LPDRjZ4PlJIM/0RcKKTVzlugPn474AskHJIlR7ZZC4uY7EK74g30necE2r9WxmhnOGA8+DdiDriKMpB53b+p19Zr4HloBNT028lh3x2yFYxY1usPX1geufwfr1+52fgWXTPqcNTmwTUJ91DcxvA9qIrM/7bglXO7f5rm8vesZLKTfy8v7NvRPpadONF6QTvMFwYfy/r+NAA5+ZhvgmLE3Jio19/HdQ8vLjEXdF/xQpuU9UTl2AtEiKP52WusE1d/h66ViO4d7VgYD3JiFh+apfcQMZArFf2EmsjupteauX7GiFWQ/XHX2cfZybFuscA7Vu8zf4uI9fYhc/NG6NWr/YCWLiq+nSWJXTx9VSiiGs7f32OonQL0PF14Y8AAjkVXMl/byw2n3o/0Fn4RMAP3t/6AD4DdGv6f3rNau68ngAg5KM/nqKnf8Bbc+3s4IbQXP5G142T+krGDGL3L6MulcNuCKIjiPQeF1YwqzrlmRca8m2scOdYUufT16pfvN94IKs1lij1JIVSFCs0QQTycYaA4sRLkqUIRI1qtdotDo4xSShrB4tMqgPkTx9OkmCCShVm2FsHYvaIBcZ1KP1b6RwcjFJmDqySZfIYH66wTyVD+vNJk88ccKyEDeMNc50R1mzFpMOH77opVimUilKCNxA9VGkTgt9VyKFDbEMugAA); unicode-range: U+c514-c5fc; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAAQQABEAAAAADCgAAAO4AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKgTSBLwsGAAE2AiQD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tQudVFUji4fS1Oo9c6U1CiYsj6PlovGTcWumCVKrGewTVauRaNysiyxclVr10HWohk2rM+gQdNmVKsMq00q+BA2okenIQOoTpub3+0Uq300UZ5DSxUb3CEzEFaHjLUSnel+I3qdknXeIoXV7ULUxBaqtbpmbmxfF1B1LVr12cpq1elcfnHTg51W5IuTR53n644grQIMR4cMHJCK6AY=); unicode-range: U+c258-c340; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAARgABEAAAAADJAAAAQIAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKghyCBwsGAAE2AiQDCAQgBYJeByAMFBtIC1GUDE6f7OeBbQx7NEQqZWPXPFZaKd1OfRcP04bpD2m/xgP8/njPffd9GCOSgEREtbW5gmlrSohrUtwiGvx8+HH5Dk7ET8dZ7Euw61bBRFWFqolrflVPZGBpPO0w33kK7/r92l28ayq7p9h5Y4jvf9Te4hYazRexTCLq0pYeGP7/e/Vj7n9ZgmOL5eX8myUakb1pzAkyQVrCarhjA+aEq1zxfpcOupsUrL9fiYBiQEAiCAIKNVOhTJsRkQC2FLIMBh6P8SJskEMiQdibyO5jdGBPJYGJGFyARbA2b1VwMnwej6djsSbbC9Eb9G6ie2fefyQ51D+A9i3dZDeiGk1I9OnaQSoI9cfjswxnJzxZPZ+j2vuR92HY4GHFLLI/IdyThuxcgX7mFyNuXKkqcDCAs28kbKoqaLACB2JVwYPBldjjTtkCAbfz7C1ud2FvfUvSnsTZ+q1tXl0HMbD7IIYWZRKlnK1tot6qQrYgaYJXwywcLCYHTnLNv6pCBw+DxN4JO2nlWD8lkwylEMGRRxNWHpkUElUVdklnUjjdj18X8CQ2kESIDYLTzEnyxKcqiQLCJWabu8i6VwMqmpRWs2djj6Ph2ER79VgBU+glBSwgpZBMVZGDh6etY4SDOmGQ+lzbCBFB0cAQ2vwsg+bwPAcBRFaQSIJJFGPH/pb3pmWEQqmgEdX8OoM28CYHC2zW4qsDa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1bqDg1qtRoUQnHYX7cYD68gnYocXqzW+xAs0ZFhrY25r1B1ito+whoJHFyOD/uKjXovkQay4OFyGQ2tOv0TNy3c1lQGtq0G3BsUKde987tFz0WSyVJUABxA2XbeRlkePo0mKAAVQL6AAAAAA==); unicode-range: U+11d1-11e5,U+b225-b2f8; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAASkABEAAAAADOQAAARMAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKgnCCQQsGAAE2AiQDCAQgBYJeByAMFBuCC8iuBmxjOtKhpiUZBpuMNcJqr+PgZ/FTNpeLANrv2+zbM/Ms4ri0TyTRTEOlmiZKpl8Hb+aD36Evl2tnVLnKvFS+DnIGq3U6f239G6RfaerUzDFAcp4OkoA9F0BqubvmWdyS64Hb2krk/Qn/tUACs9zgCBOME40ty3zRcbj/4fwL+//dm4N7/2zFBStdbGfPf9tEV6S0llqsVKAKkhBGewXrGOKg54taBt1NCtbfoQLIAyj6CWLMkMP8NyGz8am56E4F/oOB62O8ER4Ch4QCQioxfcQWshYkwRQ0uEBA8E2rhxIKEPkqrymPpv4HMYV1poa9z/+QpCv/0MQEJCCCMhSBRhVDmopMvNL/WHP96eoD6QZ7P/IjoL4VCW5TbyJpDZfk76OrvhMcerLUTQLuYyzOiG0k5iaB9EnAPZqbBNrH4hsp47N1G84EE0nVgsWz+orqRpVJtPVVNYJ7sEZ8DhmsEd9DWmMkN3M21HAe7CaBbcHViuCwyRoW84Youcvf/o/A+1JYI+2ZepbeOH/WDGdi6RpNY3GNV+5DQeeq1ZwoKRKXZNFkcI4x/Logq0QPKVAbZHNYlAxwISoVGw2u+N2uFTbc2lcSUM2uS8xeTBkniWe2j7mNZoYqNpo4i5tpPNZNgu5LydHjYoFB41nmc0OD0lACC46z/ucZWaCLMiTIkqRTVJECvM3/W3hvUSVogg6D6/43Gdmi2zIcuJKjVA+IPiEQQkQ89H/MyAk9lZEhlzKlFkAsCZVQo+G1/1tG7ui9jAGjNCh1Ap7zQwFRd4rhyH8iIOEW0ySu4TGU0pIPqHUdYjNG5B9xvkTC7KDL1vvlh143rdNrO8A8lttaJJoP5OeeILG1c+s1NuQK+yNFlHTOO0eTzs7KrdPOGrJ5N6B3+Tu30uFoC7vbyDP+7T3P4MCuAuOubx+pOGJ5QGZOshGL7XnzrczhdOT++cGBROR/BaAcyr1Tujt/gueeuOU+gwrW7fw0bfbl/Dq9aXHIdWzkP58vuHiu0GYKmSIbr+NSn7TwxMV5uxLqlKOHvtbK4+NfXjleYzMoasmPzJ9e3BXmTKe6v/Ywy+hRpP9J25BhHYGlO5Y0vvz5pPd+Pyy3WfjjTu+YSXsjB/drnRtOVqp3m71WZym1qEUOOP+Zyu/qv9zzau//1dvGOifPpLf7JwtHv2ax9APw+cmXDNjvbd/wf9XYn/gAsigLEv+hStrvAf1vr8CNo3nxOh42nySfCeahOCIT7nWZClEkrQegx6PCTgx21a7oS9opd2KzOmw3Md3ArKn5PjjEUGGc0SoYcsTIV2OiSQzjjMX4cOfFS4hYNarUGKMSzjK+XFnfm2cQgfn46bOTxZgIsxUZxvUZrw2KnkHfm38jy5KD+XJTyTD5EnnGdxfMs9mwX2fKxB0nLoty8zjjzXA31Kk3efPxix7KpNIlKEC54f7H08hHVL0SATQwNagX); unicode-range: U+11bc-11d0,U+b151-b224; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAARIABEAAAAADGgAAAPuAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKgXSBZQsGAAE2AiQDCAQgBYJeByAMFBsmC8g+DHCHZeFeEE9POiKOhlQIY7WvD/+XVtbGiSaf+i19yxIRX2KuEPNL3b86QyoupErV9K+9ZXPATTXEhyatj4B+v7bv/l1ILniJYj7dOqGRRBsksf4bjVAJjdDIuMFpGISUW0iNMA64Tm7nb0cKONIqCiSVhCpF91oZTYSWsf6H8y/8f5c2m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uOhGhCUnixSklcbwS8QY3y+eR8phscuIiTuHLvNw1SCDjTHV6NJt+Prmi17IFBLlqEG5rrQJVVP1gwGkYIOYRQEAAA==); unicode-range: U+1152-115e,U+1160-1166,U+ad2d-ae01; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAARcABEAAAAADKQAAAQDAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKgjCCGwsGAAE2AiQDCAQgBYJeByAMFBtcC8ieBTmZazoyOypNNJ5/tmYZJx769vvd2VlEk6iETPMo1sg/gsfyT38p0gmZ/P7vvbc7m9RMt2dSiO/VSlKBf7Owsp6F/QlwdNsNUwmR0CCGj/4v9Cfvf63pybzbkI1wwMZlM/dDxsYYwA2BAi6jUChMq2QVaUKhUNbqGt/zooPuJgXr71ciMAwIFCEEBs2xgk7jUnJAXYW2BQxcnXkdzQSGoiA6ibmBO9RXlVCFDBcQFLad38QLoOhO0GVM6/9WEN0DZpayaMWzewClZ9I/LG2ZICIDMYbzwU2sJVRNjLsT/8Fm9vfq7R5j3o9sAOydUZCvxZ0ITZco+h+FZ/4AyPK52J0C3MM4ti5GRqXuFNAeBbjDu1PAezhOZuzjskRbCRNMEisJjsO1ZZUya49jrS+qIpInluG9qcMyfDe8rJA4Z1eVJIW4UyBbMLZCJNjE9YtZfYy85193CsxeMpYZhwwxU5RHYzhZESNxPI9j5eMZonw8huMlyZ0Ce8lY0hmqM78uuCq7Qwr8BiKbxUhbIqRSseXhJkI4YitZJ1IEVKeoU5i9lrGPpWg0o304astzqGLLexWJo2fFuFMQ9pKzxdiYSpTGoBA/NzzwOp6TIDMp8IpEVumaAh2GrBtMjYIDX6N/C96btwg258BlTuA9iezTAwUhIjlUawz4hJByGXKWBb6QyCW9UlCjkWu1toDvCD03YGRD4CeJPNMXBSs2eVXrDryPOwFI/YopqAUJaC1UuOUF+AYMwx1z3dpWIKbz56OxLfciTwlLuLsO603hG5bs17pzxmQe0LlLzW/fzjnfRCwX5921ziMOPcvMFmwQhHtRVss7Y8oq+K3miiRv/pyzUy7f1lyP0IL0e8KKJQMx8j/YZHIn947zPKDGcxd8V/XdXWCut2giY/EnLrc74jnK3GUqaKjdF5c3oTnmg6pMwJL+yW09M4diOfdA88I8lIbyimKRwvSIjtag+K2HRY1Mw+FlxpmscUlra3a/Ch+0pPP/CoO53RVehost1Jb+GopXU+Yunp05h1XlIkyyh7KSPf/0aBn9aAcF4L1dzqgwehDIOefEORo7SvTCvqprMS8A+F3zzg6AP1f72f/Huf7JNgD9b9gOfjqV+o+Nf3NccBNoTv5AP5sr5TU4YhbFE5l0r+pzhxFVA9jxsHCEMWcdxajGkQ6QvXXY0eOVoeg13wdu1CnTolGZOtmi5anSrkOdFs0wXx68eQsVo0qFKk3K4Qzmx421fHgFUZiPmz7TKVo7FGUZWlqY9wZFr6DlI6AhcHI6P+7K1em8RB7zo4VwkQVbNbomHtq+LMYtLVr1edapUatz76aLXoqlEMUTMNxIbYeXfgP9rkQKG2IN7AIA); unicode-range: U+113d-1151,U+ac59-ad2c; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAAioABEAAAAAEtwAAAhPAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAAbAgKCY4uERAKjhSLJgsUAAE2AiQDFgQgBYJeByAMFBstEKOiZg5SbLK/SjCHiNHuEL+gTSNT46JXL5d2dDYNgYUXm+YfzDX+SHc2ivETmNDwKPDoyOfVpV+WL0y+vCcH0A6j74JkhdgpEKtIY6duLqtbpm7Ey9y1veFpm/+eeI84UQ+7OKuxt4GVxKIYq2RV4BrW2ogRzSLy4ldEPwOcyCeCnfdVRkkCCYQB5hjiQBYww7YRbXSP73h6NW2R2TuqakKVbhz3k50ogVGlXUK50I8LVfViSxcGPMagWmseZbCGWIllVWfiArkE9Hb6lwgEEAGwFV2GIBgJhPHWk+UvlOfz1L8DziZATUdaX+Q8wIYCpZhcP+KB+PA6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d025kSUyu55MTRgpEUAAAAgADgeJKmY7fTl9ml/crDOV8AAMAbHd8FAgDwcVjQxf8/CSzqP5xtzQBCKD3Sf9WE+tcE/ffNdISR3uYI9HPL7tnugK32eEKiQ8vXlt5jfNl3cKdgkyjS+AAo8CeOJRK8i1VEkbFUETFWrY/1OCiOB+FHADbHgh22WuAY0W7cit32cOywHVOuSKlS9Swrlmy1zSLUMxUMXpUpAVXP375+r3a7gS+EsEMxpSPkltiqTFWOM39uFUyLHHtXYTNhanUCH6Zqzb6Wk+/ux9tB7nSI504ruW4vjn26Usn09unUYQJlJBfYqkS1JB42eIMjCApAIQA=); unicode-range: U+2f74-2fd5,U+3000,U+3003-3007,U+3012-3013,U+3018-301c,U+3020-3029,U+302f-303f,U+3041-3096,U+3099-30a1; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAASoABEAAAAADRwAAARNAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAARAgKCY4uERAKgxCCVQsKAAE2AiQDDAQgBYJeByAMFBuqC1GU7E2R7MdBbqa5F152coabOiktpMaU8/nqrF+pgEOG6JmlMpT2JOPdCTYBcLn7NQC/jRtwbG6L5VhCUeCBxP3vmhbBXh8mAy7ZKcrdkPIHAJ44Y3oeM/51NXZO7GpNX2bvgioTFwlsXC7zGzI2xgBCgR2CRmFaoyI7tYyuU8WyqkpU+v4yNwZtRdw6FQQg5RTBKTUpEv89Yn78kHVodDKEuACwLAA9k2l0kcwBbynglMkj1jwxOBBO4gR80MAhUHKdGH0LS8P4WZI5SevZejDugDn5JrL6wQ2Ak3D+A+RrBulSCnBDkVjFxTSEhO27MC/mOHOSZdPV7/ALoy+MAuG0eNzYjxxBzFWoq+P5u54cAOrZDdStg0k1aF53BAVmQtQxJvX5ERSaUWCkERSZiSaNGq2RpwMRXXEYFEQjo32D0qSJ/Y3PGhIQI9KRjxHpxKmcg99eNARQGEHxGtSUE3cok/HZdNxP4/8D3isxVxEZaet5A5fLzC/nDPyUElWm6rlMMT8FiKD0lP64vTCmnBeyfGqkqXyFeBP30xYIUcqlU5glhF8MwNwRAzDJ+CKaPNWoUVHfX9/c359O/TiXTuVJ4KfAIqgwVzVxlSEFhbinxK/rGUKJkJGAlEqcL+PQDnhHHk7gTJxkLqLxDOz1/y88N+uKcGPcwYO6O9+TQ3vhvXn4gC/xEaofYv0RAUwgyGmg8xUcWolX8VCDhqiFqkWsDqFnDGCkBuebOLQZb+FhBRuxCpVBtkEDOoB+r929kD+Lft5pYdq9B7ABaH0tgOAgI53Hr+PC4/r12C3JZ2KxdhEZSGu7kfbwqv0QIb4npttnTd+IfrerV5OPXkvxVs4KrHGbz5iuDNo/Ku+TP3Y+8T0s0dR9Ax0T1IX36L/qNE5WOYzp13k1C9tyBQ5Qe+Q+SqYsRcrnWor168Ue11MzvM4YxvXoVE5WbcPd9u1XTrnyDctc3Hvn+hY2rI9rstBqorFnWubXzu+ijWTSFheRSavCZHvvh7iEpYs85t+CfWNXW+bVpI2aDzdyy1Oi0bDChT9PqpbPWjfoePN+ETdabVMMk9SdifKisa9T9omTtaZ5I/xzb7TRU1ik56cvDpQstWdYRpwKJJ9yJEd9Mv3CWTD5mMucWt+fL7VPPvpUbw3QxjDJ5+jyvKO/CSX0JQDcXP9eDQBPTJoT9ilr4P6lDQCEODNCf6Yc99cj//92OwJOEC8F/WIFWoJSrOeGb6ALjUsHDwg5lwlkokgsAmB0OzcSbo4bORwcMVJW09Zy+4087VzifOP7gHQVCtSpVqBCkklSlWjUpEKdWnKDWAUJMopdiSIlahTCfnKDmckFY3yfkQwdP9ZskkaIF6RQ15QLWiHN+M1gQ2txeby3wSwKVWg+RVIutjZSxBOhWaZl5KaN8/xCW6deh3WFMuWa12496b5y0dKFSUM53th6jN4j0A99CAA3EBdgAgAAAA==); unicode-range: U+30a2-30ff,U+3105-312f,U+3131-318e,U+3190-3191; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAAXIABEA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a,U+5356,U+5361,U+536b,U+5370,U+538b,U+53e4,U+53e6,U+5403,U+5426,U+5428,U+542c,U+5438,U+5668,U+56ed,U+56f4,U+56fe,U+57df,U+592a,U+5957,U+5b69,U+5b81,U+5b8f,U+5b98,U+5b9d,U+5ba1,U+5ba4,U+5bb3,U+5bc6,U+5bdf,U+5c3d,U+5c5e,U+5c81,U+5ddd,U+5de8,U+5dee,U+5e0c,U+5e86,U+5e8f,U+5e93,U+5e95,U+5e97,U+5ea7,U+5ead,U+5eb7,U+5f55,U+5f81,U+5f85,U+5ff5,U+6001,U+613f,U+6258,U+6267,U+6269,U+626c,U+627e,U+62db,U+62ec,U+6325,U+635f,U+6362,U+6388,U+6392,U+63a2,U+63a7,U+63aa,U+641e,U+6545,U+6597,U+65e2,U+65e9,U+661f,U+665a,U+666e-666f,U+66fe,U+6728,U+67d0,U+6811,U+6838,U+6865,U+697c,U+6b22,U+6b27,U+6b4c,U+6b62,U+6b66,U+6b7b,U+6bdb,U+6c47,U+6c49,U+6c7d,U+6c99,U+6cfd,U+6d0b,U+6d25,U+6d32,U+6d3e,U+6d4b,U+6e29,U+6e56,U+6e7e,U+6f14,U+6fc0,U+706b,U+70c8,U+7247,U+72af,U+72b6,U+72ec,U+732e,U+73ed,U+7403,U+7533,U+753b,U+7559,U+7565,U+7597,U+767b,U+773c,U+7763,U+77ed,U+77ff,U+7968,U+798f,U+79bb,U+79c0-79c1,U+7ad9,U+7ae0,U+7b51,U+7b7e,U+7cae,U+7d22,U+7ea2,U+7eb3,U+7eb7,U+7ec3,U+7ec8,U+7ecd,U+7edd,U+7efc,U+7f16,U+7f3a,U+7f51,U+7f57,U+7f6e,U+80dc,U+822a,U+8239,U+826f,U+82cf,U+82e6,U+8349,U+8363,U+83dc,U+8457,U+85cf,U+878d,U+8865,U+8a00,U+8b66,U+8ba2,U+8ba8,U+8bad,U+8bb2,U+8bc9,U+8bd5,U+8bfb,U+8d2b,U+8d35,U+8d37,U+8f7b,U+8f93,U+8fce,U+8fdd,U+9000-9002,U+9010,U+9047,U+9093,U+9152,U+9488,U+94a2,U+9633,U+9636,U+963f,U+9646,U+9648,U+964d,U+9664,U+9669,U+9760,U+97f3,U+987a,U+987e,U+9884,U+98de,U+9986,U+9ed1; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAARcABEAAAAADMQAAAQEAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbHhweBmAANAgKCY4uERAKglCCKQsGAAE2AiQDCAQgBYJeByAMFBtqC8geBW5bAymcujyXPnR0tWIhHuIv882fK53SGu9tKnCsY6mAiwENQiNLvIOE7+dzzvfrGhrkp4qYtEU1mJeJ6ClMXLJbJu5XlROw/ofzL+z//2UO7p2/TdcWSxfbv2feNtEV6Q1rSUKlg1SQBCjAodapHi8VQxz0jGIG3U0K1t+dBEaAQBHMyMDab4IOvSU1INGCGcDA7ZkPYgUIKQqiSQxvEB+SWSVEkOECfHqWHV/k10P2WTt+Vv74/4FsYEW7AG1//xygtHkj2CJEQWIOXyQ6gS20FNE/e/iPVdmdQzO0zeEf+QZQH3GgOG84gdAymkP/x4F7/SQo5H1rBAeoxtjjc7OoPYIDXs0BqqgIDvg19rJ8h7eqwUZjBjOF3Qz24v6OblbgSMKtT+ph6CjMQvWFD7NQc0Gx2TTprOqh6dQIDgRbMEGKoQ0vHljMBsLkPYcjOBDWxZjlOysaKhvY+W6SzXbTJEVhD3uhooG94CYpmo7gQHTJcNKY4yOuC3FZVJGcZIN0NQuTOs0wlZKNgosYhmRstLUrh4CqsqsczJ7Ld3g4NL+ivTvfRpGoZKPEQTRJ0e4IDqR18YSSxw1DNAzTss8NDBKVhJNDweTeVwpkFV0tQQOtqNHoFNkcuJv/t+C9eT3BwBlhYkbvmwUyQfeTYAEpWuTqD/gAQiAXBMyCvE8JZCvdJsEOh2iXqxPwLkIwF4JQFuL9MIEcTo+QEIkoMVKu0cA15o4AUk+xBM1AghLlWwwNnqDQSi5Y1WrjamXObajxAEusoQevQ8/f69fLHWvhSE1LzbF+nWmd5XleepCWnjyBqY5+w7FnVRZybHQ8vRgAHWsY06nMU4EhqA9pqtuSWCE+fS3RMQjzDVvY4K5/YEGcrHnDhyZRyr8I0TqL99VJc8o5Q+zYnvfJA6/9Us4QZ1JXKrsX3Vx+9+fJrZrg0ZY3OnHRZrPdQ2S/e3lXLAqpCS38YF51SrsjpLj+eN3qgz9PiVe1I4tzEadVVfB/PSNWkzty0pyyhDAUp24gil5ohQVLzURB3V1ktUhLOodUPamt9p7TB1FN+T/q+XItJClj8fY2dfpfiZz/AfCx+5sdgM8wx6r/X0JaQzkB4H3jC2L/nlLrf0D7LzsEN4am5Z9sNl3KZy7MIn8gY+5tXVf4oiUFKq8Ka5hzzVpMvFnTDmZ9a9ja9kiX7pjvAxd8OowzWgefannq9JhoEp9xxsLiRIoRI41bjy49xuiEEyxeOKvFig5CMOudPpksz0SY7sgwrobFbJCPDmqxEhtpnOwvXoROPpMvkcV8e6k8XQVrfaZM3HLisjA3jjPeDGefPv0mrz940WOxEg3y1eNzg80Srf0GwdMAgTBAVoEp); unicode-range: U+4e14,U+4e25,U+4e48,U+4e50,U+4e5d,U+4e9a,U+4ec5,U+4efd,U+4f17,U+4f4e-4f4f,U+4f55,U+4f59,U+4f60,U+4f8b,U+4f9b,U+4f9d,U+4fbf,U+4fc3,U+5065,U+513f,U+5149,U+514b,U+516b,U+5174,U+517b,U+518d,U+51b5,U+5207,U+5217-5219,U+521d,U+526f,U+529f,U+52a9,U+52b3,U+5305,U+533b,U+5343,U+5360,U+5373-5374,U+5386,U+53cb-53cd,U+53f2,U+53f7,U+544a,U+5468,U+547d,U+54cd,U+552e,U+5584,U+56f0,U+571f,U+5747,U+575a,U+57f9,U+5883,U+58eb,U+58f0,U+5907,U+590d,U+592e,U+5931,U+5956,U+5965,U+5973,U+5979,U+59cb,U+5b57-5b58,U+5b83,U+5ba2-5ba3,U+5bb9,U+5bcc,U+5c42,U+5c45,U+5c4a,U+5dde,U+5df1,U+5df4,U+5e03,U+5e08,U+5e26,U+5e2d,U+5f71,U+5f80,U+5f8b,U+5fb7,U+606f,U+611f,U+6237,U+623f,U+6253,U+627f,U+6293,U+62a4,U+62c5,U+62c9,U+6309,U+6574,U+6599,U+65ad,U+65af,U+65c5,U+65cf,U+6625,U+663e,U+671b,U+672a,U+6750,U+6781,U+6821,U+6839,U+6848,U+68c0,U+6a21,U+6b3e,U+6bb5,U+6c14,U+6cb3,U+6cb9,U+6ce8,U+6e05,U+6e2f,U+6e38,U+6e90,U+6ee1,U+70ed,U+7167,U+7231,U+7248,U+724c,U+7387,U+738b,U+73af,U+7530,U+75c5,U+767d,U+76d1,U+76f4,U+771f,U+77e5,U+77f3,U+7834,U+7840,U+786e,U+793a,U+795e,U+79f0,U+7a33,U+7a7a,U+7a81,U+7ade,U+7b56,U+7b97,U+7c73,U+7c7b,U+7d20,U+7d27,U+7ea6,U+7eaa,U+7ebf,U+7ee7,U+7eed,U+7ef4,U+7fa4,U+8003,U+80a1,U+81f4,U+8272,U+827a,U+8282,U+82b1,U+82f1,U+8303,U+836f,U+83b7,U+843d,U+88c5,U+8ba9,U+8baf,U+8bb8,U+8bbf,U+8bc4,U+8bc6,U+8bdd,U+8be5,U+8bf7,U+8c08,U+8c61,U+8d1f,U+8d22-8d23,U+8d27,U+8d2d,U+8d38,U+8d5b,U+8d70,U+8d85,U+8d8a,U+8db3,U+8eab,U+8f83,U+8fb9,U+8fdc,U+8fde,U+9009,U+901f,U+914d,U+91c7,U+94b1,U+94c1,U+94f6,U+95fb,U+9632,U+9650,U+968f,U+9752,U+975e,U+987b,U+989d,U+98df,U+9999,U+9a6c,U+9a8c,U+9ec4,U+9feb-9fec; }
@font-face { font-family: "Xiaolai"; src: url(data:font/woff2;base64,d09GMgABAAAAAAukABEAAAAAGfwAAAtJAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbHhyBKAZgAIEECAoJji4REAqabJQ7CyYAATYCJAMoBCAFgl4HIAwUG3w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T4nfY7tX7JnqzEW91IMaskzQT33BHVPKX9YLhW/PNBtZ+HFJkM10oSnE0XoOut8kQ9dfdsgsgufi59Xv2ja6zIRyl1IvvL2RxdwtYPppJsXbVuYeDoTyuO2m3CWfkNwXl6nM27ConnIF83jPdCCKzIl+C6G4NV/vzLUb6HXnr4Pjcpl8b8hY9w8ZRqr3kV+fpAPqPsXH8SfUtPuiVeGXLxb1/D91L6bdDxtk5cKrQRcdGBJ9741f+Pm5kZZ3PdVzafh4Tp0tHPi8phAPji944FfYedjs/rW41T9TUfqLUII/Jymvn/rWdR34yJvBpz9Ou8m/8XIAEAJBnPBjyUv+0hDx79ebAYFpBiWAP4cxQhA13zDwEPBOZBQOLo1+dAOdA4v/wq2oVFX5CrplDGdBb6vZXwBTYECkKEnweDMdgcaj6QTIIZmOIUdsItmcTsE6KqTVpwPoFzXbUovMFtWlRq+IFVaKWmoJTqEc+fKVCIqYK2KxObSNU8THVxTIcypK1HZvW6XGCsDZESyt4OSP4MpzKgpMLCAX7KyI3xxRq1YhcMLMigXspBWDVnecfgUOa0BaZj2P0U44HzZyLqxU4jRj/Or0wWAWlF4mT20SsmcHrKABsQheAA==); unicode-range: U+2e3a,U+3001-3002,U+3008-3011,U+3014-3017,U+301d-301f,U+4dae,U+4e00,U+4e07,U+4e09-4e0b,U+4e0d-4e0e,U+4e1a,U+4e2a,U+4e2d,U+4e3a-4e3b,U+4e4b,U+4e5f,U+4e86,U+4e8b,U+4e8e,U+4ea7,U+4eba,U+4ece,U+4ed1,U+4ed6,U+4ee3,U+4ee5,U+4eec,U+4f01,U+4f1a,U+4f4d,U+4f53,U+4f5c,U+4fdd,U+5143,U+5165,U+5168,U+516c,U+5173,U+5176,U+5185,U+519c,U+51fa,U+5206,U+5229,U+5230,U+5236,U+524d,U+529b,U+52a0-52a1,U+52a8,U+5316-5317,U+533a,U+5341,U+5362,U+53d1,U+53ef,U+53f8,U+5404,U+5408,U+540c,U+540e,U+5458,U+548c,U+54c1,U+54e5,U+5546,U+559c,U+56fd,U+5728,U+5730,U+573a,U+5916,U+591a,U+5927,U+5929,U+592b,U+597d,U+59d4,U+5b50,U+5b66,U+5b9a,U+5b9e,U+5bb6,U+5bf9,U+5c0f,U+5c14,U+5c31,U+5c55,U+5de5,U+5df2,U+5e02,U+5e73-5e74,U+5ea6,U+5efa,U+5f00,U+5f53,U+5f97,U+5fc3,U+603b,U+6210-6211,U+6240,U+6280,U+62a5,U+63d0,U+6539,U+653f,U+6587,U+65b0,U+65b9,U+65e5,U+65f6,U+662f,U+6708-6709,U+672c,U+673a,U+675c,U+6765,U+6c11,U+6c34,U+6cd5,U+6ce2,U+6d4e,U+6d77,U+73b0,U+Line truncated
@font-face { font-family: "Excalifont"; src: url(data:font/woff2;base64,d09GMgABAAAAAAi8AA4AAAAADzAAAAhnAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbgygcNAZgAIEEEQgKkVSMfgseAAE2AiQDOAQgBYMYByAbywtRlHFSDdnPhEzuD8sFIqcVVQPGX5YIb+bD42nvJ+naVdw6ZZALDjfzBJj4b9f+F3jESULNBBIk8YHo9T+Af/9523zpFU77LwmVb2Lza2Xqp+0kSjeH096SUBOgohN1ZP7395rmplSqgM8DnC4eC1hpZ26alkadStPk07d4xALYGmWrbUdaMFnbWYLVgF0Ri7yEFwZBAAgBUCLRxJhFIF8D8BFBhzFZsgqhPT07tYH2dmraGtpX16UdtBjg49EEad20UxU8yUwBLYq4wiEjHngcH+v5I35zA1yIgPn/b/jkDVnvv+n/ETziK+6UPaTRTcAFA07Q4YEPwTXqpyCEIzhJnoagAAfazAUfpAmOLKOZMU6OK6JyD07HBwEXhGfag8BkMiYKpjnmFKP3yB4lypV7BcB9imYXqUIyARzwqFFUKYDMaBlSjSi/wJ/goGlZm+AAWD1at3+jwAn6SDcWmN+Jh82TZe8/aA/KgElkZtCh5USKJm/zFKZOU8211EZ7nXTRY2dytlHb7vv8/5AhLSEuJiIsKIBEgA75DxSrEpOrQtZPPQZoC9g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ZFa62VMHLbhQI0UjKkKATFGL4wXO7oSdnq3bpIBVE05y1LQkTcIY5TvoSaBlL26xEgJ6IDDKR4nwEGOinpSzY/ONOnH57sKa8nptnDnWeO5cQNOImqKb1NcoDA0E+v8vDgAAAA==); unicode-range: U+20-7e,U+a0-a3,U+a5-a6,U+a8-ab,U+ad-b1,U+b4,U+b6-b8,U+ba-ff,U+131,U+152-153,U+2bc,U+2c6,U+2da,U+2dc,U+304,U+308,U+2013-2014,U+2018-201a,U+201c-201e,U+2020,U+2022,U+2024-2026,U+2030,U+2039-203a,U+20ac,U+2122,U+2212; }
@font-face { font-family: "Nunito"; src: url(data:font/woff2;base64,d09GMgABAAAAAAY8AA8AAAAADAwAAAXkAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbgkocZAZgP1NUQVREAHwRCAqKAIgNCyAAATYCJAM8BCAFhCQHIBv4CVFUchKQ/TyMjWWPhbGVsLhp9GSH50tTI0kpiVprztv5Fg//7Ue7b76siAPJNIlodGtQN2PVLBMSh9QsiSdPzOBa2yGm7yb77eytNyKhUQpUht7Tv2xOByU3QenAtgPMB7F4fyAboXSW9/+/n6v/TjQN8ThtnIUEjdIpZXKR+wRP5pOEmJw+KE2scl5CrJImJdM0EiorlZ5YdBMRC560xeTjuPbtLy7QCkiSUAq1ViHQbDaL3Q2bEgVwd6KYhuDuYjSLwJ09yP8F4sIpGoEjBEIpaZS81yy5rcQrjzVpEJ1J/k3+gsP/ff8Il5G/2fNPGkF4pUAjvJfNawrz6+6nByVFqa9kYlFhOgoleq5SgazextGgsaNdiThmeeBJXBYr4z15AL5i/ioJvcwoWg7EgX1xjpO37MHbHk9cvNKHBpa8cWVIoeH9ZVoeX1Sk6ykIsL08SRz2FoqiqiH0H80ZBl8mbYqf/59QLgvtScQdiPfpNCbtCqFRQq+nzZp37cyEJfB7ESNYvPedtBiOKeCsCogqfiETZge9IpzwbzwL6HdlV21S19DYFITRWJv8H8yErsk/8lQez2N5NH4HI3koD+Y+If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SyjvhlccIYEk6RqBT+rLBhq++6mCeaVmSnhRSRLhqn858kQhmckK8KdDho33l762L3oRbXFaJswnP/GldY6NuVtHvpKmyw2lmyXZVhDWdtPtWkoNUMGcLYD5WxmaYg9eyDLXQhSUMDU0sLUawuaKqvbGhqbIKVYjiQaQQL2njT0LoS/m7lCr4lQzTmuxjCoadioqGD8nYpaSnBrVwZcjQGguzd9Lz9OWZlztV+GGmLZo3W0dAyABUGMFy9YkQGraQZyvui5GUQK8TxDTs4JGuoWSSGjZraeB5NvHiPSv+dQ4gKw8agodG7ECucqIZ2GpDaFVWXt4wC); font-weight: 500; unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; }
</style>
</defs>
<g
@@ -150,13 +144,8 @@ exports[`exportToSvg > with default arguments 1`] = `
class="style-fonts"
>
@font-face { font-family: Excalifont; src: url(data:font/woff2;base64,d09GMgABAAAAAAf0AA4AAAAADbQAAAegAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbgjgcNAZgAHwRCAqPYItcCxoAATYCJAMwBCAFgxgHIBujClGUblKX7Edh3Pg8OJbt5MlDFPwWk6FmJ08terdayeDx9O8Fa5eunTJ1ykAUGuAvgOF5bPfuH0nXrvQrNkFoNlERBLIQDd/mj2kP7fdg8avL4M/sm4cbu4L2i1VQVjShz/+90/YE3IJFmOC+f0Z1Xhs3bVxiJZZGa1IgY5sHCJ2EM2iBndkLWsZvFxCAhRBGCknKEOQenHCpmE2fVQTl1atzWyjvzs3aQPnWd20PJQZeG3mQp1lnLimFBAhOKFIQSrGa+vOB69gLCRkjLr4NIjd5rXiz8hhu+LIe9DZCgkJjmZEy34MkhXNBJ8GhNMMnJUgmSYA0AowAwT2zRor05iZAeN/80c4UkYlgSTOaKgOQCUOSE5F+z6+DXqndDTk4CEHP2v3/aK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7EAAAA=); }
@font-face { font-family: Excalifont; src: url(data:font/woff2;base64,d09GMgABAAAAAAHcAA0AAAAAA9gAAAGMAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cNAZgAAQRCAoAKgsEAAE2AiQDBAQgBYMYByAbHQPIrgp4MjSeIQLqpl4jnPFQwveqm205gmrZevZ2/8kKGaJ6ictBuCwMMnsKo8hC4RwaLBrJ7dXaFrFk0Re1e/Dk3t9wCUVrYAiZkgiZ5rGDVFdY04wBF4APOCzXHr/ljrNIDqLAY/slkQf0SyjxLNBaAq8Z1AJqYW5j0GjbckRLQhoJCgwYoyfY3q33QS5DrSAwYB4hFruNve4WoN2On4P29GEFWsC+nVM/UvSlVwIcsWycI/5gbqfUhE/9Q2P7UppTOAVeIR4TYIocELVKIEACZJgXCJ5GXl0o+esbFP3g+763DcDPx6/60MrnBaBPAsGPUDRC/8+FGIqGUSBA+NIJOwTWe13HRCIrgEvfRhj1RjLiE42eG7I5DIpVNuqkNNhxwaItTI2srRz4dfHGjhZoO0O8nb2pilFYQKhenFaycLUxsYcoAQRyoRBEnPvcgfysPq+npClt8UxLyvHWjaudqbGJA+TCckNECBGBGFforuTs0M4CUMbCAvp+P4in4o864XECREBtFQAAAAA=); }
@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAIsAA4AAAAABLQAAAHYAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQDBAQgBYQkByAb5wPIrgp4Mt6IIcJZFNCfWmZY6KzqazTt6AiVHCFawzJ7V0CQBKoSQQEpFKrCVxiSFbqqqsaTevKs/q7s6uBYmujMyA9wxb6a7XnEOcNnDLgG4nW8PoPzHzYpS2uqp51pL3eB/xZoxIllCQc80B9o4j/4xMbxQB+j+SC3hsm6JmI8RMaHj+aJApW6ZbkXlg4vXSE5FECg0og6LzxP9pOarug4tF1RLpbHeZqLX0pIt2mfy3pNG6eyGaRIjrnrr/gv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V1VWUUeciDjE+P07FJBxPiCij0EiQBmINBFCV4aukhKBBImYd0UfgKZEAIBAxeEBHTKU6I9yhpVChXUCAAAA); }
@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAIsAA4AAAAABLQAAAHYAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQDBAQgBYQkByAb5wPILgps9xRFkFEihAtyRcm3sWFhmEeo5Dz8tx/rvpmPqESTBE0lkSBySERCJxSLhLR5U7Uk2jzt3GfnB66lLWNU8Qd04uTtzX70HcgYcA3E63iUZs1n9bQz7eUu8N8CjTixwAIOeKA/0MR/8IlNNx7oYzQf5NYwWddEjIfI+PDR3FGg0bAs9+b23pkrpIJSQKDRjCovPE/2jZqu6Di0XVEulttVWotfakj36YLLQQ0bl7KZpEiOueu9/Jf8839UqzEzzv0A8SF9YJxXCPUSunkwzXN3raIbN+dMdwjdfLKQYoILgYCoiV+AEKVoAwESscqBAvl55Pju68dV2/rv+py/wJu+4f2SMlM2UqnaudRKIPgl5Qwg9QWdJuKXJW6EE163fAIAZIEm97KoGvDi38iw4F8mrV7LbNNzvWJZY9CdqDWnXgiaTQYM2gtraOOVJkRwDlg4tn0SkYaxbEMck0ZwSaJRqNABxqZBYOkVojh71KwZ7AsSyrkLbERHXV9Tu92JA4cOLMs0w5N1BWPi0Fs3SZ8sz4GNN5Tea2tq6SLOqCTE+P1HKKCTCBAxxSAVoBxEkQqhDcdYQ4NCg1QMr04ALA0KABQmiQzYkKPBfpRLvBQqrwwDAA==); }
@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAIoAA4AAAAABLQAAAHVAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQDBAQgBYQkByAb5wMRFZQHZF8mb0PNXjkIbeHQ4UpbWDTlYMnK5cOfavAw/zzrESo5EbTf6+zdCyBIAqHiUlk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m6M5VNQlFM3yJ/7EAAAA=); unicode-range: U+20-7e,U+a0-a3,U+a5-a6,U+a8-ab,U+ad-b1,U+b4,U+b6-b8,U+ba-ff,U+131,U+152-153,U+2bc,U+2c6,U+2da,U+2dc,U+304,U+308,U+2013-2014,U+2018-201a,U+201c-201e,U+2020,U+2022,U+2024-2026,U+2030,U+2039-203a,U+20ac,U+2122,U+2212; }
@font-face { font-family: "Nunito"; src: url(data:font/woff2;base64,d09GMgABAAAAAAY8AA8AAAAADAwAAAXkAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbgkocZAZgP1NUQVREAHwRCAqKAIgNCyAAATYCJAM8BCAFhCQHIBv4CVFUchKQ/TyMjWWPhbGVsLhp9GSH50tTI0kpiVprztv5Fg//7Ue7b76siAPJNIlodGtQN2PVLBMSh9QsiSdPzOBa2yGm7yb77eytNyKhUQpUht7Tv2xOByU3QenAtgPMB7F4fyAboXSW9/+/n6v/TjQN8ThtnIUEjdIpZXKR+wRP5pOEmJw+KE2scl5CrJImJdM0EiorlZ5YdBMRC560xeTjuPbtLy7QCkiSUAq1ViHQbDaL3Q2bEgVwd6KYhuDuYjSLwJ09yP8F4sIpGoEjBEIpaZS81yy5rcQrjzVpEJ1J/k3+gsP/ff8Il5G/2fNPGkF4pUAjvJfNawrz6+6nByVFqa9kYlFhOgoleq5SgazextGgsaNdiThmeeBJXBYr4z15AL5i/ioJvcwoWg7EgX1xjpO37MHbHk9cvNKHBpa8cWVIoeH9ZVoeX1Sk6ykIsL08SRz2FoqiqiH0H80ZBl8mbYqf/59QLgvtScQdiPfpNCbtCqFRQq+nzZp37cyEJfB7ESNYvPedtBiOKeCsCogqfiETZge9IpzwbzwL6HdlV21S19DYFITRWJv8H8yErsk/8lQez2N5NH4HI3koD+Y+IfILkbMOmItxUMQzUoFWr05wQJLEsdEC75K6R820tQUE+AQklUUEZHTU+fxbmEyk+i6LRAJoC/0YmL5Nar15FkGqz7RnmvctjIyMwqOsoReDAVLV0rwVJEh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D5WxmaYg9eyDLXQhSUMDU0sLUawuaKqvbGhqbIKVYjiQaQQL2njT0LoS/m7lCr4lQzTmuxjCoadioqGD8nYpaSnBrVwZcjQGguzd9Lz9OWZlztV+GGmLZo3W0dAyABUGMFy9YkQGraQZyvui5GUQK8TxDTs4JGuoWSSGjZraeB5NvHiPSv+dQ4gKw8agodG7ECucqIZ2GpDaFVWXt4wC); font-weight: 500; unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; }
</style>
</defs>
<g
@@ -241,11 +230,6 @@ exports[`exportToSvg > with elements that have a link 1`] = `
exports[`exportToSvg > with exportEmbedScene 1`] = `
"<!-- svg-source:excalidraw --><metadata><!-- payload-type:application/vnd.excalidraw+json --><!-- payload-version:2 --><!-- payload-start -->eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO1WXW/aMFx1MDAxNH3fr4iy12p1XHUwMDAyXHUwMDE0xlx1MDAxYlvbrdK6TWNSpU17MPFNYmHs1Hb4KOp/n+1AnKSok/bCXHUwMDAzXHUwMDA0KZLP9f0699yI7ZsgXGL1poBwXHUwMDFjhLBOMKNE4lV4YfElSEVcdTAwMDU3ptidlShl4m7mWlx1MDAxN+PLSyaMQy6UXHUwMDFl91x1MDAxMEKVXHUwMDEzMFhcdTAwMDDXylxc+23OQbB1b2OhxLouXHUwMDFm5OO3STqnnMSPyWL45Xry6ZdzdZfW5k4/6tfnjc3eXHUwMDFi1udcdTAwMTUlOjdYhFCN5UCzXFx3QMwzZmv1iNJSzOGjYELaQt5cIvf41DOczDMpSk78nWiA8Sz1d1LK2FRvWMVcdTAwMDJO8lJC2MnwsC+xg9d+Slx1MDAxOJa9l0mZ5Vx1MDAxY5Rq+YhcdTAwMDInVG86Xdn6ijvi2P3jq5J4XHUwMDAxd5ZeXjLWXGbMyS5wy2C4XHUwMDA3S3SIXHUwMDFi7StcdTAwMDDisvWjq8HwPVx1MDAxYdVcdTAwMTavgyhGXfSr4E5cdTAwMTNRNFx1MDAxYSHUj4dXPo26NmrQLmyKmVx1MDAwMk+1reymoVx1MDAxNN9LWVx1MDAxMFxcuXguXHUwMDEyXHQ7rNVcdTAwMDajfP5cdTAwMDJcdTAwMTPJ/EDCvcRcdMVcdTAwMGLBSejw54tDXHUwMDAypSRGZz1cdTAwMWVJj9GJ6Vx1MDAxMVx1MDAxOKOFgn/oMTqKXHUwMDFlI7C/09ZjfGJ61LDWjWlcbq6n9MlaXHUwMDFhjc2wgltvaYW3XHUwMDFlt3hBmVx1MDAxZMzAh7dhTXghaUY5ZkE7z1x1MDAxZf75+jV7mjCaWaZDXHUwMDA2acNkyNbU/Fx1MDAxOanNWlx1MDAxNN6amKow5SBfasBwXHUwMDA0n+v9eFx1MDAxN/uacanFXHUwMDBmUFWTbbZcdTAwMTieXHUwMDAx+y5cdTAwMTTV1dhtxNc3OD5v8JE2uHfe4P/fYN/pyWywebtRhbgoptpcZsVYq3020qSkQ2aFaSj8585B94LAXHLHM9adVLiksPpwYFx1MDAwZlP37DreXHL5vmSaTo3CXHUwMDEyW6aV0dbW574ydlFhXHUwMDA3Pf9cdTAwMDUqLIdcdTAwMTQifQ==<!-- payload-end --></metadata><defs><style class="style-fonts">
@font-face { font-family: Excalifont; src: url(data:font/woff2;base64,d09GMgABAAAAAAf0AA4AAAAADbQAAAegAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbgjgcNAZgAHwRCAqPYItcCxoAATYCJAMwBCAFgxgHIBujClGUblKX7Edh3Pg8OJbt5MlDFPwWk6FmJ08terdayeDx9O8Fa5eunTJ1ykAUGuAvgOF5bPfuH0nXrvQrNkFoNlERBLIQDd/mj2kP7fdg8avL4M/sm4cbu4L2i1VQVjShz/+90/YE3IJFmOC+f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EB0FElKG8DIXEQkASS4s/2PSN2DGs1Bi6eh9EhVoZDAH0NblyEbw9tsoChtttEDDbQxvDTZWKm+YcYcDOj01qtdWK8110F5XIQq+nMJuwnpSopmb7KJVWbUgQqhwkyQxlOd76aglFYEKoxAJ8OeFkYPjBPTuQejsbXStQgY5klp1cr1LoQHSUa8StKqVbKnrXAqNAgg8wm1EB6RBL7ejLWnSmSI9hGJQZdAW2trTXRJoBsJm6M5VNQlFM3yJ/7EAAAA=); }
@font-face { font-family: Excalifont; src: url(data:font/woff2;base64,d09GMgABAAAAAAHcAA0AAAAAA9gAAAGMAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cNAZgAAQRCAoAKgsEAAE2AiQDBAQgBYMYByAbHQPIrgp4MjSeIQLqpl4jnPFQwveqm205gmrZevZ2/8kKGaJ6ictBuCwMMnsKo8hC4RwaLBrJ7dXaFrFk0Re1e/Dk3t9wCUVrYAiZkgiZ5rGDVFdY04wBF4APOCzXHr/ljrNIDqLAY/slkQf0SyjxLNBaAq8Z1AJqYW5j0GjbckRLQhoJCgwYoyfY3q33QS5DrSAwYB4hFruNve4WoN2On4P29GEFWsC+nVM/UvSlVwIcsWycI/5gbqfUhE/9Q2P7UppTOAVeIR4TYIocELVKIEACZJgXCJ5GXl0o+esbFP3g+763DcDPx6/60MrnBaBPAsGPUDRC/8+FGIqGUSBA+NIJOwTWe13HRCIrgEvfRhj1RjLiE42eG7I5DIpVNuqkNNhxwaItTI2srRz4dfHGjhZoO0O8nb2pilFYQKhenFaycLUxsYcoAQRyoRBEnPvcgfysPq+npClt8UxLyvHWjaudqbGJA+TCckNECBGBGFforuTs0M4CUMbCAvp+P4in4o864XECREBtFQAAAAA=); }
@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAIsAA4AAAAABLQAAAHYAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQDBAQgBYQkByAb5wPIrgp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ALA0KABQmiQzYkKPBfpRLvBQqrwwDAA==); }
@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAIoAA4AAAAABLQAAAHVAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQDBAQgBYQkByAb5wMRFZQHZF8mb0PNXjkIbeHQ4UpbWDTlYMnK5cOfavAw/zzrESo5EbTf6+zdCyBIAqHiUlkJRMJHmIKskVWRFZ4Uelb50Iz7S0IKNNGB0oyDDbgkjnxA+VCvYpk1vog5la7RoxGwSoMFQHNIwf6bvMXbb7uB/zbQEScWUOABB/oDJf6DJ5YWB/oY5UFuDZN1TcR4iIwPH80dBd1mzcrh6sxZnRpoDQTd1qyp8Hzy6v/JPaP30LMHRmG53ZSD/CblWFLgqIbNBWE2y5SSY+mk9V/qr9Nr9rO2mFcC8rUMi6qITgWjClaVl+6tZxG4/ezyvYhiVKOKkiUQBNKW3wCR1gQCConGgYL6Vik5uYHBH+T6E3yc6OHLTplP/6g2k2hXQPgla1sH3lJf6DTJbxPEedV9bQIAqqDHcZWmC+/+j44tH3TR772uDr2oN6zbTDun2m3YKIReywFCxkEb6b7Skm4ghBglR9vyebxlKPLNt+27HjvxxGew/DGCDtQsGvyXTehdSPR6qVWpddg/nU/LMs3gtu7yCJFbt56xvjyH9E/ovVql2tAfnq0bv/9CILBNpk8584BQPeMxltJeuez6zONGyYS47AK4ke1Awmg5eZRnZSUd); }
@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAY8AA8AAAAADAwAAAXkAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbgkocZAZgP1NUQVREAHwRCAqKAIgNCyAAATYCJAM8BCAFhCQHIBv4CVFUchKQ/TyMjWWPhbGVsLhp9GSH50tTI0kpiVprztv5Fg//7Ue7b76siAPJNIlodGtQN2PVLBMSh9QsiSdPzOBa2yGm7yb77eytNyKhUQpUht7Tv2xOByU3QenAtg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+rAfBAhwrgCPZOdT6SsdeXdHTmEap+SEbKnmYUKl1kF9ixbBTvAjDi8Q7YTIeJvVGXPKVlMwVSfFrRErAQx6USuEfFmB4AXxvPKPOeytqahwT5VCsEgL5NVYIh7RnYQnQZ8M1wmpj5aGh4k8+gIk4brwGIaTM7D1T/l89ALkmOy2yKTb5MBsigGfagSxd+I0mLtr2Goo0qyBK3Se3V1eCadQGKKzhwsmjoL8DbcjsH/TZ2UwJIYLL2cX9CiYCEVZUDVWa5Td7EUMhYQMR+3ReC44nK7341kBYyFC0+J0Zy0R0AJ2+LirQcHa3APhUgt78p9aYOtMXb8kQ/JHUseYN+SQyliokRGB+U+fVV+/elyG/lb4jcj1HRtNAyNBRcYlDEpJLEhIroFYlYR+19qt2YF3+7UU6JVDcHxum1ZyNvFzxG3vxGV4PxIB3izP535BXlNqlEKCWQPBN0h6G1nAEQvSyjvhlccIYEk6RqBT+rLBhq++6mCeaVmSnhRSRLhqn858kQhmckK8KdDho33l762L3oRbXFaJswnP/GldY6NuVtHvpKmyw2lmyXZVhDWdtPtWkoNUMGcLYD5WxmaYg9eyDLXQhSUMDU0sLUawuaKqvbGhqbIKVYjiQaQQL2njT0LoS/m7lCr4lQzTmuxjCoadioqGD8nYpaSnBrVwZcjQGguzd9Lz9OWZlztV+GGmLZo3W0dAyABUGMFy9YkQGraQZyvui5GUQK8TxDTs4JGuoWSSGjZraeB5NvHiPSv+dQ4gKw8agodG7ECucqIZ2GpDaFVWXt4wC); }</style></defs><g stroke-linecap="round" transform="translate(10 10) rotate(0 50 50)" data-id="vWrqOAfkind2qcm7LDAGZ"><path d="M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M2.68 54.01 C17.68 37.03, 33.95 20.86, 40.74 10.24 M2.68 54.01 C16.59 38.38, 31.52 22.36, 40.74 10.24 M5.7 56.63 C19.86 43.02, 33.12 27.27, 52.94 2.29 M5.7 56.63 C23.06 37.39, 40.39 16.53, 52.94 2.29 M8.72 59.26 C23.62 43.85, 37.66 28.7, 55.96 4.92 M8.72 59.26 C27.67 38.75, 44.88 17.7, 55.96 4.92 M11.74 61.88 C23.55 50.54, 31.34 37.36, 58.98 7.54 M11.74 61.88 C25.4 47.12, 38.59 32.54, 58.98 7.54 M14.76 64.51 C25.64 54.29, 34.7 42.69, 61.34 10.92 M14.76 64.51 C25.83 51.81, 38 38.36, 61.34 10.92 M17.12 67.88 C34.34 49.26, 48.5 31.65, 64.36 13.55 M17.12 67.88 C33.86 49.33, 49.44 31.94, 64.36 13.55 M20.14 70.51 C28.87 60.06, 40.4 48.29, 66.72 16.92 M20.14 70.51 C29.76 60.14, 39.05 48.61, 66.72 16.92 M23.16 73.13 C37.73 55.91, 51.72 40.01, 69.74 19.55 M23.16 73.13 C35.28 60.9, 46.76 46.19, 69.74 19.55 M26.18 75.76 C38.75 61.93, 48.87 47, 72.76 22.17 M26.18 75.76 C41.17 57.48, 56.57 40.42, 72.76 22.17 M29.2 78.38 C38.58 66.84, 49.28 56.06, 75.12 25.55 M29.2 78.38 C45.23 60.41, 60.56 42.59, 75.12 25.55 M31.56 81.76 C48.47 62.24, 65.95 45.31, 78.14 28.18 M31.56 81.76 C45.84 64.05, 61.69 48.32, 78.14 28.18 M34.58 84.39 C53.9 64.75, 70.59 44.84, 81.16 30.8 M34.58 84.39 C52.97 64.26, 69.66 43.17, 81.16 30.8 M37.6 87.01 C48.25 74.78, 55.5 66.41, 83.52 34.18 M37.6 87.01 C48.99 71.83, 62.27 58.43, 83.52 34.18 M40.62 89.63 C50.34 79.26, 59.13 68.4, 86.54 36.8 M40.62 89.63 C54.92 72.51, 68.88 57.45, 86.54 36.8 M43.64 92.26 C53.65 80.81, 66.89 67.98, 89.56 39.43 M43.64 92.26 C58.66 75.45, 72.42 57.89, 89.56 39.43 M46 95.64 C61.79 76.78, 78.15 59.99, 91.92 42.81 M46 95.64 C61.9 78.99, 77.17 61.29, 91.92 42.81 M49.02 98.26 C62.86 82.2, 75.55 68.59, 94.94 45.43 M49.02 98.26 C66.35 78.07, 84.72 56.67, 94.94 45.43 M61.22 90.32 C67.86 83.05, 77.21 73.12, 97.96 48.06 M61.22 90.32 C71.29 78.99, 79.23 69.82, 97.96 48.06" stroke="#15aabf" stroke-width="0.5" fill="none"></path><path d="M51 0 C63.55 12.43, 75.75 25.91, 100 51 M51 0 C68.7 19, 85.84 36.05, 100 51 M100 51 C86.33 62.39, 74.98 74.41, 51 100 M100 51 C82.86 68.81, 63.17 88.61, 51 100 M51 100 C30.58 80.76, 12.2 63.63, 0 51 M51 100 C32.58 80.36, 11.39 62.79, 0 51 M0 51 C13.05 38.39, 26.48 26.08, 51 0 M0 51 C14.03 37.59, 27.42 24.3, 51 0" stroke="#000000" stroke-width="1" fill="none"></path></g><g stroke-linecap="round" transform="translate(10 10) rotate(0 50 50)" data-id="id20"><path d="M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M4.65 33.19 C11.77 27.87, 17.81 20.43, 26.3 8.29 M4.65 33.19 C12.84 24.59, 20.75 14.56, 26.3 8.29 M4.39 39.59 Line truncated
@font-face { font-family: "Excalifont"; src: url(data:font/woff2;base64,d09GMgABAAAAAAf0AA4AAAAADbQAAAegAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbgjgcNAZgAHwRCAqPYItcCxoAATYCJAMwBCAFgxgHIBujClGUblKX7Edh3Pg8OJbt5MlDFPwWk6FmJ08terdayeDx9O8Fa5eunTJ1ykAUGuAvgOF5bPfuH0nXrvQrNkFoNlERBLIQDd/mj2kP7fdg8avL4M/sm4cbu4L2i1VQVjShz/+90/YE3IJFmOC+f0Z1Xhs3bVxiJZZGa1IgY5sHCJ2EM2iBndkLWsZvFxCAhRBGCknKEOQenHCpmE2fVQTl1atzWyjvzs3aQPnWd20PJQZeG3mQp1lnLimFBAhOKFIQSrGa+vOB69gLCRkjLr4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FYEKoxAJ8OeFkYPjBPTuQejsbXStQgY5klp1cr1LoQHSUa8StKqVbKnrXAqNAgg8wm1EB6RBL7ejLWnSmSI9hGJQZdAW2trTXRJoBsJm6M5VNQlFM3yJ/7EAAAA=); unicode-range: U+20-7e,U+a0-a3,U+a5-a6,U+a8-ab,U+ad-b1,U+b4,U+b6-b8,U+ba-ff,U+131,U+152-153,U+2bc,U+2c6,U+2da,U+2dc,U+304,U+308,U+2013-2014,U+2018-201a,U+201c-201e,U+2020,U+2022,U+2024-2026,U+2030,U+2039-203a,U+20ac,U+2122,U+2212; }
@font-face { font-family: "Nunito"; src: url(data:font/woff2;base64,d09GMgABAAAAAAY8AA8AAAAADAwAAAXkAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbgkocZAZgP1NUQVREAHwRCAqKAIgNCyAAATYCJAM8BCAFhCQHIBv4CVFUchKQ/TyMjWWPhbGVsLhp9GSH50tTI0kpiVprztv5Fg//7Ue7b76siAPJNIlodGtQN2PVLBMSh9QsiSdPzOBa2yGm7yb77eytNyKhUQpUht7Tv2xOByU3QenAtgPMB7F4fyAboXSW9/+/n6v/TjQN8ThtnIUEjdIpZXKR+wRP5pOEmJw+KE2scl5CrJImJdM0EiorlZ5YdBMRC560xeTjuPbtLy7QCkiSUAq1ViHQbDaL3Q2bEgVwd6KYhuDuYjSLwJ09yP8F4sIpGoEjBEIpaZS81yy5rcQrjzVpEJ1J/k3+gsP/ff8Il5G/2fNPGkF4pUAjvJfNawrz6+6nByVFqa9kYlFhOgoleq5SgazextGgsaNdiThmeeBJXBYr4z15AL5i/ioJvcwoWg7EgX1xjpO37MHbHk9cvNKHBpa8cWVIoeH9ZVoeX1Sk6ykIsL08SRz2FoqiqiH0H80ZBl8mbYqf/59QLgvtScQdiPfpNCbtCqFRQq+nzZp37cyEJfB7ESNYvPedtBiOKeCsCogqfiETZge9IpzwbzwL6HdlV21S19DYFITRWJv8H8yErsk/8lQez2N5NH4HI3koD+Y+IfILkbMOmItx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YEk6RqBT+rLBhq++6mCeaVmSnhRSRLhqn858kQhmckK8KdDho33l762L3oRbXFaJswnP/GldY6NuVtHvpKmyw2lmyXZVhDWdtPtWkoNUMGcLYD5WxmaYg9eyDLXQhSUMDU0sLUawuaKqvbGhqbIKVYjiQaQQL2njT0LoS/m7lCr4lQzTmuxjCoadioqGD8nYpaSnBrVwZcjQGguzd9Lz9OWZlztV+GGmLZo3W0dAyABUGMFy9YkQGraQZyvui5GUQK8TxDTs4JGuoWSSGjZraeB5NvHiPSv+dQ4gKw8agodG7ECucqIZ2GpDaFVWXt4wC); font-weight: 500; unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; }</style></defs><g stroke-linecap="round" transform="translate(10 10) rotate(0 50 50)" data-id="vWrqOAfkind2qcm7LDAGZ"><path d="M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M2.68 54.01 C17.68 37.03, 33.95 20.86, 40.74 10.24 M2.68 54.01 C16.59 38.38, 31.52 22.36, 40.74 10.24 M5.7 56.63 C19.86 43.02, 33.12 27.27, 52.94 2.29 M5.7 56.63 C23.06 37.39, 40.39 16.53, 52.94 2.29 M8.72 59.26 C23.62 43.85, 37.66 28.7, 55.96 4.92 M8.72 59.26 C27.67 38.75, 44.88 17.7, 55.96 4.92 M11.74 61.88 C23.55 50.54, 31.34 37.36, 58.98 7.54 M11.74 61.88 C25.4 47.12, 38.59 32.54, 58.98 7.54 M14.76 64.51 C25.64 54.29, 34.7 42.69, 61.34 10.92 M14.76 64.51 C25.83 51.81, 38 38.36, 61.34 10.92 M17.12 67.88 C34.34 49.26, 48.5 31.65, 64.36 13.55 M17.12 67.88 C33.86 49.33, 49.44 31.94, 64.36 13.55 M20.14 70.51 C28.87 60.06, 40.4 48.29, 66.72 16.92 M20.14 70.51 C29.76 60.14, 39.05 48.61, 66.72 16.92 M23.16 73.13 C37.73 55.91, 51.72 40.01, 69.74 19.55 M23.16 73.13 C35.28 60.9, 46.76 46.19, 69.74 19.55 M26.18 75.76 C38.75 61.93, 48.87 47, 72.76 22.17 M26.18 75.76 C41.17 57.48, 56.57 40.42, 72.76 22.17 M29.2 78.38 C38.58 66.84, 49.28 56.06, 75.12 25.55 M29.2 78.38 C45.23 60.41, 60.56 42.59, 75.12 25.55 M31.56 81.76 C48.47 62.24, 65.95 45.31, 78.14 28.18 M31.56 81.76 C45.84 64.05, 61.69 48.32, 78.14 28.18 M34.58 84.39 C53.9 64.75, 70.59 44.84, 81.16 30.8 M34.58 84.39 C52.97 64.26, 69.66 43.17, 81.16 30.8 M37.6 87.01 C48.25 74.78, 55.5 66.41, 83.52 34.18 M37.6 87.01 C48.99 71.83, 62.27 58.43, 83.52 34.18 M40.62 89.63 C50.34 79.26, 59.13 68.4, 86.54 36.8 M40.62 89.63 C54.92 72.51, 68.88 57.45, 86.54 36.8 M43.64 92.26 C53.65 80.81, 66.89 67.98, 89.56 39.43 M43.64 92.26 C58.66 75.45, 72.42 57.89, 89.56 39.43 M46 95.64 C61.79 76.78, 78.15 59.99, 91.92 42.81 M46 95.64 C61.9 78.99, 77.17 61.29, 91.92 42.81 M49.02 98.26 C62.86 82.2, 75.55 68.59, 94.94 45.43 M49.02 98.26 C66.35 78.07, 84.72 56.67, 94.94 45.43 M61.22 90.32 C67.86 83.05, 77.21 73.12, 97.96 48.06 M61.22 90.32 C71.29 78.99, 79.23 69.82, 97.96 48.06" stroke="#15aabf" stroke-width="0.5" fill="none"></path><path d="M51 0 C63.55 12.43, 75.75 25.91, 100 51 M51 0 C68.7 19, 85.84 36.05, 100 51 M100 51 C86.33 62.39, 74.98 74.41, 51 100 M100 51 C82.86 68.81, 63.17 88.61, 51 100 M51 100 C30.58 80.76, 12.2 63.63, 0 51 M51 100 C32.58 80.36, 11.39 62.79, 0 51 M0 51 C13.05 38.39, 26.48 26.08, 51 0 M0 51 C14.03 37.59, 27.42 24.3, 51 0" stroke="#000000" stroke-width="1" fill="none"></path></g><g stroke-linecap="round" transform="translate(10 10) rotate(0 50 50)" data-id="id20"><path d=Line truncated
`;
+280 -1
View File
@@ -1,8 +1,12 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import {
applyDarkModeFilter,
BOUND_TEXT_PADDING,
FONT_FAMILY,
FRAME_STYLE,
TEXT_RENDERING,
THEME,
} from "@excalidraw/common";
@@ -19,7 +23,8 @@ import type { LocalPoint } from "@excalidraw/math";
import { getDefaultAppState } from "../../appState";
import * as staticSceneModule from "../../renderer/staticScene";
import { exportScene } from "../../scene/export";
import { registerFontResolvers } from "../../fonts";
import { exportScene, serializeSvg } from "../../scene/export";
import { prepareElementsForExport } from "../../data";
import {
@@ -419,6 +424,168 @@ describe("exportToCanvas", () => {
]);
getContextSpy.mockRestore();
});
it("draws text with the setting it's measured with", async () => {
const renderingWhenDrawn: string[] = [];
const fillTextSpy = vi
.spyOn(CanvasRenderingContext2D.prototype, "fillText")
.mockImplementation(function (this: CanvasRenderingContext2D) {
renderingWhenDrawn.push(this.textRendering);
});
await exportScene({
type: "canvas",
data: {
elements: [API.createElement({ type: "text", text: "A V A T A R" })],
files: null,
},
});
expect(renderingWhenDrawn).toEqual([TEXT_RENDERING]);
fillTextSpy.mockRestore();
});
});
describe("registerFontResolvers", () => {
const METADATA = {
metrics: {
unitsPerEm: 1000,
ascender: 800,
descender: -200,
lineHeight: 1.2,
},
};
const createResolver = () =>
vi.fn(async () => ({
fontFaces: [{ uri: "https://example.com/font.woff2" }] as const,
metadata: METADATA,
}));
const exportText = (
fontFamily: string,
fontResolvers?: Parameters<typeof registerFontResolvers>[0],
) =>
exportScene({
type: "svg",
data: {
elements: [
API.createElement({
type: "text",
text: "a",
fontFamily: fontFamily as `${string}:${string}`,
}),
],
appState: {},
files: null,
},
config: { skipInliningFonts: true, fontResolvers },
});
it("resolves custom fonts in every export, until taken back", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const resolver = createResolver();
const unregister = registerFontResolvers({ "test.registered": resolver });
await exportText("test.registered:First");
expect(resolver).toHaveBeenCalledWith("First");
expect(warn).not.toHaveBeenCalled();
unregister();
await exportText("test.registered:Second");
expect(resolver).toHaveBeenCalledTimes(1);
// nothing supplies the font any more - that isn't silent
expect(warn).toHaveBeenCalledTimes(1);
warn.mockRestore();
});
it("doesn't resolve the font of a deleted element", async () => {
const resolver = createResolver();
await exportScene({
type: "svg",
data: {
elements: [
API.createElement({
type: "text",
text: "a",
fontFamily: "test.deleted:Gone",
isDeleted: true,
}),
],
appState: {},
files: null,
},
config: {
skipInliningFonts: true,
fontResolvers: { "test.deleted": resolver },
},
});
expect(resolver).not.toHaveBeenCalled();
});
it("lets a resolver passed to the export win", async () => {
const registered = createResolver();
const passed = createResolver();
const unregister = registerFontResolvers({ "test.override": registered });
await exportText("test.override:Font", { "test.override": passed });
expect(passed).toHaveBeenCalledWith("Font");
expect(registered).not.toHaveBeenCalled();
unregister();
});
it("is shared with another copy of the package in the realm", async () => {
const resolver = createResolver();
const unregister = registerFontResolvers({ "test.shared": resolver });
// i.e. `@excalidraw/utils`, or a second bundle - loaded later, at that
vi.resetModules();
const otherCopy = await import("../../fonts/resolvers");
expect(otherCopy.registerFontResolvers).not.toBe(registerFontResolvers);
expect(otherCopy.getExportFontResolvers()).toMatchObject({
"test.shared": resolver,
});
unregister();
expect(otherCopy.getExportFontResolvers()).not.toHaveProperty(
"test.shared",
);
});
it("rejects a provider key the editor wouldn't accept", () => {
expect(() => registerFontResolvers({ acme: createResolver() })).toThrow(
"Invalid font provider key",
);
});
});
describe("serializeSvg", () => {
it("serializes a non-breaking space as XML can parse it", async () => {
const svg = await exportScene({
type: "svg",
data: {
// the entity typed out must survive as text
elements: [
API.createElement({ type: "text", text: "a\u00a0b &nbsp; c" }),
],
appState: {},
files: null,
},
config: { skipInliningFonts: true },
});
// HTML serialization writes `&nbsp;`, an entity XML doesn't define
expect(svg.outerHTML).toContain("&nbsp;");
const markup = serializeSvg(svg);
expect(markup).toContain("a&#160;b &amp;nbsp; c");
const parsed = new DOMParser().parseFromString(markup, "image/svg+xml");
expect(parsed.querySelector("parsererror")).toBe(null);
expect(parsed.querySelector("text")?.textContent).toBe("a\u00a0b &nbsp; c");
});
});
describe("export background", () => {
@@ -612,6 +779,99 @@ describe("export inputs", () => {
consoleWarn.mockRestore();
});
it.each([
["a local font", FONT_FAMILY.Helvetica],
["a font of a provider nobody configured", "test.unconfigured:Brand"],
["a font a configured resolver supplies", "test.headless:Brand"],
] as const)("needs no `FontFace` either, for %s", async (_, fontFamily) => {
const consoleWarn = vi
.spyOn(console, "warn")
.mockImplementation(() => {});
const ownerDocument = document.implementation.createHTMLDocument();
vi.stubGlobal("document", ownerDocument);
vi.stubGlobal("FontFace", undefined);
const loadFonts = vi.fn(async () => {});
// twice: the second export finds the resolved family registered
for (let i = 0; i < 2; i++) {
const svg = await exportScene({
type: "svg",
data: {
elements: [
API.createElement({ type: "text", text: "hi", fontFamily }),
],
},
config: {
skipInliningFonts: true,
fontResolvers: {
"test.headless": async () => ({
fontFaces: [{ uri: "https://example.com/font.woff2" }],
metadata: {
metrics: {
unitsPerEm: 1000,
ascender: 800,
descender: -200,
lineHeight: 1.2,
},
},
}),
},
environment: { document: ownerDocument, loadFonts },
},
});
expect(svg.querySelector("text")?.textContent).toBe("hi");
}
expect(loadFonts).toHaveBeenCalledTimes(2);
consoleWarn.mockRestore();
});
it("embeds a resolved font with no `window`, `document` or `FontFace` at all (i.e. Node)", async () => {
// the export is handed the document to build the SVG in
const ownerDocument = document.implementation.createHTMLDocument();
const font = readFileSync(
path.resolve(__dirname, "../../fonts/Virgil/Virgil-Regular.woff2"),
);
const element = API.createElement({
type: "text",
text: "hi",
fontFamily: "test.node:Virgil",
});
vi.stubGlobal("FontFace", undefined);
vi.stubGlobal("window", undefined);
vi.stubGlobal("document", undefined);
vi.stubGlobal("self", undefined);
const svg = await exportScene({
type: "svg",
data: { elements: [element] },
config: {
fontResolvers: {
// a face without a `unicodeRange`
"test.node": async () => ({
fontFaces: [
{ uri: `data:font/woff2;base64,${font.toString("base64")}` },
],
metadata: {
metrics: {
unitsPerEm: 1000,
ascender: 800,
descender: -200,
lineHeight: 1.25,
},
},
}),
},
environment: { document: ownerDocument, loadFonts: async () => {} },
},
});
expect(svg.querySelector("text")?.textContent).toBe("hi");
expect(svg.querySelector("style.style-fonts")?.textContent).toMatch(
/@font-face.*url\(data:/,
);
});
it("loads fonts into a worker's own font set", async () => {
const fonts = {
has: () => true,
@@ -634,6 +894,25 @@ describe("export inputs", () => {
});
});
it("loads fonts into the document it's given (e.g. a popout window's)", async () => {
const ownerDocument = document.implementation.createHTMLDocument();
const load = vi.fn(async () => []);
Object.defineProperty(ownerDocument, "fonts", {
value: { has: () => true, add: vi.fn(), check: () => false, load },
});
await exportScene({
type: "svg",
data: { elements: [API.createElement({ type: "text", text: "hi" })] },
config: { environment: { document: ownerDocument } },
});
expect(load).toHaveBeenCalledWith(
expect.stringContaining("Excalifont"),
"hi",
);
});
it("renders frame decorations per config.frames", async () => {
const elements = [API.createElement({ type: "frame" })];
const countFrameNames = (svg: SVGSVGElement) =>
+205 -4
View File
@@ -5,6 +5,7 @@ import type {
MIME_TYPES,
EditorInterface,
StrokeWidthKey,
FontFamily,
} from "@excalidraw/common";
import type { LinearElementEditor } from "@excalidraw/element";
@@ -25,7 +26,6 @@ import type {
ExcalidrawBindableElement,
ExcalidrawArrowElement,
Arrowhead,
FontFamilyValues,
FileId,
Theme,
StrokeRoundness,
@@ -68,6 +68,9 @@ import type { ImportedDataState } from "./data/types";
import type { SetViewportOptions } from "./viewport";
import type { Language } from "./i18n";
import type { FontResolver } from "./fonts";
import type { isOverScrollBars } from "./scene/scrollbars";
import type React from "react";
import type { JSX } from "react";
@@ -468,12 +471,12 @@ export interface AppState {
currentItemRoughness: number;
currentItemStrokeVariability: StrokeVariability;
currentItemOpacity: number;
currentItemFontFamily: FontFamilyValues;
currentItemFontFamily: FontFamily;
currentItemFontSize: number;
currentItemTextAlign: TextAlign;
currentItemStartArrowhead: Arrowhead | null;
currentItemEndArrowhead: Arrowhead | null;
currentHoveredFontFamily: FontFamilyValues | null;
currentHoveredFontFamily: FontFamily | null;
currentItemRoundness: StrokeRoundness;
currentItemArrowType: "sharp" | "round" | "elbow";
viewBackgroundColor: string;
@@ -600,7 +603,7 @@ export interface AppState {
};
/** user-customized font-picker top picks (pinned via drag & drop from the
* font picker popup). `null` means no customization (defaults are used) */
fontTopPicks: readonly FontFamilyValues[] | null;
fontTopPicks: readonly FontFamily[] | null;
}
export type SearchMatch = {
@@ -726,6 +729,165 @@ export type OnExportProgress = {
progress?: number;
};
/**
* What a font is for, as the font picker's icons tell it: handwriting, text,
* code (monospace) or headings (display).
*/
export type FontKind = "hand-drawn" | "normal" | "code" | "heading";
export interface FontProvider {
/**
* The icon of a family's row in the font list where the provider says
* nothing else about it - see `getKind` and `getPreviewText`. Without one
* such a row gets the icon of a "normal" font.
*/
icon?: React.JSX.Element;
/**
* Resolve a bare font family name (i.e. "Roboto") into a loadable font
* definition.
*
* WARN: family names are treated as *exact* - reject a name you don't
* recognise verbatim rather than normalising it. The name is persisted into
* `fontFamily`, so it has to mean one thing: resolving both "Roboto" and
* "roboto" puts two ids for one font into documents.
*/
resolve: FontResolver;
/**
* The fonts to offer up front in the font picker - see {@link ProvidedFont}.
*
* Taken as-is: keep them unique, and mind that a name shadowing a built-in
* font (i.e. "Nunito") shows up as a separate entry next to it.
*/
availableFonts: readonly ProvidedFont[];
/**
* Text previewing a family, written in that family. Return a sample in the
* family's script, i.e. "あ" for a Japanese font, and nothing for a Latin
* one.
*
* It stands for the family when pinned to the font picker's top picks -
* "Aa" when omitted, empty or failed, and while a returned promise is
* pending ("Aa" falls back to another font where the family has no Latin
* glyphs). In the font list it is the icon of the family's row, so that a
* family named in Latin letters shows which script it writes; without one
* the row's icon follows `getKind`, then `icon`.
*
* Asked once per listed or pinned family, the answer is kept for the
* session.
*
* @param fontFamily the family's id, i.e. "Roboto" - see {@link ProvidedFont}
*/
getPreviewText?(fontFamily: string): string | Promise<string>;
/**
* What kind of font a family is. Its row in the font list gets the icon
* our own fonts of that kind have, so that the list reads the same way
* throughout. Return nothing for a family you can't tell it of - its row
* gets `icon`.
*
* Asked once per listed family, the answer is kept for the session.
*
* @param fontFamily the family's id, i.e. "Roboto" - see {@link ProvidedFont}
*/
getKind?(
fontFamily: string,
): FontKind | undefined | Promise<FontKind | undefined>;
/**
* Find families beyond `availableFonts` as the user types into the font
* picker's search (debounced, and aborted via `signal` once superseded).
*
* Return every hit, most relevant first - the picker lists only the first
* few, so the user narrows down by typing more. Ids follow `resolve`'s
* exactness rule: return the canonical spelling.
*
* Only what this returns is offered: a typed name is never tried as a font
* of its own, as ids aren't necessarily something a user could type.
*
* @param query trimmed search text, i.e. "rob"
*/
search?(
query: string,
opts: { signal: AbortSignal },
): Promise<FontSearchResult>;
/**
* More of the provider's fonts than `availableFonts`, a page at a time -
* turns "Browse more fonts" on at the end of the font picker's list, as
* long as there is a font to show for it: the picker asks for the first
* page as it opens (once), and offers nothing where that brings no font it
* doesn't list already. It asks for the next page when the user clicks, and
* from then on whenever they reach the end of the list.
*
* Return the fonts in an order which stays the same between calls (i.e.
* most popular first), `limit` of them at most - fewer mean there are no
* more. Fonts the picker lists already are skipped, and what gets loaded is
* appended as it comes, not sorted. It stays listed when the picker closes
* and reopens, until `fontProviders` changes.
*
* @param opts.offset how many fonts the earlier calls returned
*/
loadMore?(opts: {
offset: number;
limit: number;
signal: AbortSignal;
}): Promise<readonly ProvidedFont[]>;
}
/**
* A font a provider offers. `id` is the family part of its font id
* (`"<provider>:<id>"`) - what gets saved into `fontFamily` and handed to
* `resolve` - and `label` the name the font picker shows and searches by. A
* plain string is shorthand for the two being the same, i.e. "Roboto" for a
* Google font.
*
* Tell them apart wherever the id isn't a name - an uploaded font's id
* should be something stable (i.e. a hash or a uuid), so that renaming the
* font or another organization uploading one under the same name doesn't
* change what a document refers to.
*/
export type ProvidedFont = string | { id: string; label: string };
export type FontSearchResult = {
/**
* "match" when every label contains the query (case-insensitive substring),
* "suggestion" when none does and the labels are merely similar, i.e.
* "Roboto" for "rovoto" - listed only while nothing matches
*/
kind: "match" | "suggestion";
fonts: readonly ProvidedFont[];
};
/**
* Font providers, by provider key. The key is persisted as part of every font
* family id it resolves (`<provider>:<family>`, i.e. "com.acme.fonts:Brand
* Sans") and travels with the document, so it can never change. It must be:
*
* - `"google"` ({@link GOOGLE_FONT_PROVIDER_KEY}) for Google Fonts, or
* - a lowercase reverse-DNS key under a domain you own, containing at least
* one dot, i.e. "com.acme.fonts". Keys without a dot are reserved.
*
* The key names the catalog, not whoever serves the files: a mirror of Google
* Fonts still registers as `"google"`.
*
* The contract every provider signs up to, as ids end up in files, libraries
* and the clipboard, and are read by other hosts:
*
* - One id means one rendering. A family is resolved once, then cached and
* shared across every editor on the page until reload, so resolvers must
* return equivalent faces and metadata for the same family.
* - Ids are exact. Resolve only the names you publish, verbatim, and reject
* the rest rather than normalizing them.
* - Never stop resolving a family you once offered - documents using it are
* out there for good.
* - A family is a family: don't publish its weights or styles as separate
* families (i.e. "Roboto Light").
*
* A rejection is not retried automatically - the family is shown as failed in
* the picker until a deliberate user action, which keeps host code off the
* path of every scene update. Resolvers are expected to cache their
* definitions and to retry internally before rejecting. The verdict is
* page-scoped and clears as soon as the family resolves anywhere; image
* exports never record one, so a blip while rendering cannot disable a font.
*/
export type FontProviders = Record<string, FontProvider>;
export type InteractionConfig = {
/**
* Interactions that stay enabled while the editor is otherwise
@@ -980,6 +1142,10 @@ export interface ExcalidrawProps {
* prevent the duplication as a whole, return `false`. If no duplicate
* remains, the duplication is cancelled and the returned elements are
* ignored (alt-drag then moves the original elements instead).
*
* NOTE: replacing a text element's `fontFamily` here leaves its measured
* geometry (width, wrapping, container size) to you - the editor does not
* re-measure host-swapped duplicates.
*/
onDuplicate?: (
nextElements: readonly ExcalidrawElement[],
@@ -1112,6 +1278,41 @@ export interface ExcalidrawProps {
) => JSX.Element | null;
aiEnabled?: boolean;
showDeprecatedFonts?: boolean;
/**
* Font providers for custom font support, keyed by provider key. Custom
* fonts are identified by that key as a prefix in `fontFamily`, i.e.
* `"google:Roboto"`; built-in fonts are unaffected. See
* {@link FontProviders} for which keys are allowed.
*
* Providers are scoped to this editor; resolved font faces are shared
* page-wide, so a family any editor resolved renders in all of them.
*/
fontProviders?: FontProviders;
/**
* The user's favorite fonts, and what to do when they change - turns
* favorites on in the font picker. A font is added by dragging it from the
* picker's list onto the drop zone which takes the search's place for the
* drag, and removed the same way. Favorites are listed in a section of
* their own, below the fonts the scene uses.
*
* Controlled: the editor keeps nothing, so that the host can store the
* list where it stores the user's other preferences.
*/
fontFavorites?: {
/** font ids as in `fontFamily`, i.e. `5` or `"google:Roboto"` */
fonts: readonly FontFamily[];
onChange: (fonts: FontFamily[]) => void;
};
/**
* Replaces the tip at the bottom of the font picker ("Drag a font to pin"),
* i.e. to say where the fonts offered there come from and where to change
* them. `null` shows none.
*
* Replaces the whole text rather than adding to it, so that the tip never
* mixes the host's translations with the editor's - localize it yourself.
* The editor's reset link for customized top picks stays next to it.
*/
fontPickerTip?: React.ReactNode;
renderScrollbars?: boolean;
viewportStatusFrame?: ViewportStatusFrame | null;
/**
@@ -1799,6 +1799,29 @@ describe("textWysiwyg", () => {
expect(diamond.height).toBe(70);
});
it("should shrink a bound-text container using a custom font", async () => {
API.setAppState({ currentItemFontFamily: "provider:Custom" });
const diamond = API.createElement({
type: "diamond",
x: 10,
y: 20,
width: 90,
height: 75,
});
API.setElements([diamond]);
API.setSelectedElements([diamond]);
Keyboard.keyPress(KEYS.ENTER);
const editor = await getTextEditor();
const value = new Array(1000).fill("1").join("\n");
fireEvent.input(editor, { target: { value } });
expect(diamond.height).toBe(50020);
updateTextEditor(editor, "");
expect(diamond.height).toBe(70);
});
it("should bind text to container when double clicked inside of the transparent container", async () => {
const rectangle = API.createElement({
type: "rectangle",
+7 -23
View File
@@ -366,25 +366,12 @@ export const textWysiwyg = ({
y: number;
} | null = null;
const textPropertiesUpdated = (
updatedTextElement: ExcalidrawTextElement,
editable: HTMLTextAreaElement,
) => {
if (!editable.style.fontFamily || !editable.style.fontSize) {
return false;
}
const currentFont = editable.style.fontFamily.replace(/"/g, "");
if (
getFontFamilyString({ fontFamily: updatedTextElement.fontFamily }) !==
currentFont
) {
return true;
}
if (`${updatedTextElement.fontSize}px` !== editable.style.fontSize) {
return true;
}
return false;
};
// compare against the last layout we set, not against the DOM style - the
// browser re-serializes `style.fontFamily` (quoting is engine-specific),
// so a string comparison against it breaks for quoted custom families
const textPropertiesUpdated = (updatedTextElement: ExcalidrawTextElement) =>
currentTextLayout !== null &&
currentTextLayout.font !== getFontString(updatedTextElement);
let LAST_THEME = app.state.theme;
@@ -444,10 +431,7 @@ export const textWysiwyg = ({
coordX = x;
coordY = y;
} else {
const propertiesUpdated = textPropertiesUpdated(
updatedTextElement,
editable,
);
const propertiesUpdated = textPropertiesUpdated(updatedTextElement);
let originalContainerData;
if (propertiesUpdated) {
+2
View File
@@ -5,6 +5,8 @@ export {
MIME_TYPES,
} from "@excalidraw/excalidraw/scene/export";
export { registerFontResolvers } from "@excalidraw/excalidraw/fonts/resolvers";
export type {
ExportSceneData,
ExportSceneConfig,
+721
View File
@@ -0,0 +1,721 @@
/**
* Generates the Google Fonts catalog shipped with the package
* (`packages/excalidraw/fonts/google/catalog.json`), which the Google font
* resolver reads its family names and metrics from.
*
* yarn gen:google-fonts # add newly offered families, report drift
* yarn gen:google-fonts --new-only # the same, without checking existing ones
* yarn gen:google-fonts --refresh # also take over drifted metrics
* yarn gen:google-fonts --allow "A Family" --allow "Another"
* # add families which were held back
*
* Per family it asks Google's `css2` API for the regular (400) face, downloads
* the first subset file and reads the vertical metrics out of its `head` and
* `hhea` tables - every subset of a family shares those.
*
* Rules:
*
* - The catalog holds the families we offer and nothing else - see
* `OFFERED_FAMILIES`. Each was looked at in Chrome, Firefox and Safari
* before it went in: the canvas and the text editor have to lay its text
* out alike, in each of them and between them. The rules further down are
* what a family is checked against here, before anyone looks at it.
* - The catalog is append-only. A font id (i.e. "google:Roboto") is saved
* into documents, so an entry never goes away and never changes:
* - A family which leaves Google's list keeps its entry. The run fails if
* the output would lose a name.
* - A family keeps the metrics it was added with, even when Google has
* since changed the font. Every version of the package, and every host
* and renderer using one, then lays the same text out the same way. The
* drift is reported, and taking it over is a deliberate `--refresh`.
* - Only families with a regular 400 face. Without one `css2` needs an
* explicit weight, and which weight such a family should default to is
* left open until weights are supported.
* - Text fonts only. Google's list has no icon fonts (Material Icons and
* Symbols aren't in it), but it has families whose letters aren't letters:
* barcodes, pictograms, emoji, knitting charts, redacted text. Left out
* are the families Google classifies as "Symbols", and those matching
* `NON_TEXT_FAMILIES` which it doesn't. The math families (STIX Two
* Math, Noto Sans Math) are in: their letters are letters, and they hold
* the math symbols their text companions lack.
* - No families known to draw wrong - see `BROKEN_FAMILIES`.
* - No families which are slow to draw - see `SLOW_FAMILIES`. A family new
* to Google's list whose font file looks like one of those is held back
* until someone has measured it - see `getHeavyOutlinesReason`.
* - No families whose text would jump when the text editor opens, because
* browsers don't agree on their vertical metrics - see
* `OFF_BASELINE_FAMILIES`. A family new to Google's list is held back
* when its font file says the same - see `getOffBaselineReason`.
* - No families whose lines the canvas and the text editor lay out at
* different widths - see `UNEVEN_WIDTH_FAMILIES`. A font file doesn't
* tell, so a family new to Google's list isn't held back for it: that
* takes measuring in a browser.
* A family already in the catalog stays, whatever it's classified as
* later - see the second rule.
*
* Entry: [name, unitsPerEm, ascender, descender, lineGap, kind, script?], in
* the order of `OFFERED_FAMILIES`. `kind` is what the family is for, as the font
* picker's icons tell it. `script` is set where "Aa" makes a poor preview: CJK
* families, and families with no Latin subset.
*/
import { readFile, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
const require = createRequire(import.meta.url);
const wawoff2 = require("wawoff2");
const CATALOG_PATH = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../packages/excalidraw/fonts/google/catalog.json",
);
const METADATA_URL = "https://fonts.google.com/metadata/fonts";
const CSS_URL = "https://fonts.googleapis.com/css2";
/**
* `css2` answers by User-Agent: a browser gets woff2 split into
* `unicode-range` subsets - what the editor loads - anything else gets a
* single unsubsetted TrueType file.
*/
const BROWSER_USER_AGENT =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const CONCURRENCY = 8;
const ATTEMPTS = 4;
/** scripts whose families get a native preview even with Latin glyphs */
const CJK_SCRIPTS = new Set(["Jpan", "Hira", "Kore", "Hans", "Hant"]);
/** not text fonts, and not classified as "Symbols" by Google - see the rules */
const NON_TEXT_FAMILIES = / Emoji$| Charted$| SignWriting$/;
/**
* Families which draw wrong in plain text, each with what's wrong. Checked
* in a browser's own text rendering, so it's the font as Google serves it.
*/
const BROKEN_FAMILIES = new Map([
// seen 2026-11-14 in Chromium: "⊂" draws as a mark on top of the letter
// before it ("ℕ ⊂ ℤ"), and "𝑓(" overlaps
["Libertinus Math", "relation signs draw over the preceding letter"],
// seen 2026-11-19 in Chromium and Firefox, 2026-11-24 in Safari: at 20 px a
// line starting with "rs" is about 900 px wide, where a sentence is 317
["Vibur", 'a line starting with "rs" is drawn three times too wide'],
// seen 2026-11-19 in Chromium: not a font to write with
["Libertinus Keyboard", "draws key caps for sequences of letters"],
]);
/**
* Families whose glyphs take long to draw: over 10 ms for one line of text
* on a canvas, where the median family takes 1.5 ms. Their outlines are huge
* (Rubik Pixels: up to 20,084 points in a glyph, Roboto: 105), or they are
* layered colour fonts. An editor draws every visible text anew at each zoom
* level, so one such text stalls it for everyone looking at the scene.
*
* Measured 2026-11-14 in Chromium, for every family of the catalog: the ms
* it took to draw "The quick brown fox jumps over the lazy dog" at a size
* not drawn before. Families added since aren't measured - do that for the
* ones a run adds whose design is of this kind.
*/
const SLOW_FAMILIES = new Map([
["Rubik Pixels", 4756],
["Rubik 80s Fade", 1162],
["Rubik Maps", 359],
["Rubik Glitch Pop", 187],
["Geist Pixel", 158],
["Rubik Doodle Triangles", 144],
["Rubik Microbe", 101],
["Rubik Dirt", 74],
["Bitcount Ink", 62],
["Rubik Lines", 59],
["Bitcount Prop Double Ink", 54],
["Bitcount Grid Double Ink", 53],
["Fredericka the Great", 50],
["Rubik Storm", 44],
["Bitcount Single Ink", 39],
["Bitcount Grid Single Ink", 38],
["Bitcount Prop Single Ink", 37],
["Rubik Distressed", 28],
["Splash", 28],
["Rubik Broken Fax", 27],
["Handjet", 24],
["Protest Revolution", 17.8],
["Rubik Doodle Shadow", 14.4],
["Rubik Spray Paint", 13.3],
["Rubik Maze", 12],
["Raleway Dots", 11.8],
["Love Ya Like A Sister", 10.7],
["Edu AU VIC WA NT Dots", 10.1],
]);
/**
* Why a font file looks slow to draw, if it does: huge glyph outlines, or
* colour layers. Of the 21 families measured over 20 ms this tells 20, along
* with 20 of the roughly 1,900 measured under - so it holds a new family
* back rather than leaving it out for good.
*
* Measure a family held back in a browser's console, with the latin `woff2`
* of its `css2` stylesheet:
*
* document.fonts.add(await new FontFace("probe", "url(<woff2>)").load());
* const canvas = document.createElement("canvas");
* const context = canvas.getContext("2d");
* context.scale(0.7, 0.7); // a size nothing was drawn at yet
* context.font = '20px "probe"';
* const start = performance.now();
* context.fillText("The quick brown fox jumps over the lazy dog", 4, 24);
* document.createElement("canvas").getContext("2d").drawImage(canvas, 0, 0);
* performance.now() - start;
*
* Over 10 ms: add it to `SLOW_FAMILIES`. Otherwise run with `--allow`.
*/
const getHeavyOutlinesReason = (sfnt) => {
const { view, tables } = readSfntTables(sfnt);
const colorTable = ["COLR", "SVG ", "sbix", "CBDT"].find((tag) =>
tables.has(tag),
);
if (colorTable) {
return `a colour font (${colorTable.trim()})`;
}
const maxp = tables.get("maxp");
const outlines = tables.get("glyf") ?? tables.get("CFF ");
if (!maxp || !outlines) {
return undefined;
}
const glyphCount = view.getUint16(maxp.offset + 4);
const bytesPerGlyph = Math.round(outlines.length / glyphCount);
// TrueType outlines only
const maxContours =
view.getUint32(maxp.offset) === 0x00010000
? view.getUint16(maxp.offset + 8)
: 0;
return bytesPerGlyph > 1000 || (bytesPerGlyph > 600 && maxContours > 150)
? `outlines of ${bytesPerGlyph} bytes a glyph, up to ${maxContours} contours`
: undefined;
};
/**
* Families whose text jumps up or down when the text editor opens and
* closes. The canvas places a line's baseline from the catalog's metrics
* (the file's `hhea` table). The editor is a textarea, which the browser
* lays out with the metrics it reads itself - and a font file has three
* sets of those:
*
* - `hhea`: what browsers read on macOS
* - OS/2 `usWinAscent` / `usWinDescent`: what Chrome and Firefox read on
* Windows
* - OS/2 `sTypoAscender` / `sTypoDescender`: what they read there when the
* font sets `USE_TYPO_METRICS`
*
* Google's rules ask for the three to agree. Where they don't, no catalog
* value is right on every platform, and a catalog entry never changes once
* shipped - so these are out.
*
* Measured 2026-11-16 for every family of the catalog, as the distance
* between the browser's baseline and the canvas' for a line at 40 px: in
* Chrome, Firefox and Safari on macOS and in Chrome and Firefox on Windows.
* Out are the ones over 3.2 px, which is what system Helvetica has always
* had. The rest of the catalog is within 2.9 px, and nine in ten families
* within pixel snapping (about 1 px). Linux and Android weren't measured.
*/
const OFF_BASELINE_FAMILIES = new Map([
["Katibeh", "16.4 px at 40 px on Windows"],
["Mirza", "14.1 px at 40 px on Windows"],
// their `hhea` descender is positive, which browsers read as a descent
["Coiny", "10 px at 40 px on every platform"],
["Revalia", "7.9 px at 40 px on every platform"],
["Tajawal", "7.3 px at 40 px on Windows"],
["Luckiest Guy", "5.9 px at 40 px on Windows"],
["Noto Traditional Nushu", "5.2 px at 40 px on every platform"],
["Maiden Orange", "4.9 px at 40 px on Windows"],
["Jomolhari", "3.8 px at 40 px on Windows"],
["Farsan", "3.6 px at 40 px on Windows"],
["Meera Inimai", "3.4 px at 40 px on Windows, and in Firefox on macOS"],
]);
/**
* Families whose metrics give a line height lines of text don't fit in.
* A text's line height is the one its font asks for, and it's saved with
* the text.
*/
const UNUSABLE_LINE_HEIGHT_FAMILIES = new Map([
// a descender of zero: its baseline is right, but lines overlap
["Allkin", 0.6],
]);
/**
* Families whose lines come out at different widths on the canvas and in
* the text editor, in a browser where no setting brings the two together.
* A line which fits on the canvas then wraps in the editor or the other way
* round, and letters shift as the editor opens and closes.
*
* Measured 2026-11-19 to 2026-11-24 for every family of the catalog, in px
* at 20 px, on 21 lines of Latin text and a line in each of the family's own
* scripts: in Chromium 145 and Firefox 146 on Linux, in Chrome 150, Firefox
* 157 and Safari 15.5 on macOS, and the families over the limit in Safari
* 27.2. Chrome was measured with its canvas set to kern and shape text the
* way its editor does (`fontKerning`, `textRendering`); without that it
* disagrees for hundreds more.
*
* Out are the ones off by over 5 px on a line, off at every punctuation mark
* or off after nearly every edit. Smaller gaps stay: Caveat is 2.2 px off on
* a line in Safari.
*
* A font file doesn't tell which family is of this kind, so nothing holds a
* new one back, and families added since aren't measured.
*/
const UNEVEN_WIDTH_FAMILIES = new Map([
// Chrome's canvas and editor disagree, whatever the canvas is set to
["Arvo", "2.3 px for every comma followed by a space, in Chrome"],
["Ruslan Display", "2.2 px on a line with punctuation, in Chrome"],
["Orelega One", "up to 2.3 px on a line, in Chrome"],
// the same on Japanese text, and the other way round in Safari
["Cherry Bomb One", "5.2 px on a Japanese sentence, in Chrome and Safari"],
// Safari's canvas draws their Latin letters unlike its editor, and unlike
// every other browser
["Qahiri", "58.7 px on a sentence, in Safari"],
["Aref Ruqaa", "41.2 px on a sentence, in Safari"],
["Aref Ruqaa Ink", "41.2 px on a sentence, in Safari"],
["Gulzar", "13.2 px on a sentence, in Safari"],
["Tiro Bangla", "8.8 px on a sentence, in Safari"],
["Tiro Devanagari Hindi", "8.8 px on a sentence, in Safari"],
["Tiro Devanagari Marathi", "8.8 px on a sentence, in Safari"],
["Tiro Devanagari Sanskrit", "8.8 px on a sentence, in Safari"],
["Tiro Gurmukhi", "8.8 px on a sentence, in Safari"],
["Tiro Kannada", "8.8 px on a sentence, in Safari"],
["Tiro Tamil", "8.8 px on a sentence, in Safari"],
["Tiro Telugu", "8.8 px on a sentence, in Safari"],
["Playpen Sans", "7.1 px on a sentence, in Safari"],
["Playpen Sans Arabic", "7.1 px on a sentence, in Safari"],
["Playpen Sans Deva", "7.1 px on a sentence, in Safari"],
["Playpen Sans Hebrew", "7.1 px on a sentence, in Safari"],
["Playpen Sans Thai", "7.1 px on a sentence, in Safari"],
// Safari's editor lays their Latin letters out unlike its canvas
["Barrio", "13.1 px on a sentence, in Safari"],
["Mansalva", "5.9 px on a sentence, in Safari"],
["Mynerve", "5.9 px on a sentence, in Safari"],
// Safari keeps two letters unkerned once a line break was removed between
// them. Any kerned font has that; in these nearly every pair is kerned
["Betania Patmos", "2.2 to 2.7 px wider per edit, in Safari"],
["Betania Patmos GDL", "2.2 to 2.7 px wider per edit, in Safari"],
["Betania Patmos In", "2.2 to 2.7 px wider per edit, in Safari"],
["Betania Patmos In GDL", "2.2 to 2.7 px wider per edit, in Safari"],
["Momo Signature", "1.7 px wider per edit, in Safari"],
]);
/** the gap system Helvetica has between editor and canvas, in em */
const MAX_BASELINE_GAP = 0.08;
const MIN_LINE_HEIGHT = 0.75;
/**
* Why a font file's vertical metrics would put its text off the baseline, or
* give it an unusable line height, if they do - see `OFF_BASELINE_FAMILIES`.
*
* Read from the file alone: the baseline a browser on Windows gives a line,
* against the one the catalog's `hhea` values give. Checked 2026-11-16
* against the measurements: of the catalog's 1,895 families it tells
* exactly the 11 measured over the limit.
*/
const getOffBaselineReason = (sfnt) => {
const { view, tables } = readSfntTables(sfnt);
const [unitsPerEm, ascender, descender, lineGap] = readMetrics(sfnt);
const lineHeight = (ascender - descender + lineGap) / unitsPerEm;
if (lineHeight < MIN_LINE_HEIGHT) {
return `a line height of ${lineHeight.toFixed(2)}`;
}
const os2 = tables.get("OS/2")?.offset;
if (os2 === undefined) {
return undefined;
}
// fsSelection bit 7
const useTypoMetrics = (view.getUint16(os2 + 62) & 0x80) !== 0;
const [ascent, descent] = useTypoMetrics
? [view.getInt16(os2 + 68), -view.getInt16(os2 + 70)]
: [view.getUint16(os2 + 74), view.getUint16(os2 + 76)];
// a line's baseline sits at half the line height plus half of (ascent -
// descent), so the two differ by half of what the metrics differ by
const gap = (ascent - descent - (ascender + descender)) / (2 * unitsPerEm);
return Math.abs(gap) > MAX_BASELINE_GAP
? `baseline off by ${Math.round(
Math.abs(gap) * 100,
)}% of the font size on Windows (hhea ${ascender} / ${descender}, ${
useTypoMetrics ? "typo" : "win"
} ${ascent} / ${useTypoMetrics ? -descent : descent})`
: undefined;
};
/** what a family is for - the font picker's icon for it (`FontKind`) */
const KINDS = new Set(["hand-drawn", "normal", "code", "heading"]);
/**
* The families the catalog holds, in its order: what a font picker lists and
* pages through. To offer another one, add it - after looking at it in
* Chrome, Firefox and Safari, on the canvas and in the text editor, at a few
* font sizes. A name can't be taken out again once a release has had it.
*
* Each with its kind, set by hand: Google's own categories aren't it (they
* file Bevan, a display face, as a serif).
*
* All are under the SIL Open Font License, with no reserved font name.
*/
const OFFERED_FAMILIES = [
// handwriting
["Kalam", "hand-drawn"],
["Patrick Hand", "hand-drawn"],
["Pacifico", "hand-drawn"],
// sans
["Open Sans", "normal"],
// serif
["Literata", "normal"],
// monospace
["Fira Mono", "code"],
// display
["Bevan", "heading"],
// Japanese
["Zen Maru Gothic", "normal"],
// Korean
["Gowun Dodum", "normal"],
];
const OFFERED_NAMES = OFFERED_FAMILIES.map(([name]) => name);
const KIND_BY_NAME = new Map(OFFERED_FAMILIES);
/** why a family can't be offered, if it can't */
const getExclusionReason = (family) => {
const name = family.family;
if (
family.classifications?.includes("Symbols") ||
NON_TEXT_FAMILIES.test(name)
) {
return "not a text font";
}
if (BROKEN_FAMILIES.has(name)) {
return `draws wrong: ${BROKEN_FAMILIES.get(name)}`;
}
if (SLOW_FAMILIES.has(name)) {
return `slow to draw: ${SLOW_FAMILIES.get(name)} ms a line`;
}
if (OFF_BASELINE_FAMILIES.has(name)) {
return `text jumps in the editor: ${OFF_BASELINE_FAMILIES.get(name)}`;
}
if (UNEVEN_WIDTH_FAMILIES.has(name)) {
return `canvas and text editor disagree on its width: ${UNEVEN_WIDTH_FAMILIES.get(
name,
)}`;
}
if (UNUSABLE_LINE_HEIGHT_FAMILIES.has(name)) {
return `a line height of ${UNUSABLE_LINE_HEIGHT_FAMILIES.get(name)}`;
}
return undefined;
};
/** families which were held back, got measured and may come in */
const allowed = new Set(
process.argv.flatMap((arg, i) =>
arg === "--allow" && process.argv[i + 1] ? [process.argv[i + 1]] : [],
),
);
const newOnly = process.argv.includes("--new-only");
const refresh = process.argv.includes("--refresh");
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const fetchWithRetry = async (url, init) => {
let lastError;
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
try {
const response = await fetch(url, {
...init,
signal: AbortSignal.timeout(30_000),
});
if (response.ok) {
return response;
}
lastError = new Error(`${response.status} for ${url}`);
// a 4xx other than "slow down" is an answer, not a blip
if (response.status < 500 && response.status !== 429) {
break;
}
} catch (error) {
lastError = error;
}
await sleep(500 * 2 ** attempt);
}
throw lastError;
};
/** the tables' byte ranges out of an sfnt (TrueType / OpenType) file */
const readSfntTables = (sfnt) => {
const view = new DataView(sfnt.buffer, sfnt.byteOffset, sfnt.byteLength);
const tables = new Map();
const count = view.getUint16(4);
for (let i = 0; i < count; i++) {
const record = 12 + i * 16;
const tag = String.fromCharCode(
view.getUint8(record),
view.getUint8(record + 1),
view.getUint8(record + 2),
view.getUint8(record + 3),
);
tables.set(tag, {
offset: view.getUint32(record + 8),
length: view.getUint32(record + 12),
});
}
return { view, tables };
};
const readMetrics = (sfnt) => {
const { view, tables } = readSfntTables(sfnt);
const head = tables.get("head")?.offset;
const hhea = tables.get("hhea")?.offset;
if (head === undefined || hhea === undefined) {
throw new Error("no head / hhea table");
}
const unitsPerEm = view.getUint16(head + 18);
const ascender = view.getInt16(hhea + 4);
const descender = view.getInt16(hhea + 6);
const lineGap = view.getInt16(hhea + 8);
if (!unitsPerEm || ascender - descender + lineGap <= 0) {
throw new Error(
`unusable metrics (${unitsPerEm}, ${ascender}, ${descender}, ${lineGap})`,
);
}
return [unitsPerEm, ascender, descender, lineGap];
};
// copied: what `decompress` returns doesn't outlive the next call to it
const fetchSfnt = async (url) =>
Uint8Array.from(
await wawoff2.decompress(
new Uint8Array(await (await fetchWithRetry(url)).arrayBuffer()),
),
);
/**
* The family's metrics, and for a family new to the catalog (`checkOutlines`)
* why it's held back, if it is: its font file looks slow to draw, or its
* vertical metrics would put its text off the baseline.
*/
const resolveFamily = async (family, checkOutlines) => {
const css = await (
await fetchWithRetry(
`${CSS_URL}?${new URLSearchParams({ family, display: "swap" })}`,
{ headers: { "User-Agent": BROWSER_USER_AGENT } },
)
).text();
const urls = [...css.matchAll(/url\((https:[^)]+\.woff2)\)/g)].map(
(match) => match[1],
);
if (!urls.length) {
throw new Error("no woff2 face in the stylesheet");
}
const sfnt = await fetchSfnt(urls[0]);
const metrics = readMetrics(sfnt);
if (!checkOutlines) {
return { metrics };
}
// the last subset is the family's main one (latin, where it has it) - a
// CJK family's first ones hold its most intricate glyphs, which says
// little about the design
const mainSfnt = urls.length > 1 ? await fetchSfnt(urls.at(-1)) : sfnt;
return {
metrics,
heldBackReason:
getOffBaselineReason(sfnt) ?? getHeavyOutlinesReason(mainSfnt),
};
};
const main = async () => {
const unkind = OFFERED_FAMILIES.find(([, kind]) => !KINDS.has(kind));
if (unkind) {
throw new Error(`"${unkind[0]}" has a kind unknown to us: ${unkind[1]}`);
}
/** @type {Array<[string, number, number, number, number, string, string?]>} */
const previous = JSON.parse(
await readFile(CATALOG_PATH, "utf8").catch(() => "[]"),
);
const previousByName = new Map(previous.map((entry) => [entry[0], entry]));
let metadataText = await (await fetchWithRetry(METADATA_URL)).text();
// served with an anti-JSON-hijacking prefix
if (metadataText.startsWith(")]}'")) {
metadataText = metadataText.slice(metadataText.indexOf("\n") + 1);
}
const familiesByName = new Map(
JSON.parse(metadataText).familyMetadataList.map((family) => [
family.family,
family,
]),
);
const skipped = [];
const excluded = [];
const heldBack = [];
const failed = [];
const changed = [];
const drifted = [];
const added = [];
const entries = new Map();
// the offered ones which Google lists, in our order
const queue = OFFERED_NAMES.flatMap(
(name) => familiesByName.get(name) ?? [],
).filter((family) => {
// an entry is forever, also when its family got reclassified since
const exclusionReason = getExclusionReason(family);
if (exclusionReason && !previousByName.has(family.family)) {
excluded.push(`${family.family} (${exclusionReason})`);
return false;
}
// a regular, upright 400 - see the rules above
if (!family.fonts["400"]) {
skipped.push(
`${family.family} (${Object.keys(family.fonts).join(", ")})`,
);
return false;
}
return true;
});
const unknown = OFFERED_NAMES.filter(
(name) => !familiesByName.has(name) && !previousByName.has(name),
);
let done = 0;
const work = async (family) => {
const name = family.family;
const before = previousByName.get(name);
const script =
CJK_SCRIPTS.has(family.primaryScript) ||
(family.primaryScript && !family.subsets.includes("latin"))
? family.primaryScript
: undefined;
const kept = before?.slice(1, 5);
let live;
if (!before || !newOnly) {
try {
const resolved = await resolveFamily(name, !before);
if (resolved.heldBackReason && !allowed.has(name)) {
heldBack.push(`${name} (${resolved.heldBackReason})`);
return;
}
live = resolved.metrics;
} catch (error) {
failed.push(`${name}: ${error.message}`);
}
}
// an existing entry keeps its metrics, unless told otherwise
const metrics = kept && !(refresh && live) ? kept : live;
if (metrics) {
const kind = KIND_BY_NAME.get(name);
entries.set(
name,
script ? [name, ...metrics, kind, script] : [name, ...metrics, kind],
);
if (!before) {
added.push(name);
} else if (live && kept.join() !== live.join()) {
(refresh ? changed : drifted).push(`${name}: ${kept} -> ${live}`);
}
}
if (++done % 100 === 0) {
console.info(`${done} / ${queue.length}`);
}
};
let next = 0;
await Promise.all(
Array.from({ length: CONCURRENCY }, async () => {
while (next < queue.length) {
await work(queue[next++]);
}
}),
);
// in our order; what left Google's list (or failed to resolve this time)
// keeps the entry it had
const retired = previous.filter((entry) => !entries.has(entry[0]));
const catalog = OFFERED_NAMES.map(
(name) => entries.get(name) ?? previousByName.get(name),
).filter(Boolean);
const names = new Set(catalog.map((entry) => entry[0]));
const lost = previous.filter((entry) => !names.has(entry[0]));
if (lost.length) {
throw new Error(
`The catalog is append-only, but would lose: ${lost
.map((entry) => entry[0])
.join(", ")}`,
);
}
// one entry per line, so that a regenerated catalog diffs per family -
// written the way prettier formats it, which CI checks
await writeFile(
CATALOG_PATH,
`[\n${catalog
.map(
(entry) =>
` [${entry.map((item) => JSON.stringify(item)).join(", ")}]`,
)
.join(",\n")}\n]\n`,
);
const report = (title, items) => {
if (items.length) {
console.info(`\n${title} (${items.length}):\n ${items.join("\n ")}`);
}
};
console.info(`\n${catalog.length} families written to ${CATALOG_PATH}`);
report("Added", added);
report("Metrics changed (--refresh)", changed);
report(
"Metrics differ from Google's current files, kept (--refresh takes them over)",
drifted,
);
report(
"No longer in Google's list, kept",
retired.map((entry) => entry[0]),
);
report("Offered, but can't be: see the rules", excluded);
report("Offered, but not in Google's list", unknown);
report(
"Held back: looks slow to draw, or off the baseline. Measure it (see getHeavyOutlinesReason, OFF_BASELINE_FAMILIES), then add it to the list it belongs to or run with --allow",
heldBack,
);
report("Offered, but has no regular 400 face", skipped);
report("Failed to resolve", failed);
if (
failed.length ||
excluded.length ||
skipped.length ||
unknown.length ||
heldBack.length
) {
process.exitCode = 1;
}
};
main().catch((error) => {
console.error(error);
process.exit(1);
});
+13 -1
View File
@@ -107,7 +107,19 @@ function buildProd(config) {
const createESMRawBuild = async () => {
const chunksConfig = {
entryPoints: ["index.tsx", "**/*.chunk.ts"],
entryPoints: [
"index.tsx",
"**/*.chunk.ts",
// its own entry (`@excalidraw/excalidraw/fonts/google`), so that the
// catalog stays out of the main bundle and loads without the editor
// (entries are emitted flat, by name)
{ in: "fonts/google/index.ts", out: "fonts-google" },
// The catalog, which the entry above imports on first use. An entry
// too, so that it's emitted next to it: as a chunk it would land in
// `fonts/google/`, and `fonts/` is the folder of font files which
// hosts copy over to serve them themselves
{ in: "fonts/google/catalog.json", out: "fonts-google-catalog" },
],
entryNames: "[name]",
};
+10 -3
View File
@@ -64,6 +64,8 @@ Object.defineProperty(window, "matchMedia", {
Object.defineProperty(window, "FontFace", {
enumerable: true,
// a test of an environment without one takes it away (`vi.stubGlobal`)
configurable: true,
value: class {
private family: string;
private source: string;
@@ -87,10 +89,15 @@ Object.defineProperty(window, "FontFace", {
Object.defineProperty(document, "fonts", {
value: {
load: vi.fn().mockResolvedValue([]),
check: vi.fn().mockResolvedValue(true),
has: vi.fn().mockResolvedValue(true),
// an implementation (unlike `mockResolvedValue`) survives a test's
// `mockRestore()` - `load` always returns a promise in the browser
load: vi.fn(() => Promise.resolve([])),
// `check` and `has` are synchronous booleans in the browser - a promise
// here would be always-truthy and silently skip loading branches
check: vi.fn(() => true),
has: vi.fn(() => true),
add: vi.fn(),
delete: vi.fn(),
},
});