AI-native design editor. Open-source Figma alternative.
fix(typography): offer only the weights a font family has, as Figma does (#1087)
Danila Poyarkovcbf140bfbe00
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 20ea032e7..a5a675f06 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@### Breaking changes+- `useTypography().weights` and the `weights` slot prop of `TypographyControlsRoot` in `@open-pencil/vue` are a computed list of the weights the selected layers' families have, instead of a fixed list of all nine, so read them with `.value`.- In scripts, a text node's `fontSize`, `fontName`, `fontWeight`, `fills`, `letterSpacing`, `lineHeight`, and `textDecoration` read `figma.mixed` while its characters differ, as in Figma, instead of the text's first value, and setting one restyles every character instead of only characters without a style of their own. `fills` is typed `readonly Fill[] | symbol`, so scripts that index it narrow it first.- `SceneNode` from `@open-pencil/scene-graph` has `textParagraphs`, `listSpacing`, `paragraphSpacing`, `paragraphIndent`, and `hangingList`, so code that builds `SceneNode` objects itself must include them. `SkiaRenderer.buildParagraph` returns a `TextLayout`, which answers the `Paragraph` queries the renderer and text editor use for the whole text and draws with `draw(canvas, x, y)`, instead of a CanvasKit `Paragraph`.- `AUTO_LAYOUT_BREAK_THRESHOLD` is removed from `@open-pencil/core/constants`: a layer dragged out of auto layout now leaves by how far its own edge is past the frame, not by a cursor margin.@@ -130,6 +131,7 @@- Customize the toolbar in **Settings → Toolbar**, also opened from **Customize toolbar…** when you right-click it: hide tools, reorder them, and choose which share a flyout, on desktop and mobile alike. Hidden tools keep their shortcuts, **Move** always stays, and tools added in later versions join their default flyout in a customized toolbar.### Changed+- The font weight list offers only the weights the text's family has, as Figma's style list does, read from installed fonts and web font providers; a family whose faces cannot be read still offers all nine. Switching family keeps the weight and italic where the new family has them, otherwise takes the nearest weight with the same slant, so Inter Black becomes Lora Bold, and Bold and Italic toggles leave text alone when its family has no such face.- The plugin API refuses to move, rotate, constrain, or mask a layer an instance takes from its component, with Figma's errors, such as `in set_x: This property cannot be overridden in an instance: relative-transform`. Those fields always follow the component. Slot content stays editable, and editing a slot's default content makes the instance own it, as in Figma.- A layer dragged out of an auto layout frame leaves it as in Figma, once its edge is 5 px past the frame across the flow or about 15 px along it, instead of after the cursor travels 96 px beyond it.- Bound variables show as a neutral chip in the properties panel instead of purple text, so they no longer read as components.@@ -183,6 +185,7 @@### Fixed+- Searching the font picker lists the family the search names first, then families that begin with it, as Figma does: "Lora" puts Lora above Explora.- Instances opened from a `.fig` file keep the style overrides Figma gives them, such as corner radius, stroke weight and alignment, line height, letter spacing, font, effects, and fill, stroke, and effect styles. Editing their component used to overwrite them on the canvas while the saved file kept them, and a later edit to one of these fields in the instance was not saved. Text edited in an instance is saved with its styled ranges and list lines, as Figma writes it; saving kept only its characters.- A component edit reaches every field its instances do not override, as in Figma: stroke weight, alignment, caps, joins, and dashes, corner smoothing, blend mode, layout grids, letter spacing, line height, text case, decoration, alignment, truncation, styled ranges, and the position, rotation, and flips of layers outside auto layout. Such a layer is placed by its constraints when the instance has another size than its component.- Crash recovery, chat history, diagnostics, local files, libraries, saved credentials, and the sync outbox keep saving after Safari suspends the tab. Safari closes their IndexedDB connections without telling the page, and every later write failed with "The database connection is closing" until the page was reloaded.diff --git a/packages/core/src/text/font/faces.ts b/packages/core/src/text/font/faces.tsnew file mode 100644index 000000000..d9b3f2ea8--- /dev/null+++ b/packages/core/src/text/font/faces.ts@@ -0,0 +1,43 @@+import { uniqBy } from 'es-toolkit'++import { parseFontStyle } from '@open-pencil/scene-graph'++/** One face a font family has: a weight, upright or italic. */+export interface FamilyFace {+ weight: number+ italic: boolean+}++/** The faces named by a family's style names, such as "Bold Italic" or "SemiBold". */+export function facesFromStyles(styles: readonly string[]): FamilyFace[] {+ return uniqBy(+ styles.map((style) => parseFontStyle(style)),+ (face) => `${face.weight}${face.italic ? 'i' : ''}`+ )+}++export function hasFamilyFace(faces: readonly FamilyFace[], weight: number, italic: boolean) {+ return faces.some((face) => face.weight === weight && face.italic === italic)+}++/**+ * The face a text takes in a family, as Figma picks it when the family changes: the same weight+ * and slant where the family has it, otherwise the nearest weight with the same slant, or the+ * nearest weight at all in a family without that slant. Equally near weights take the lighter.+ */+export function nearestFamilyFace(+ faces: readonly FamilyFace[],+ weight: number,+ italic: boolean+): FamilyFace | null {+ const sameSlant = faces.filter((face) => face.italic === italic)+ const candidates = sameSlant.length > 0 ? sameSlant : faces+ let nearest: FamilyFace | null = null+ for (const face of candidates) {+ const distance = Math.abs(face.weight - weight)+ const best = nearest ? Math.abs(nearest.weight - weight) : Infinity+ if (distance < best || (distance === best && nearest && face.weight < nearest.weight))+ nearest = face+ }+ return nearest+}diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.tsindex de095a589..f9b94a871 100644--- a/packages/core/src/text/fonts.ts+++ b/packages/core/src/text/fonts.ts@@ -5,6 +5,7 @@ import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'import type { FontVariation, SceneGraph } from '@open-pencil/scene-graph'import { DEFAULT_FONT_FAMILY, IS_BROWSER } from '#core/constants'+import { facesFromStyles, hasFamilyFace, type FamilyFace } from '#core/text/font/faces'import {chooseLocalFontMatch,normalizeFontFamily,@@ -57,6 +58,10 @@ export class FontManager {private registrationGeneration = 0private providerRegistrations = new WeakMap<TypefaceFontProvider, Map<string, Set<ArrayBuffer>>>()private localFonts: FontInfo[] | null = null+ private hostStyles = new Map<string, readonly string[]>()+ private familyFaceLoads = new Map<string, Promise<FamilyFace[] | null>>()+ private knownFamilyFaces = new Map<string, FamilyFace[] | null>()+ private familyFacesListeners = new Set<() => void>()private localFontAccessState: LocalFontAccessState = IS_BROWSER ? 'prompt' : 'unsupported'private downloadedFontCache: DownloadedFontCache | null = nullprivate fallbackUserAgent: string | undefined@@ -144,6 +149,71 @@ export class FontManager {setOnlineFontProviders(settings: Partial<Record<WebFontProviderId, boolean>>): void {this.webFonts.setEnabled(settings)+ this.forgetFamilyFaces()+ }++ /** The system fonts a desktop host lists, by family, with the style names of their faces. */+ setHostFontCatalog(fonts: readonly { family: string; styles: readonly string[] }[]): void {+ this.hostStyles = new Map(fonts.map((font) => [font.family, [...font.styles]]))+ this.forgetFamilyFaces()+ }++ /**+ * The faces a family has: its installed fonts', else a web provider's, else the bundled ones;+ * `null` when nothing says, so a caller offers every weight.+ */+ familyFaces(family: string): Promise<FamilyFace[] | null> {+ let load = this.familyFaceLoads.get(family)+ if (!load) {+ const pending = this.loadFamilyFaces(family).then((faces) => {+ // Faces forgotten while the lookup ran came from the sources it read before.+ if (this.familyFaceLoads.get(family) === pending) this.knownFamilyFaces.set(family, faces)+ return faces+ })+ load = pending+ this.familyFaceLoads.set(family, load)+ }+ return load+ }++ /** The faces `familyFaces` found for a family, once it has; `undefined` before. */+ loadedFamilyFaces(family: string): FamilyFace[] | null | undefined {+ return this.knownFamilyFaces.get(family)+ }++ /** Whether a family has this face, or nothing found so far says it has not. */+ offersFace(family: string, weight: number, italic: boolean): boolean {+ const faces = this.knownFamilyFaces.get(family)+ return !faces || hasFamilyFace(faces, weight, italic)+ }++ /**+ * Calls the listener whenever the faces found so far are forgotten, as when the host's font+ * catalog arrives or online providers change, so a caller asks for its families again.+ */+ onFamilyFacesReset(listener: () => void): () => void {+ this.familyFacesListeners.add(listener)+ return () => this.familyFacesListeners.delete(listener)+ }++ private async loadFamilyFaces(family: string): Promise<FamilyFace[] | null> {+ const installed =+ this.hostStyles.get(family) ??+ this.localFonts?.filter((font) => font.family === family).map((font) => font.style) ??+ []+ if (installed.length > 0) return facesFromStyles(installed)+ const web = await this.webFonts.familyFaces(family)+ if (web.length > 0) return web+ const bundled = Object.keys(BUNDLED_FONTS)+ .filter((key) => key.startsWith(`${family}|`))+ .map((key) => key.slice(family.length + 1))+ return bundled.length > 0 ? facesFromStyles(bundled) : null+ }++ private forgetFamilyFaces(): void {+ this.familyFaceLoads.clear()+ this.knownFamilyFaces.clear()+ for (const listener of this.familyFacesListeners) listener()}setWebFontFetch(fetcher: WebFontFetch | null): void {@@ -195,6 +265,7 @@ export class FontManager {}this.localFonts = resultthis.localFontAccessState = 'granted'+ this.forgetFamilyFaces()return result} catch {this.localFonts = []diff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.tsindex 0869fd643..98a83d518 100644--- a/packages/core/src/text/index.ts+++ b/packages/core/src/text/index.ts@@ -11,3 +11,4 @@ export * from './resolved-requirements'export * from './web-fonts'export * from './path'export * from './prepare'+export * from './font/faces'diff --git a/packages/core/src/text/web-fonts.ts b/packages/core/src/text/web-fonts.tsindex 1be0127fd..b3c49e379 100644--- a/packages/core/src/text/web-fonts.ts+++ b/packages/core/src/text/web-fonts.ts@@ -2,6 +2,7 @@ import type { FontFaceData, RemoteFontSource, ResolveFontResult } from 'unifont'import { IS_BROWSER } from '#core/constants'import { parseFontStyle } from '#core/text/face'+import type { FamilyFace } from '#core/text/font/faces'import {createProviderUnifont,isRemoteFontSource,@@ -66,6 +67,30 @@ function preferredRemoteSource(face: FontFaceData): RemoteFontSource | undefined)}+const STANDARD_WEIGHTS = [100, 200, 300, 400, 500, 600, 700, 800, 900]++/** The standard weights a face covers: one, or every one in a variable font's range. */+function faceWeights(weight: FontFaceData['weight']): number[] {+ const bounds = Array.isArray(weight)+ ? weight+ : String(weight ?? 400)+ .trim()+ .split(/\s+/u)+ .map(Number)+ const [min = 400, max = min] = bounds+ return STANDARD_WEIGHTS.filter((value) => value >= min && value <= max)+}++function familyFacesOf(result: ResolveFontResult): FamilyFace[] {+ const faces = new Map<string, FamilyFace>()+ for (const font of result.fonts) {+ const italic = font.style === 'italic' || font.style?.startsWith('oblique') === true+ for (const weight of faceWeights(font.weight))+ faces.set(`${weight}${italic ? 'i' : ''}`, { weight, italic })+ }+ return [...faces.values()]+}+function resolvedRemoteFaces(result: ResolveFontResult): Array<{source: RemoteFontSourceinit?: RequestInit@@ -127,6 +152,7 @@ export class WebFontResolver {)private unifontPromises = new Map<WebFontProviderId, Promise<WebUnifont>>()private familiesCache = new Map<WebFontProviderId, string[]>()+ private facesCache = new Map<string, Promise<FamilyFace[]>>()private familiesPromises = new Map<WebFontProviderId, Promise<string[]>>()private failedFonts = new Set<string>()private fontPromises = new Map<string, Promise<ArrayBuffer[]>>()@@ -136,6 +162,7 @@ export class WebFontResolver {setEnabled(settings: Partial<Record<WebFontProviderId, boolean>>): void {this.enabled = new Set(WEB_FONT_PROVIDER_IDS.filter((provider) => settings[provider] === true))this.failedFonts.clear()+ this.facesCache.clear()}setRemoteFetch(fetcher: WebFontFetch | null): void {@@ -143,6 +170,7 @@ export class WebFontResolver {this.unifontPromises.clear()this.familiesPromises.clear()this.familiesCache.clear()+ this.facesCache.clear()this.failedFonts.clear()}@@ -164,6 +192,42 @@ export class WebFontResolver {for (const provider of this.enabledProviders()) void this.listFamilies(provider)}+ /**+ * The faces a family has at the first enabled provider that serves it, or none when no+ * provider does. Asking a provider for every weight in both slants returns only the faces it+ * has, without downloading them.+ */+ familyFaces(family: string): Promise<FamilyFace[]> {+ let faces = this.facesCache.get(family)+ if (!faces) {+ faces = this.loadFamilyFaces(family)+ this.facesCache.set(family, faces)+ }+ return faces+ }++ private async loadFamilyFaces(family: string): Promise<FamilyFace[]> {+ if (typeof fetch === 'undefined' || (IS_BROWSER && !this.remoteFetch)) return []+ for (const provider of this.enabledProviders()) {+ try {+ const unifont = await this.unifont(provider)+ const result = await this.withFetchProxy<ResolveFontResult>(() =>+ unifont.resolveFont(family, {+ weights: STANDARD_WEIGHTS.map(String),+ styles: ['normal', 'italic'],+ formats: ['woff2', 'woff', 'ttf', 'otf']+ })+ )+ const faces = familyFacesOf(result)+ if (faces.length > 0) return faces+ } catch (error) {+ // The next provider may serve the family.+ console.warn(`[fonts] ${provider} could not list the faces of ${family}:`, error)+ }+ }+ return []+ }+async listFamilies(provider: WebFontProviderId): Promise<string[]> {const cached = this.familiesCache.get(provider)if (cached) return cacheddiff --git a/packages/core/tests/text/font/faces.test.ts b/packages/core/tests/text/font/faces.test.tsnew file mode 100644index 000000000..c8a3baf67--- /dev/null+++ b/packages/core/tests/text/font/faces.test.ts@@ -0,0 +1,37 @@+import { expect, test } from 'bun:test'++import { facesFromStyles, nearestFamilyFace } from '@open-pencil/core/text'++// Lora's faces as Figma desktop 126 lists them.+const lora = facesFromStyles([+ 'Regular',+ 'Medium',+ 'SemiBold',+ 'Bold',+ 'Italic',+ 'Medium Italic',+ 'SemiBold Italic',+ 'Bold Italic'+])++test('reads faces from style names, once each', () => {+ expect(facesFromStyles(['Bold', 'Bold', 'Light Italic', 'ExtraLight'])).toEqual([+ { weight: 700, italic: false },+ { weight: 300, italic: true },+ { weight: 200, italic: false }+ ])+})++test('the nearest face keeps the slant, as Figma picks one on a family switch', () => {+ expect(nearestFamilyFace(lora, 100, false)).toEqual({ weight: 400, italic: false })+ expect(nearestFamilyFace(lora, 900, false)).toEqual({ weight: 700, italic: false })+ expect(nearestFamilyFace(lora, 500, true)).toEqual({ weight: 500, italic: true })+ expect(nearestFamilyFace(lora, 900, true)).toEqual({ weight: 700, italic: true })+})++test('a family without the slant gives the nearest weight, and a tie takes the lighter', () => {+ const upright = facesFromStyles(['Regular', 'SemiBold'])+ expect(nearestFamilyFace(upright, 700, true)).toEqual({ weight: 600, italic: false })+ expect(nearestFamilyFace(upright, 500, false)).toEqual({ weight: 400, italic: false })+ expect(nearestFamilyFace([], 400, false)).toBeNull()+})diff --git a/packages/core/tests/text/fonts.test.ts b/packages/core/tests/text/fonts.test.tsnew file mode 100644index 000000000..cf189ee58--- /dev/null+++ b/packages/core/tests/text/fonts.test.ts@@ -0,0 +1,32 @@+import { expect, test } from 'bun:test'++import { FontManager } from '@open-pencil/core/text'++/** A font manager that asks no web provider, so a family's faces come from its catalog. */+function offlineManager() {+ const manager = new FontManager()+ manager.setOnlineFontProviders({})+ return manager+}++test('a face lookup that outlives a new catalog does not overwrite what the catalog says', async () => {+ const manager = offlineManager()+ const before = manager.familyFaces('Oswald')+ manager.setHostFontCatalog([{ family: 'Oswald', styles: ['Regular', 'Bold'] }])+ expect(await before).toBeNull()+ expect(manager.loadedFamilyFaces('Oswald')).toBeUndefined()+ expect(await manager.familyFaces('Oswald')).toEqual([+ { weight: 400, italic: false },+ { weight: 700, italic: false }+ ])+})++test('a new catalog tells listeners to ask for their families again', () => {+ const manager = offlineManager()+ let resets = 0+ const stop = manager.onFamilyFacesReset(() => resets++)+ manager.setHostFontCatalog([{ family: 'Oswald', styles: ['Regular'] }])+ stop()+ manager.setHostFontCatalog([])+ expect(resets).toBe(1)+})diff --git a/packages/docs/programmable/sdk/api/composables/use-typography.md b/packages/docs/programmable/sdk/api/composables/use-typography.mdindex 938bb5876..0ed55c6c0 100644--- a/packages/docs/programmable/sdk/api/composables/use-typography.md+++ b/packages/docs/programmable/sdk/api/composables/use-typography.md@@ -12,7 +12,7 @@ of them in one undo step, so a selection of text and other layers edits only theIt exposes:- font family-- font weight+- font weight, and `weights`: the weights the selected layers' families have, read from installed fonts and web font providers, every weight while a family's faces are unknown- font size- formatting state- missing-font status@@ -66,6 +66,8 @@ const typography = useTypography({### Toggle formatting+As in Figma, a family switch keeps each layer's weight and slant where the new family has them, otherwise the nearest weight with the same slant, and `toggleBold` or `toggleItalic` leave a layer alone when its family has no such face.+```tstypography.toggleBold()typography.toggleItalic()diff --git a/packages/vue/src/canvas/text-edit/formatting.ts b/packages/vue/src/canvas/text-edit/formatting.tsindex deb4de8b2..e7d90e208 100644--- a/packages/vue/src/canvas/text-edit/formatting.ts+++ b/packages/vue/src/canvas/text-edit/formatting.ts@@ -1,5 +1,7 @@import type { Editor } from '@open-pencil/core/editor'import {+ fontManager,+ getStyleAt,toggleBoldInRange,toggleDecorationInRange,toggleItalicInRange@@ -14,6 +16,22 @@ export function createTextFormattingActions(store: Editor) {store.requestRender()}+ /** Whether the family has the face every character in the range takes with these runs. */+ function rangeOffersFaces(+ node: SceneNode,+ runs: SceneNode['styleRuns'],+ [start, end]: [number, number]+ ) {+ for (let index = start; index < end; index++) {+ const style = getStyleAt(runs, index)+ const weight = style.fontWeight ?? node.fontWeight+ if (!fontManager.offersFace(node.fontFamily, weight, style.italic ?? node.italic))+ return false+ }+ return true+ }++ // A family without the face the toggle would set is left as it is, as in Figma.function toggleBold(node: SceneNode) {const editor = store.textEditorconst range = editor?.getSelectionRange()@@ -25,9 +43,12 @@ export function createTextFormattingActions(store: Editor) {node.fontWeight,node.text.length)+ if (!rangeOffersFaces(node, runs, range)) returnapplyFormatting(node.id, { styleRuns: runs }, 'Toggle bold')} else {- applyFormatting(node.id, { fontWeight: node.fontWeight >= 700 ? 400 : 700 }, 'Toggle bold')+ const fontWeight = node.fontWeight >= 700 ? 400 : 700+ if (!fontManager.offersFace(node.fontFamily, fontWeight, node.italic)) return+ applyFormatting(node.id, { fontWeight }, 'Toggle bold')}}@@ -42,8 +63,10 @@ export function createTextFormattingActions(store: Editor) {node.italic,node.text.length)+ if (!rangeOffersFaces(node, runs, range)) returnapplyFormatting(node.id, { styleRuns: runs }, 'Toggle italic')} else {+ if (!fontManager.offersFace(node.fontFamily, node.fontWeight, !node.italic)) returnapplyFormatting(node.id, { italic: !node.italic }, 'Toggle italic')}}diff --git a/packages/vue/src/controls/typography/actions.ts b/packages/vue/src/controls/typography/actions.tsindex 416373de9..6c95bd122 100644--- a/packages/vue/src/controls/typography/actions.ts+++ b/packages/vue/src/controls/typography/actions.ts@@ -2,7 +2,12 @@ import { computed } from 'vue'import type { ComputedRef } from 'vue'import type { Editor } from '@open-pencil/core/editor'-import { FONT_WEIGHT_NAMES, weightToStyle } from '@open-pencil/core/text'+import {+ FONT_WEIGHT_NAMES,+ fontManager,+ nearestFamilyFace,+ weightToStyle+} from '@open-pencil/core/text'import type {SceneNode,TextDecoration,@@ -17,6 +22,7 @@ import {paragraphSpacingOf} from '#vue/canvas/text-edit/paragraphs'import { MIXED, type MixedValue } from '#vue/controls/node-props/use'+import { useFamilyFaces } from '#vue/controls/typography/faces'import type { UseTypographyOptions } from '#vue/controls/typography/use'import { selectedNodesAsShown } from '#vue/editor/selection-state/nodes'import { useSceneComputed } from '#vue/internal/scene-computed/use'@@ -28,11 +34,6 @@ type TextVerticalAlign = SceneNode['textAlignVertical']type TextCase = SceneNode['textCase']type TextTruncation = SceneNode['textTruncation']-export const TYPOGRAPHY_WEIGHTS = Object.entries(FONT_WEIGHT_NAMES).map(([value, label]) => ({- value: Number(value),- label-}))-function sharedValue<T>(values: readonly T[]): MixedValue<T> {const [first] = valuesreturn values.every((value) => value === first) ? first : MIXED@@ -66,6 +67,7 @@ export function createTypographyState(editor: Editor) {() => FONT_WEIGHT_NAMES[node.value?.fontWeight ?? 400] ?? 'Regular')const activeFormatting = computed(() => sharedFormatting(nodes.value))+ const { weights, supports } = useFamilyFaces(nodes)/*** The list style every selected text shares, or that of the paragraphs being edited; `null`* when they differ.@@ -108,6 +110,8 @@ export function createTypographyState(editor: Editor) {currentWeightLabel,activeFormatting,listType,+ weights,+ supports,missingFonts,hasMissingFonts}@@ -117,6 +121,8 @@ type TypographyActionOptions = {editor: Editornodes: ComputedRef<SceneNode[]>activeFormatting: ComputedRef<string[]>+ /** Whether a layer's family has a face; true when nothing says it has not. */+ supports: (node: SceneNode, weight: number, italic: boolean) => booleanoptions: UseTypographyOptions}@@ -124,6 +130,7 @@ export function createTypographyActions({editor,nodes,activeFormatting,+ supports,options}: TypographyActionOptions) {const lists = createTextListActions(editor)@@ -151,41 +158,64 @@ export function createTypographyActions({const latestLoadingRequest = new Map<string, symbol>()/**- * Applies a change once its faces have loaded, to the layers selected when it was asked for:- * the selection may change while the load is pending, and a layer may be deleted.+ * Applies each layer's change once its face has loaded, to the layers selected when it was+ * asked for: the selection may change while the load is pending, and a layer may be deleted.+ * `prepare` loads a layer's face and returns its change, or null to leave the layer alone.*/async function updateAfterLoading(label: string,- changes: Partial<SceneNode>,- load: (target: SceneNode) => Promise<unknown> | undefined+ fields: readonly (keyof SceneNode)[],+ prepare: (target: SceneNode) => Promise<Partial<SceneNode> | null>,+ targets = nodes.value) {- const targets = nodes.valueif (targets.length === 0) returnconst request = Symbol(label)- const keys = (target: SceneNode) => Object.keys(changes).map((field) => `${target.id}:${field}`)+ const keys = (target: SceneNode) => fields.map((field) => `${target.id}:${field}`)for (const target of targets)for (const key of keys(target)) latestLoadingRequest.set(key, request)- await Promise.all(targets.map(load))+ const changes = await Promise.all(targets.map(prepare))// A later choice for the same field wins, even when its face loaded first.const current = targets.filter((target) =>keys(target).every((key) => latestLoadingRequest.get(key) === request))for (const target of current) for (const key of keys(target)) latestLoadingRequest.delete(key)- const live = current.filter((target) => editor.graph.getNode(target.id))- updateEach(label, () => changes, live)+ const changed = new Map(targets.map((target, index) => [target.id, changes[index]]))+ const live = current.filter(+ (target) => editor.graph.getNode(target.id) && changed.get(target.id)+ )+ updateEach(label, (target) => changed.get(target.id) ?? {}, live)}+ /**+ * Keeps each layer's weight and slant where the family has them, otherwise takes the nearest+ * face, as Figma does: Black goes to Bold in a family that ends at Bold.+ */async function setFamily(family: string) {- await updateAfterLoading('Change font', { fontFamily: family }, (target) =>- options.fontLoader?.load(family, FONT_WEIGHT_NAMES[target.fontWeight] ?? 'Regular')+ const faces = fontManager.familyFaces(family)+ await updateAfterLoading(+ 'Change font',+ ['fontFamily', 'fontWeight', 'italic'],+ async (target) => {+ const known = await faces+ const face = known ? nearestFamilyFace(known, target.fontWeight, target.italic) : null+ const fontWeight = face?.weight ?? target.fontWeight+ const italic = face?.italic ?? target.italic+ await options.fontLoader?.load(family, weightToStyle(fontWeight, italic))+ return { fontFamily: family, fontWeight, italic }+ })}/** Loads the face first, as for a family, so the text is laid out once with it. */- async function setWeight(weight: number) {- const style = weightToStyle(weight)- await updateAfterLoading('Change font weight', { fontWeight: weight }, (target) =>- options.fontLoader?.load(target.fontFamily, style)+ async function setWeight(weight: number, targets = nodes.value) {+ await updateAfterLoading(+ 'Change font weight',+ ['fontWeight'],+ async (target) => {+ await options.fontLoader?.load(target.fontFamily, weightToStyle(weight, target.italic))+ return { fontWeight: weight }+ },+ targets)}@@ -284,14 +314,29 @@ export function createTypographyActions({update('Change hanging lists', { hangingList })}- /** Bold unless every text layer already is, as Figma's toggle does for a mixed selection. */+ /**+ * Bold unless every text layer already is, as Figma's toggle does for a mixed selection. A layer+ * whose family has no such face is left alone, as Figma leaves it.+ */function toggleBold() {- const bold = activeFormatting.value.includes('bold')- void setWeight(bold ? 400 : 700)+ const weight = activeFormatting.value.includes('bold') ? 400 : 700+ void setWeight(+ weight,+ nodes.value.filter((target) => supports(target, weight, target.italic))+ )}function toggleItalic() {- update('Toggle italic', { italic: !activeFormatting.value.includes('italic') })+ const italic = !activeFormatting.value.includes('italic')+ void updateAfterLoading(+ 'Toggle italic',+ ['italic'],+ async (target) => {+ await options.fontLoader?.load(target.fontFamily, weightToStyle(target.fontWeight, italic))+ return { italic }+ },+ nodes.value.filter((target) => supports(target, target.fontWeight, italic))+ )}function toggleDecoration(deco: 'UNDERLINE' | 'STRIKETHROUGH') {diff --git a/packages/vue/src/controls/typography/faces.ts b/packages/vue/src/controls/typography/faces.tsnew file mode 100644index 000000000..6009497ec--- /dev/null+++ b/packages/vue/src/controls/typography/faces.ts@@ -0,0 +1,52 @@+import { uniq } from 'es-toolkit'+import { computed, onScopeDispose, ref, watch, type ComputedRef } from 'vue'++import { fontManager } from '@open-pencil/core/text'+import type { SceneNode } from '@open-pencil/scene-graph'++import { TYPOGRAPHY_WEIGHTS } from '#vue/controls/typography/weights'++/**+ * The faces of the selected text layers' families, read as they arrive. A family whose faces are+ * not known yet, or cannot be, offers every weight, as Figma shows a generic style list for a+ * family it cannot read.+ */+export function useFamilyFaces(nodes: ComputedRef<SceneNode[]>) {+ // Bumped when a family's faces arrive, so the lists that read them follow.+ const arrived = ref(0)+ const families = computed(() => uniq(nodes.value.map((node) => node.fontFamily)))+ function request(current: readonly string[]) {+ for (const family of current) {+ if (fontManager.loadedFamilyFaces(family) !== undefined) continue+ void fontManager.familyFaces(family).then(() => arrived.value++)+ }+ }+ watch(families, request, { immediate: true })+ // The host's font catalog can arrive after a first lookup; ask again with it.+ onScopeDispose(+ fontManager.onFamilyFacesReset(() => {+ arrived.value+++ request(families.value)+ })+ )++ /** Whether a layer's family has this face, or nothing says it has not. */+ function supports(node: SceneNode, weight: number, italic: boolean): boolean {+ void arrived.value+ return fontManager.offersFace(node.fontFamily, weight, italic)+ }++ /**+ * The weights every selected layer's family has at that layer's slant, and the weights the+ * layers already use, so the field still names one their family lacks.+ */+ const weights = computed(() =>+ TYPOGRAPHY_WEIGHTS.filter(+ ({ value }) =>+ nodes.value.some((node) => node.fontWeight === value) ||+ nodes.value.every((node) => supports(node, value, node.italic))+ )+ )++ return { weights, supports }+}diff --git a/packages/vue/src/controls/typography/use.ts b/packages/vue/src/controls/typography/use.tsindex a80f4dcdd..466ec5122 100644--- a/packages/vue/src/controls/typography/use.ts+++ b/packages/vue/src/controls/typography/use.ts@@ -1,8 +1,4 @@-import {- TYPOGRAPHY_WEIGHTS,- createTypographyActions,- createTypographyState-} from '#vue/controls/typography/actions'+import { createTypographyActions, createTypographyState } from '#vue/controls/typography/actions'import { useEditor } from '#vue/editor/context'/**@@ -32,7 +28,6 @@ export function useTypography(options: UseTypographyOptions = {}) {return {editor,...typographyState,- weights: TYPOGRAPHY_WEIGHTS,...actions}}diff --git a/packages/vue/src/controls/typography/weights.ts b/packages/vue/src/controls/typography/weights.tsnew file mode 100644index 000000000..445e1be5a--- /dev/null+++ b/packages/vue/src/controls/typography/weights.ts@@ -0,0 +1,7 @@+import { FONT_WEIGHT_NAMES } from '@open-pencil/core/text'++/** The standard weights by value, Thin 100 to Black 900, named as Figma names them. */+export const TYPOGRAPHY_WEIGHTS = Object.entries(FONT_WEIGHT_NAMES).map(([value, label]) => ({+ value: Number(value),+ label+}))diff --git a/packages/vue/src/primitives/FontPicker/useFontPicker.ts b/packages/vue/src/primitives/FontPicker/useFontPicker.tsindex 35f855459..bf24db653 100644--- a/packages/vue/src/primitives/FontPicker/useFontPicker.ts+++ b/packages/vue/src/primitives/FontPicker/useFontPicker.ts@@ -1,4 +1,5 @@import { tryOnScopeDispose, watchImmediate } from '@vueuse/core'+import { sortBy } from 'es-toolkit'import { useFilter } from 'reka-ui'import { computed, ref, watch } from 'vue'@@ -58,10 +59,18 @@ export function useFontPicker(options: UseFontPickerOptions) {)tryOnScopeDispose(cancelLoad)- const { contains } = useFilter({ sensitivity: 'base' })+ const { contains, startsWith } = useFilter({ sensitivity: 'base' })+ /** 0 for the family the search names, 1 for one it begins, 2 for any other match. */+ function rank(family: string, term: string): number {+ if (!startsWith(family, term)) return 2+ return family.length === term.length ? 0 : 1+ }+ // Figma lists the family a search names first: "Lora" gives Lora, then Explora.const filtered = computed(() => {- if (!searchTerm.value) return families.value- return families.value.filter((option) => contains(option.family, searchTerm.value))+ const term = searchTerm.value.trim()+ if (!term) return families.value+ const matches = families.value.filter((option) => contains(option.family, term))+ return sortBy(matches, [(option) => rank(option.family, term)])})async function loadFamilies() {diff --git a/packages/vue/tests/controls/typography.test.ts b/packages/vue/tests/controls/typography.test.tsindex 5ac84be1a..ba8de9592 100644--- a/packages/vue/tests/controls/typography.test.ts+++ b/packages/vue/tests/controls/typography.test.ts@@ -1,10 +1,41 @@-import { expect, test } from 'bun:test'-import { computed, shallowRef } from 'vue'+import { afterAll, beforeAll, expect, test } from 'bun:test'++import { computed, effectScope, nextTick, shallowRef } from 'vue'import { createEditor } from '@open-pencil/core/editor'+import { DEFAULT_WEB_FONT_PROVIDER_SETTINGS, fontManager } from '@open-pencil/core/text'import type { SceneNode } from '@open-pencil/scene-graph'import { createTypographyActions } from '#vue/controls/typography/actions'+import { useFamilyFaces } from '#vue/controls/typography/faces'++// The faces Figma lists for these families (desktop 126), given as installed fonts so no test+// asks a web provider.+const LORA = [+ 'Regular',+ 'Medium',+ 'SemiBold',+ 'Bold',+ 'Italic',+ 'Medium Italic',+ 'SemiBold Italic',+ 'Bold Italic'+]+const OSWALD = ['ExtraLight', 'Light', 'Regular', 'Medium', 'SemiBold', 'Bold']+const CATALOG = [+ { family: 'Lora', styles: LORA },+ { family: 'Oswald', styles: OSWALD }+]++beforeAll(() => {+ fontManager.setOnlineFontProviders({})+ fontManager.setHostFontCatalog(CATALOG)+})++afterAll(() => {+ fontManager.setHostFontCatalog([])+ fontManager.setOnlineFontProviders(DEFAULT_WEB_FONT_PROVIDER_SETTINGS)+})/** Two text layers, the typography actions over a selection, and a font load that waits. */function setup() {@@ -22,6 +53,7 @@ function setup() {editor,nodes: computed(() => selection.value),activeFormatting: computed(() => []),+ supports: () => true,options: { fontLoader: { load: () => loading } }})return { editor, first, second, selection, actions, finishLoading }@@ -46,6 +78,7 @@ test('a later choice wins over an earlier one whose face loads after it', asynceditor,nodes: computed(() => [text]),activeFormatting: computed(() => []),+ supports: () => true,options: {fontLoader: {load: (family) =>@@ -55,11 +88,16 @@ test('a later choice wins over an earlier one whose face loads after it', async}}})+ /** Resolves a family's load once the change has asked for it, after reading its faces. */+ const finish = async (family: string) => {+ for (let tick = 0; tick < 50 && !loads.has(family); tick++) await Promise.resolve()+ loads.get(family)?.()+ }const slow = actions.setFamily('Roboto')const fast = actions.setFamily('Lora')- loads.get('Lora')?.()+ await finish('Lora')await fast- loads.get('Roboto')?.()+ await finish('Roboto')await slowexpect(text.fontFamily).toBe('Lora')})@@ -74,3 +112,72 @@ test('a family chosen while loading skips layers deleted in the meantime', asyncexpect(editor.graph.getNode(second.id)?.fontFamily).toBe('Roboto')expect(editor.graph.getNode(first.id)).toBeUndefined()})++/** Text layers in Inter at these styles, with typography actions and face lists over them. */+function styled(...faces: { fontWeight: number; italic?: boolean; fontFamily?: string }[]) {+ const editor = createEditor()+ const page = editor.state.currentPageId+ const texts = faces.map((face) =>+ editor.graph.createNode('TEXT', page, { text: 'a', fontFamily: 'Inter', ...face })+ )+ const nodes = computed(() => texts)+ const scope = effectScope()+ const lists = scope.run(() => useFamilyFaces(nodes))+ if (!lists) throw new Error('Expected family faces')+ const { weights, supports } = lists+ const actions = createTypographyActions({+ editor,+ nodes,+ activeFormatting: computed(() => []),+ supports,+ options: {}+ })+ return { texts, weights, actions, stop: () => scope.stop() }+}++test('a family switch keeps a face the family has, or takes the nearest weight, as in Figma', async () => {+ const { texts, actions } = styled(+ { fontWeight: 100 },+ { fontWeight: 900 },+ { fontWeight: 500, italic: true },+ { fontWeight: 900, italic: true }+ )+ await actions.setFamily('Lora')+ expect(texts.map((text) => [text.fontFamily, text.fontWeight, text.italic])).toEqual([+ ['Lora', 400, false],+ ['Lora', 700, false],+ ['Lora', 500, true],+ ['Lora', 700, true]+ ])+})++test('the weight list offers only the weights the family has', async () => {+ const { weights } = styled({ fontWeight: 400, fontFamily: 'Oswald' })+ await fontManager.familyFaces('Oswald')+ await nextTick()+ expect(weights.value.map((weight) => weight.value)).toEqual([200, 300, 400, 500, 600, 700])+})++test('italic does nothing on a family without italics, and bold goes to Bold', async () => {+ const { texts, actions } = styled({ fontWeight: 400, fontFamily: 'Oswald' })+ await fontManager.familyFaces('Oswald')+ actions.toggleItalic()+ await Promise.resolve()+ expect(texts[0].italic).toBe(false)+ actions.toggleBold()+ for (let tick = 0; tick < 5; tick++) await Promise.resolve()+ expect(texts[0].fontWeight).toBe(700)+})++test('the weight list follows a font catalog that arrives after the first lookup', async () => {+ const { weights, stop } = styled({ fontWeight: 400, fontFamily: 'Late Sans' })+ await fontManager.familyFaces('Late Sans')+ await nextTick()+ expect(weights.value).toHaveLength(9)+ fontManager.setHostFontCatalog([...CATALOG, { family: 'Late Sans', styles: ['Regular', 'Bold'] }])+ await fontManager.familyFaces('Late Sans')+ await nextTick()+ expect(weights.value.map((weight) => weight.value)).toEqual([400, 700])+ stop()+ fontManager.setHostFontCatalog(CATALOG)+})diff --git a/packages/vue/tests/primitives/FontPicker/useFontPicker.test.ts b/packages/vue/tests/primitives/FontPicker/useFontPicker.test.tsnew file mode 100644index 000000000..a7630a4bc--- /dev/null+++ b/packages/vue/tests/primitives/FontPicker/useFontPicker.test.ts@@ -0,0 +1,21 @@+import { expect, test } from 'bun:test'+import { nextTick, ref } from 'vue'++import { useFontPicker } from '@open-pencil/vue'++test('a search lists the family it names first, then families it begins, as Figma does', async () => {+ const picker = useFontPicker({+ modelValue: ref('Inter'),+ listFamilies: async () => ['Explora', 'Grandiflora One', 'Inter', 'Lora', 'Lora Serif']+ })+ picker.open.value = true+ await nextTick()+ for (let tick = 0; tick < 5 && picker.loading.value; tick++) await Promise.resolve()+ picker.searchTerm.value = 'lora'+ expect(picker.filtered.value.map((option) => option.family)).toEqual([+ 'Lora',+ 'Lora Serif',+ 'Explora',+ 'Grandiflora One'+ ])+})diff --git a/src/app/editor/fonts/index.ts b/src/app/editor/fonts/index.tsindex 302bb91cd..b2bba5f55 100644--- a/src/app/editor/fonts/index.ts+++ b/src/app/editor/fonts/index.ts@@ -81,6 +81,8 @@ async function getTauriFonts(): Promise<TauriFontFamily[]> {.then(({ invoke }) => invoke<TauriFontFamily[]>('list_system_fonts')).then((fonts) => {tauriFontsCache = fonts+ // The weight list and family switches read each family's faces from these.+ fontManager.setHostFontCatalog(fonts)return fonts}).catch(() => [])diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vueindex d21c8870a..c8b490e48 100644--- a/src/components/properties/TypographySection.vue+++ b/src/components/properties/TypographySection.vue@@ -124,7 +124,7 @@ function picked<T>(value: MixedValue<T>): T | '' {<AppSelect:label="panels.fontWeight":model-value="picked(ctx.merged('fontWeight'))"- :options="ctx.weights"+ :options="ctx.weights.value":placeholder="panels.mixed"@update:model-value="ctx.actions.setWeight(+$event)"/>diff --git a/tests/engine/vue/controls/typography-depth.test.ts b/tests/engine/vue/controls/typography-depth.test.tsindex bf1079b53..f70e4bb86 100644--- a/tests/engine/vue/controls/typography-depth.test.ts+++ b/tests/engine/vue/controls/typography-depth.test.ts@@ -20,6 +20,7 @@ describe('typography depth actions', () => {editor,nodes,activeFormatting: computed(() => []),+ supports: () => true,options: {}})@@ -41,6 +42,7 @@ describe('typography depth actions', () => {editor,nodes: computed(() => [editor.graph.getNode(text.id)].filter((node) => node !== undefined)),activeFormatting: computed(() => []),+ supports: () => true,options: {}})@@ -73,6 +75,7 @@ describe('typography depth actions', () => {.filter((node) => node !== undefined)),activeFormatting: computed(() => []),+ supports: () => true,options: {}})