@open-artifact/ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +48 -4
  5. package/src/button.d.ts +30 -0
  6. package/src/button.js +28 -0
  7. package/src/cn.d.ts +3 -0
  8. package/src/cn.js +5 -0
  9. package/src/color-picker.d.ts +98 -0
  10. package/src/color-picker.js +370 -0
  11. package/src/color.d.ts +144 -0
  12. package/src/color.js +528 -0
  13. package/src/data/google-fonts.json +1775 -0
  14. package/src/effect-editors.d.ts +48 -0
  15. package/src/effect-editors.js +230 -0
  16. package/src/effects.d.ts +118 -0
  17. package/src/effects.js +425 -0
  18. package/src/fields.d.ts +105 -0
  19. package/src/fields.js +77 -0
  20. package/src/focusables.d.ts +26 -0
  21. package/src/focusables.js +42 -0
  22. package/src/font-picker.d.ts +62 -0
  23. package/src/font-picker.js +238 -0
  24. package/src/fonts.d.ts +121 -0
  25. package/src/fonts.js +273 -0
  26. package/src/history-diff.d.ts +64 -0
  27. package/src/history-diff.js +151 -0
  28. package/src/history.d.ts +95 -0
  29. package/src/history.js +160 -0
  30. package/src/index.d.ts +25 -0
  31. package/src/index.js +25 -0
  32. package/src/keys.d.ts +60 -0
  33. package/src/keys.js +78 -0
  34. package/src/layout.d.ts +55 -0
  35. package/src/layout.js +64 -0
  36. package/src/menu.d.ts +50 -0
  37. package/src/menu.js +36 -0
  38. package/src/numbers.d.ts +24 -0
  39. package/src/numbers.js +114 -0
  40. package/src/overlays.d.ts +38 -0
  41. package/src/overlays.js +26 -0
  42. package/src/scroll.d.ts +24 -0
  43. package/src/scroll.js +111 -0
  44. package/src/scrub-number-field.d.ts +56 -0
  45. package/src/scrub-number-field.js +190 -0
  46. package/src/styles.css +122 -0
  47. package/src/tooltip.d.ts +18 -0
  48. package/src/tooltip.js +10 -0
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Which descendants a keyboard user can Tab to, and whether a box scrolls.
3
+ * {@link ScrollBody} uses both to give a scrolling region with no tab stop
4
+ * of its own one, so it can be scrolled from the keyboard.
5
+ */
6
+ /** Elements that may be tab stops. */
7
+ export const TABBABLE_CANDIDATE_SELECTOR = [
8
+ 'a[href]',
9
+ 'button',
10
+ 'iframe',
11
+ 'input',
12
+ 'select',
13
+ 'textarea',
14
+ 'summary',
15
+ 'audio[controls]',
16
+ 'video[controls]',
17
+ "[contenteditable]:not([contenteditable='false'])",
18
+ '[tabindex]',
19
+ ].join(', ');
20
+ /** Elements that are tab stops without a `tabindex` attribute even when `tabIndex` reads -1. */
21
+ const IMPLICIT_TAB_STOP_SELECTOR = "audio[controls], video[controls], [contenteditable]:not([contenteditable='false'])";
22
+ /** True when `element` is a tab stop: enabled, shown, not hidden from assistive technology. */
23
+ export function isTabbable(element) {
24
+ const stop = element.tabIndex >= 0 || (!element.hasAttribute('tabindex') && element.matches(IMPLICIT_TAB_STOP_SELECTOR));
25
+ if (!stop || element.getAttribute('aria-hidden') === 'true' || element.matches(':disabled'))
26
+ return false;
27
+ return typeof element.checkVisibility !== 'function' || element.checkVisibility({ visibilityProperty: true });
28
+ }
29
+ /** The tab stops inside `root`, in document order. */
30
+ export function tabbableElements(root) {
31
+ return Array.from(root.querySelectorAll(TABBABLE_CANDIDATE_SELECTOR)).filter(isTabbable);
32
+ }
33
+ /**
34
+ * True when the content overflows an axis that scrolls (`auto` or
35
+ * `scroll`; `visible`, `hidden` and `clip` do not). A pixel of rounding is
36
+ * ignored.
37
+ */
38
+ export function scrollsOverflow(metrics) {
39
+ const scrolls = (overflow) => !/visible|hidden|clip/.test(overflow);
40
+ return ((metrics.scrollWidth > metrics.clientWidth + 1 && scrolls(metrics.overflowX)) ||
41
+ (metrics.scrollHeight > metrics.clientHeight + 1 && scrolls(metrics.overflowY)));
42
+ }
@@ -0,0 +1,62 @@
1
+ import { type ReactElement } from 'react';
2
+ import { type FontCategory, type GoogleFont } from './fonts.ts';
3
+ /** A font the design system provides. */
4
+ export interface DesignSystemFont {
5
+ family: string;
6
+ /** Token or role name shown beside it (`heading`, `--font-body`). */
7
+ label?: string;
8
+ /** Stylesheet that loads it (an `@font-face` file or a Google Fonts URL). */
9
+ stylesheet?: string | null;
10
+ category?: FontCategory;
11
+ }
12
+ /** Where a picked font comes from. */
13
+ export type FontSource = 'design-system' | 'installed' | 'google';
14
+ /** What {@link FontPicker} reports. */
15
+ export interface FontPick {
16
+ family: string;
17
+ source: FontSource;
18
+ /**
19
+ * CSS to link so the family renders: the Google Fonts URL for the chosen
20
+ * weights, the design system's stylesheet, or null (installed fonts).
21
+ */
22
+ stylesheet: string | null;
23
+ /** A `font-family` value with a generic fallback. */
24
+ css: string;
25
+ category?: FontCategory;
26
+ /** The catalog entry of a Google font (weights, italics, axes). */
27
+ google?: GoogleFont;
28
+ }
29
+ /** Props of {@link FontPicker}. */
30
+ export interface FontPickerProps {
31
+ /** The current family, or null. */
32
+ value: string | null;
33
+ onChange: (pick: FontPick) => void;
34
+ 'aria-label': string;
35
+ designSystemFonts?: readonly DesignSystemFont[];
36
+ /** Families that render here. Default: common system fonts that are installed, plus fonts the page loaded. */
37
+ installedFonts?: readonly string[];
38
+ /** Offer the Google Fonts catalog (default true). */
39
+ googleFonts?: boolean;
40
+ /** Weights the returned Google stylesheet asks for (default 400 and 700, those the family has). */
41
+ weights?: readonly number[];
42
+ /** Also request italics. */
43
+ italic?: boolean;
44
+ /** Request the whole weight range of variable families. */
45
+ variable?: boolean;
46
+ /** Trigger text while no font is set. */
47
+ placeholder?: string;
48
+ /** Several selected things differ. */
49
+ mixed?: boolean;
50
+ disabled?: boolean;
51
+ /** Your own trigger element instead of the field. */
52
+ trigger?: ReactElement<Record<string, unknown>>;
53
+ open?: boolean;
54
+ onOpenChange?: (open: boolean) => void;
55
+ className?: string;
56
+ }
57
+ /**
58
+ * A font family picker. Type to search the design system's fonts, the
59
+ * installed ones and Google Fonts; arrow keys move, Enter picks, Escape
60
+ * closes. Category chips narrow the list.
61
+ */
62
+ export declare function FontPicker({ value, onChange, designSystemFonts, installedFonts, googleFonts, weights, italic, variable, placeholder, mixed, disabled, trigger, open: openProp, onOpenChange, className, ...aria }: FontPickerProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,238 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * {@link FontPicker}: one searchable list of the design system's fonts, the
4
+ * fonts that render on this computer, and the Google Fonts catalog (loaded
5
+ * on first open, grouped by category). Each visible Google row loads just
6
+ * the glyphs of its own name from fonts.googleapis.com, so it shows in its
7
+ * face without downloading whole families.
8
+ */
9
+ import { Popover as BasePopover } from '@base-ui/react/popover';
10
+ import { Check, ChevronDown, Search } from 'lucide-react';
11
+ import { useEffect, useId, useMemo, useRef, useState } from 'react';
12
+ import { cn } from "./cn.js";
13
+ import { FONT_CATEGORIES, detectInstalledFonts, ensureFontPreview, fontFamilyCss, fontMatchScore, googleFontStylesheetUrl, loadGoogleFontCatalog, normalizeFontName, searchFonts, } from "./fonts.js";
14
+ import { preventRepeatedActivation } from "./keys.js";
15
+ import { POPUP_CLASS } from "./menu.js";
16
+ const ROW_HEIGHT = 30;
17
+ const LIST_HEIGHT = 320;
18
+ const OVERSCAN = 6;
19
+ /** Wait for scrolling to settle before loading previews. */
20
+ const PREVIEW_DELAY_MS = 120;
21
+ const loadedStylesheets = new Set();
22
+ function ensureStylesheet(href) {
23
+ if (typeof document === 'undefined' || loadedStylesheets.has(href))
24
+ return;
25
+ loadedStylesheets.add(href);
26
+ const link = document.createElement('link');
27
+ link.rel = 'stylesheet';
28
+ link.href = href;
29
+ document.head.appendChild(link);
30
+ }
31
+ /** Builds the rows for a query and category. */
32
+ function buildRows(query, category, designSystem, installed, catalog) {
33
+ const q = normalizeFontName(query);
34
+ const rows = [];
35
+ const seen = new Set();
36
+ const rank = (items, name) => items
37
+ .map((item) => ({ item, score: Math.max(...name(item).map((n) => fontMatchScore(n, q))) }))
38
+ .filter((entry) => entry.score > 0)
39
+ .sort((a, b) => b.score - a.score)
40
+ .map((entry) => entry.item);
41
+ const ds = rank(designSystem.filter((font) => !category || font.category === category), (font) => [font.family, font.label ?? '']);
42
+ if (ds.length) {
43
+ rows.push({ kind: 'header', key: 'h:ds', label: 'Design system' });
44
+ for (const font of ds) {
45
+ seen.add(font.family.toLowerCase());
46
+ rows.push({ kind: 'font', key: `ds:${font.label ?? ''}:${font.family}`, family: font.family, source: 'design-system', detail: font.label, category: font.category, stylesheet: font.stylesheet });
47
+ }
48
+ }
49
+ if (!category) {
50
+ const local = rank(installed, (family) => [family]).filter((family) => !seen.has(family.toLowerCase()));
51
+ if (local.length) {
52
+ rows.push({ kind: 'header', key: 'h:installed', label: 'On this computer' });
53
+ for (const family of local) {
54
+ seen.add(family.toLowerCase());
55
+ rows.push({ kind: 'font', key: `local:${family}`, family, source: 'installed' });
56
+ }
57
+ }
58
+ }
59
+ if (catalog) {
60
+ const fontRow = (font) => ({ kind: 'font', key: `g:${font.family}`, family: font.family, source: 'google', category: font.category, google: font });
61
+ if (q) {
62
+ const found = searchFonts(catalog, q, { category }).filter((font) => !seen.has(font.family.toLowerCase()));
63
+ if (found.length) {
64
+ rows.push({ kind: 'header', key: 'h:google', label: 'Google Fonts' });
65
+ rows.push(...found.map(fontRow));
66
+ }
67
+ }
68
+ else {
69
+ for (const group of FONT_CATEGORIES) {
70
+ if (category && group.value !== category)
71
+ continue;
72
+ const fonts = catalog.filter((font) => font.category === group.value && !seen.has(font.family.toLowerCase()));
73
+ if (!fonts.length)
74
+ continue;
75
+ rows.push({ kind: 'header', key: `h:${group.value}`, label: `Google Fonts · ${group.label}` });
76
+ rows.push(...fonts.map(fontRow));
77
+ }
78
+ }
79
+ }
80
+ return rows;
81
+ }
82
+ /**
83
+ * A font family picker. Type to search the design system's fonts, the
84
+ * installed ones and Google Fonts; arrow keys move, Enter picks, Escape
85
+ * closes. Category chips narrow the list.
86
+ */
87
+ export function FontPicker({ value, onChange, designSystemFonts = [], installedFonts, googleFonts = true, weights, italic, variable, placeholder = 'Font', mixed = false, disabled, trigger, open: openProp, onOpenChange, className, ...aria }) {
88
+ const [openState, setOpenState] = useState(false);
89
+ const open = openProp ?? openState;
90
+ const setOpen = (next) => {
91
+ setOpenState(next);
92
+ onOpenChange?.(next);
93
+ };
94
+ const label = aria['aria-label'];
95
+ const text = mixed ? 'Mixed' : (value ?? placeholder);
96
+ const element = trigger ?? (_jsxs("button", { type: "button", "aria-label": `${label}: ${text}`, className: cn('flex h-7 w-full min-w-0 items-center gap-1 rounded-control border border-line bg-surface-2 pl-2 pr-1.5 text-left text-[13px] text-fg outline-none', 'focus-visible:border-accent data-[popup-open]:border-accent disabled:opacity-45', className), children: [_jsx("span", { className: cn('min-w-0 flex-1 truncate', (mixed || !value) && 'text-fg-subtle'), style: value && !mixed ? { fontFamily: fontFamilyCss(value) } : undefined, children: text }), _jsx(ChevronDown, { className: "size-3.5 shrink-0 text-fg-subtle" })] }));
97
+ return (_jsxs(BasePopover.Root, { open: open, onOpenChange: (next) => setOpen(next), children: [_jsx(BasePopover.Trigger, { render: element, disabled: disabled, onKeyDown: preventRepeatedActivation }), _jsx(BasePopover.Portal, { children: _jsx(BasePopover.Positioner, { side: "bottom", align: "start", sideOffset: 6, collisionPadding: 8, className: "z-[1000]", children: _jsx(BasePopover.Popup, { "aria-label": `${label} fonts`, className: cn(POPUP_CLASS, 'w-72 p-0'), children: open ? (_jsx(FontList, { value: mixed ? null : value, designSystemFonts: designSystemFonts, installedFonts: installedFonts, googleFonts: googleFonts, onPick: (row) => {
98
+ const google = row.google;
99
+ const stylesheet = row.source === 'google' ? googleFontStylesheetUrl(row.family, { weights, italic, variable }, google) : row.source === 'design-system' ? (row.stylesheet ?? null) : null;
100
+ onChange({ family: row.family, source: row.source, stylesheet, css: fontFamilyCss(row.family, row.category), category: row.category, google });
101
+ setOpen(false);
102
+ } })) : null }) }) })] }));
103
+ }
104
+ /** The popover body: search, category chips, the virtualized list. */
105
+ function FontList({ value, designSystemFonts, installedFonts, googleFonts, onPick, }) {
106
+ const id = useId();
107
+ const [query, setQuery] = useState('');
108
+ const [category, setCategory] = useState(null);
109
+ const [catalog, setCatalog] = useState(null);
110
+ const [catalogError, setCatalogError] = useState(false);
111
+ const installed = useMemo(() => installedFonts ?? detectInstalledFonts(), [installedFonts]);
112
+ const listRef = useRef(null);
113
+ const inputRef = useRef(null);
114
+ const [scrollTop, setScrollTop] = useState(0);
115
+ useEffect(() => {
116
+ if (!googleFonts)
117
+ return;
118
+ let live = true;
119
+ loadGoogleFontCatalog()
120
+ .then((loaded) => live && setCatalog(loaded))
121
+ .catch(() => live && setCatalogError(true));
122
+ return () => {
123
+ live = false;
124
+ };
125
+ }, [googleFonts]);
126
+ useEffect(() => inputRef.current?.focus(), []);
127
+ const rows = useMemo(() => buildRows(query, category, designSystemFonts, installed, catalog), [query, category, designSystemFonts, installed, catalog]);
128
+ const valueKey = value ? normalizeFontName(value) : null;
129
+ const selectedIndex = valueKey ? rows.findIndex((row) => row.kind === 'font' && normalizeFontName(row.family) === valueKey) : -1;
130
+ const firstFont = rows.findIndex((row) => row.kind === 'font');
131
+ const [active, setActive] = useState(-1);
132
+ // Start on the current font (once it is in the list), else the first match.
133
+ const started = useRef(false);
134
+ useEffect(() => {
135
+ if (!started.current && selectedIndex >= 0) {
136
+ started.current = true;
137
+ setActive(selectedIndex);
138
+ scrollToRow(selectedIndex, 'center');
139
+ return;
140
+ }
141
+ if (started.current || query)
142
+ setActive(firstFont);
143
+ else
144
+ setActive(selectedIndex >= 0 ? selectedIndex : firstFont);
145
+ // eslint-disable-next-line react-hooks/exhaustive-deps
146
+ }, [rows]);
147
+ const scrollToRow = (index, mode = 'nearest') => {
148
+ const list = listRef.current;
149
+ if (!list || index < 0)
150
+ return;
151
+ const top = index * ROW_HEIGHT;
152
+ if (mode === 'center')
153
+ list.scrollTop = Math.max(0, top - LIST_HEIGHT / 2 + ROW_HEIGHT / 2);
154
+ else if (top < list.scrollTop)
155
+ list.scrollTop = top;
156
+ else if (top + ROW_HEIGHT > list.scrollTop + LIST_HEIGHT)
157
+ list.scrollTop = top + ROW_HEIGHT - LIST_HEIGHT;
158
+ setScrollTop(list.scrollTop);
159
+ };
160
+ const moveActive = (by) => {
161
+ if (!rows.length)
162
+ return;
163
+ let next = active;
164
+ const direction = Math.sign(by);
165
+ let remaining = Math.abs(by);
166
+ while (remaining > 0) {
167
+ let probe = next + direction;
168
+ while (probe >= 0 && probe < rows.length && rows[probe].kind !== 'font')
169
+ probe += direction;
170
+ if (probe < 0 || probe >= rows.length)
171
+ break;
172
+ next = probe;
173
+ remaining--;
174
+ }
175
+ if (next !== active && next >= 0) {
176
+ setActive(next);
177
+ scrollToRow(next);
178
+ }
179
+ };
180
+ const onKeyDown = (event) => {
181
+ const moves = { ArrowDown: 1, ArrowUp: -1, PageDown: 8, PageUp: -8 };
182
+ const by = moves[event.key];
183
+ if (by !== undefined) {
184
+ event.preventDefault();
185
+ moveActive(by);
186
+ return;
187
+ }
188
+ if (event.key === 'Enter') {
189
+ const row = rows[active];
190
+ if (row?.kind === 'font') {
191
+ event.preventDefault();
192
+ onPick(row);
193
+ }
194
+ }
195
+ };
196
+ // Rows on screen (plus a margin).
197
+ const first = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - OVERSCAN);
198
+ const last = Math.min(rows.length, Math.ceil((scrollTop + LIST_HEIGHT) / ROW_HEIGHT) + OVERSCAN);
199
+ const visible = rows.slice(first, last);
200
+ // Load previews of the Google rows actually on screen once scrolling settles.
201
+ useEffect(() => {
202
+ const timer = setTimeout(() => {
203
+ const top = Math.floor(scrollTop / ROW_HEIGHT);
204
+ const bottom = Math.ceil((scrollTop + LIST_HEIGHT) / ROW_HEIGHT);
205
+ for (const row of rows.slice(top, bottom)) {
206
+ if (row.kind !== 'font')
207
+ continue;
208
+ if (row.source === 'google')
209
+ ensureFontPreview(row.family, row.google);
210
+ else if (row.source === 'design-system' && row.stylesheet)
211
+ ensureStylesheet(row.stylesheet);
212
+ }
213
+ }, PREVIEW_DELAY_MS);
214
+ return () => clearTimeout(timer);
215
+ }, [rows, scrollTop]);
216
+ const listId = `${id}-list`;
217
+ const optionId = (index) => `${id}-opt-${index}`;
218
+ const activeRow = rows[active];
219
+ return (_jsxs("div", { className: "flex flex-col", children: [_jsxs("div", { className: "flex items-center gap-1.5 border-b border-line px-2.5", children: [_jsx(Search, { className: "size-3.5 shrink-0 text-fg-subtle", "aria-hidden": "true" }), _jsx("input", { ref: inputRef, role: "combobox", "aria-expanded": "true", "aria-controls": listId, "aria-autocomplete": "list", "aria-activedescendant": activeRow?.kind === 'font' ? optionId(active) : undefined, "aria-label": "Search fonts", placeholder: "Search fonts", spellCheck: false, autoComplete: "off", value: query, onChange: (event) => {
220
+ setQuery(event.target.value);
221
+ if (listRef.current)
222
+ listRef.current.scrollTop = 0;
223
+ setScrollTop(0);
224
+ }, onKeyDown: onKeyDown, className: "h-9 min-w-0 flex-1 bg-transparent text-[13px] text-fg outline-none placeholder:text-fg-subtle" })] }), googleFonts ? (_jsx("div", { role: "group", "aria-label": "Category", className: "flex flex-wrap gap-1 border-b border-line px-2 py-1.5", children: [{ value: null, label: 'All' }, ...FONT_CATEGORIES].map((chip) => (_jsx("button", { type: "button", "aria-pressed": category === chip.value, onClick: () => {
225
+ setCategory(chip.value);
226
+ if (listRef.current)
227
+ listRef.current.scrollTop = 0;
228
+ setScrollTop(0);
229
+ }, className: cn('h-6 rounded-full px-2 text-[11px] text-fg-muted outline-none hover:bg-hover hover:text-fg focus-visible:outline-2 focus-visible:outline-accent', category === chip.value && 'bg-accent-soft text-accent hover:bg-accent-soft hover:text-accent'), children: chip.label }, chip.value ?? 'all'))) })) : null, _jsxs("div", { ref: listRef, id: listId, role: "listbox", "aria-label": "Fonts", tabIndex: -1, className: "relative overflow-y-auto p-1", style: { height: LIST_HEIGHT }, onScroll: (event) => setScrollTop(event.currentTarget.scrollTop), children: [_jsx("div", { style: { height: rows.length * ROW_HEIGHT, position: 'relative' }, children: visible.map((row, offset) => {
230
+ const index = first + offset;
231
+ const style = { position: 'absolute', top: index * ROW_HEIGHT, left: 0, right: 0, height: ROW_HEIGHT };
232
+ if (row.kind === 'header') {
233
+ return (_jsx("div", { role: "presentation", style: style, className: "flex items-end px-2 pb-1 text-[11px] font-medium text-fg-subtle", children: row.label }, row.key));
234
+ }
235
+ const selected = index === selectedIndex;
236
+ return (_jsxs("div", { id: optionId(index), role: "option", "aria-selected": index === active, "aria-checked": selected, style: style, onPointerMove: () => index !== active && setActive(index), onClick: () => onPick(row), className: cn('flex cursor-default select-none items-center gap-2 rounded-md px-2 text-[14px]', index === active && 'bg-hover'), children: [_jsx("span", { className: "flex size-4 shrink-0 items-center justify-center", children: selected ? _jsx(Check, { className: "size-3.5 text-accent" }) : null }), _jsx("span", { className: "min-w-0 flex-1 truncate", style: { fontFamily: fontFamilyCss(row.family, row.category) }, children: row.family }), row.detail ? _jsx("span", { className: "shrink-0 truncate text-[11px] text-fg-subtle", children: row.detail }) : null, row.google && row.google.axes.length ? (_jsx("span", { className: "shrink-0 text-[10px] text-fg-subtle", title: row.google.axes.map((axis) => `${axis.tag} ${axis.min}–${axis.max}`).join(', '), children: "Variable" })) : null] }, row.key));
237
+ }) }), !rows.length ? (_jsx("div", { className: "absolute inset-x-0 top-8 px-3 text-center text-xs text-fg-subtle", children: googleFonts && !catalog && !catalogError ? 'Loading fonts…' : 'No fonts match' })) : null, googleFonts && !catalog && !catalogError && rows.length ? (_jsx("div", { className: "sticky bottom-0 bg-surface px-2 py-1 text-[11px] text-fg-subtle", children: "Loading Google Fonts\u2026" })) : null] })] }));
238
+ }
package/src/fonts.d.ts ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Fonts for the font picker: the Google Fonts catalog (loaded on demand from
3
+ * `data/google-fonts.json`), search, stylesheet URLs, and which families
4
+ * render on this computer.
5
+ *
6
+ * Everything here except {@link isFontAvailable}, {@link detectInstalledFonts}
7
+ * and {@link ensureFontPreview} runs without a DOM.
8
+ */
9
+ /** Google Fonts' categories, as CSS-ish names. */
10
+ export type FontCategory = 'sans-serif' | 'serif' | 'display' | 'handwriting' | 'monospace';
11
+ /** Categories in the order the picker groups them. */
12
+ export declare const FONT_CATEGORIES: readonly {
13
+ value: FontCategory;
14
+ label: string;
15
+ }[];
16
+ /** A variable font axis and its range. */
17
+ export interface FontAxis {
18
+ tag: string;
19
+ min: number;
20
+ max: number;
21
+ }
22
+ /** One family of the Google Fonts catalog. */
23
+ export interface GoogleFont {
24
+ family: string;
25
+ category: FontCategory;
26
+ /** Upright weights (100…1000). */
27
+ weights: number[];
28
+ /** Italic weights; empty when the family has no italics. */
29
+ italics: number[];
30
+ /** Variable axes (`wght`, `wdth`, `opsz`…); empty for static families. */
31
+ axes: FontAxis[];
32
+ /** Popularity rank, 0 the most used. */
33
+ rank: number;
34
+ }
35
+ /** The catalog file as stored: rows of `[family, category, weights, italics, axes?]`. */
36
+ export interface GoogleFontCatalogFile {
37
+ source: string;
38
+ categories: string[];
39
+ families: (string | number)[][];
40
+ }
41
+ /** Expands the stored catalog into {@link GoogleFont} records, in popularity order. */
42
+ export declare function decodeFontCatalog(file: GoogleFontCatalogFile): GoogleFont[];
43
+ /**
44
+ * The Google Fonts catalog, loaded once on first use (the JSON is a separate
45
+ * chunk, about 64 KB, 15 KB gzipped).
46
+ */
47
+ export declare function loadGoogleFontCatalog(): Promise<GoogleFont[]>;
48
+ /** Lowercase, accents and punctuation dropped, spaces collapsed. */
49
+ export declare function normalizeFontName(name: string): string;
50
+ /**
51
+ * How well `family` matches `query` (already normalized); higher is better,
52
+ * 0 for no match. Exact > prefix > word prefix > substring > initials
53
+ * ("ibm" for "IBM Plex Sans", "pf" for "Playfair").
54
+ */
55
+ export declare function fontMatchScore(family: string, query: string): number;
56
+ /** Options of {@link searchFonts}. */
57
+ export interface FontSearchOptions {
58
+ category?: FontCategory | null;
59
+ /** At most this many results. */
60
+ limit?: number;
61
+ }
62
+ /**
63
+ * Catalog families matching `query`, best match first, ties by popularity.
64
+ * An empty query lists the catalog in popularity order.
65
+ */
66
+ export declare function searchFonts(catalog: readonly GoogleFont[], query: string, options?: FontSearchOptions): GoogleFont[];
67
+ /** The catalog entry for `family` (case and spacing ignored). */
68
+ export declare function findGoogleFont(catalog: readonly GoogleFont[], family: string): GoogleFont | undefined;
69
+ /** The catalog entry of `family`, loading the catalog if needed. */
70
+ export declare function lookupGoogleFont(family: string): Promise<GoogleFont | undefined>;
71
+ /** Options of {@link googleFontStylesheetUrl}. */
72
+ export interface FontStylesheetOptions {
73
+ /** Weights wanted; those the family lacks are dropped (default: 400 and 700, or what it has). */
74
+ weights?: readonly number[];
75
+ /** Also load italics. */
76
+ italic?: boolean;
77
+ /**
78
+ * Request the whole `wght` range of a variable family instead of single
79
+ * weights (one file serves every weight).
80
+ */
81
+ variable?: boolean;
82
+ /** Only the glyphs of this text (for previews). */
83
+ text?: string;
84
+ /** `font-display` (default `swap`). */
85
+ display?: 'auto' | 'block' | 'swap' | 'fallback' | 'optional';
86
+ }
87
+ /**
88
+ * The Google Fonts CSS URL for `family`. With the catalog entry, the
89
+ * request names only weights and italics the family has (the API rejects
90
+ * others); without one it asks for the weights given (default 400).
91
+ */
92
+ export declare function googleFontStylesheetUrl(family: string, options?: FontStylesheetOptions, font?: GoogleFont): string;
93
+ /** The CSS `font-family` value for a family with a generic fallback. */
94
+ export declare function fontFamilyCss(family: string, category?: FontCategory): string;
95
+ /** CSS generic families and keywords, which always render. */
96
+ export declare const GENERIC_FAMILIES: ReadonlySet<string>;
97
+ /**
98
+ * Families commonly installed on macOS, Windows, Linux, iOS and Android.
99
+ * {@link detectInstalledFonts} checks which of them render here.
100
+ */
101
+ export declare const COMMON_SYSTEM_FONTS: readonly string[];
102
+ /**
103
+ * True when `family` measures differently from both the monospace and the
104
+ * serif fallback (a missing family falls back to them and measures the
105
+ * same). `measure(font)` returns the width of a sample in a CSS `font`
106
+ * shorthand.
107
+ */
108
+ export declare function fontRenders(family: string, measure: (font: string) => number): boolean;
109
+ /** {@link fontRenders} measured on a canvas, cached per family. False outside a browser. */
110
+ export declare function isFontAvailable(family: string): boolean;
111
+ /**
112
+ * Families that render here: those of `candidates` (default
113
+ * {@link COMMON_SYSTEM_FONTS}) that are installed, plus every family the
114
+ * page has loaded with `@font-face` (preview faces excluded). Sorted by name.
115
+ */
116
+ export declare function detectInstalledFonts(candidates?: readonly string[]): string[];
117
+ /**
118
+ * Loads just the glyphs of `family`'s own name (a few KB) so a picker row
119
+ * can show the name in its face. Adds one `<link>` per family, once.
120
+ */
121
+ export declare function ensureFontPreview(family: string, font?: GoogleFont): void;