mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-12-05 18:55:28 +03:00
* 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>
722 lines
27 KiB
JavaScript
722 lines
27 KiB
JavaScript
/**
|
||
* 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);
|
||
});
|