Skip to content

AI-native design editor. Open-source Figma alternative.

fix(fonts): restore font picker selection

Danila Poyarkov59550c1c070f
diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.ts
index 8eb321bc7..e08728203 100644
--- a/packages/core/src/text/fonts.ts
+++ b/packages/core/src/text/fonts.ts
@@ -3,9 +3,9 @@ import { uniq } from 'es-toolkit/array'
import { DEFAULT_FONT_FAMILY, IS_BROWSER, GOOGLE_FONTS_API_KEY } from '#core/constants'
import type { SceneGraph } from '#core/scene-graph'
+import { fontFaceRenderFamily, parseFontStyle } from '#core/text/face'
import { fontFallbackEntry } from '#core/text/fallbacks'
import type { FontFallbackScript } from '#core/text/fallbacks'
-import { fontFaceRenderFamily, parseFontStyle } from '#core/text/face'
export interface FontInfo {
family: string
@@ -15,6 +15,12 @@ export interface FontInfo {
}
export type LocalFontAccessState = 'unsupported' | 'prompt' | 'granted' | 'denied'
+export type FontFamilySource = 'local' | 'google' | 'bundled'
+
+export interface FontFamilyOption {
+ family: string
+ source: FontFamilySource
+}
export interface DownloadedFontCache {
read(family: string, style: string): Promise<ArrayBuffer | null>
@@ -131,6 +137,8 @@ export class FontManager {
private fallbackUserAgent: string | undefined
private googleFontsCache = new Map<string, Record<string, string>>()
private googleFontsFailed = new Set<string>()
+ private googleFamiliesCache: string[] | null = null
+ private googleFamiliesPromise: Promise<string[]> | null = null
private registeredRenderFamilies = new Set<string>()
private cjkFallbackFamilies: string[] = []
private cjkFallbackPromise: Promise<string[]> | null = null
@@ -204,8 +212,23 @@ export class FontManager {
}
async listFamilies(): Promise<string[]> {
+ const options = await this.listFamilyOptions()
+ return options.map((option) => option.family)
+ }
+
+ async listFamilyOptions(): Promise<FontFamilyOption[]> {
const fonts = this.localFonts ?? (await this.requestLocalFontAccess())
- return uniq(fonts.map((f) => f.family)).sort()
+ const googleFamilies = await this.listGoogleFamilies()
+ const byFamily = new Map<string, FontFamilyOption>()
+ byFamily.set(DEFAULT_FONT_FAMILY, { family: DEFAULT_FONT_FAMILY, source: 'bundled' })
+ for (const family of googleFamilies) byFamily.set(family, { family, source: 'google' })
+ for (const font of fonts) byFamily.set(font.family, { family: font.family, source: 'local' })
+ return [...byFamily.values()].sort((a, b) => a.family.localeCompare(b.family))
+ }
+
+ preloadGoogleFamilies(): void {
+ if (this.googleFamiliesCache || this.googleFamiliesPromise) return
+ this.googleFamiliesPromise = this.loadGoogleFamilies()
}
async fetchBundledFont(url: string): Promise<ArrayBuffer | null> {
@@ -438,6 +461,29 @@ export class FontManager {
return result
}
+ private async listGoogleFamilies(): Promise<string[]> {
+ if (this.googleFamiliesCache) return this.googleFamiliesCache
+ this.googleFamiliesPromise ??= this.loadGoogleFamilies()
+ return this.googleFamiliesPromise
+ }
+
+ private async loadGoogleFamilies(): Promise<string[]> {
+ if (typeof fetch === 'undefined') return []
+
+ try {
+ const response = await fetch(
+ `https://www.googleapis.com/webfonts/v1/webfonts?key=${GOOGLE_FONTS_API_KEY}`
+ )
+ if (!response.ok) return []
+ const data = (await response.json()) as { items?: Array<{ family?: string }> }
+ const families = uniq(data.items?.flatMap((item) => (item.family ? [item.family] : [])) ?? [])
+ this.googleFamiliesCache = families.sort()
+ return this.googleFamiliesCache
+ } catch {
+ return []
+ }
+ }
+
private async fetchGoogleFontFiles(family: string): Promise<Record<string, string> | null> {
if (this.googleFontsCache.has(family)) return this.googleFontsCache.get(family) ?? null
if (this.googleFontsFailed.has(family)) return null
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index 04ae70d3e..a95948863 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -127,7 +127,7 @@ export {
export type { ColorFieldFormat, OkHCLControls } from '#vue/primitives/ColorPicker'
export { FillPickerRoot } from '#vue/primitives/FillPicker'
export { FontPickerRoot } from '#vue/primitives/FontPicker'
-export type { FontPickerUi } from '#vue/primitives/FontPicker'
+export type { FontFamilyOption, FontPickerUi } from '#vue/primitives/FontPicker'
export {
GradientEditorRoot,
GradientEditorBar,
diff --git a/packages/vue/src/primitives/FontPicker/FontPickerRoot.vue b/packages/vue/src/primitives/FontPicker/FontPickerRoot.vue
index 3afe758a5..5eddc5c2e 100644
--- a/packages/vue/src/primitives/FontPicker/FontPickerRoot.vue
+++ b/packages/vue/src/primitives/FontPicker/FontPickerRoot.vue
@@ -9,18 +9,23 @@ import {
ComboboxItemIndicator,
ComboboxPortal,
ComboboxRoot,
+ ComboboxTrigger,
ComboboxVirtualizer,
ComboboxViewport,
type AcceptableValue
} from 'reka-ui'
-import { useFontPicker, type FontAccessController } from '#vue/primitives/FontPicker/useFontPicker'
+import {
+ useFontPicker,
+ type FontAccessController,
+ type FontFamilyOption
+} from '#vue/primitives/FontPicker/useFontPicker'
import type { FontPickerUi } from '#vue/primitives/FontPicker/types'
const { listFamilies, localFontAccess, ui, emptySearchText, emptyFontsText, emptyFontsHint } =
defineProps<{
- listFamilies: () => Promise<string[]>
+ listFamilies: () => Promise<string[] | FontFamilyOption[]>
localFontAccess?: FontAccessController
ui?: FontPickerUi
emptySearchText?: string
@@ -61,11 +66,13 @@ const { searchTerm, open, filtered, loading, accessState, requestAccess, select
"
>
<ComboboxAnchor as-child>
- <slot name="trigger" :value="modelValue" :open="open">
- <button :class="ui?.trigger">
- <span class="truncate">{{ modelValue }}</span>
- </button>
- </slot>
+ <ComboboxTrigger as-child>
+ <slot name="trigger" :value="modelValue" :open="open">
+ <button :class="ui?.trigger">
+ <span class="truncate">{{ modelValue }}</span>
+ </button>
+ </slot>
+ </ComboboxTrigger>
</ComboboxAnchor>
<ComboboxPortal>
@@ -81,6 +88,7 @@ const { searchTerm, open, filtered, loading, accessState, requestAccess, select
<slot name="search" :search-term="searchTerm">
<ComboboxInput
v-model="searchTerm"
+ :display-value="() => ''"
:class="ui?.search"
placeholder="Search fonts…"
autocomplete="off"
@@ -94,21 +102,26 @@ const { searchTerm, open, filtered, loading, accessState, requestAccess, select
<ComboboxVirtualizer
v-slot="{ option }"
:options="filtered"
- :text-content="(family: string) => family"
+ :text-content="(option: FontFamilyOption) => option.family"
:estimate-size="36"
>
- <slot name="item" :family="option" :selected="option === modelValue">
- <ComboboxItem
- :value="option"
- :class="ui?.item"
- :style="{ fontFamily: `'${option}', sans-serif` }"
+ <ComboboxItem
+ :value="option.family"
+ :class="ui?.item"
+ :style="{ fontFamily: `'${option.family}', sans-serif` }"
+ >
+ <slot
+ name="item"
+ :family="option.family"
+ :source="option.source"
+ :selected="option.family === modelValue"
>
<ComboboxItemIndicator>
- <slot name="indicator" :selected="option === modelValue" />
+ <slot name="indicator" :selected="option.family === modelValue" />
</ComboboxItemIndicator>
- <span class="truncate">{{ option }}</span>
- </ComboboxItem>
- </slot>
+ <span class="truncate">{{ option.family }}</span>
+ </slot>
+ </ComboboxItem>
</ComboboxVirtualizer>
<div v-if="filtered.length === 0 && searchTerm" :class="ui?.empty">
diff --git a/packages/vue/src/primitives/FontPicker/index.ts b/packages/vue/src/primitives/FontPicker/index.ts
index 04ff3394a..f0a94bbbd 100644
--- a/packages/vue/src/primitives/FontPicker/index.ts
+++ b/packages/vue/src/primitives/FontPicker/index.ts
@@ -1,2 +1,3 @@
export { default as FontPickerRoot } from '#vue/primitives/FontPicker/FontPickerRoot.vue'
export type { FontPickerUi } from '#vue/primitives/FontPicker/types'
+export type { FontFamilyOption } from '#vue/primitives/FontPicker/useFontPicker'
diff --git a/packages/vue/src/primitives/FontPicker/types.ts b/packages/vue/src/primitives/FontPicker/types.ts
index 2889ebe71..4ab6db4ee 100644
--- a/packages/vue/src/primitives/FontPicker/types.ts
+++ b/packages/vue/src/primitives/FontPicker/types.ts
@@ -2,6 +2,7 @@ export interface FontPickerUi {
trigger?: string
content?: string
item?: string
+ itemMeta?: string
search?: string
viewport?: string
empty?: string
diff --git a/packages/vue/src/primitives/FontPicker/useFontPicker.ts b/packages/vue/src/primitives/FontPicker/useFontPicker.ts
index c2b8efa62..e03d7f152 100644
--- a/packages/vue/src/primitives/FontPicker/useFontPicker.ts
+++ b/packages/vue/src/primitives/FontPicker/useFontPicker.ts
@@ -1,11 +1,14 @@
import { useFilter } from 'reka-ui'
import { computed, ref, watch } from 'vue'
+import type { FontFamilyOption } from '@open-pencil/core/text'
+
export type FontAccessState = 'unsupported' | 'prompt' | 'granted' | 'denied'
+export type { FontFamilyOption, FontFamilySource } from '@open-pencil/core/text'
export interface FontAccessController {
state: () => FontAccessState
- load: () => Promise<string[]>
+ load: () => Promise<string[] | FontFamilyOption[]>
}
/**
@@ -15,18 +18,22 @@ export interface UseFontPickerOptions {
/** Writable model for the selected font family. */
modelValue: { value: string }
/** Async source for available font families. */
- listFamilies: () => Promise<string[]>
+ listFamilies: () => Promise<string[] | FontFamilyOption[]>
/** Host-provided local-font permission controller. */
localFontAccess?: FontAccessController
/** Optional callback fired after a family is selected. */
onSelect?: (family: string) => void
}
+function normalizeOptions(items: string[] | FontFamilyOption[]): FontFamilyOption[] {
+ return items.map((item) => (typeof item === 'string' ? { family: item, source: 'local' } : item))
+}
+
/**
* Returns searchable font-picker state and selection helpers.
*/
export function useFontPicker(options: UseFontPickerOptions) {
- const families = ref<string[]>([])
+ const families = ref<FontFamilyOption[]>([])
const searchTerm = ref('')
const open = ref(false)
const loading = ref(false)
@@ -35,14 +42,14 @@ export function useFontPicker(options: UseFontPickerOptions) {
const { contains } = useFilter({ sensitivity: 'base' })
const filtered = computed(() => {
if (!searchTerm.value) return families.value
- return families.value.filter((family) => contains(family, searchTerm.value))
+ return families.value.filter((option) => contains(option.family, searchTerm.value))
})
async function loadFamilies() {
if (families.value.length > 0 || loading.value) return
loading.value = true
try {
- families.value = await options.listFamilies()
+ families.value = normalizeOptions(await options.listFamilies())
accessState.value = options.localFontAccess?.state() ?? accessState.value
} finally {
loading.value = false
@@ -53,16 +60,18 @@ export function useFontPicker(options: UseFontPickerOptions) {
if (!isOpen) return
searchTerm.value = ''
accessState.value = options.localFontAccess?.state() ?? accessState.value
- if (accessState.value !== 'prompt') {
- await loadFamilies()
+ if (accessState.value === 'prompt') {
+ await requestAccess()
+ return
}
+ await loadFamilies()
})
async function requestAccess() {
if (!options.localFontAccess || loading.value) return
loading.value = true
try {
- families.value = await options.localFontAccess.load()
+ families.value = normalizeOptions(await options.localFontAccess.load())
accessState.value = options.localFontAccess.state()
} finally {
loading.value = false
diff --git a/src/app/editor/fonts/index.ts b/src/app/editor/fonts/index.ts
index 1d59945c3..2a16c9da6 100644
--- a/src/app/editor/fonts/index.ts
+++ b/src/app/editor/fonts/index.ts
@@ -1,4 +1,11 @@
-import { fontManager, styleToWeight, type LocalFontAccessState } from '@open-pencil/core/text'
+import { useLocalStorage } from '@vueuse/core'
+
+import {
+ fontManager,
+ styleToWeight,
+ type FontFamilyOption,
+ type LocalFontAccessState
+} from '@open-pencil/core/text'
import {
clearDownloadedFontCache as clearTauriDownloadedFontCache,
@@ -11,6 +18,8 @@ if (typeof navigator !== 'undefined') {
fontManager.setFallbackUserAgent(navigator.userAgent)
}
+export const googleFontsEnabled = useLocalStorage('op-google-fonts-enabled', true)
+
let tauriFontCacheConfigured = false
function configureTauriFontCache() {
@@ -47,17 +56,19 @@ export function preloadFonts(): void {
configureTauriFontCache()
if (isTauri()) {
void getTauriFonts().then(registerFontFaces)
+ return
}
+ if (googleFontsEnabled.value) fontManager.preloadGoogleFamilies()
}
export function localFontAccessState(): LocalFontAccessState {
return isTauri() ? 'granted' : fontManager.localAccessState()
}
-export async function requestLocalFontAccess(): Promise<string[]> {
+export async function requestLocalFontAccess(): Promise<FontFamilyOption[]> {
if (isTauri()) return listFamilies()
await fontManager.requestLocalFontAccess()
- return fontManager.listFamilies()
+ return listFamilies()
}
export async function downloadedFontCacheSummary() {
@@ -84,13 +95,14 @@ function registerFontFaces(fonts: TauriFontFamily[]): void {
}
}
-export async function listFamilies(): Promise<string[]> {
+export async function listFamilies(): Promise<FontFamilyOption[]> {
configureTauriFontCache()
if (isTauri()) {
const fonts = await getTauriFonts()
- return fonts.map((f) => f.family)
+ return fonts.map((f) => ({ family: f.family, source: 'local' }))
}
- return fontManager.listFamilies()
+ const fonts = await fontManager.listFamilyOptions()
+ return googleFontsEnabled.value ? fonts : fonts.filter((font) => font.source !== 'google')
}
export async function listFonts(): Promise<TauriFontFamily[]> {
diff --git a/src/components/FontPicker.vue b/src/components/FontPicker.vue
index 156fe594f..be1bb8631 100644
--- a/src/components/FontPicker.vue
+++ b/src/components/FontPicker.vue
@@ -16,7 +16,7 @@ const cls = usePopoverUI({
})
const selectCls = useSelectUI({
trigger: 'w-full rounded px-2 py-1 text-xs',
- item: 'w-full gap-2 px-2 py-2 text-sm'
+ item: 'w-full gap-2 px-3 py-2.5 text-sm leading-tight'
})
const ui = computed<FontPickerUi>(() => ({
@@ -24,7 +24,7 @@ const ui = computed<FontPickerUi>(() => ({
content: cls.content,
item: selectCls.item,
search:
- 'w-full border-b border-border bg-transparent px-2 py-1 text-xs text-surface outline-none placeholder:text-muted',
+ 'w-full border-b border-border bg-transparent px-3 py-2 text-sm text-surface outline-none placeholder:text-muted',
empty: 'px-2 py-3 text-center text-xs text-muted',
emptyAction: 'mt-2 rounded bg-accent px-2 py-1 text-xs font-medium text-white disabled:opacity-50'
}))
@@ -52,15 +52,18 @@ const localFontAccess = {
</button>
</template>
- <template #item="{ family, selected }">
- <div
- data-test-id="font-picker-item"
- :class="selectCls.item"
- :style="{ fontFamily: `'${family}', sans-serif` }"
- >
+ <template #item="{ family, selected, source }">
+ <div data-test-id="font-picker-item" class="flex min-w-0 flex-1 items-center gap-2">
<icon-lucide-check v-if="selected" class="size-3 shrink-0 text-accent" />
<span v-else class="size-3 shrink-0" />
- <span class="truncate">{{ family }}</span>
+ <span class="truncate" :style="{ fontFamily: `'${family}', sans-serif` }">{{
+ family
+ }}</span>
+ <span
+ class="font-sans ml-auto shrink-0 rounded bg-input px-1.5 py-0.5 text-[9px] uppercase text-muted"
+ >
+ {{ source }}
+ </span>
</div>
</template>
</FontPickerRoot>
diff --git a/src/components/FontSettings/FontSettingsPopover.vue b/src/components/FontSettings/FontSettingsPopover.vue
index 23020f169..41baeab40 100644
--- a/src/components/FontSettings/FontSettingsPopover.vue
+++ b/src/components/FontSettings/FontSettingsPopover.vue
@@ -2,6 +2,7 @@
import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'
import { onMounted } from 'vue'
+import { isTauri } from '@/app/tauri/env'
import { useFontSettings } from '@/components/FontSettings/use'
import { useButtonUI } from '@/components/ui/button'
import { usePopoverUI } from '@/components/ui/popover'
@@ -24,6 +25,8 @@ const primaryButton = useButtonUI({
size: 'sm',
ui: { base: 'w-full px-2 py-1.5 text-[10px] font-medium disabled:opacity-50' }
})
+const showDownloadedFonts = isTauri()
+
const {
accessState,
accessStateLabel,
@@ -33,10 +36,12 @@ const {
cacheUpdatedLabel,
canRequestLocalFonts,
status,
+ googleFontsEnabled,
clearCache,
downloadFallbacks,
refreshSummary,
- requestAccess
+ requestAccess,
+ setGoogleFontsEnabled
} = useFontSettings()
onMounted(() => {
@@ -73,7 +78,11 @@ onMounted(() => {
<div>
<h3 class="text-[11px] font-semibold text-surface">Font settings</h3>
<p class="mt-0.5 text-[10px] leading-relaxed text-muted">
- Access system fonts, predownload fallback packs, and manage cached downloads.
+ {{
+ showDownloadedFonts
+ ? 'Access system fonts, Google Fonts, fallback packs, and cached downloads.'
+ : 'Allow browser access to local fonts and manage Google Fonts.'
+ }}
</p>
</div>
</div>
@@ -84,10 +93,14 @@ onMounted(() => {
<span class="text-surface">{{ accessStateLabel }}</span>
</div>
<div class="flex justify-between gap-3 text-muted">
+ <span>Google Fonts</span>
+ <span class="text-surface">{{ googleFontsEnabled ? 'Enabled' : 'Disabled' }}</span>
+ </div>
+ <div v-if="showDownloadedFonts" class="flex justify-between gap-3 text-muted">
<span>Downloaded cache</span>
<span class="text-surface">{{ cacheCount }} fonts · {{ cacheSize }}</span>
</div>
- <div class="flex justify-between gap-3 text-muted">
+ <div v-if="showDownloadedFonts" class="flex justify-between gap-3 text-muted">
<span>Last updated</span>
<span class="text-surface">{{ cacheUpdatedLabel }}</span>
</div>
@@ -117,6 +130,27 @@ onMounted(() => {
</div>
<div class="grid grid-cols-[1fr_auto] gap-2 rounded border border-border p-2">
+ <div>
+ <p class="text-[10px] font-medium text-surface">Google Fonts</p>
+ <p class="mt-0.5 text-[10px] leading-relaxed text-muted">
+ Show fonts from Google in the font picker.
+ </p>
+ </div>
+ <button
+ type="button"
+ data-test-id="font-settings-toggle-google-fonts"
+ :class="secondaryButton.base"
+ :disabled="busyAction !== null"
+ @click="setGoogleFontsEnabled(!googleFontsEnabled)"
+ >
+ {{ googleFontsEnabled ? 'Disable' : 'Enable' }}
+ </button>
+ </div>
+
+ <div
+ v-if="showDownloadedFonts"
+ class="grid grid-cols-[1fr_auto] gap-2 rounded border border-border p-2"
+ >
<div>
<p class="text-[10px] font-medium text-surface">Fallback packs</p>
<p class="mt-0.5 text-[10px] leading-relaxed text-muted">
@@ -135,7 +169,7 @@ onMounted(() => {
</div>
</div>
- <div class="grid grid-cols-2 gap-1.5">
+ <div v-if="showDownloadedFonts" class="grid grid-cols-2 gap-1.5">
<button
type="button"
data-test-id="font-settings-refresh-cache"
diff --git a/src/components/FontSettings/use.ts b/src/components/FontSettings/use.ts
index 26ed7ba66..12171c058 100644
--- a/src/components/FontSettings/use.ts
+++ b/src/components/FontSettings/use.ts
@@ -1,10 +1,11 @@
import { computed, ref } from 'vue'
-import type { LocalFontAccessState } from '@open-pencil/core/text'
+import type { FontFamilyOption, LocalFontAccessState } from '@open-pencil/core/text'
import {
clearDownloadedFontCache,
downloadedFontCacheSummary,
+ googleFontsEnabled,
localFontAccessState,
predownloadFallbackFonts,
requestLocalFontAccess
@@ -21,7 +22,8 @@ export interface FontSettingsActions {
downloadedFontCacheSummary: () => Promise<FontCacheSummary>
localFontAccessState: () => LocalFontAccessState
predownloadFallbackFonts: () => Promise<unknown>
- requestLocalFontAccess: () => Promise<string[]>
+ requestLocalFontAccess: () => Promise<string[] | FontFamilyOption[]>
+ googleFontsEnabled: { value: boolean }
}
export type FontSettingsBusyAction = 'access' | 'download' | 'clear' | 'refresh'
@@ -31,7 +33,8 @@ const defaultActions: FontSettingsActions = {
downloadedFontCacheSummary,
localFontAccessState,
predownloadFallbackFonts,
- requestLocalFontAccess
+ requestLocalFontAccess,
+ googleFontsEnabled
}
export function useFontSettings(actions: FontSettingsActions = defaultActions) {
@@ -41,6 +44,7 @@ export function useFontSettings(actions: FontSettingsActions = defaultActions) {
const accessState = ref(actions.localFontAccessState())
const busyAction = ref<FontSettingsBusyAction | null>(null)
const status = ref('')
+ const googleFontsEnabled = actions.googleFontsEnabled
const accessStateLabel = computed(() => {
if (accessState.value === 'granted') return 'Enabled'
@@ -91,6 +95,11 @@ export function useFontSettings(actions: FontSettingsActions = defaultActions) {
}
}
+ function setGoogleFontsEnabled(enabled: boolean) {
+ googleFontsEnabled.value = enabled
+ status.value = enabled ? 'Google Fonts enabled.' : 'Google Fonts disabled.'
+ }
+
async function downloadFallbacks() {
busyAction.value = 'download'
status.value = ''
@@ -128,9 +137,11 @@ export function useFontSettings(actions: FontSettingsActions = defaultActions) {
cacheSize,
cacheUpdatedLabel,
status,
+ googleFontsEnabled,
clearCache,
downloadFallbacks,
refreshSummary,
- requestAccess
+ requestAccess,
+ setGoogleFontsEnabled
}
}
diff --git a/tests/e2e/fonts/picker.spec.ts b/tests/e2e/fonts/picker.spec.ts
new file mode 100644
index 000000000..fd9d9c8ba
--- /dev/null
+++ b/tests/e2e/fonts/picker.spec.ts
@@ -0,0 +1,149 @@
+import { expect, test, type Page } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+async function openTypographyForText(page: Page) {
+ await page.goto('/')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+
+ return page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const id = store.createShape('TEXT', 120, 120, 240, 40)
+ store.updateNode(id, { characters: 'Font picker smoke' })
+ store.select([id])
+ return id
+ })
+}
+
+async function openFontPicker(page: Page) {
+ await page.getByTestId('font-picker-trigger').click()
+}
+
+async function installGoogleFontsMock(page: Page, families = ['Inter', 'OpenPencil Google Font']) {
+ await page.addInitScript((googleFamilies) => {
+ const win = window as Window & { __googleFontsFetchCount?: number }
+ win.__googleFontsFetchCount = 0
+ const originalFetch = window.fetch.bind(window)
+ window.fetch = async (input, init) => {
+ let url: string
+ if (typeof input === 'string') url = input
+ else if (input instanceof URL) url = input.href
+ else url = input.url
+ if (url.startsWith('https://www.googleapis.com/webfonts/v1/webfonts')) {
+ if (!url.includes('family='))
+ win.__googleFontsFetchCount = (win.__googleFontsFetchCount ?? 0) + 1
+ return new Response(
+ JSON.stringify({
+ items: googleFamilies.map((family) => ({ family }))
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } }
+ )
+ }
+ return originalFetch(input, init)
+ }
+ }, families)
+}
+
+test('font picker preloads Google fonts and selects local fonts after first-open access', async ({
+ page
+}) => {
+ await installGoogleFontsMock(page)
+ await page.addInitScript(() => {
+ Object.defineProperty(window, 'queryLocalFonts', {
+ configurable: true,
+ value: async () => [
+ {
+ family: 'Inter',
+ fullName: 'Inter Regular',
+ postscriptName: 'Inter-Regular',
+ style: 'Regular'
+ },
+ {
+ family: 'OpenPencil Local Font',
+ fullName: 'OpenPencil Local Font Regular',
+ postscriptName: 'OpenPencilLocalFont-Regular',
+ style: 'Regular'
+ }
+ ]
+ })
+ })
+
+ const textId = await openTypographyForText(page)
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => (window as Window & { __googleFontsFetchCount?: number }).__googleFontsFetchCount
+ )
+ )
+ .toBe(1)
+ await openFontPicker(page)
+
+ await expect(
+ page.getByTestId('font-picker-item').filter({ hasText: 'OpenPencil Local Font' })
+ ).toBeVisible()
+ await page.getByTestId('font-picker-item').filter({ hasText: 'OpenPencil Local Font' }).click()
+
+ await expect(page.getByTestId('font-picker-trigger')).toContainText('OpenPencil Local Font')
+ await expect
+ .poll(async () =>
+ page.evaluate((id) => {
+ const store = window.openPencil?.getStore?.()
+ const node = store?.graph.getNode(id)
+ return node?.type === 'TEXT' ? node.fontFamily : null
+ }, textId)
+ )
+ .toBe('OpenPencil Local Font')
+})
+
+test('font picker lists Google fonts when local font API is unavailable', async ({ page }) => {
+ await installGoogleFontsMock(page)
+ await page.addInitScript(() => {
+ Reflect.deleteProperty(window, 'queryLocalFonts')
+ })
+
+ await openTypographyForText(page)
+ await openFontPicker(page)
+
+ await expect(
+ page.getByTestId('font-picker-item').filter({ hasText: 'OpenPencil Google Font' })
+ ).toBeVisible()
+ await expect(page.getByText('Local fonts are not available in this browser.')).toHaveCount(0)
+})
+
+test('font picker still lists Google fonts when local font permission is rejected', async ({
+ page
+}) => {
+ await installGoogleFontsMock(page)
+ await page.addInitScript(() => {
+ Object.defineProperty(window, 'queryLocalFonts', {
+ configurable: true,
+ value: async () => {
+ throw new Error('denied')
+ }
+ })
+ })
+
+ await openTypographyForText(page)
+ await openFontPicker(page)
+
+ await expect(
+ page.getByTestId('font-picker-item').filter({ hasText: 'OpenPencil Google Font' })
+ ).toBeVisible()
+ await expect(page.getByText('Local font access is blocked for this site.')).toHaveCount(0)
+})
+
+test('font picker keeps bundled Inter available when local and Google fonts are unavailable', async ({
+ page
+}) => {
+ await installGoogleFontsMock(page, [])
+ await page.addInitScript(() => {
+ Reflect.deleteProperty(window, 'queryLocalFonts')
+ })
+
+ await openTypographyForText(page)
+ await openFontPicker(page)
+
+ await expect(page.getByTestId('font-picker-item').filter({ hasText: 'Inter' })).toBeVisible()
+})
diff --git a/tests/e2e/fonts/settings.spec.ts b/tests/e2e/fonts/settings.spec.ts
index 1c00447a9..7aef538f8 100644
--- a/tests/e2e/fonts/settings.spec.ts
+++ b/tests/e2e/fonts/settings.spec.ts
@@ -2,7 +2,9 @@ import { expect, test } from '@playwright/test'
import { CanvasHelper } from '#tests/helpers/canvas'
-test('font settings popover is available from typography panel', async ({ page }) => {
+test('font settings popover exposes web font access without desktop-only cache actions', async ({
+ page
+}) => {
await page.goto('/')
const canvas = new CanvasHelper(page)
await canvas.waitForInit()
@@ -18,9 +20,15 @@ test('font settings popover is available from typography panel', async ({ page }
await expect(page.getByTestId('typography-section')).toBeVisible()
await page.getByTestId('font-settings-trigger').click()
- await expect(page.getByText('Access system fonts')).toBeVisible()
+ await expect(page.getByText('Allow browser access to local fonts')).toBeVisible()
await expect(page.getByTestId('font-settings-request-access')).toBeVisible()
- await expect(page.getByTestId('font-settings-download-fallbacks')).toBeVisible()
- await expect(page.getByTestId('font-settings-refresh-cache')).toBeVisible()
- await expect(page.getByTestId('font-settings-clear-cache')).toBeVisible()
+ await expect(page.getByTestId('font-settings-toggle-google-fonts')).toHaveText('Disable')
+ await page.getByTestId('font-settings-toggle-google-fonts').click()
+ await expect(page.getByTestId('font-settings-toggle-google-fonts')).toHaveText('Enable')
+ await page.getByTestId('font-settings-toggle-google-fonts').click()
+ await expect(page.getByTestId('font-settings-toggle-google-fonts')).toHaveText('Disable')
+ await expect(page.getByTestId('font-settings-download-fallbacks')).toHaveCount(0)
+ await expect(page.getByTestId('font-settings-refresh-cache')).toHaveCount(0)
+ await expect(page.getByTestId('font-settings-clear-cache')).toHaveCount(0)
+ await expect(page.getByText('Download CJK and Arabic fallbacks')).toHaveCount(0)
})