Form primitive
Vue Font Picker Component
<DomFontPicker>Searchable Google Fonts picker that previews only visible families and keeps font network loading inside the mounted control.
Playground
Search and preview Google Fonts
Font picker playground
Open to browse around the selected font, then use the separate search field. Only the mounted selected label and visible rows request previews.
Properties
Control props
Selected font family or application-defined font value.
Lightweight family metadata. Font files are never bundled in this array. Set source: system for installed fonts, whose value is a CSS stack that is never fetched.
Optionally restrict results to one Google Fonts category.
Number of metadata rows appended near the end. Preview fonts load only near the viewport.
Optional shared sample. Empty uses each family name as its own preview.
Google Fonts CSS v2 endpoint or an application-controlled compatible proxy.
Preferred side before collision handling.
viewport keeps the list inside the browser; anchor keeps it attached while scrolling.
Field props
Optional ID override. By default parent forms derive the input ID from the field path using underscores.
Local field name. Parent forms derive the full field path and native HTML name from the form hierarchy.
Visible field label.
Optional helper copy below the field.
Placeholder shown when the control is empty.
Validation errors for this field.
Validators
No validators yet.
Validators attached to this field. Use functions in Vue code, or serializable records such as { name: "minLength", props: { min: 2 } } in generated schemas.
Render default field chrome, or hide chrome while keeping form state wiring.
npm install @getdom/studio<script setup>
import '@getdom/studio/style.css';
import { reactive } from 'vue';
import { DomFontPicker } from '@getdom/studio';
const data = reactive({
"modelValue": "Lato",
"id": "",
"name": "",
"label": "Font family",
"description": "",
"placeholder": "Search Google Fonts",
"required": false,
"disabled": false,
"readOnly": false,
"invalid": false,
"errors": [],
"visible": true,
"validators": [],
"validateOnBlur": true,
"chrome": "field",
"fonts": [],
"category": "",
"pageSize": 24,
"previewText": "",
"loadFonts": true,
"stylesheetUrl": "https://fonts.googleapis.com/css2",
"clearable": true,
"placement": "bottom",
"floatingMode": "viewport"
});
</script>
<template>
<DomFontPicker
v-bind="data"
@update:modelValue="data.modelValue = $event"
/>
</template>Demo
Choose a font family
The selected value is an ordinary family name; the application decides how and where to use it.
Type a family such as Lato. Only visible previews are requested.
Selected family
Lato
npm install @getdom/studio<script setup>
import '@getdom/studio/style.css';
import { DomFontPicker } from '@getdom/studio';
import { computed, ref } from 'vue';
const family = ref('Lato');
const sampleStyle = computed(getSampleStyle);
/**
* Build the demonstration font stack from the selected family.
*
* @returns {Record<string, string>} Inline style for the preview sentence.
*/
function getSampleStyle() {
const escapedFamily = family.value.replace(/[\\']/g, '\\$&');
return { fontFamily: `'${escapedFamily}', sans-serif` };
}
</script>
<template>
<div class="grid w-full max-w-lg gap-4">
<DomFontPicker
v-model="family"
label="Font family"
description="Type a family such as Lato. Only visible previews are requested."
placeholder="Search Google Fonts"
/>
<div class="rounded-2xl border border-border bg-secondary/40 p-5">
<p class="text-xs font-medium uppercase tracking-wide text-muted-fg">Selected family</p>
<p class="mt-2 text-2xl text-canvas-fg" :style="sampleStyle">{{ family || 'Choose a font' }}</p>
</div>
</div>
</template>
Loading model
Preview fonts stay local to the picker
No font bundle
The built-in snapshot contains 1,946 family names and categories (27 September 2026), but no font files. Importing the control does not start a Google Fonts request.
Incremental batches
Select appends pageSize rows near its end. Only intersecting preview rows, a small overscan, and the selected label request CSS v2 fonts with exact text subsetting. Opening near a distant selection does not download the intervening fonts.
Explicit ownership
The stylesheet node is removed when the picker unmounts. Applications own persistent loading for content that uses the chosen font elsewhere.
Optional integration
Keep the catalogue current in your app
The bundled catalogue is a release-time snapshot, not a live feed. DOM Studio can refresh that snapshot in later releases, but does not host a catalogue service or manage Google API keys. If your app needs new families between package updates, your backend can supply its own metadata through the existing fonts prop.
- Google Fonts CSS v2 API: no key; already used by the picker to download preview fonts lazily.
- Google Fonts Developer API: requires a key; supplies the current catalogue and metadata. It does not make preview loading faster.
The recipes below are for your application, not a DOM Studio endpoint. They are displayed as source only and do not make Developer API requests on this page.
Your backend
1. Fetch and cache the metadata
Follow Google’s Developer API setup to obtain a key for your project. Store it as GOOGLE_FONTS_API_KEY in your backend’s environment or secret manager. Restrict it to the required API and your server environment where supported. Never put it in a VITE_ variable, client bundle, API response, or logged request URL.
This Node.js 22 / Express example mounts at /api/fonts in your own app. It caches a successful catalogue for 24 hours, shares concurrent refreshes, times out after five seconds, and backs off for five minutes after a failure. Failed refreshes retain the last successful catalogue; a cold-cache failure returns 503.
// Copy into your own Node.js 22 / Express backend; this is not a DOM Studio API.
// Mount with: import getFonts from './fonts.get.js'; app.get('/api/fonts', getFonts);
// Set GOOGLE_FONTS_API_KEY on the server only.
const refreshInterval = 24 * 60 * 60 * 1000;
const retryInterval = 5 * 60 * 1000;
let catalogue = null;
let nextRefreshAt = 0;
let pendingRefresh = null;
/**
* Refresh the process-local catalogue, retaining the last good data on failure.
* Only validated family/category records are exposed to consumers. Never log
* the upstream URL or raw errors, which could contain the private API key.
*
* @returns {Promise<void>} Resolves after updating the cache or retry deadline.
*/
async function refreshCatalogue() {
try {
const key = process.env.GOOGLE_FONTS_API_KEY;
if (!key) throw new Error('Missing server-side Google Fonts key.');
const url = new URL('https://www.googleapis.com/webfonts/v1/webfonts');
url.searchParams.set('key', key);
url.searchParams.set('sort', 'alpha');
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
if (!response.ok) throw new Error('Catalogue request failed.');
const body = await response.json();
if (!Array.isArray(body.items) || !body.items.length) {
throw new Error('Empty or invalid catalogue.');
}
const fonts = [];
for (const item of body.items) {
if (typeof item?.family !== 'string' || !item.family.trim()) {
throw new Error('Invalid font family.');
}
fonts.push({
family: item.family.trim(),
category: typeof item.category === 'string' ? item.category : 'sans-serif',
});
}
catalogue = { fonts, updatedAt: new Date().toISOString() };
nextRefreshAt = Date.now() + refreshInterval;
} catch {
nextRefreshAt = Date.now() + retryInterval;
// Add a sanitised failure metric here in your application's monitoring.
}
}
/**
* Serve cached metadata, coalescing expired-cache requests into one refresh.
* A missing cache fails explicitly so the frontend can use its bundled list.
*
* @param {import('express').Request} _request Incoming application request.
* @param {import('express').Response} response Application JSON response.
* @returns {Promise<void>} Resolves once the catalogue or a 503 is sent.
*/
export default async function getFonts(_request, response) {
if (!pendingRefresh && Date.now() >= nextRefreshAt) {
pendingRefresh = refreshCatalogue();
}
if (pendingRefresh) {
await pendingRefresh;
pendingRefresh = null;
}
if (!catalogue) {
response.set('Cache-Control', 'no-store');
response.set('Retry-After', '300');
response.status(503).json({ error: 'Font catalogue temporarily unavailable.' });
return;
}
response.set('Cache-Control', 'public, max-age=300');
response.json(catalogue);
}
The in-memory cache is only for a single long-running process and resets on restart. For serverless or multiple instances, use a shared persistent cache and refresh coordination, or a scheduled job that refreshes stored JSON. Choose a refresh interval for your app, monitor failures and catalogue age, and keep serving the last known good data. Only family/category metadata goes to the browser—not font files or the key.
Your frontend
2. Pass the catalogue to the picker
Fetch your endpoint when the view containing the picker mounts, or reuse your app’s cached data store. A non-empty fonts array replaces the built-in catalogue; an empty array uses the bundled fallback. This example keeps that fallback during loading or failure and cancels its request on unmount.
npm install @getdom/studio<script setup>
import '@getdom/studio/style.css';
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { DomFontPicker } from '@getdom/studio';
const family = ref('Lato');
const fonts = ref([]); // Empty means use DOM Studio's bundled catalogue.
const catalogueNotice = ref('');
let requestController;
/**
* Fetch application-owned metadata only while this view is mounted.
* Preserve the bundled catalogue and selected family if the endpoint fails.
*
* @returns {Promise<void>} Resolves after applying records or a fallback notice.
*/
async function loadCatalogue() {
requestController = new AbortController();
try {
const response = await fetch('/api/fonts', { signal: requestController.signal });
if (!response.ok) throw new Error('Catalogue unavailable.');
const catalogue = await response.json();
if (!Array.isArray(catalogue.fonts) || !catalogue.fonts.length) {
throw new Error('Empty or invalid catalogue.');
}
if (!requestController.signal.aborted) fonts.value = catalogue.fonts;
} catch {
if (!requestController.signal.aborted) {
catalogueNotice.value = 'Using the bundled font list. The latest catalogue is unavailable.';
}
}
}
/**
* Cancel an outstanding metadata request when the owning view leaves the page.
*
* @returns {void}
*/
function cancelCatalogueRequest() {
requestController?.abort();
}
onMounted(loadCatalogue);
onBeforeUnmount(cancelCatalogueRequest);
</script>
<template>
<div class="grid gap-3">
<DomFontPicker v-model="family" :fonts="fonts" label="Font family" />
<p v-if="catalogueNotice" role="status" class="text-sm text-muted-fg">
{{ catalogueNotice }}
</p>
</div>
</template>
Return the complete lightweight catalogue from this endpoint. The picker searches it locally and reveals options in pageSize batches; this is UI pagination, not Google API pagination. The Developer API does not document cursor pagination, and the picker does not fetch remote catalogue pages. Do not call Google on every query event or replace fonts with just one server page.
Supplying current metadata does not download every font: the existing component still loads only the mounted selected label and nearby visible previews through CSS v2. Your app remains responsible for loading the chosen font in content outside the picker.
Prefer no runtime endpoint? Run the same metadata fetch in a build or scheduled publishing job and serve the resulting JSON as a static asset. Keep the key in that job’s environment and pass the downloaded records through fonts in the same way.
Reference
Props
Control props
| Name | Type | TS | Default | Description |
|---|---|---|---|---|
modelValue | string | string | '' | Selected font family or application-defined font value. |
fontsts | array | Array< | [] | Lightweight family metadata. Font files are never bundled in this array. Set source: system for installed fonts, whose value is a CSS stack that is never fetched. |
category | '' | 'sans-serif' | 'serif' | 'display' | 'handwriting' | 'monospace' | string | '' | Optionally restrict results to one Google Fonts category. |
pageSize | number | number | 24 | Number of metadata rows appended near the end. Preview fonts load only near the viewport. |
previewText | string | string | '' | Optional shared sample. Empty uses each family name as its own preview. |
loadFonts | boolean | boolean | true | Load the mounted selected label and visible previews from Google Fonts. |
stylesheetUrl | string | string | 'https://fonts.googleapis.com/css2' | Google Fonts CSS v2 endpoint or an application-controlled compatible proxy. |
clearable | boolean | boolean | true | Show a clear button after a font is selected. |
placement | 'bottom' | 'top' | 'right' | 'left' | string | 'bottom' | Preferred side before collision handling. |
floatingMode | 'viewport' | 'anchor' | string | 'viewport' | viewport keeps the list inside the browser; anchor keeps it attached while scrolling. |
Field props
| Name | Type | TS | Default | Description |
|---|---|---|---|---|
id | string | string | '' | Optional ID override. By default parent forms derive the input ID from the field path using underscores. |
name | string | string | '' | Local field name. Parent forms derive the full field path and native HTML name from the form hierarchy. |
label | string | string | '' | Visible field label. |
description | string | string | '' | Optional helper copy below the field. |
placeholder | string | string | '' | Placeholder shown when the control is empty. |
required | boolean | boolean | false | Mark the field as required. |
disabled | boolean | boolean | false | Disable field interaction. |
readOnly | boolean | boolean | false | Show the value but prevent editing. |
invalid | boolean | boolean | false | Mark the field invalid. |
errorsts | array | object | string | Array< | [] | Validation errors for this field. |
visible | boolean | boolean | true | Show or hide the field. |
validators | array | Array<unknown> | [] | Validators attached to this field. Use functions in Vue code, or serializable records such as { name: "minLength", props: { min: 2 } } in generated schemas. |
validateOnBlur | boolean | boolean | true | Run validators when the field loses focus. |
chrome | 'field' | 'none' | false | string | 'field' | Render default field chrome, or hide chrome while keeping form state wiring. |
Auto-generated from Font picker.props and inline _edit hints.
Events
| Name | Payload | Description |
|---|---|---|
| @update:modelValue | string | Fired with the selected font value. |
| @select | { item, value, label } | Fired when a font family is selected. |
| @query | string | Fired as the user searches the catalog. |
| @focus | — | — |
| @blur | — | — |
Names auto-detected from defineEmits and source emit() calls; payload and description from __doc.events when present.