Skip to content

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

feat(core): draw Material Symbols from Google's variable fonts (#1459)

Danila Poyarkov483694bf4a01
diff --git a/bun.lock b/bun.lock
index 637246865..a24ae98a8 100644
--- a/bun.lock
+++ b/bun.lock
@@ -835,6 +835,9 @@
},
},
},
+ "patchedDependencies": {
+ },
"overrides": {
"@codemirror/view": "6.43.9",
"protobufjs": "7.5.5",
diff --git a/changes/1459/added.md b/changes/1459/added.md
new file mode 100644
index 000000000..2f86cc96c
--- /dev/null
+++ b/changes/1459/added.md
@@ -0,0 +1 @@
+- Material Symbols icons draw from Google's variable fonts in the Outlined, Rounded, and Sharp sets, each icon at its own optical size, weight, fill, and grade, and `.pen` files' Material icons import as these icons at pen.dev's weight.
diff --git a/changes/1459/breaking.md b/changes/1459/breaking.md
new file mode 100644
index 000000000..93e8b7c8a
--- /dev/null
+++ b/changes/1459/breaking.md
@@ -0,0 +1 @@
+- `@open-pencil/pen` no longer exports `iconFontFamily`, and `penAssets(doc).icons` lists `{ name, options }` requests, one per way an icon is drawn, instead of icon names; a host loads each with `provider.icons([name], size, options)`.
diff --git a/changes/1459/fixed.md b/changes/1459/fixed.md
new file mode 100644
index 000000000..8419679df
--- /dev/null
+++ b/changes/1459/fixed.md
@@ -0,0 +1 @@
+- Text in some variable fonts keeps its glyph shapes at non-default axes in `.fig` exports, copies pasted into Figma, and PDF exports, instead of drawing misplaced or collapsed contours.
diff --git a/package.json b/package.json
index dbbd481d9..60a35f26b 100644
--- a/package.json
+++ b/package.json
@@ -300,5 +300,8 @@
"protobufjs": "7.5.5",
"websocket-driver": "0.7.5"
},
- "packageManager": "[email protected]"
+ "packageManager": "[email protected]",
+ "patchedDependencies": {
+ }
}
diff --git a/packages/core/src/design-jsx/renderer.ts b/packages/core/src/design-jsx/renderer.ts
index e7e9e9292..e1fbd5462 100644
--- a/packages/core/src/design-jsx/renderer.ts
+++ b/packages/core/src/design-jsx/renderer.ts
@@ -1,6 +1,6 @@
import { createDesignJSXRenderer, type SVGSource } from '@open-pencil/design-jsx'
-import { iconify, placeIcon, type IconProvider } from '#core/icons'
+import { defaultIcons, placeIcon, type IconProvider } from '#core/icons'
import { extractPaths, extractPathsFromElements, scalePathInfos } from '#core/icons/svg'
import type { IconData } from '#core/icons/types'
import { layoutAuthoredNodes } from '#core/layout'
@@ -62,7 +62,7 @@ const renderers = new WeakMap<IconProvider, ReturnType<typeof createRenderer>>()
* Design JSX rendering with OpenPencil's SVG conversion and layout, drawing `<Icon>` from
* `icons`, such as the `FigmaAPI`'s provider, so a host's own icons render too.
*/
-export function designJSXRenderer(icons: IconProvider = iconify) {
+export function designJSXRenderer(icons: IconProvider = defaultIcons) {
let renderer = renderers.get(icons)
if (!renderer) {
renderer = createRenderer(icons)
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index c5d534b4d..2c202db11 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -13,7 +13,7 @@ import {
hasStoredBackground,
setDefaultPageBackground
} from '#core/figma-api/page-backgrounds'
-import { iconify } from '#core/icons'
+import { defaultIcons } from '#core/icons'
import { releaseFigPopulationWorker } from '#core/kiwi/fig/population/client'
import { releaseOriginalFigArchive } from '#core/kiwi/fig/session/original-archive'
import { installTextMeasurer } from '#core/layout'
@@ -259,7 +259,7 @@ export function createEditor(options?: EditorOptions) {
resolveFigmaClipboardImages: options?.resolveFigmaClipboardImages ?? null,
getViewportSize: _getViewportSize,
getUserName: () => options?.getUserName?.() ?? '',
- icons: options?.icons ?? iconify,
+ icons: options?.icons ?? defaultIcons,
getCk: () => _ck,
getRenderer: () => _renderer,
getRenderers: () => _renderers,
diff --git a/packages/core/src/editor/icons.ts b/packages/core/src/editor/icons.ts
index 489ac2dbe..e054fa205 100644
--- a/packages/core/src/editor/icons.ts
+++ b/packages/core/src/editor/icons.ts
@@ -1,11 +1,12 @@
import type { SceneNode } from '@open-pencil/scene-graph'
import { BLACK } from '@open-pencil/scene-graph/constants'
-import { readIcon } from '@open-pencil/scene-graph/icons'
+import { readIcon, type IconOptions } from '@open-pencil/scene-graph/icons'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { restoreSubtree, snapshotSubtree } from '#core/editor/history/subtree'
import type { EditorContext } from '#core/editor/types'
import { pushCreatedSubtreesUndo } from '#core/editor/undo'
+import { parseIconName } from '#core/icons/provider'
import { detachIcon, placeIcon, recolorIcon, swapIcon } from '#core/icons/render'
import type { IconData } from '#core/icons/types'
@@ -17,8 +18,8 @@ const ICON_SIZE = 24
* so inserting and swapping record the frame's whole subtree and swap between the copies.
*/
export function createIconActions(ctx: EditorContext) {
- async function fetchIcon(name: string, size: number): Promise<IconData> {
- const icon = (await ctx.icons.icons([name], size)).get(name)
+ async function fetchIcon(name: string, size: number, options?: IconOptions): Promise<IconData> {
+ const icon = (await ctx.icons.icons([name], size, options)).get(name)
if (!icon || icon.paths.length === 0) throw new Error(`Icon "${name}" not found`)
return icon
}
@@ -74,26 +75,32 @@ export function createIconActions(ctx: EditorContext) {
}
/** Draws the icon `name` fresh in the icon `frameId`, as one step called `label`. */
- async function drawIcon(label: string, frameId: string, name: string) {
+ async function drawIcon(label: string, frameId: string, name: string, options?: IconOptions) {
const graph = ctx.graph
const frame = graph.getNode(frameId)
if (!frame || !readIcon(frame)) return
- const icon = await fetchIcon(name, Math.min(frame.width, frame.height))
+ const icon = await fetchIcon(name, Math.min(frame.width, frame.height), options)
// The document or the frame may have been replaced while the icon loaded.
if (ctx.graph !== graph || graph.getNode(frameId) !== frame) return
changeIcon(label, frameId, () => swapIcon(graph, frameId, icon))
}
- /** Draws the icon `name` in the icon `frameId`, keeping its size, position, and color. */
+ /**
+ * Draws the icon `name` in the icon `frameId`, keeping its size, position, and color, and how
+ * it is drawn when the new icon is from the same set.
+ */
async function swapIconGlyph(frameId: string, name: string) {
- await drawIcon('Swap icon', frameId, name)
+ const frame = ctx.graph.getNode(frameId)
+ const current = frame && readIcon(frame)
+ const sameSet = current && parseIconName(current.name)?.prefix === parseIconName(name)?.prefix
+ await drawIcon('Swap icon', frameId, name, sameSet ? current.options : undefined)
}
/** Draws the icon `frameId` was placed as afresh, undoing edits to its paths. */
async function resetIcon(frameId: string) {
const frame = ctx.graph.getNode(frameId)
const icon = frame && readIcon(frame)
- if (icon) await drawIcon('Reset icon', frameId, icon.name)
+ if (icon) await drawIcon('Reset icon', frameId, icon.name, icon.options)
}
/** Makes the icon `frameId` plain artwork that keeps its paths; see `detachIcon`. */
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index d8d908b31..68559a781 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -14,7 +14,7 @@ import { booleanOperationPaints, createBooleanOperation } from '#core/editor/str
import { wrapNodes } from '#core/editor/structure/container-wrap'
import { ungroupNode } from '#core/editor/structure/group/ungroup'
import { setDefaultPageBackground } from '#core/figma-api/page-backgrounds'
-import { iconify, type IconProvider } from '#core/icons'
+import { defaultIcons, type IconProvider } from '#core/icons'
import type { RasterCodec } from '#core/io/formats/raster'
import { createSVGNodes } from '#core/io/formats/svg'
import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
@@ -587,7 +587,7 @@ export class FigmaAPI implements NodeProxyHost {
exportImage?: (nodeIds: string[], options: ExportImageOptions) => Promise<Uint8Array | null>
/** Where icon tools search and fetch icons; hosts may pass a self-hosted or bundled set. */
- icons: IconProvider = iconify
+ icons: IconProvider = defaultIcons
rasterCodec?: RasterCodec
/** The document as it was before the current AI run first edited `pageId`, or null if unedited. */
changeBaseline?: (pageId: string) => SceneGraph | null
diff --git a/packages/core/src/icons/index.ts b/packages/core/src/icons/index.ts
index f4422ed78..6cd7ca3ad 100644
--- a/packages/core/src/icons/index.ts
+++ b/packages/core/src/icons/index.ts
@@ -1,4 +1,7 @@
+import { MATERIAL_SYMBOLS_PREFIXES } from './material-symbols/font'
+import { createMaterialSymbolsProvider } from './material-symbols/provider'
import { createIconifyProvider, type IconProvider } from './provider'
+import { createIconSetsProvider } from './sets'
export {
createIconifyProvider,
@@ -15,7 +18,32 @@ export {
swapIcon,
type PlaceIconOptions
} from './render'
-export type { IconCollection, IconData, IconPath, IconSearchResult } from './types'
+export type { IconCollection, IconData, IconOption, IconPath, IconSearchResult } from './types'
+export { createMaterialSymbolsProvider } from './material-symbols/provider'
+export { MATERIAL_SYMBOLS_PREFIXES } from './material-symbols/font'
+export { createIconSetsProvider, type IconSetSource, type IconSetsOptions } from './sets'
-/** The Iconify icons hosts use unless they pass a provider of their own. */
+/** Iconify's icons, every set as Iconify serves it. */
export const iconify: IconProvider = createIconifyProvider()
+
+/** Iconify's copies of Material Symbols: one fixed weight each, without the fonts' axes. */
+const ICONIFY_MATERIAL_SYMBOLS = ['material-symbols', 'material-symbols-light']
+
+/**
+ * Icons from Iconify, with Material Symbols drawn from Google's variable fonts at any of their
+ * axes in place of Iconify's copies. `fetcher` reaches Google, as a host's web fonts do.
+ */
+export function createIconProvider(
+ fetcher: typeof globalThis.fetch = globalThis.fetch
+): IconProvider {
+ return createIconSetsProvider({
+ sources: [
+ { prefixes: MATERIAL_SYMBOLS_PREFIXES, provider: createMaterialSymbolsProvider(fetcher) }
+ ],
+ fallback: iconify,
+ replaced: ICONIFY_MATERIAL_SYMBOLS
+ })
+}
+
+/** The icons hosts use unless they pass a provider of their own. */
+export const defaultIcons: IconProvider = createIconProvider()
diff --git a/packages/core/src/icons/material-symbols/catalogue.ts b/packages/core/src/icons/material-symbols/catalogue.ts
new file mode 100644
index 000000000..c1cb62207
--- /dev/null
+++ b/packages/core/src/icons/material-symbols/catalogue.ts
@@ -0,0 +1,53 @@
+import {
+ MATERIAL_SYMBOLS_PREFIXES,
+ MATERIAL_SYMBOLS_SETS,
+ type MaterialSymbolsPrefix
+} from '#core/icons/material-symbols/font'
+
+/**
+ * Google's Material Symbols repository, where each font's names sit beside it, at a fixed commit so
+ * the names cannot move under a release. jsDelivr serves it to any page, which Google's own icon
+ * catalogue does not. Moving the commit forward lists the icons Google has added since.
+ */
+const REPOSITORY =
+ 'https://cdn.jsdelivr.net/gh/google/material-design-icons@10ecc14790612ca8fd164e3f4ffe9c16fc50d5b7/variablefont'
+
+/** A Material Symbols icon and the sets that draw it. */
+export interface MaterialSymbolsEntry {
+ name: string
+ sets: ReadonlySet<MaterialSymbolsPrefix>
+}
+
+/** The names a set's font draws, from the codepoints list Google publishes with it. */
+async function fetchSetNames(
+ fetcher: typeof globalThis.fetch,
+ prefix: MaterialSymbolsPrefix
+): Promise<string[]> {
+ const file = `${MATERIAL_SYMBOLS_SETS[prefix].replaceAll(' ', '')}[FILL,GRAD,opsz,wght].codepoints`
+ const response = await fetcher(`${REPOSITORY}/${encodeURIComponent(file)}`)
+ if (!response.ok) throw new Error(`Material Symbols answered ${response.status} for ${prefix}`)
+ return (await response.text())
+ .split('\n')
+ .map((line) => line.split(' ')[0])
+ .filter((name) => name !== '')
+}
+
+/** Every Material Symbols icon in name order, with the sets that draw it. */
+export async function fetchMaterialSymbolsCatalogue(
+ fetcher: typeof globalThis.fetch
+): Promise<MaterialSymbolsEntry[]> {
+ const lists = await Promise.all(
+ MATERIAL_SYMBOLS_PREFIXES.map((prefix) => fetchSetNames(fetcher, prefix))
+ )
+ const sets = new Map<string, Set<MaterialSymbolsPrefix>>()
+ MATERIAL_SYMBOLS_PREFIXES.forEach((prefix, index) => {
+ for (const name of lists[index] ?? []) {
+ const drawn = sets.get(name) ?? new Set()
+ drawn.add(prefix)
+ sets.set(name, drawn)
+ }
+ })
+ return [...sets]
+ .map(([name, drawn]) => ({ name, sets: drawn }))
+ .sort((a, b) => a.name.localeCompare(b.name))
+}
diff --git a/packages/core/src/icons/material-symbols/font.ts b/packages/core/src/icons/material-symbols/font.ts
new file mode 100644
index 000000000..c3b2af54b
--- /dev/null
+++ b/packages/core/src/icons/material-symbols/font.ts
@@ -0,0 +1,185 @@
+import * as OpenType from 'opentype.js'
+
+import type { IconOptions } from '@open-pencil/scene-graph/icons'
+import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
+
+import type { IconOption, IconPath } from '#core/icons/types'
+import { sfntFont } from '#core/text/font/woff2'
+import type { OutlineCommand } from '#core/text/opentype'
+
+/** Material Symbols' sets, each one of Google's three fonts. */
+export const MATERIAL_SYMBOLS_PREFIXES = [
+ 'material-symbols-outlined',
+ 'material-symbols-rounded',
+ 'material-symbols-sharp'
+] as const
+
+export type MaterialSymbolsPrefix = (typeof MATERIAL_SYMBOLS_PREFIXES)[number]
+
+/** The font each set is drawn from. */
+export const MATERIAL_SYMBOLS_SETS: Readonly<Record<MaterialSymbolsPrefix, string>> = {
+ 'material-symbols-outlined': 'Material Symbols Outlined',
+ 'material-symbols-rounded': 'Material Symbols Rounded',
+ 'material-symbols-sharp': 'Material Symbols Sharp'
+}
+
+export function isMaterialSymbolsPrefix(prefix: string): prefix is MaterialSymbolsPrefix {
+ return MATERIAL_SYMBOLS_PREFIXES.some((known) => known === prefix)
+}
+
+/** The axes Google serves Material Symbols with, as the icon's options, in its request order. */
+export const MATERIAL_SYMBOLS_OPTIONS = [
+ { key: 'opsz', name: 'Optical size', min: 20, max: 48, default: 24, step: 1 },
+ { key: 'wght', name: 'Weight', min: 100, max: 700, default: 400, step: 1 },
+ { key: 'FILL', name: 'Fill', min: 0, max: 1, default: 0, step: 1 },
+ { key: 'GRAD', name: 'Grade', min: -50, max: 200, default: 0, step: 1 }
+] as const satisfies readonly IconOption[]
+
+interface LigatureSubtable {
+ coverage?: { glyphs?: number[]; ranges?: { start: number; end: number; index: number }[] }
+ ligatureSets?: { ligGlyph: number; components: number[] }[][]
+ extension?: LigatureSubtable
+}
+
+/** What drawing Material Symbols reads of a font parsed by opentype.js, which ships no types. */
+export interface MaterialSymbolsFont {
+ charToGlyphIndex(character: string): number
+ glyphs: {
+ get(index: number): {
+ getPath(
+ x: number,
+ y: number,
+ fontSize: number,
+ options: { variation: Record<string, number> },
+ font: MaterialSymbolsFont
+ ): { commands: OutlineCommand[] }
+ }
+ }
+ tables: { gsub?: { lookups: { subtables: LigatureSubtable[] }[] } }
+}
+
+interface OpenTypeModule {
+ parse(buffer: ArrayBuffer): MaterialSymbolsFont
+}
+
+const CSS_API = 'https://fonts.googleapis.com/css2'
+/** Google serves variable fonts as WOFF2, and only to clients that say they read it. */
+const WOFF2_USER_AGENT =
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
+
+/** Every option set, each clamped to its axis and defaulted where `options` leaves it out. */
+export function materialSymbolsOptions(options: IconOptions = {}): Record<string, number> {
+ return Object.fromEntries(
+ MATERIAL_SYMBOLS_OPTIONS.map(({ key, min, max, default: fallback }) => {
+ const value = options[key]
+ return [key, typeof value === 'number' ? Math.min(max, Math.max(min, value)) : fallback]
+ })
+ )
+}
+
+/** A Material Symbols font holding just `names`, every axis variable, as Google cuts it. */
+export async function fetchMaterialSymbolsFont(
+ fetcher: typeof globalThis.fetch,
+ prefix: MaterialSymbolsPrefix,
+ names: readonly string[]
+): Promise<MaterialSymbolsFont> {
+ const axes = MATERIAL_SYMBOLS_OPTIONS.map((option) => option.key).join(',')
+ const ranges = MATERIAL_SYMBOLS_OPTIONS.map((option) => `${option.min}..${option.max}`).join(',')
+ const query = new URLSearchParams({
+ family: `${MATERIAL_SYMBOLS_SETS[prefix]}:${axes}@${ranges}`,
+ // Google wants the names sorted.
+ icon_names: [...names].sort().join(',')
+ })
+ const css = await fetcher(`${CSS_API}?${query}`, { headers: { 'user-agent': WOFF2_USER_AGENT } })
+ if (!css.ok) throw new Error(`Google Fonts answered ${css.status} for ${prefix}`)
+ const url = /src:\s*url\((https:[^)]+)\)/.exec(await css.text())?.[1]
+ if (!url) throw new Error(`Google Fonts served no font for ${prefix}`)
+ const file = await fetcher(url)
+ if (!file.ok) throw new Error(`Google Fonts answered ${file.status} for ${url}`)
+ return (OpenType as OpenTypeModule).parse(await sfntFont(await file.arrayBuffer()))
+}
+
+/** Where `glyph` stands in a coverage table, or -1 when the table does not cover it. */
+function coverageIndex(coverage: LigatureSubtable['coverage'], glyph: number): number {
+ const listed = coverage?.glyphs?.indexOf(glyph) ?? -1
+ if (listed !== -1) return listed
+ const range = coverage?.ranges?.find((item) => glyph >= item.start && glyph <= item.end)
+ return range ? range.index + glyph - range.start : -1
+}
+
+/**
+ * The glyph a Material Symbols name draws: the ligature its letters form. The fonts keep their
+ * ligatures in an extension lookup, which opentype.js parses but does not apply, so the lookup is
+ * read here.
+ */
+export function materialSymbolsGlyph(font: MaterialSymbolsFont, name: string): number | null {
+ const letters = Array.from(name, (character) => font.charToGlyphIndex(character))
+ const [first, ...rest] = letters
+ for (const lookup of font.tables.gsub?.lookups ?? []) {
+ for (const table of lookup.subtables) {
+ const subtable = table.extension ?? table
+ const set = subtable.ligatureSets?.[coverageIndex(subtable.coverage, first)]
+ const ligature = set?.find(
+ (item) =>
+ item.components.length === rest.length &&
+ item.components.every((component, index) => component === rest[index])
+ )
+ if (ligature) return ligature.ligGlyph
+ }
+ }
+ return null
+}
+
+/**
+ * A glyph's outline as SVG path data in a `size` square: the font's em square, whose top is one
+ * em above the baseline, with the glyph at `axes`.
+ */
+export function materialSymbolsPathData(
+ font: MaterialSymbolsFont,
+ glyph: number,
+ size: number,
+ axes: Record<string, number>
+): string {
+ const path = font.glyphs.get(glyph).getPath(0, size, size, { variation: axes }, font)
+ return closedPathData(path.commands)
+}
+
+const coordinate = (value: number | undefined) => Number((value ?? 0).toFixed(3))
+
+/**
+ * Commands as SVG path data with every contour closed. TrueType contours always are, but
+ * opentype.js leaves the close out of a glyph it draws at variation axes, and an open contour
+ * fills on its own rather than cutting the holes its direction cuts.
+ */
+function closedPathData(commands: readonly OutlineCommand[]): string {
+ const parts: string[] = []
+ let open = false
+ for (const command of commands) {
+ if (command.type === 'Z') continue
+ if (command.type === 'M' && open) parts.push('Z')
+ const points = [command.x1, command.y1, command.x2, command.y2].filter(
+ (value) => value !== undefined
+ )
+ parts.push(`${command.type}${[...points, command.x, command.y].map(coordinate).join(' ')}`)
+ open = true
+ }
+ if (open) parts.push('Z')
+ return parts.join('')
+}
+
+/** A glyph as an icon path filling a `size` square, painted in the icon's color. */
+export function materialSymbolsPath(
+ font: MaterialSymbolsFont,
+ glyph: number,
+ size: number,
+ axes: Record<string, number>
+): IconPath {
+ return {
+ vectorNetwork: parseSVGPath(materialSymbolsPathData(font, glyph, size, axes), 'NONZERO'),
+ fill: 'currentColor',
+ stroke: null,
+ strokeWidth: 0,
+ strokeCap: 'butt',
+ strokeJoin: 'miter'
+ }
+}
diff --git a/packages/core/src/icons/material-symbols/provider.ts b/packages/core/src/icons/material-symbols/provider.ts
new file mode 100644
index 000000000..0882bf47e
--- /dev/null
+++ b/packages/core/src/icons/material-symbols/provider.ts
@@ -0,0 +1,189 @@
+import type { IconOptions } from '@open-pencil/scene-graph/icons'
+
+import {
+ fetchMaterialSymbolsCatalogue,
+ type MaterialSymbolsEntry
+} from '#core/icons/material-symbols/catalogue'
+import {
+ fetchMaterialSymbolsFont,
+ isMaterialSymbolsPrefix,
+ MATERIAL_SYMBOLS_OPTIONS,
+ MATERIAL_SYMBOLS_PREFIXES,
+ MATERIAL_SYMBOLS_SETS,
+ materialSymbolsGlyph,
+ materialSymbolsOptions,
+ materialSymbolsPath,
+ materialSymbolsPathData,
+ type MaterialSymbolsFont,
+ type MaterialSymbolsPrefix
+} from '#core/icons/material-symbols/font'
+import { parseIconName, type IconProvider } from '#core/icons/provider'
+import type { IconCollection, IconData } from '#core/icons/types'
+
+/** The size previews are drawn at, which their SVG scales. */
+const PREVIEW_SIZE = 24
+/** Names asked of Google at once, which its URL limit holds comfortably. */
+const NAMES_PER_FONT = 150
+
+/** The sets a search looks in: the one asked for when it is ours, every one when none is. */
+function searchedSets(prefix: string | undefined): readonly MaterialSymbolsPrefix[] {
+ if (!prefix) return MATERIAL_SYMBOLS_PREFIXES
+ return isMaterialSymbolsPrefix(prefix) ? [prefix] : []
+}
+
+/** A loaded icon: the font that holds it and its glyph there. */
+interface LoadedGlyph {
+ font: MaterialSymbolsFont
+ glyph: number
+}
+
+/**
+ * Material Symbols, drawn from Google's variable fonts at any of their axes: each font is asked
+ * for just the icons wanted, and each icon's options are the axes it is drawn at. The catalogue,
+ * for searching and browsing, comes from Google too, and is loaded the first time it is needed.
+ */
+export function createMaterialSymbolsProvider(
+ fetcher: typeof globalThis.fetch = globalThis.fetch
+): IconProvider {
+ let catalogue: Promise<MaterialSymbolsEntry[]> | null = null
+ const loaded = new Map<string, LoadedGlyph | null>()
+ const pending = new Map<string, Promise<void>>()
+
+ function entries(): Promise<MaterialSymbolsEntry[]> {
+ catalogue ??= fetchMaterialSymbolsCatalogue(fetcher)
+ // A failed catalogue is asked for again next time.
+ catalogue.catch(() => {
+ catalogue = null
+ })
+ return catalogue
+ }
+
+ async function fetchGlyphs(prefix: MaterialSymbolsPrefix, names: string[]): Promise<void> {
+ const font = await fetchMaterialSymbolsFont(fetcher, prefix, names)
+ for (const name of names) {
+ const glyph = materialSymbolsGlyph(font, name)
+ loaded.set(`${prefix}:${name}`, glyph === null ? null : { font, glyph })
+ }
+ }
+
+ /**
+ * Loads the fonts holding `names`, one request per set for the names not yet loaded. A font
+ * that fails leaves its names out; only when every one fails does loading fail.
+ */
+ async function load(names: readonly string[]): Promise<void> {
+ const waiting = new Set<Promise<void>>()
+ const wanted = new Map<MaterialSymbolsPrefix, string[]>()
+ for (const name of names) {
+ const parsed = parseIconName(name)
+ if (!parsed || !isMaterialSymbolsPrefix(parsed.prefix) || loaded.has(name)) continue
+ const request = pending.get(name)
+ if (request) waiting.add(request)
+ else wanted.set(parsed.prefix, [...(wanted.get(parsed.prefix) ?? []), parsed.iconName])
+ }
+ for (const [prefix, iconNames] of wanted) {
+ for (let start = 0; start < iconNames.length; start += NAMES_PER_FONT) {
+ const part = iconNames.slice(start, start + NAMES_PER_FONT)
+ const request = fetchGlyphs(prefix, part)
+ const keys = part.map((iconName) => `${prefix}:${iconName}`)
+ for (const key of keys) pending.set(key, request)
+ const settle = () => {
+ for (const key of keys) if (pending.get(key) === request) pending.delete(key)
+ }
+ void request.then(settle, settle)
+ waiting.add(request)
+ }
+ }
+ const settled = await Promise.allSettled(waiting)
+ const failed = settled.find((result) => result.status === 'rejected')
+ if (failed && settled.every((result) => result.status === 'rejected')) throw failed.reason
+ }
+
+ function iconData(name: string, size: number, options: IconOptions): IconData | null {
+ const glyph = loaded.get(name)
+ const parsed = parseIconName(name)
+ if (!glyph || !parsed) return null
+ const axes = materialSymbolsOptions(options)
+ return {
+ prefix: parsed.prefix,
+ name: parsed.iconName,
+ width: size,
+ height: size,
+ paths: [materialSymbolsPath(glyph.font, glyph.glyph, size, axes)],
+ options: axes
+ }
+ }
+
+ return {
+ async search(query, options = {}) {
+ const term = query.trim().toLowerCase().replace(/\s+/g, '_')
+ const prefixes = searchedSets(options.prefix)
+ const found: string[] = []
+ for (const entry of await entries()) {
+ if (!entry.name.includes(term)) continue
+ for (const prefix of prefixes)
+ if (entry.sets.has(prefix)) found.push(`${prefix}:${entry.name}`)
+ }
+ const icons = found.slice(0, options.limit ?? found.length)
+ const collections = Object.fromEntries(
+ prefixes.map((prefix) => [
+ prefix,
+ {
+ name: MATERIAL_SYMBOLS_SETS[prefix],
+ total: icons.filter((name) => name.startsWith(`${prefix}:`)).length
+ }
+ ])
+ )
+ return { icons, total: icons.length, collections }
+ },
+
+ async collections(): Promise<IconCollection[]> {
+ const listed = await entries()
+ return MATERIAL_SYMBOLS_PREFIXES.map((prefix) => ({
+ prefix,
+ name: MATERIAL_SYMBOLS_SETS[prefix],
+ total: listed.filter((entry) => entry.sets.has(prefix)).length,
+ category: 'Material',
+ license: 'Apache 2.0',
+ multicolor: false,
+ options: MATERIAL_SYMBOLS_OPTIONS
+ }))
+ },
+
+ async browse(prefix) {
+ if (!isMaterialSymbolsPrefix(prefix)) return []
+ return (await entries())
+ .filter((entry) => entry.sets.has(prefix))
+ .map((entry) => `${prefix}:${entry.name}`)
+ },
+
+ async icons(names, size, options = {}) {
+ await load(names)
+ const found = new Map<string, IconData>()
+ for (const name of names) {
+ const icon = iconData(name, size, options)
+ if (icon) found.set(name, icon)
+ }
+ return found
+ },
+
+ async previews(names) {
+ await load(names)
+ const found = new Map<string, string>()
+ for (const name of names) {
+ const glyph = loaded.get(name)
+ if (!glyph) continue
+ const data = materialSymbolsPathData(
+ glyph.font,
+ glyph.glyph,
+ PREVIEW_SIZE,
+ materialSymbolsOptions()
+ )
+ found.set(
+ name,
+ `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 ${PREVIEW_SIZE} ${PREVIEW_SIZE}"><path fill="currentColor" d="${data}"/></svg>`
+ )
+ }
+ return found
+ }
+ }
+}
diff --git a/packages/core/src/icons/provider.ts b/packages/core/src/icons/provider.ts
index 130633586..949df19ff 100644
--- a/packages/core/src/icons/provider.ts
+++ b/packages/core/src/icons/provider.ts
@@ -1,6 +1,8 @@
import { iconToHTML, iconToSVG } from '@iconify/utils'
import { chunk } from 'es-toolkit'
+import type { IconOptions } from '@open-pencil/scene-graph/icons'
+
import { createIconifyAPIClient } from './api'
import { buildIconData } from './svg'
import type { IconCollection, IconData, IconifyIconEntry, IconSearchResult } from './types'
@@ -18,8 +20,15 @@ export interface IconSearchOptions {
*/
export interface IconProvider {
search(query: string, options?: IconSearchOptions): Promise<IconSearchResult>
- /** Each named icon at `size`, by name; names the source lacks are left out. */
- icons(names: readonly string[], size: number): Promise<Map<string, IconData>>
+ /**
+ * Each named icon at `size`, by name; names the source lacks are left out. `options` sets how
+ * a set that has options draws them, its defaults filling in the rest; other sets ignore it.
+ */
+ icons(
+ names: readonly string[],
+ size: number,
+ options?: IconOptions
+ ): Promise<Map<string, IconData>>
/**
* Each named icon as SVG markup for pickers to show, painted in `currentColor` where the icon
* takes its color; names the source lacks are left out.
diff --git a/packages/core/src/icons/render.ts b/packages/core/src/icons/render.ts
index bfeb96e08..134adc1fa 100644
--- a/packages/core/src/icons/render.ts
+++ b/packages/core/src/icons/render.ts
@@ -9,6 +9,7 @@ import {
readIconTint,
withIcon,
withIconTint,
+ type IconOptions,
type IconPaint
} from '@open-pencil/scene-graph/icons'
import Matrix from '@open-pencil/scene-graph/matrix'
@@ -98,7 +99,7 @@ export function placeIcon(
...overrides
})
for (const path of icon.paths) addPath(graph, frame.id, path, size, color)
- if (identity) recordIcon(graph, frame.id, name)
+ if (identity) recordIcon(graph, frame.id, name, icon.options)
return graph.getNode(frame.id) ?? frame
}
@@ -125,15 +126,19 @@ export function drawIcon(
color: Color
): void {
for (const path of scaledPaths(icon, size)) addPath(graph, frameId, path, size, color)
- recordIcon(graph, frameId, `${icon.prefix}:${icon.name}`)
+ recordIcon(graph, frameId, `${icon.prefix}:${icon.name}`, icon.options)
}
-/** Writes the icon `name` on its frame with a fingerprint of the paths it draws now. */
-function recordIcon(graph: SceneGraph, frameId: string, name: string): void {
+/**
+ * Writes the icon `name` on its frame with a fingerprint of the paths it draws now, and how a set
+ * we draw ourselves drew it.
+ */
+function recordIcon(graph: SceneGraph, frameId: string, name: string, options?: IconOptions): void {
const frame = graph.getNode(frameId)
if (!frame) return
const glyph = iconGlyph(graph, frame)
- graph.updateNode(frameId, { pluginData: withIcon(frame, { name, glyph }) })
+ const icon = options ? { name, glyph, options } : { name, glyph }
+ graph.updateNode(frameId, { pluginData: withIcon(frame, icon) })
}
/**
@@ -190,7 +195,7 @@ export function swapIcon(graph: SceneGraph, frameId: string, icon: IconData): vo
})
for (const path of icon.paths) addPath(graph, frameId, path, size, color)
fitPaths(graph, frameId, size)
- recordIcon(graph, frameId, name)
+ recordIcon(graph, frameId, name, icon.options)
}
/**
diff --git a/packages/core/src/icons/sets.ts b/packages/core/src/icons/sets.ts
new file mode 100644
index 000000000..8ece6b77f
--- /dev/null
+++ b/packages/core/src/icons/sets.ts
@@ -0,0 +1,116 @@
+import type { IconOptions } from '@open-pencil/scene-graph/icons'
+
+import { parseIconName, type IconProvider } from '#core/icons/provider'
+import type { IconCollection, IconData, IconSearchResult } from '#core/icons/types'
+
+/** A provider of its own for some sets, such as fonts we draw icons from ourselves. */
+export interface IconSetSource {
+ prefixes: readonly string[]
+ provider: IconProvider
+}
+
+export interface IconSetsOptions {
+ /** Sets served by a source of their own instead of the fallback. */
+ sources: readonly IconSetSource[]
+ /** Everything else, such as Iconify. */
+ fallback: IconProvider
+ /**
+ * The fallback's sets a source replaces, left out of its catalogue and searches; icons already
+ * placed from them are still drawn.
+ */
+ replaced?: readonly string[]
+}
+
+/**
+ * One provider over several: each icon name is answered by the source that owns its set, and
+ * everything else by the fallback. Searches over every set ask them all.
+ */
+export function createIconSetsProvider({
+ sources,
+ fallback,
+ replaced = []
+}: IconSetsOptions): IconProvider {
+ const owner = (prefix: string): IconProvider =>
+ sources.find((source) => source.prefixes.includes(prefix))?.provider ?? fallback
+ const shown = (name: string) => !replaced.includes(parseIconName(name)?.prefix ?? '')
+
+ /** `names` split by the provider that answers them, in the order they were given. */
+ function byProvider(names: readonly string[]): Map<IconProvider, string[]> {
+ const parts = new Map<IconProvider, string[]>()
+ for (const name of names) {
+ const provider = owner(parseIconName(name)?.prefix ?? '')
+ parts.set(provider, [...(parts.get(provider) ?? []), name])
+ }
+ return parts
+ }
+
+ /** What every provider answers for its names; one that fails leaves only its own out. */
+ async function answered<T>(
+ names: readonly string[],
+ ask: (provider: IconProvider, names: string[]) => Promise<Map<string, T>>
+ ): Promise<Map<string, T>> {
+ const parts = await Promise.allSettled(
+ [...byProvider(names)].map(([provider, part]) => ask(provider, part))
+ )
+ const failed = parts.find((part) => part.status === 'rejected')
+ if (failed && parts.every((part) => part.status === 'rejected')) throw failed.reason
+ return new Map(parts.flatMap((part) => (part.status === 'fulfilled' ? [...part.value] : [])))
+ }
+
+ return {
+ async search(query, options = {}): Promise<IconSearchResult> {
+ if (options.prefix && replaced.includes(options.prefix))
+ return { icons: [], total: 0, collections: {} }
+ if (options.prefix) return owner(options.prefix).search(query, options)
+ const results = await Promise.allSettled(
+ [fallback, ...sources.map((source) => source.provider)].map((provider) =>
+ provider.search(query, options)
+ )
+ )
+ const found = results.flatMap((result) =>
+ result.status === 'fulfilled' ? [result.value] : []
+ )
+ if (found.length === 0 && results[0]?.status === 'rejected') throw results[0].reason
+ // The sources take turns, so one with many matches cannot crowd the others past the limit.
+ const lists = found.map((result) => result.icons.filter(shown))
+ const longest = Math.max(0, ...lists.map((list) => list.length))
+ const icons = Array.from({ length: longest }, (_, index) =>
+ lists.flatMap((list) => (index < list.length ? [list[index]] : []))
+ )
+ .flat()
+ .slice(0, options.limit)
+ return {
+ icons,
+ total: icons.length,
+ collections: Object.fromEntries(
+ found
+ .flatMap((result) => Object.entries(result.collections))
+ .filter(([prefix]) => !replaced.includes(prefix))
+ )
+ }
+ },
+
+ icons(names, size, options?: IconOptions) {
+ return answered<IconData>(names, (provider, part) => provider.icons(part, size, options))
+ },
+
+ previews(names) {
+ return answered<string>(names, (provider, part) => provider.previews(part))
+ },
+
+ async collections(): Promise<IconCollection[]> {
+ const lists = await Promise.allSettled(
+ [fallback, ...sources.map((source) => source.provider)].map((provider) =>
+ provider.collections()
+ )
+ )
+ const listed = lists.flatMap((list) => (list.status === 'fulfilled' ? list.value : []))
+ if (listed.length === 0 && lists[0]?.status === 'rejected') throw lists[0].reason
+ return listed.filter((info) => !replaced.includes(info.prefix))
+ },
+
+ async browse(prefix) {
+ return replaced.includes(prefix) ? [] : owner(prefix).browse(prefix)
+ }
+ }
+}
diff --git a/packages/core/src/icons/types.ts b/packages/core/src/icons/types.ts
index 1e34c93b4..8d1da1a25 100644
--- a/packages/core/src/icons/types.ts
+++ b/packages/core/src/icons/types.ts
@@ -1,4 +1,5 @@
import type { VectorNetwork, WindingRule } from '@open-pencil/scene-graph'
+import type { IconOptions } from '@open-pencil/scene-graph/icons'
export interface IconPath {
vectorNetwork: VectorNetwork
@@ -15,8 +16,15 @@ export interface IconData {
width: number
height: number
paths: IconPath[]
+ /** How a set we draw ourselves drew it, every option filled in; none for Iconify icons. */
+ options?: IconOptions
}
+/** A control for how a set's icons are drawn: a range, such as a font axis, or a choice. */
+export type IconOption =
+ | { key: string; name: string; min: number; max: number; default: number; step: number }
+ | { key: string; name: string; values: readonly string[]; default: string }
+
export interface IconifyIconEntry {
body: string
width?: number
@@ -48,6 +56,8 @@ export interface IconCollection {
license: string | null
/** Drawn in the set's own colors, which an icon color does not change. */
multicolor: boolean
+ /** How the set's icons can be drawn, for a set we draw ourselves. */
+ options?: readonly IconOption[]
}
export interface IconPathInfo {
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.ts
index fd5f63029..e7b439506 100644
--- a/packages/core/src/io/formats.ts
+++ b/packages/core/src/io/formats.ts
@@ -1,3 +1,5 @@
+import { groupBy } from 'es-toolkit'
+
import { sceneNodeToJSX, selectionToJSX } from '@open-pencil/design-jsx'
import { isDrawIOExportFileName } from '@open-pencil/drawio'
import {
@@ -5,11 +7,12 @@ import {
isDataURL,
parsePenDocument,
penAssets,
+ type PenIconRequest,
type PenIconSource
} from '@open-pencil/pen'
import type { SceneGraph } from '@open-pencil/scene-graph'
-import { drawIcon, iconify, type IconData, type IconProvider } from '#core/icons'
+import { defaultIcons, drawIcon, type IconData, type IconProvider } from '#core/icons'
import { layoutAuthoredNodes } from '#core/layout'
import type { DrawIOExportTarget } from './formats/drawio/export'
@@ -255,17 +258,32 @@ async function loadPenImages(
}
/** Icons from `provider`; a document whose icons cannot be fetched opens with empty icons. */
+/** A request's options as a key, so requests drawn the same way share a fetch. */
+const optionsKey = (options: Record<string, number> | undefined) => JSON.stringify(options ?? null)
+
+/**
+ * Icons from `provider`, fetched once for each way they are drawn; a document whose icons cannot
+ * be fetched opens with empty icons.
+ */
async function loadPenIcons(
- names: readonly string[],
+ requests: readonly PenIconRequest[],
provider: IconProvider
): Promise<PenIconSource> {
- const glyphs: Map<string, IconData> =
- names.length > 0
- ? await provider.icons(names, PEN_ICON_SIZE).catch(() => new Map<string, IconData>())
- : new Map()
+ const glyphs = new Map<string, IconData>()
+ const byOptions = groupBy(requests, (request) => optionsKey(request.options))
+ await Promise.all(
+ Object.values(byOptions).map(async (group) => {
+ const names = group.map((request) => request.name)
+ const found = await provider
+ .icons(names, PEN_ICON_SIZE, group[0]?.options)
+ .catch(() => new Map<string, IconData>())
+ for (const [name, icon] of found)
+ glyphs.set(`${name}\0${optionsKey(group[0]?.options)}`, icon)
+ })
+ )
return {
- draw(graph, frameId, name, size, color) {
- const icon = glyphs.get(name)
+ draw(graph, frameId, name, size, color, options) {
+ const icon = glyphs.get(`${name}\0${optionsKey(options)}`)
if (!icon) return false
drawIcon(graph, frameId, icon, size, color)
return true
@@ -291,7 +309,7 @@ export const penFormat: IOFormatAdapter<'pen'> = {
const assets = penAssets(doc)
const [images, icons] = await Promise.all([
loadPenImages(assets.images, input),
- loadPenIcons(assets.icons, context?.icons ?? iconify)
+ loadPenIcons(assets.icons, context?.icons ?? defaultIcons)
])
// A .pen file stores its layout intent, not the sizes and positions it implies.
const graph = buildPenGraph(doc, {
diff --git a/packages/core/tests/icons/material-symbols/provider.test.ts b/packages/core/tests/icons/material-symbols/provider.test.ts
new file mode 100644
index 000000000..bcf848893
--- /dev/null
+++ b/packages/core/tests/icons/material-symbols/provider.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, test } from 'bun:test'
+import { join } from 'node:path'
+
+import { FIXTURES } from '#core-tests/helpers/paths'
+
+import { createMaterialSymbolsProvider } from '#core/icons/material-symbols/provider'
+
+const FONT_URL = 'https://fonts.gstatic.com/s/test/material.ttf'
+
+/** The names each set's font draws, as Google lists them beside the fonts. */
+const CODEPOINTS: Record<string, string> = {
+ MaterialSymbolsOutlined: 'home e88a\ndark_mode e51c\n',
+ MaterialSymbolsRounded: 'home e88a\ndark_mode e51c\n',
+ MaterialSymbolsSharp: 'dark_mode e51c\n'
+}
+
+/**
+ * A provider over a fake Google that serves the fixture font, recording each request; it fails
+ * the requests for fonts holding any of `failing`.
+ */
+async function setup(failing: readonly string[] = []) {
+ const font = await Bun.file(
+ join(FIXTURES, 'fonts', 'MaterialSymbolsRounded-home-dark_mode.ttf')
+ ).arrayBuffer()
+ const requests: URL[] = []
+ const google = async (input: string | URL | Request) => {
+ const url = new URL(String(input))
+ requests.push(url)
+ const names = url.searchParams.get('icon_names')?.split(',') ?? []
+ if (url.pathname === '/css2' && names.some((name) => failing.includes(name)))
+ return new Response(null, { status: 503 })
+ if (url.pathname === '/css2')
+ return new Response(`@font-face { src: url(${FONT_URL}) format('woff2'); }`)
+ if (url.href === FONT_URL) return new Response(font)
+ const list = /\/(\w+)\[FILL,GRAD,opsz,wght\]\.codepoints$/.exec(
+ decodeURIComponent(url.pathname)
+ )
+ if (url.hostname === 'cdn.jsdelivr.net' && list?.[1]) return new Response(CODEPOINTS[list[1]])
+ return new Response(null, { status: 404 })
+ }
+ const provider = createMaterialSymbolsProvider(
+ Object.assign(google, { preconnect: fetch.preconnect })
+ )
+ return { provider, requests }
+}
+
+function bounds(xs: number[]) {
+ return [Math.min(...xs), Math.max(...xs)]
+}
+
+describe('Material Symbols', () => {
+ test('draws each icon from one font Google cuts to the names asked for', async () => {
+ const { provider, requests } = await setup()
+ const icons = await provider.icons(
+ [
+ 'material-symbols-rounded:home',
+ 'material-symbols-rounded:dark_mode',
+ 'material-symbols-rounded:nothing'
+ ],
+ 40
+ )
+ expect([...icons.keys()]).toEqual([
+ 'material-symbols-rounded:home',
+ 'material-symbols-rounded:dark_mode'
+ ])
+ const css = requests.filter((url) => url.pathname === '/css2')
+ expect(css).toHaveLength(1)
+ expect(css[0]?.searchParams.get('family')).toBe(
+ 'Material Symbols Rounded:opsz,wght,FILL,[email protected],100..700,0..1,-50..200'
+ )
+ expect(css[0]?.searchParams.get('icon_names')).toBe('dark_mode,home,nothing')
+ })
+
+ test('draws an icon in its em square at the axes its options set, defaults filling the rest', async () => {
+ const { provider } = await setup()
+ const name = 'material-symbols-rounded:home'
+ const thin = (await provider.icons([name], 40, { wght: 100 })).get(name)
+ const bold = (await provider.icons([name], 40, { wght: 900 })).get(name)
+ expect(thin?.options).toEqual({ opsz: 24, wght: 100, FILL: 0, GRAD: 0 })
+ // Past the axis, the weight is the axis' end.
+ expect(bold?.options).toMatchObject({ wght: 700 })
+ const box = (icon: typeof thin) => {
+ const vertices = icon?.paths[0]?.vectorNetwork.vertices ?? []
+ return [bounds(vertices.map((v) => v.x)), bounds(vertices.map((v) => v.y))]
+ }
+ const [[thinLeft, thinRight], [thinTop, thinBottom]] = box(thin)
+ const [[boldLeft, boldRight]] = box(bold)
+ expect(thinLeft).toBeGreaterThan(0)
+ expect(thinRight).toBeLessThan(40)
+ expect(thinTop).toBeGreaterThan(0)
+ expect(thinBottom).toBeLessThan(40)
+ expect(boldRight - boldLeft).toBeGreaterThan(thinRight - thinLeft)
+ expect(thin?.paths[0]?.fill).toBe('currentColor')
+ // One region of closed contours, so the inner ones cut the house's holes.
+ expect(thin?.paths[0]?.vectorNetwork.regions[0]?.loops.length).toBeGreaterThan(1)
+ })
+
+ test('keeps the icons of the fonts that loaded when another font of the set fails', async () => {
+ // Past 150 names a set loads in several fonts; the second one fails here.
+ const { provider } = await setup(['dark_mode'])
+ const extra = Array.from({ length: 149 }, (_, index) => `material-symbols-rounded:extra_${index}`)
+ const icons = await provider.icons(
+ ['material-symbols-rounded:home', ...extra, 'material-symbols-rounded:dark_mode'],
+ 40
+ )
+ expect([...icons.keys()]).toEqual(['material-symbols-rounded:home'])
+ await expect(provider.icons(['material-symbols-rounded:dark_mode'], 40)).rejects.toThrow()
+ })
+
+ test('fills an icon at the axes its fill sets, as fontTools draws the font', async () => {
+ const { provider } = await setup()
+ const name = 'material-symbols-rounded:home'
+ // At the font's own 960-unit em, so the outline reads in font units, y from the top.
+ const outlined = (await provider.icons([name], 960)).get(name)
+ const filled = (await provider.icons([name], 960, { FILL: 1 })).get(name)
+ const vertices = (icon: typeof filled) => icon?.paths[0]?.vectorNetwork.vertices ?? []
+ const box = (icon: typeof filled) => [
+ bounds(vertices(icon).map((v) => v.x)),
+ bounds(vertices(icon).map((v) => v.y))
+ ]
+ expect(box(filled)).toEqual(box(outlined))
+ // The door's corners on the floor, where every tuple's deltas land on their own points.
+ expect(vertices(filled)).toContainEqual({ x: 400, y: 800 })
+ expect(vertices(filled)).toContainEqual({ x: 560, y: 800 })
+ })
+
+ test('lists, browses, and searches the sets by the names Google lists for each font', async () => {
+ const { provider } = await setup()
+ const sets = await provider.collections()
+ expect(sets.map((set) => [set.prefix, set.total])).toEqual([
+ ['material-symbols-outlined', 2],
+ ['material-symbols-rounded', 2],
+ ['material-symbols-sharp', 1]
+ ])
+ expect(sets[0]?.options?.map((option) => option.key)).toEqual(['opsz', 'wght', 'FILL', 'GRAD'])
+ expect(await provider.browse('material-symbols-sharp')).toEqual([
+ 'material-symbols-sharp:dark_mode'
+ ])
+ expect((await provider.search('dark', { prefix: 'material-symbols-rounded' })).icons).toEqual([
+ 'material-symbols-rounded:dark_mode'
+ ])
+ expect((await provider.search('mode')).icons).toEqual([
+ 'material-symbols-outlined:dark_mode',
+ 'material-symbols-rounded:dark_mode',
+ 'material-symbols-sharp:dark_mode'
+ ])
+ expect((await provider.search('home')).icons).toEqual([
+ 'material-symbols-outlined:home',
+ 'material-symbols-rounded:home'
+ ])
+ })
+
+ test('previews an icon as SVG painted in the current color', async () => {
+ const { provider } = await setup()
+ const preview = (await provider.previews(['material-symbols-rounded:home'])).get(
+ 'material-symbols-rounded:home'
+ )
+ expect(preview).toStartWith('<svg')
+ expect(preview).toContain('fill="currentColor"')
+ })
+})
diff --git a/packages/core/tests/icons/sets.test.ts b/packages/core/tests/icons/sets.test.ts
new file mode 100644
index 000000000..011f22227
--- /dev/null
+++ b/packages/core/tests/icons/sets.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { IconProvider } from '#core/icons/provider'
+import { createIconSetsProvider } from '#core/icons/sets'
+import type { IconCollection } from '#core/icons/types'
+
+/** A provider that answers for `prefixes`, recording the names it is asked for. */
+function fake(prefixes: string[], asked: string[][]): IconProvider {
+ const collection = (prefix: string): IconCollection => ({
+ prefix,
+ name: prefix,
+ total: 1,
+ category: null,
+ license: null,
+ multicolor: false
+ })
+ return {
+ async icons(names, size) {
+ asked.push([...names])
+ return new Map(
+ names.map((name) => [
+ name,
+ {
+ prefix: name.split(':')[0] ?? '',
+ name: name.split(':')[1] ?? '',
+ width: size,
+ height: size,
+ paths: []
+ }
+ ])
+ )
+ },
+ previews: async (names) => new Map(names.map((name) => [name, `<svg>${name}</svg>`])),
+ search: async () => ({
+ icons: prefixes.map((prefix) => `${prefix}:found`),
+ total: prefixes.length,
+ collections: Object.fromEntries(
+ prefixes.map((prefix) => [prefix, { name: prefix, total: 1 }])
+ )
+ }),
+ collections: async () => prefixes.map(collection),
+ browse: async (prefix) => [`${prefix}:one`]
+ }
+}
+
+describe('icon sets', () => {
+ const setup = () => {
+ const fontAsked: string[][] = []
+ const iconifyAsked: string[][] = []
+ const provider = createIconSetsProvider({
+ sources: [{ prefixes: ['font-set'], provider: fake(['font-set'], fontAsked) }],
+ fallback: fake(['lucide', 'iconify-copy'], iconifyAsked),
+ replaced: ['iconify-copy']
+ })
+ return { provider, fontAsked, iconifyAsked }
+ }
+
+ test('asks each set’s own source for its icons, and the fallback for the rest', async () => {
+ const { provider, fontAsked, iconifyAsked } = setup()
+ const icons = await provider.icons(['lucide:a', 'font-set:b', 'lucide:c'], 24)
+ expect([...icons.keys()].sort()).toEqual(['font-set:b', 'lucide:a', 'lucide:c'])
+ expect(fontAsked).toEqual([['font-set:b']])
+ expect(iconifyAsked).toEqual([['lucide:a', 'lucide:c']])
+ expect(await provider.browse('font-set')).toEqual(['font-set:one'])
+ })
+
+ test('leaves the sets a source replaces out of the catalogue and searches', async () => {
+ const { provider } = setup()
+ expect((await provider.collections()).map((set) => set.prefix)).toEqual(['lucide', 'font-set'])
+ const found = await provider.search('anything')
+ expect(found.icons).toEqual(['lucide:found', 'font-set:found'])
+ expect(Object.keys(found.collections)).toEqual(['lucide', 'font-set'])
+ })
+
+ test('hides a replaced set from a search or browse scoped to it', async () => {
+ const { provider } = setup()
+ expect((await provider.search('anything', { prefix: 'iconify-copy' })).icons).toEqual([])
+ expect(await provider.browse('iconify-copy')).toEqual([])
+ })
+
+ test('takes matches from each source in turn up to the limit', async () => {
+ const many = (prefix: string): IconProvider => ({
+ ...fake([prefix], []),
+ search: async () => ({
+ icons: ['a', 'b', 'c'].map((name) => `${prefix}:${name}`),
+ total: 3,
+ collections: { [prefix]: { name: prefix, total: 3 } }
+ })
+ })
+ const provider = createIconSetsProvider({
+ sources: [{ prefixes: ['font-set'], provider: many('font-set') }],
+ fallback: many('lucide')
+ })
+ expect((await provider.search('anything', { limit: 4 })).icons).toEqual([
+ 'lucide:a',
+ 'font-set:a',
+ 'lucide:b',
+ 'font-set:b'
+ ])
+ })
+
+ test('keeps the icons other sources answer when one source fails', async () => {
+ const offline: IconProvider = {
+ ...fake(['font-set'], []),
+ icons: async () => {
+ throw new Error('offline')
+ },
+ previews: async () => {
+ throw new Error('offline')
+ }
+ }
+ const provider = createIconSetsProvider({
+ sources: [{ prefixes: ['font-set'], provider: offline }],
+ fallback: fake(['lucide'], [])
+ })
+ expect([...(await provider.previews(['lucide:a', 'font-set:b'])).keys()]).toEqual(['lucide:a'])
+ await expect(provider.icons(['font-set:b'], 24)).rejects.toThrow('offline')
+ })
+})
diff --git a/packages/core/tests/io/formats/pen/assets.test.ts b/packages/core/tests/io/formats/pen/assets.test.ts
index 5ee500eaf..141a193df 100644
--- a/packages/core/tests/io/formats/pen/assets.test.ts
+++ b/packages/core/tests/io/formats/pen/assets.test.ts
@@ -1,9 +1,11 @@
import { describe, expect, test } from 'bun:test'
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { fromUint8Array, toUint8Array } from 'js-base64'
import type { IconData, IconProvider } from '@open-pencil/core/icons'
import { IORegistry, penFormat } from '@open-pencil/core/io'
+import { readIcon, type IconOptions } from '@open-pencil/scene-graph/icons'
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
// A 2 × 1 PNG.
@@ -11,8 +13,13 @@ const PNG = toUint8Array(
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAADElEQVR4nGP8zwACAAYIAQFazwZIAAAAAElFTkSuQmCC'
)
-function iconProvider(available: string[], requested: string[][]): IconProvider {
- const glyph = (name: string, size: number): IconData => {
+interface IconRequest {
+ names: string[]
+ options?: IconOptions
+}
+
+function iconProvider(available: string[], requested: IconRequest[]): IconProvider {
+ const glyph = (name: string, size: number, options?: IconOptions): IconData => {
const [prefix = '', iconName = ''] = name.split(':')
return {
prefix,
@@ -28,14 +35,17 @@ function iconProvider(available: string[], requested: string[][]): IconProvider
strokeCap: 'butt',
strokeJoin: 'miter'
}
- ]
+ ],
+ ...(options ? { options } : {})
}
}
return {
- async icons(names, size) {
- requested.push([...names])
+ async icons(names, size, options) {
+ requested.push(options ? { names: [...names], options } : { names: [...names] })
return new Map(
- names.filter((name) => available.includes(name)).map((name) => [name, glyph(name, size)])
+ names
+ .filter((name) => available.includes(name))
+ .map((name) => [name, glyph(name, size, options)])
)
},
search: () => Promise.resolve({ icons: [], total: 0, collections: {} }),
@@ -52,27 +62,20 @@ function penBytes(children: unknown[]) {
}
describe('penFormat.readDocument — assets', () => {
- test('draws Iconify icons from the provider', async () => {
- const requested: string[][] = []
- const icons = iconProvider(['lucide:house'], requested)
+ test('draws every library from its set, Material Symbols at their weight', async () => {
+ const requested: IconRequest[] = []
+ const icons = iconProvider(['lucide:house', 'material-symbols-outlined:home'], requested)
const { graph } = await io.readDocument(
{
name: 'icons.pen',
data: penBytes([
- {
- id: 'home',
- type: 'icon',
- library: 'lucide',
- icon: 'house',
- width: 48,
- height: 48,
- fill: '#222222'
- },
+ { id: 'house', type: 'icon', library: 'lucide', icon: 'house', width: 48, height: 48 },
{
id: 'symbol',
type: 'icon',
library: 'Material Symbols Outlined',
icon: 'home',
+ weight: 650,
width: 48,
height: 48
}
@@ -80,11 +83,18 @@ describe('penFormat.readDocument — assets', () => {
},
{ icons }
)
- expect(requested).toEqual([['lucide:house']])
- const glyphs = graph.getChildren('home')
- expect(glyphs).toHaveLength(1)
- expect(glyphs[0]?.width).toBe(48)
- expect(graph.getChildren('symbol').map((glyph) => glyph.type)).toEqual(['TEXT'])
+ expect(requested).toEqual(
+ expect.arrayContaining([
+ { names: ['lucide:house'] },
+ { names: ['material-symbols-outlined:home'], options: { wght: 650 } }
+ ])
+ )
+ expect(readIcon(getNodeOrThrow(graph, 'house'))).toMatchObject({ name: 'lucide:house' })
+ expect(readIcon(getNodeOrThrow(graph, 'symbol'))).toMatchObject({
+ name: 'material-symbols-outlined:home',
+ options: { wght: 650 }
+ })
+ expect(graph.getChildren('symbol').map((glyph) => glyph.type)).toEqual(['VECTOR'])
})
test('reads image files through the host and leaves unreadable ones unpainted', async () => {
diff --git a/packages/core/tests/io/formats/pen/oracle.test.ts b/packages/core/tests/io/formats/pen/oracle.test.ts
index a27f5a567..40880323e 100644
--- a/packages/core/tests/io/formats/pen/oracle.test.ts
+++ b/packages/core/tests/io/formats/pen/oracle.test.ts
@@ -6,7 +6,12 @@ import { FIXTURES } from '#core-tests/helpers/paths'
import { once, pick } from 'es-toolkit'
import * as v from 'valibot'
-import { createIconifyProvider } from '@open-pencil/core/icons'
+import {
+ createIconifyProvider,
+ createIconSetsProvider,
+ createMaterialSymbolsProvider,
+ MATERIAL_SYMBOLS_PREFIXES
+} from '@open-pencil/core/icons'
import { IORegistry, penFormat } from '@open-pencil/core/io'
import {
comparePNGs,
@@ -53,18 +58,41 @@ const iconSetSchema = v.pipe(
const manifest = v.parse(manifestSchema, await Bun.file(join(ORACLES, 'manifest.json')).text())
const source = await Bun.file(join(ORACLES, manifest.document)).text()
-/** Icons from the recorded Iconify sets only. */
+const googleIndexSchema = v.pipe(v.string(), v.parseJson(), v.record(v.string(), v.string()))
+
+/** Google's recorded answers for the Material Symbols the probes draw, served back by URL. */
+async function recordedGoogle(input: RequestInfo | URL): Promise<Response> {
+ const index = v.parse(
+ googleIndexSchema,
+ await Bun.file(join(ORACLES, 'google', 'index.json')).text()
+ )
+ const file = index[input instanceof Request ? input.url : String(input)]
+ if (!file) return new Response(null, { status: 404 })
+ return new Response(await Bun.file(join(ORACLES, 'google', file)).arrayBuffer())
+}
+
+/** Icons from the recorded Iconify sets and Google answers only. */
function recordedIcons() {
- return createIconifyProvider({
- async fetchCollection(prefix, names) {
- const file = Bun.file(join(ORACLES, 'iconify', `${prefix}.json`))
- if (!(await file.exists())) throw new Error(`No "${prefix}" icons were recorded`)
- const set = v.parse(iconSetSchema, await file.text())
- return { ...set, icons: pick(set.icons, names) }
- },
- search: () => Promise.resolve({ icons: [], total: 0, collections: {} }),
- collections: () => Promise.resolve([]),
- collectionIcons: () => Promise.resolve([])
+ return createIconSetsProvider({
+ sources: [
+ {
+ prefixes: MATERIAL_SYMBOLS_PREFIXES,
+ provider: createMaterialSymbolsProvider(
+ Object.assign(recordedGoogle, { preconnect: fetch.preconnect })
+ )
+ }
+ ],
+ fallback: createIconifyProvider({
+ async fetchCollection(prefix, names) {
+ const file = Bun.file(join(ORACLES, 'iconify', `${prefix}.json`))
+ if (!(await file.exists())) throw new Error(`No "${prefix}" icons were recorded`)
+ const set = v.parse(iconSetSchema, await file.text())
+ return { ...set, icons: pick(set.icons, names) }
+ },
+ search: () => Promise.resolve({ icons: [], total: 0, collections: {} }),
+ collections: () => Promise.resolve([]),
+ collectionIcons: () => Promise.resolve([])
+ })
})
}
diff --git a/packages/design-jsx/src/export/icons.ts b/packages/design-jsx/src/export/icons.ts
index 6a2877a17..d362b7189 100644
--- a/packages/design-jsx/src/export/icons.ts
+++ b/packages/design-jsx/src/export/icons.ts
@@ -3,6 +3,7 @@ import { colorToHex } from '@open-pencil/scene-graph/color'
import {
isIconModified,
isPlacedIconName,
+ isNamedIcon,
readIcon,
readIconTint
} from '@open-pencil/scene-graph/icons'
@@ -28,8 +29,9 @@ function tintColor(graph: SceneGraph, frame: SceneNode): string | null {
*/
export function iconProps(node: SceneNode, graph: SceneGraph): JSXProp[] | null {
const icon = readIcon(node)
- // An icon whose paths were edited exports as the paths it draws, which <Icon> would lose.
- if (!icon || isIconModified(graph, node)) return null
+ // An icon whose paths were edited exports as the paths it draws, which <Icon> would lose, as
+ // does one drawn from a set of our own, which its name alone does not draw.
+ if (!icon || !isNamedIcon(icon) || isIconModified(graph, node)) return null
const color = tintColor(graph, node)
return [
['name', icon.name],
diff --git a/packages/dom-css/src/export/components/references.ts b/packages/dom-css/src/export/components/references.ts
index 61bcdb60f..a650f6f06 100644
--- a/packages/dom-css/src/export/components/references.ts
+++ b/packages/dom-css/src/export/components/references.ts
@@ -6,7 +6,7 @@ import { isEmptyObject } from 'es-toolkit/predicate'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { behaviourOwner, findLayerByPath } from '@open-pencil/scene-graph/behaviours'
import { findComponentPropertyTargets } from '@open-pencil/scene-graph/components'
-import { isIconModified, readIcon } from '@open-pencil/scene-graph/icons'
+import { isIconModified, isNamedIcon, readIcon } from '@open-pencil/scene-graph/icons'
import { instanceMainComponent } from '@open-pencil/scene-graph/instances'
import { drawsAsMain } from './drawn'
@@ -174,7 +174,9 @@ function usedLayer(
...referenceValues(graph, node, component)
}
const icon = readIcon(node)
- return icon && !isIconModified(graph, node) ? { type: 'icon', icon: icon.name } : null
+ return icon && isNamedIcon(icon) && !isIconModified(graph, node)
+ ? { type: 'icon', icon: icon.name }
+ : null
}
/**
diff --git a/packages/pen/src/assets.ts b/packages/pen/src/assets.ts
index 51d6097e3..ffa1b2f09 100644
--- a/packages/pen/src/assets.ts
+++ b/packages/pen/src/assets.ts
@@ -2,29 +2,46 @@ import type { PenDocument, PenNode, PenOverride, PenPaint, PenPaints } from './s
import { possibleValues } from './variables'
/**
- * Where pen.dev's icon libraries come from. Lucide, Feather, and Phosphor are drawn from their
- * Iconify sets, which pen.dev draws at one weight; Material Symbols are glyphs of Google's variable
- * fonts, drawn at the icon's weight, as pen.dev draws them.
+ * The icon set each of pen.dev's libraries is drawn from: Iconify's for Lucide, Feather, and
+ * Phosphor, which pen.dev draws at one weight, and Google's variable fonts for Material Symbols.
*/
-const ICON_LIBRARIES: Partial<Record<string, { iconify: string } | { font: string }>> = {
- lucide: { iconify: 'lucide' },
- feather: { iconify: 'feather' },
- phosphor: { iconify: 'ph' },
- 'Material Symbols Outlined': { font: 'Material Symbols Outlined' },
- 'Material Symbols Rounded': { font: 'Material Symbols Rounded' },
- 'Material Symbols Sharp': { font: 'Material Symbols Sharp' }
+const ICON_SETS: Partial<Record<string, string>> = {
+ lucide: 'lucide',
+ feather: 'feather',
+ phosphor: 'ph',
+ 'Material Symbols Outlined': 'material-symbols-outlined',
+ 'Material Symbols Rounded': 'material-symbols-rounded',
+ 'Material Symbols Sharp': 'material-symbols-sharp'
}
-/** The Iconify name of an icon from a library drawn from Iconify. */
+/** The libraries pen.dev draws at an icon's `weight`: Material Symbols' variable fonts. */
+const WEIGHTED_LIBRARIES = new Set([
+ 'Material Symbols Outlined',
+ 'Material Symbols Rounded',
+ 'Material Symbols Sharp'
+])
+
+/** The weight pen.dev draws Material Symbols at when an icon sets none. */
+const MATERIAL_SYMBOLS_WEIGHT = 200
+
+/** An icon's name in its set. */
export function iconName(library: string, icon: string): string | null {
- const source = ICON_LIBRARIES[library]
- return source && 'iconify' in source ? `${source.iconify}:${icon}` : null
+ const set = ICON_SETS[library]
+ return set ? `${set}:${icon}` : null
+}
+
+/** How an icon from `library` is drawn at `weight`: its font's weight axis, for Material Symbols. */
+export function iconOptions(
+ library: string,
+ weight: number | undefined
+): Record<string, number> | undefined {
+ return WEIGHTED_LIBRARIES.has(library) ? { wght: weight ?? MATERIAL_SYMBOLS_WEIGHT } : undefined
}
-/** The font family of a library whose icons are font glyphs. */
-export function iconFontFamily(library: string): string | null {
- const source = ICON_LIBRARIES[library]
- return source && 'font' in source ? source.font : null
+/** An icon a document draws: its name in its set and how it is drawn there. */
+export interface PenIconRequest {
+ name: string
+ options?: Record<string, number>
}
/**
@@ -43,8 +60,8 @@ export function isDataURL(url: string): boolean {
/** What a document draws from outside itself. */
export interface PenAssets {
- /** Iconify names of every icon drawn from Iconify. */
- icons: string[]
+ /** Every icon, each way it is drawn. */
+ icons: PenIconRequest[]
/** Images to load: files relative to the document, and data URLs. */
images: string[]
}
@@ -64,18 +81,45 @@ function paintImages(paints: PenPaints | undefined, images: Set<string>) {
interface Found {
doc: PenDocument
- icons: Set<string>
+ /** Requests by their name and options, so each is listed once. */
+ icons: Map<string, PenIconRequest>
images: Set<string>
libraries: Set<string>
/** Icons an override names without its library, which comes from the layer it overrides. */
bareIcons: Set<string>
+ /** The weights icons are drawn at, for icons whose library an override leaves out. */
+ weights: Set<number | undefined>
+}
+
+/**
+ * Every weight a field can take, through the variables it names. A value that is no number, or a
+ * variable without one, leaves the weight unset, as drawing reads it.
+ */
+function possibleWeights(weight: PenOverride['weight'], doc: PenDocument): (number | undefined)[] {
+ if (weight === undefined) return [undefined]
+ if (typeof weight === 'number') return [weight]
+ const values = possibleValues(weight, doc).map((value) => {
+ const parsed = Number(value)
+ return Number.isFinite(parsed) ? parsed : undefined
+ })
+ return values.length > 0 ? values : [undefined]
}
-function addIcons(libraries: readonly string[], icons: readonly string[], found: Set<string>) {
+function addIcons(
+ libraries: readonly string[],
+ icons: readonly string[],
+ weights: readonly (number | undefined)[],
+ found: Found
+) {
for (const library of libraries) {
for (const icon of icons) {
- const name = iconName(library, icon)
- if (name) found.add(name)
+ // A variable without a name in some theme draws no icon there.
+ const name = icon ? iconName(library, icon) : null
+ if (!name) continue
+ for (const weight of weights) {
+ const options = iconOptions(library, weight)
+ found.icons.set(`${name}\0${JSON.stringify(options ?? null)}`, { name, options })
+ }
}
}
}
@@ -83,10 +127,12 @@ function addIcons(libraries: readonly string[], icons: readonly string[], found:
function collect(node: PenOverride, assets: Found) {
if (node.icon && (node.type === 'icon' || node.type === undefined)) {
const icons = possibleValues(node.icon, assets.doc)
+ const weights = possibleWeights(node.weight, assets.doc)
+ for (const weight of weights) assets.weights.add(weight)
if (node.library) {
const libraries = possibleValues(node.library, assets.doc)
for (const library of libraries) assets.libraries.add(library)
- addIcons(libraries, icons, assets.icons)
+ addIcons(libraries, icons, weights, assets)
} else {
for (const icon of icons) assets.bareIcons.add(icon)
}
@@ -100,18 +146,19 @@ function collect(node: PenOverride, assets: Found) {
}
/**
- * The Iconify icons and the image files a document draws, so a host can load them before reading
- * it. An icon or library bound to a variable counts every value the variable has.
+ * The icons and the image files a document draws, so a host can load them before reading it. An
+ * icon, library, or weight bound to a variable counts every value the variable has.
*/
export function penAssets(doc: PenDocument): PenAssets {
const assets: Found = {
doc,
- icons: new Set(),
+ icons: new Map(),
images: new Set(),
libraries: new Set(),
- bareIcons: new Set()
+ bareIcons: new Set(),
+ weights: new Set()
}
for (const node of doc.children) collect(node satisfies PenNode, assets)
- addIcons([...assets.libraries], [...assets.bareIcons], assets.icons)
- return { icons: [...assets.icons], images: [...assets.images] }
+ addIcons([...assets.libraries], [...assets.bareIcons], [...assets.weights], assets)
+ return { icons: [...assets.icons.values()], images: [...assets.images] }
}
diff --git a/packages/pen/src/icons.ts b/packages/pen/src/icons.ts
index 991f8ef36..783b48f18 100644
--- a/packages/pen/src/icons.ts
+++ b/packages/pen/src/icons.ts
@@ -13,45 +13,18 @@ import {
} from '@open-pencil/scene-graph/instances'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import { iconFontFamily, iconName } from './assets'
+import { iconName, iconOptions } from './assets'
import type { Build } from './nodes'
import type { PenNode } from './schema'
-import { resolveNumber, resolveString } from './variables'
-
-/** The weight pen.dev draws Material Symbols at when an icon sets none. */
-const MATERIAL_SYMBOLS_WEIGHT = 200
+import { resolveOptionalNumber, resolveString } from './variables'
/** Space between the icon components on their page. */
const ICON_COMPONENT_GAP = 16
-/** A font icon's glyph: its name set in the icon font, which turns it into the glyph. */
-function drawFontGlyph(
- build: Build,
- frameId: string,
- family: string,
- icon: string,
- weight: number,
- size: number,
- color: Color
-): void {
- build.graph.createNode('TEXT', frameId, {
- name: icon,
- text: icon,
- fontFamily: family,
- fontWeight: weight,
- fontVariations: [{ axis: 'wght', value: weight }],
- fontSize: size,
- lineHeight: size,
- width: size,
- height: size,
- textAutoResize: 'NONE',
- fills: [{ type: 'SOLID', color, opacity: 1, visible: true }]
- })
-}
-
/**
* An icon draws its glyph in its fill colour, scaled to fit its box and centred, as pen.dev does;
- * an icon the host could not load is an empty frame. Its library and name may be variables.
+ * an icon the host could not load is an empty frame. Its library, name, and weight may be
+ * variables.
*/
export function drawIcon(node: SceneNode, pen: PenNode, build: Build): void {
const { graph, ctx } = build
@@ -61,13 +34,10 @@ export function drawIcon(node: SceneNode, pen: PenNode, build: Build): void {
const library = resolveString(pen.library, ctx)
const icon = resolveString(pen.icon, ctx)
const size = Math.min(node.width, node.height)
- if (!library || !icon || size <= 0) return
- const family = iconFontFamily(library)
- const name = iconName(library, icon)
- if (family) {
- const weight = resolveNumber(pen.weight, ctx, MATERIAL_SYMBOLS_WEIGHT)
- drawFontGlyph(build, node.id, family, icon, weight, size, color)
- } else if (!name || !build.icons?.draw(graph, node.id, name, size, color)) return
+ const name = library && icon ? iconName(library, icon) : null
+ if (!library || !name || size <= 0) return
+ const options = iconOptions(library, resolveOptionalNumber(pen.weight, ctx))
+ if (!build.icons?.draw(graph, node.id, name, size, color, options)) return
const dx = (node.width - size) / 2
const dy = (node.height - size) / 2
for (const glyph of graph.getChildren(node.id)) {
@@ -96,10 +66,8 @@ function iconComponent(build: Build, pen: PenNode, width: number, height: number
const { graph, ctx } = build
const library = resolveString(pen.library, ctx) ?? ''
const icon = resolveString(pen.icon, ctx) ?? ''
- const weight = iconFontFamily(library)
- ? `/${resolveNumber(pen.weight, ctx, MATERIAL_SYMBOLS_WEIGHT)}`
- : ''
- const key = `${library}/${icon}/${width}x${height}${weight}`
+ const options = iconOptions(library, resolveOptionalNumber(pen.weight, ctx))
+ const key = `${library}/${icon}/${width}x${height}${options ? `/${JSON.stringify(options)}` : ''}`
const existing = build.iconComponents.get(key)
if (existing) return existing
build.iconPageId ??= graph.addPage('Icons').id
@@ -121,11 +89,9 @@ function iconComponent(build: Build, pen: PenNode, width: number, height: number
function recolorGlyph(graph: SceneGraph, instanceId: string, color: Color): void {
for (const glyph of graph.getChildren(instanceId)) {
const tint = readIconTint(glyph)
- // A font icon's glyph is text in the icon's colour.
- const fills =
- glyph.type === 'TEXT' || tint.includes('fill')
- ? glyph.fills.map((fill) => ({ ...fill, color }))
- : glyph.fills
+ const fills = tint.includes('fill')
+ ? glyph.fills.map((fill) => ({ ...fill, color }))
+ : glyph.fills
const strokes = tint.includes('stroke')
? glyph.strokes.map((stroke) => ({ ...stroke, color }))
: glyph.strokes
diff --git a/packages/pen/src/index.ts b/packages/pen/src/index.ts
index 957b651d2..f43f7fb62 100644
--- a/packages/pen/src/index.ts
+++ b/packages/pen/src/index.ts
@@ -1,10 +1,11 @@
export {
- iconFontFamily,
iconName,
+ iconOptions,
isDataURL,
isDocumentAssetPath,
penAssets,
- type PenAssets
+ type PenAssets,
+ type PenIconRequest
} from './assets'
export type { PenIconSource } from './nodes'
export {
diff --git a/packages/pen/src/nodes.ts b/packages/pen/src/nodes.ts
index 4a400c3bc..61ae7e151 100644
--- a/packages/pen/src/nodes.ts
+++ b/packages/pen/src/nodes.ts
@@ -30,10 +30,18 @@ import { bindIfVar, resolveBoolean, resolveNumber, type VarContext } from './var
/** Where icon glyphs come from, as the host loaded them. */
export interface PenIconSource {
/**
- * Draws the Iconify icon `name` into the frame, `size` square at its origin, painted `color`
- * where the icon takes its colour. False when the source does not have it.
+ * Draws the icon `name` into the frame, `size` square at its origin, painted `color` where the
+ * icon takes its colour and drawn with `options` where its set has them. False when the source
+ * does not have it.
*/
- draw(graph: SceneGraph, frameId: string, name: string, size: number, color: Color): boolean
+ draw(
+ graph: SceneGraph,
+ frameId: string,
+ name: string,
+ size: number,
+ color: Color,
+ options?: Record<string, number>
+ ): boolean
}
/** What reading one document builds up. */
diff --git a/packages/pen/src/variables.ts b/packages/pen/src/variables.ts
index 5a86b9920..e78a2cbba 100644
--- a/packages/pen/src/variables.ts
+++ b/packages/pen/src/variables.ts
@@ -25,6 +25,8 @@ export interface VarContext {
byName: Map<string, Variable>
resolveColor(ref: string): Color
resolveNumber(ref: string): number
+ /** The number the variable holds, or nothing when it holds none. */
+ numberValue(ref: string): number | undefined
resolveString(ref: string): string
resolveBoolean(ref: string): boolean
/** Merges a layer's theme over its parent's until the returned function is called. */
@@ -56,6 +58,18 @@ export function resolveNumber(value: PenNumber | undefined, ctx: VarContext, fal
return Number.isFinite(parsed) ? parsed : fallback
}
+/** A number, or the value of the number variable it references; nothing where there is none. */
+export function resolveOptionalNumber(
+ value: PenNumber | undefined,
+ ctx: VarContext
+): number | undefined {
+ if (value === undefined) return undefined
+ if (typeof value === 'number') return value
+ if (isVarRef(value)) return ctx.numberValue(value)
+ const parsed = Number(value)
+ return Number.isFinite(parsed) ? parsed : undefined
+}
+
/** A boolean, or the value of the variable it references. */
export function resolveBoolean(
value: boolean | string | undefined,
@@ -73,10 +87,12 @@ export function resolveString(value: string | undefined, ctx: VarContext): strin
}
/**
- * Every value a field can take: the value itself, or each value its variable has in any theme,
- * through aliases. For loading what a document may draw before it is read in a theme.
+ * Every value a field can take: the value itself, or the value its variable has in each theme,
+ * through aliases, with the empty value where a theme has none, as reading resolves it. For
+ * loading what a document may draw before it is read in a theme.
*/
export function possibleValues(value: string | undefined, doc: PenDocument): string[] {
+ const themes = combinations(themeAxes(doc))
const found = new Set<string>()
const seen = new Set<string>()
const visit = (raw: PenVariableScalar | undefined) => {
@@ -89,10 +105,12 @@ export function possibleValues(value: string | undefined, doc: PenDocument): str
const definition = doc.variables?.[name]
if (!definition || seen.has(name)) return
seen.add(name)
- const entries = Array.isArray(definition.value)
- ? definition.value
- : [{ value: definition.value }]
- for (const entry of entries) visit(entry.value)
+ const empty = emptyValue(sceneType(definition.type))
+ for (const theme of themes) {
+ const themed = rawValue(definition, theme)
+ if (themed !== undefined) visit(themed)
+ else if (typeof empty !== 'object') found.add(String(empty))
+ }
}
visit(value)
return [...found]
@@ -120,6 +138,11 @@ function emptyValue(type: VariableType): VariableValue {
type Axis = [name: string, values: string[]]
+/** The document's theme axes that have values. */
+function themeAxes(doc: PenDocument): Axis[] {
+ return Object.entries(doc.themes ?? {}).filter(([, values]) => values.length > 0)
+}
+
/** Every combination of one value per axis, the first values first. */
function combinations(axes: Axis[]): Theme[] {
return axes.reduce<Theme[]>(
@@ -164,7 +187,7 @@ function themeKey(theme: Theme, axes: Axis[]): string {
}
export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext {
- const axes: Axis[] = Object.entries(doc.themes ?? {}).filter(([, values]) => values.length > 0)
+ const axes = themeAxes(doc)
const themes = combinations(axes)
const modes: VariableCollectionMode[] = themes.map((theme) => ({
modeId: generateId(),
@@ -227,8 +250,11 @@ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext
return typeof value === 'object' && 'r' in value ? value : { ...BLACK }
},
resolveNumber(ref) {
+ return this.numberValue(ref) ?? 0
+ },
+ numberValue(ref) {
const value = resolve(ref)
- return typeof value === 'number' ? value : 0
+ return typeof value === 'number' ? value : undefined
},
resolveString(ref) {
const value = resolve(ref)
diff --git a/packages/pen/tests/assets.test.ts b/packages/pen/tests/assets.test.ts
index 65db862d5..8aef2ef4f 100644
--- a/packages/pen/tests/assets.test.ts
+++ b/packages/pen/tests/assets.test.ts
@@ -3,8 +3,8 @@ import { describe, expect, test } from 'bun:test'
import { toUint8Array } from 'js-base64'
import {
- iconFontFamily,
iconName,
+ iconOptions,
penAssets,
parsePenDocument,
type PenDocument,
@@ -21,13 +21,19 @@ const PNG =
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAADElEQVR4nGP8zwACAAYIAQFazwZIAAAAAElFTkSuQmCC'
describe('penAssets', () => {
- test('lists Iconify icons, images in the document folder, and data URLs', () => {
+ test('lists icons with how they are drawn, images in the document folder, and data URLs', () => {
const doc = parsePenDocument(
JSON.stringify({
version: '2.21',
children: [
{ id: 'a', type: 'icon', library: 'lucide', icon: 'heart' },
- { id: 'b', type: 'icon', library: 'Material Symbols Rounded', icon: 'settings' },
+ {
+ id: 'b',
+ type: 'icon',
+ library: 'Material Symbols Rounded',
+ icon: 'settings',
+ weight: 300
+ },
{ id: 'c', type: 'rectangle', fill: { type: 'image', url: './photo.png' } },
{ id: 'd', type: 'rectangle', fill: [{ type: 'image', url: '../secret.png' }] },
{ id: 'e', type: 'rectangle', fill: { type: 'image', url: 'https://example.com/a.png' } },
@@ -43,11 +49,42 @@ describe('penAssets', () => {
})
)
expect(penAssets(doc)).toEqual({
- icons: ['lucide:heart', 'ph:house', 'lucide:star', 'ph:star'],
+ icons: [
+ { name: 'lucide:heart' },
+ { name: 'material-symbols-rounded:settings', options: { wght: 300 } },
+ { name: 'ph:house' },
+ { name: 'lucide:star' },
+ // The override names no library or weight, so it may be any the document draws with.
+ { name: 'material-symbols-rounded:star', options: { wght: 200 } },
+ { name: 'material-symbols-rounded:star', options: { wght: 300 } },
+ { name: 'ph:star' }
+ ],
images: ['./photo.png', `data:image/png;base64,${PNG}`]
})
})
+ test('lists an icon whose weight variable holds no number at the default weight', () => {
+ const doc = parsePenDocument(
+ JSON.stringify({
+ version: '2.21',
+ children: [
+ { id: 'a', type: 'icon', library: 'lucide', icon: 'heart', weight: '$missing' },
+ {
+ id: 'b',
+ type: 'icon',
+ library: 'Material Symbols Rounded',
+ icon: 'home',
+ weight: '$missing'
+ }
+ ]
+ })
+ )
+ expect(penAssets(doc).icons).toEqual([
+ { name: 'lucide:heart' },
+ { name: 'material-symbols-rounded:home', options: { wght: 200 } }
+ ])
+ })
+
test('lists every icon a variable names in any theme', () => {
const doc = parsePenDocument(
JSON.stringify({
@@ -64,16 +101,48 @@ describe('penAssets', () => {
children: [{ id: 'a', type: 'icon', library: '$set', icon: '$glyph' }]
})
)
- expect(penAssets(doc).icons).toEqual(['lucide:sun', 'lucide:moon'])
+ expect(penAssets(doc).icons).toEqual([{ name: 'lucide:sun' }, { name: 'lucide:moon' }])
+ })
+
+ test('lists the empty value a theme without an entry reads, as drawing does', () => {
+ const doc = parsePenDocument(
+ JSON.stringify({
+ version: '2.21',
+ themes: { mode: ['light', 'dark'] },
+ variables: {
+ thin: { type: 'number', value: [{ value: 300, theme: { mode: 'dark' } }] },
+ glyph: { type: 'string', value: [{ value: 'moon', theme: { mode: 'dark' } }] }
+ },
+ children: [
+ {
+ id: 'a',
+ type: 'icon',
+ library: 'Material Symbols Rounded',
+ icon: 'home',
+ weight: '$thin'
+ },
+ // In the light theme the name is empty, so nothing is drawn there.
+ { id: 'b', type: 'icon', library: 'lucide', icon: '$glyph' }
+ ]
+ })
+ )
+ expect(penAssets(doc).icons).toEqual([
+ { name: 'material-symbols-rounded:home', options: { wght: 0 } },
+ { name: 'material-symbols-rounded:home', options: { wght: 300 } },
+ { name: 'lucide:moon' }
+ ])
})
- test('draws Lucide, Feather, and Phosphor from Iconify, and Material Symbols from their fonts', () => {
+ test("names each library's icons in its set, Material Symbols at their weight, 200 unless set", () => {
expect(iconName('feather', 'star')).toBe('feather:star')
expect(iconName('phosphor', 'airplane')).toBe('ph:airplane')
- expect(iconName('Material Symbols Outlined', 'home')).toBeNull()
- expect(iconFontFamily('Material Symbols Sharp')).toBe('Material Symbols Sharp')
- expect(iconFontFamily('lucide')).toBeNull()
+ expect(iconName('Material Symbols Outlined', 'dark_mode')).toBe(
+ 'material-symbols-outlined:dark_mode'
+ )
expect(iconName('unknown', 'home')).toBeNull()
+ expect(iconOptions('Material Symbols Sharp', undefined)).toEqual({ wght: 200 })
+ expect(iconOptions('Material Symbols Sharp', 650)).toEqual({ wght: 650 })
+ expect(iconOptions('lucide', 650)).toBeUndefined()
})
})
@@ -144,10 +213,18 @@ describe('parsePenFile — images', () => {
describe('parsePenFile — icons', () => {
function drawn(fields: Partial<PenNode>, doc: Partial<PenDocument> = {}) {
- const calls: { name: string; size: number; color: Color }[] = []
+ const calls: { name: string; size: number; color: Color; options?: Record<string, number> }[] =
+ []
const icons = {
- draw(graph: SceneGraph, frameId: string, name: string, size: number, color: Color) {
- calls.push({ name, size, color })
+ draw(
+ graph: SceneGraph,
+ frameId: string,
+ name: string,
+ size: number,
+ color: Color,
+ options?: Record<string, number>
+ ) {
+ calls.push(options ? { name, size, color, options } : { name, size, color })
graph.createNode('VECTOR', frameId, { width: size, height: size })
return true
}
@@ -178,22 +255,20 @@ describe('parsePenFile — icons', () => {
expect(graph.getChildren('icon').map((glyph) => [glyph.x, glyph.y])).toEqual([[33, 0]])
})
- test('sets a Material Symbol in its font at the icon weight, 200 by default', () => {
+ test('draws a Material Symbol from its set at the icon weight, 200 by default', () => {
+ // A variable that holds no weight leaves the default.
for (const [weight, expected] of [
[undefined, 200],
- [650, 650]
+ [650, 650],
+ ['$missing', 200]
] as const) {
- const { graph, calls } = drawn({ library: 'Material Symbols Rounded', icon: 'home', weight })
- expect(calls).toEqual([])
- expect(graph.getChildren('icon')).toMatchObject([
+ const { calls } = drawn({ library: 'Material Symbols Rounded', icon: 'home', weight })
+ expect(calls).toEqual([
{
- type: 'TEXT',
- text: 'home',
- fontFamily: 'Material Symbols Rounded',
- fontVariations: [{ axis: 'wght', value: expected }],
- fontSize: 30,
- x: 33,
- y: 0
+ name: 'material-symbols-rounded:home',
+ size: 30,
+ color: { r: 0.8, g: 0, b: 0, a: 1 },
+ options: { wght: expected }
}
])
}
@@ -215,4 +290,15 @@ describe('parsePenFile — icons', () => {
)
expect(calls.map((call) => call.name)).toEqual(['feather:moon'])
})
+
+ test('draws at the weight a theme without an entry reads, which the assets list', () => {
+ const { calls } = drawn(
+ { library: 'Material Symbols Rounded', icon: 'home', weight: '$thin' },
+ {
+ themes: { mode: ['light', 'dark'] },
+ variables: { thin: { type: 'number', value: [{ value: 300, theme: { mode: 'dark' } }] } }
+ }
+ )
+ expect(calls.map((call) => call.options)).toEqual([{ wght: 0 }])
+ })
})
diff --git a/packages/scene-graph/src/icons/model.ts b/packages/scene-graph/src/icons/model.ts
index 28ec345cd..04ebb3351 100644
--- a/packages/scene-graph/src/icons/model.ts
+++ b/packages/scene-graph/src/icons/model.ts
@@ -13,6 +13,15 @@ export function withIcon(node: SceneNode, icon: Icon | null): SceneNode['pluginD
return withPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.icon, icon ?? undefined)
}
+/**
+ * Whether code can draw the icon from its name alone, as Iconify's components do. An icon with
+ * options was drawn from a set of our own, such as a font at its axes, so it exports as the paths
+ * it draws.
+ */
+export function isNamedIcon(icon: Icon): boolean {
+ return icon.options === undefined
+}
+
/** The layer name an icon is placed with: its name in the set, such as `cat` for `mdi:cat`. */
export function iconLayerName(name: string): string {
return name.slice(name.indexOf(':') + 1)
diff --git a/packages/scene-graph/src/icons/schema.ts b/packages/scene-graph/src/icons/schema.ts
index e5704d434..356dbeda1 100644
--- a/packages/scene-graph/src/icons/schema.ts
+++ b/packages/scene-graph/src/icons/schema.ts
@@ -1,12 +1,28 @@
import * as v from 'valibot'
-/** An icon's name in its set, `prefix:name`, as Iconify names icons. */
-export const ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:[-_][a-z0-9]+)*$/
+/**
+ * An icon's name in its set, `prefix:name`, as Iconify names icons. Names may hold dots, as SF
+ * Symbols' do (`house.fill`).
+ */
+export const ICON_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:[-_.][a-z0-9]+)*$/
+
+/**
+ * How an icon from a set we draw ourselves is drawn: a font's axes, such as Material Symbols'
+ * `wght` and `FILL`, or SF Symbols' weight and scale. Icons from Iconify have none.
+ */
+export const iconOptionsSchema = v.record(v.string(), v.union([v.number(), v.string()]))
+
+export type IconOptions = v.InferOutput<typeof iconOptionsSchema>
export const iconSchema = v.object({
name: v.pipe(v.string(), v.regex(ICON_NAME)),
/** A fingerprint of the glyph as placed, to tell when its paths were edited; see `iconGlyph`. */
- glyph: v.optional(v.string())
+ glyph: v.optional(v.string()),
+ /**
+ * Set for an icon drawn from one of our own sets rather than Iconify, so it is drawn again and
+ * exported as the paths it draws rather than by its name alone.
+ */
+ options: v.optional(iconOptionsSchema)
})
/** An icon a frame draws. */
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 000000000..8c58bf35a
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,88 @@
+diff --git a/dist/opentype.js b/dist/opentype.js
+index 4dc6dea3bc470c5932364e0162bca66d614c8045..2568c3fc2c5a1a5cd5a556a08dd73ccf17b412f3 100644
+--- a/dist/opentype.js
++++ b/dist/opentype.js
+@@ -2322,7 +2322,6 @@ var opentype = (() => {
+ let serializedDataOffset = this.relativeOffset;
+ for (let h = 0; h < count; h++) {
+ const header = headers[h];
+- header.privatePoints = [];
+ this.relativeOffset = serializedDataOffset;
+ if (flavor === "cvar" && !header.peakTuple) {
+ console.warn("An embedded peak tuple is required in TupleVariationHeaders for the cvar table.");
+@@ -2339,11 +2338,11 @@ var opentype = (() => {
+ const parseDeltas = () => {
+ let pointsCount = 0;
+ if (flavor === "gvar") {
+- pointsCount = header.privatePoints.length || sharedPoints.length;
++ pointsCount = header.privatePoints ? header.privatePoints.length : sharedPoints.length;
+ if (!pointsCount) {
+ const glyph = glyphs.get(glyphIndex);
+ glyph.path;
+- pointsCount = glyph.points.length;
++ pointsCount = glyph.isComposite ? glyph.components.length : glyph.points.length;
+ pointsCount += 4;
+ }
+ } else if (flavor === "cvar") {
+@@ -11303,7 +11302,7 @@ var opentype = (() => {
+ const component = glyph.components[c];
+ const componentGlyph = this.font.glyphs.get(component.glyphIndex);
+ const componentTransform = copyComponent(component);
+- const deltaIndex = tuplePoints.indexOf(c);
++ const deltaIndex = tuplePoints.length ? tuplePoints.indexOf(c) : c;
+ if (deltaIndex > -1) {
+ componentTransform.dx += Math.round(header.deltas[deltaIndex] * factor);
+ componentTransform.dy += Math.round(header.deltasY[deltaIndex] * factor);
+@@ -11366,7 +11365,7 @@ var opentype = (() => {
+ if (factor === 0) {
+ continue;
+ }
+- const tuplePoints = header.privatePoints.length ? header.privatePoints : sharedPoints;
++ const tuplePoints = header.privatePoints ? header.privatePoints : sharedPoints;
+ if (flavor === "gvar" && args.glyph && args.glyph.isComposite) {
+ this.transformComponents(args.glyph, transformedPoints, coords, tuplePoints, header, factor);
+ } else if (tuplePoints.length === 0) {
+diff --git a/dist/opentype.mjs b/dist/opentype.mjs
+index 53ed20eccb08a16519bbd40a866e0bdc3fa9f2d6..30542d96f3bca0bf559fb099fa382808a78b01dd 100644
+--- a/dist/opentype.mjs
++++ b/dist/opentype.mjs
+@@ -2290,7 +2290,6 @@ Parser.prototype.parseTupleVariationStore = function(tableOffset, axisCount, fla
+ let serializedDataOffset = this.relativeOffset;
+ for (let h = 0; h < count; h++) {
+ const header = headers[h];
+- header.privatePoints = [];
+ this.relativeOffset = serializedDataOffset;
+ if (flavor === "cvar" && !header.peakTuple) {
+ console.warn("An embedded peak tuple is required in TupleVariationHeaders for the cvar table.");
+@@ -2307,11 +2306,11 @@ Parser.prototype.parseTupleVariationStore = function(tableOffset, axisCount, fla
+ const parseDeltas = () => {
+ let pointsCount = 0;
+ if (flavor === "gvar") {
+- pointsCount = header.privatePoints.length || sharedPoints.length;
++ pointsCount = header.privatePoints ? header.privatePoints.length : sharedPoints.length;
+ if (!pointsCount) {
+ const glyph = glyphs.get(glyphIndex);
+ glyph.path;
+- pointsCount = glyph.points.length;
++ pointsCount = glyph.isComposite ? glyph.components.length : glyph.points.length;
+ pointsCount += 4;
+ }
+ } else if (flavor === "cvar") {
+@@ -11271,7 +11270,7 @@ var VariationProcessor = class {
+ const component = glyph.components[c];
+ const componentGlyph = this.font.glyphs.get(component.glyphIndex);
+ const componentTransform = copyComponent(component);
+- const deltaIndex = tuplePoints.indexOf(c);
++ const deltaIndex = tuplePoints.length ? tuplePoints.indexOf(c) : c;
+ if (deltaIndex > -1) {
+ componentTransform.dx += Math.round(header.deltas[deltaIndex] * factor);
+ componentTransform.dy += Math.round(header.deltasY[deltaIndex] * factor);
+@@ -11334,7 +11333,7 @@ var VariationProcessor = class {
+ if (factor === 0) {
+ continue;
+ }
+- const tuplePoints = header.privatePoints.length ? header.privatePoints : sharedPoints;
++ const tuplePoints = header.privatePoints ? header.privatePoints : sharedPoints;
+ if (flavor === "gvar" && args.glyph && args.glyph.isComposite) {
+ this.transformComponents(args.glyph, transformedPoints, coords, tuplePoints, header, factor);
+ } else if (tuplePoints.length === 0) {
diff --git a/src/app/editor/icon-picker/history.ts b/src/app/editor/icons/history.ts
similarity index 100%
rename from src/app/editor/icon-picker/history.ts
rename to src/app/editor/icons/history.ts
diff --git a/src/app/editor/icons/provider.ts b/src/app/editor/icons/provider.ts
new file mode 100644
index 000000000..3cbef67a9
--- /dev/null
+++ b/src/app/editor/icons/provider.ts
@@ -0,0 +1,8 @@
+import { createIconProvider } from '@open-pencil/core/icons'
+
+import { browserWebFontFetch } from '@/app/editor/fonts/browser-fetch'
+import { tauriFetch } from '@/app/tauri/http'
+import { IS_TAURI } from '@/constants'
+
+/** The app's icons: Iconify's, with Material Symbols drawn from Google's fonts, reached as the app's web fonts are. */
+export const appIcons = createIconProvider(IS_TAURI ? tauriFetch : browserWebFontFetch)
diff --git a/src/app/editor/session/create.ts b/src/app/editor/session/create.ts
index f62ca28d3..f9a5956fe 100644
--- a/src/app/editor/session/create.ts
+++ b/src/app/editor/session/create.ts
@@ -15,6 +15,7 @@ import {
import { resolveFigmaClipboardImages } from '@/app/editor/clipboard/figma-images'
import { bindClipboardNotifications } from '@/app/editor/clipboard/notifications'
import { loadFont } from '@/app/editor/fonts'
+import { appIcons } from '@/app/editor/icons/provider'
import { createRecentPages } from '@/app/editor/pages/recent'
import { createCanvasPaneRegistry } from '@/app/editor/panes/registry'
import { createEditorPreparationController } from '@/app/editor/preparation/controller'
@@ -49,6 +50,7 @@ function buildEditorStore(initialGraph?: SceneGraph) {
graph,
state,
loadFont,
+ icons: appIcons,
shaderRasterizer: createShaderRasterizer(),
resolveFigmaClipboardImages: IS_TAURI ? resolveFigmaClipboardImages : undefined,
skipInitialGraphSetup: !!initialGraph,
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index 4ddd79f54..52341fff4 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -18,6 +18,7 @@ import { applyImportedDocument } from '@/app/document/io/imported-document'
import type { DocumentSourceIdentity } from '@/app/document/io/types'
import { getRecoveryStore, type RecoverySnapshotMeta } from '@/app/document/recovery'
import { setActiveEditorStore } from '@/app/editor/active-store'
+import { appIcons } from '@/app/editor/icons/provider'
import type { EditorPreparationHandle as DocumentLoadSession } from '@/app/editor/preparation/types'
import { createEditorStore } from '@/app/editor/session'
import type { EditorStore } from '@/app/editor/session'
@@ -544,12 +545,15 @@ export async function openFileInNewTab(
imported = await readFigForTab(file, load.signal)
sourceFormat = 'fig'
} else {
- const result = await io.readDocument({
- name: file.name,
- mimeType: file.type || undefined,
- data: new Uint8Array(await file.arrayBuffer()),
- readAsset: documentAssetReader(path)
- })
+ const result = await io.readDocument(
+ {
+ name: file.name,
+ mimeType: file.type || undefined,
+ data: new Uint8Array(await file.arrayBuffer()),
+ readAsset: documentAssetReader(path)
+ },
+ { icons: appIcons }
+ )
imported = result.graph
sourceFormat = result.sourceFormat
}
diff --git a/src/components/icon-picker/IconPicker.vue b/src/components/icon-picker/IconPicker.vue
index 746159777..97bd9bab6 100644
--- a/src/components/icon-picker/IconPicker.vue
+++ b/src/components/icon-picker/IconPicker.vue
@@ -7,7 +7,7 @@ import { useIconSearch } from '@open-pencil/vue/controls/icon'
import { useCommonMessages, usePanelMessages } from '@open-pencil/vue/i18n'
import { useEditorStore } from '@/app/editor/active-store'
-import { lastIconSet, recentIcons, rememberIcon } from '@/app/editor/icon-picker/history'
+import { lastIconSet, recentIcons, rememberIcon } from '@/app/editor/icons/history'
import { formatNumber } from '@/app/i18n/number'
import AppCombobox from '@/components/ui/select/AppCombobox.vue'
import type { AppComboboxOption } from '@/components/ui/select/AppCombobox.vue'
diff --git a/tests/fixtures/fonts/MaterialSymbolsRounded-home-dark_mode.ttf b/tests/fixtures/fonts/MaterialSymbolsRounded-home-dark_mode.ttf
new file mode 100644
index 000000000..bd347cb94
--- /dev/null
+++ b/tests/fixtures/fonts/MaterialSymbolsRounded-home-dark_mode.ttf
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2b2141097d816e7c077cf323f32f8268d430a4817876d28f4d9db3910b90696c
+size 9960
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Bold.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Bold.font
deleted file mode 100644
index 8e46b3880..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Bold.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--ExtraLight.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--ExtraLight.font
deleted file mode 100644
index 246a92919..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--ExtraLight.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Light.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Light.font
deleted file mode 100644
index ba3c5d7d5..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Light.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Medium.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Medium.font
deleted file mode 100644
index 083ce6315..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Medium.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Regular.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Regular.font
deleted file mode 100644
index 1526512b1..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Regular.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--SemiBold.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--SemiBold.font
deleted file mode 100644
index ff1b2df12..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--SemiBold.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Thin.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Thin.font
deleted file mode 100644
index 12b40401e..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Outlined--Thin.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Bold.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Bold.font
deleted file mode 100644
index 7cc42e8c3..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Bold.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--ExtraLight.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--ExtraLight.font
deleted file mode 100644
index 505efe3d0..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--ExtraLight.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Light.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Light.font
deleted file mode 100644
index f7c6326d0..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Light.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Medium.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Medium.font
deleted file mode 100644
index b5c744033..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Medium.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Regular.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Regular.font
deleted file mode 100644
index 93eb4208b..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Regular.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--SemiBold.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--SemiBold.font
deleted file mode 100644
index bf4085a2a..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--SemiBold.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Thin.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Thin.font
deleted file mode 100644
index ba264a8da..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Rounded--Thin.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Bold.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Bold.font
deleted file mode 100644
index 59dbef37d..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Bold.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--ExtraLight.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--ExtraLight.font
deleted file mode 100644
index 6f27d1e8f..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--ExtraLight.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Light.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Light.font
deleted file mode 100644
index e9628c88d..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Light.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Medium.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Medium.font
deleted file mode 100644
index 9ff3179f0..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Medium.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Regular.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Regular.font
deleted file mode 100644
index bc153b8b4..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Regular.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--SemiBold.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--SemiBold.font
deleted file mode 100644
index 168feae1c..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--SemiBold.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Thin.font b/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Thin.font
deleted file mode 100644
index 78b5ab813..000000000
Binary files a/tests/fixtures/pen-oracles/fonts/Material Symbols Sharp--Thin.font and /dev/null differ
diff --git a/tests/fixtures/pen-oracles/fonts/Roboto--Regular.font b/tests/fixtures/pen-oracles/fonts/Roboto--Regular.font
index 68b54693b..29ba5244e 100644
Binary files a/tests/fixtures/pen-oracles/fonts/Roboto--Regular.font and b/tests/fixtures/pen-oracles/fonts/Roboto--Regular.font differ
diff --git a/tests/fixtures/pen-oracles/google/0.bin b/tests/fixtures/pen-oracles/google/0.bin
new file mode 100644
index 000000000..23c9e66b0
--- /dev/null
+++ b/tests/fixtures/pen-oracles/google/0.bin
@@ -0,0 +1,22 @@
+@font-face {
+ font-family: 'Material Symbols Sharp';
+ font-style: normal;
+ font-weight: 100 700;
+ src: url(https://fonts.gstatic.com/l/font?kit=gNMVW2J8Roq16WD5tFNRaeLQk6-SHQ_R00k4aWHSSmlN49qeLYv7i46trSzyfg&skey=b2b11cf3b396438f&v=v377) format('woff2');
+}
+
+.material-symbols-sharp {
+ font-family: 'Material Symbols Sharp';
+ font-weight: normal;
+ font-style: normal;
+ font-size: 24px;
+ line-height: 1;
+ letter-spacing: normal;
+ text-transform: none;
+ display: inline-block;
+ white-space: nowrap;
+ word-wrap: normal;
+ direction: ltr;
+ -webkit-font-feature-settings: 'liga';
+ -webkit-font-smoothing: antialiased;
+}
diff --git a/tests/fixtures/pen-oracles/google/1.bin b/tests/fixtures/pen-oracles/google/1.bin
new file mode 100644
index 000000000..a9e5055df
--- /dev/null
+++ b/tests/fixtures/pen-oracles/google/1.bin
@@ -0,0 +1,22 @@
+@font-face {
+ font-family: 'Material Symbols Outlined';
+ font-style: normal;
+ font-weight: 100 700;
+ src: url(https://fonts.gstatic.com/l/font?kit=kJEhBvYX7BgnkSrUwT8OhrdQw4oELdPIeeII9v6oFsLjBuVYLA7hpcEoWsgTge43VQ&skey=b8dc2088854b122f&v=v380) format('woff2');
+}
+
+.material-symbols-outlined {
+ font-family: 'Material Symbols Outlined';
+ font-weight: normal;
+ font-style: normal;
+ font-size: 24px;
+ line-height: 1;
+ letter-spacing: normal;
+ text-transform: none;
+ display: inline-block;
+ white-space: nowrap;
+ word-wrap: normal;
+ direction: ltr;
+ -webkit-font-feature-settings: 'liga';
+ -webkit-font-smoothing: antialiased;
+}
diff --git a/tests/fixtures/pen-oracles/google/2.bin b/tests/fixtures/pen-oracles/google/2.bin
new file mode 100644
index 000000000..d5505efe1
--- /dev/null
+++ b/tests/fixtures/pen-oracles/google/2.bin
@@ -0,0 +1,22 @@
+@font-face {
+ font-family: 'Material Symbols Rounded';
+ font-style: normal;
+ font-weight: 100 700;
+ src: url(https://fonts.gstatic.com/l/font?kit=sykg-zNym6YjUruM-QrEh7-nyTnjDwKNJ_190FjzaqkNCeEVOt6mZXGjIbrZz9Io32A&skey=70ddea8fe54d532e&v=v381) format('woff2');
+}
+
+.material-symbols-rounded {
+ font-family: 'Material Symbols Rounded';
+ font-weight: normal;
+ font-style: normal;
+ font-size: 24px;
+ line-height: 1;
+ letter-spacing: normal;
+ text-transform: none;
+ display: inline-block;
+ white-space: nowrap;
+ word-wrap: normal;
+ direction: ltr;
+ -webkit-font-feature-settings: 'liga';
+ -webkit-font-smoothing: antialiased;
+}
diff --git a/tests/fixtures/pen-oracles/google/3.bin b/tests/fixtures/pen-oracles/google/3.bin
new file mode 100644
index 000000000..18302a242
--- /dev/null
+++ b/tests/fixtures/pen-oracles/google/3.bin
@@ -0,0 +1,22 @@
+@font-face {
+ font-family: 'Material Symbols Rounded';
+ font-style: normal;
+ font-weight: 100 700;
+ src: url(https://fonts.gstatic.com/l/font?kit=sykg-zNym6YjUruM-QrEh7-nyTnjDwKNJ_190FjzaqkNCeEVMOSgaHq4Pr2y4MoNDFzV2bUn6CT2OlbTpw&skey=70ddea8fe54d532e&v=v381) format('woff2');
+}
+
+.material-symbols-rounded {
+ font-family: 'Material Symbols Rounded';
+ font-weight: normal;
+ font-style: normal;
+ font-size: 24px;
+ line-height: 1;
+ letter-spacing: normal;
+ text-transform: none;
+ display: inline-block;
+ white-space: nowrap;
+ word-wrap: normal;
+ direction: ltr;
+ -webkit-font-feature-settings: 'liga';
+ -webkit-font-smoothing: antialiased;
+}
diff --git a/tests/fixtures/pen-oracles/google/4.bin b/tests/fixtures/pen-oracles/google/4.bin
new file mode 100644
index 000000000..2eaf30c79
Binary files /dev/null and b/tests/fixtures/pen-oracles/google/4.bin differ
diff --git a/tests/fixtures/pen-oracles/google/5.bin b/tests/fixtures/pen-oracles/google/5.bin
new file mode 100644
index 000000000..663582700
Binary files /dev/null and b/tests/fixtures/pen-oracles/google/5.bin differ
diff --git a/tests/fixtures/pen-oracles/google/6.bin b/tests/fixtures/pen-oracles/google/6.bin
new file mode 100644
index 000000000..311daa68a
Binary files /dev/null and b/tests/fixtures/pen-oracles/google/6.bin differ
diff --git a/tests/fixtures/pen-oracles/google/7.bin b/tests/fixtures/pen-oracles/google/7.bin
new file mode 100644
index 000000000..b74ef3559
Binary files /dev/null and b/tests/fixtures/pen-oracles/google/7.bin differ
diff --git a/tests/fixtures/pen-oracles/google/index.json b/tests/fixtures/pen-oracles/google/index.json
new file mode 100644
index 000000000..3fdf8f745
--- /dev/null
+++ b/tests/fixtures/pen-oracles/google/index.json
@@ -0,0 +1,10 @@
+{
+ "https://fonts.googleapis.com/css2?family=Material+Symbols+Sharp%3Aopsz%2Cwght%2CFILL%2CGRAD%4020..48%2C100..700%2C0..1%2C-50..200&icon_names=home": "0.bin",
+ "https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined%3Aopsz%2Cwght%2CFILL%2CGRAD%4020..48%2C100..700%2C0..1%2C-50..200&icon_names=home": "1.bin",
+ "https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded%3Aopsz%2Cwght%2CFILL%2CGRAD%4020..48%2C100..700%2C0..1%2C-50..200&icon_names=settings": "2.bin",
+ "https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded%3Aopsz%2Cwght%2CFILL%2CGRAD%4020..48%2C100..700%2C0..1%2C-50..200&icon_names=dark_mode%2Chome%2Csun": "3.bin",
+ "https://fonts.gstatic.com/l/font?kit=gNMVW2J8Roq16WD5tFNRaeLQk6-SHQ_R00k4aWHSSmlN49qeLYv7i46trSzyfg&skey=b2b11cf3b396438f&v=v377": "4.bin",
+ "https://fonts.gstatic.com/l/font?kit=sykg-zNym6YjUruM-QrEh7-nyTnjDwKNJ_190FjzaqkNCeEVOt6mZXGjIbrZz9Io32A&skey=70ddea8fe54d532e&v=v381": "5.bin",
+ "https://fonts.gstatic.com/l/font?kit=kJEhBvYX7BgnkSrUwT8OhrdQw4oELdPIeeII9v6oFsLjBuVYLA7hpcEoWsgTge43VQ&skey=b8dc2088854b122f&v=v380": "6.bin",
+ "https://fonts.gstatic.com/l/font?kit=sykg-zNym6YjUruM-QrEh7-nyTnjDwKNJ_190FjzaqkNCeEVMOSgaHq4Pr2y4MoNDFzV2bUn6CT2OlbTpw&skey=70ddea8fe54d532e&v=v381": "7.bin"
+}
diff --git a/tests/fixtures/pen-oracles/manifest.json b/tests/fixtures/pen-oracles/manifest.json
index c6cd51ec6..4885bc981 100644
--- a/tests/fixtures/pen-oracles/manifest.json
+++ b/tests/fixtures/pen-oracles/manifest.json
@@ -96,14 +96,12 @@
{
"node": "P Icon weights",
"penNodeId": "MOmt0",
- "maximumDifferentPercent": 0.24,
- "note": "Google's static Material Symbols faces for weights 100 and 200 both declare weight class 250, and the renderer picks a family's face by it, so with both loaded 200 draws as 100."
+ "maximumDifferentPercent": 0.05
},
{
"node": "P Icon variables",
"penNodeId": "alRyT",
- "maximumDifferentPercent": 0.19,
- "note": "Google's static Material Symbols faces for weights 100 and 200 both declare weight class 250, and the renderer picks a family's face by it, so with both loaded 200 draws as 100."
+ "maximumDifferentPercent": 0.05
}
]
}
diff --git a/tools/generate/visual-oracles/src/operations/compare/pen.ts b/tools/generate/visual-oracles/src/operations/compare/pen.ts
index a1f056d45..e9926f306 100644
--- a/tools/generate/visual-oracles/src/operations/compare/pen.ts
+++ b/tools/generate/visual-oracles/src/operations/compare/pen.ts
@@ -10,9 +10,9 @@
* Replaces the fixture folder (tests/fixtures/pen-oracles by default) with:
* probes.pen and its images — the document
* <frame id>.png — pen.dev's export of each frame, at scale 1
- * iconify/<prefix>.json — the icons the document draws, as Iconify sets
- * fonts/<family>--<style>.font — the font faces its text is drawn with, icon fonts subset to
- * the icons it draws
+ * iconify/<prefix>.json — the Iconify icons the document draws, as Iconify sets
+ * google/ — Google's answers for its Material Symbols, by URL in index.json
+ * fonts/<family>--<style>.font — the font faces its text is drawn with
* keeping manifest.json, and writes pen.png, openpencil.png, diff.png, and metrics.json per frame
* to --output.
*/
@@ -24,10 +24,16 @@ import { parseArgs } from 'node:util'
import { Client } from '@modelcontextprotocol/client'
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio'
-import { groupBy, omit, pick, uniq } from 'es-toolkit'
+import { groupBy, omit, pick } from 'es-toolkit'
import * as v from 'valibot'
-import { createIconifyProvider, parseIconName } from '@open-pencil/core/icons'
+import {
+ createIconifyProvider,
+ createIconSetsProvider,
+ createMaterialSymbolsProvider,
+ MATERIAL_SYMBOLS_PREFIXES,
+ parseIconName
+} from '@open-pencil/core/icons'
import { IORegistry, penFormat } from '@open-pencil/core/io'
import {
comparePNGs,
@@ -38,20 +44,17 @@ import {
import { computeAllLayouts } from '@open-pencil/core/layout'
import { fontManager, prepareGraphFonts } from '@open-pencil/core/text'
import {
- iconFontFamily,
isDocumentAssetPath,
parsePenDocument,
penAssets,
type PenNode,
type PenOverride
} from '@open-pencil/pen'
-import { styleToWeight } from '@open-pencil/scene-graph/font-style'
const PEN_MCP_SERVER =
'/Applications/Pen.app/Contents/Resources/app.asar.unpacked/out/mcp-server-darwin-arm64'
const ICONIFY_API = 'https://api.iconify.design'
const EXPORT_TIMEOUT_MS = 300_000
-const GOOGLE_FONTS_CSS = 'https://fonts.googleapis.com/css2'
const iconSetSchema = v.pipe(
v.string(),
@@ -133,31 +136,53 @@ try {
rmSync(exported, { recursive: true, force: true })
}
-const iconSets = await fetchIconSets(assets.icons)
+const iconifyNames = assets.icons
+ .map((request) => request.name)
+ .filter((name) => !MATERIAL_SYMBOLS_PREFIXES.some((prefix) => name.startsWith(`${prefix}:`)))
+const iconSets = await fetchIconSets(iconifyNames)
for (const set of iconSets.values()) {
writeFileSync(
join(fixtures, 'iconify', `${set.prefix}.json`),
`${JSON.stringify(set, null, 2)}\n`
)
}
-const fonts = new Map<string, { family: string; style: string; data: ArrayBuffer }>()
+const fonts = new Map<string, { data: ArrayBuffer }>()
fontManager.setDownloadedFontCache({
read: () => Promise.resolve(null),
write(family, style, data) {
- fonts.set(`${family}--${style}`, { family, style, data })
+ fonts.set(`${family}--${style}`, { data })
return Promise.resolve()
}
})
-const icons = createIconifyProvider({
- fetchCollection: (prefix, names) => {
- const set = iconSets.get(prefix)
- if (!set) return Promise.reject(new Error(`No "${prefix}" icons were recorded`))
- return Promise.resolve({ ...set, icons: pick(set.icons, names) })
+// Google's answers for the Material Symbols the document draws, kept to be served back offline.
+const google = new Map<string, Uint8Array>()
+const recordingFetch: typeof fetch = Object.assign(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const response = await fetch(input, init)
+ const url = input instanceof Request ? input.url : String(input)
+ if (response.ok) google.set(url, await response.clone().bytes())
+ return response
},
- search: () => Promise.resolve({ icons: [], total: 0, collections: {} }),
- collections: () => Promise.resolve([]),
- collectionIcons: () => Promise.resolve([])
+ { preconnect: fetch.preconnect }
+)
+const icons = createIconSetsProvider({
+ sources: [
+ {
+ prefixes: MATERIAL_SYMBOLS_PREFIXES,
+ provider: createMaterialSymbolsProvider(recordingFetch)
+ }
+ ],
+ fallback: createIconifyProvider({
+ fetchCollection: (prefix, names) => {
+ const set = iconSets.get(prefix)
+ if (!set) return Promise.reject(new Error(`No "${prefix}" icons were recorded`))
+ return Promise.resolve({ ...set, icons: pick(set.icons, names) })
+ },
+ search: () => Promise.resolve({ icons: [], total: 0, collections: {} }),
+ collections: () => Promise.resolve([]),
+ collectionIcons: () => Promise.resolve([])
+ })
})
const { graph } = await new IORegistry([penFormat]).readDocument(
{
@@ -199,24 +224,15 @@ for (const frame of frames) {
console.log(`${name} (${frame.id}): ${differentPercent.toFixed(2)}% pixels differ`)
}
-// Icon fonts are recorded as just the icons the document draws; whole, each weight is a megabyte.
-const iconsByFamily = groupBy(
- [...graph.getAllNodes()].filter(
- (node) => node.type === 'TEXT' && iconFontFamily(node.fontFamily) !== null
- ),
- (node) => node.fontFamily
-)
-for (const [face, { family, style, data }] of fonts) {
- const bytes = Object.hasOwn(iconsByFamily, family)
- ? await iconFontSubset(
- family,
- style,
- iconsByFamily[family].map((node) => node.text)
- )
- : new Uint8Array(data)
- writeFileSync(join(fixtures, 'fonts', `${face}.font`), bytes)
+for (const [face, { data }] of fonts) {
+ writeFileSync(join(fixtures, 'fonts', `${face}.font`), new Uint8Array(data))
}
-console.log(`Recorded ${iconSets.size} icon sets and ${fonts.size} font faces in ${fixtures}`)
+const index = Object.fromEntries([...google.keys()].map((url, at) => [url, `${at}.bin`]))
+for (const [url, bytes] of google) writeFileSync(join(fixtures, 'google', index[url]), bytes)
+writeFileSync(join(fixtures, 'google', 'index.json'), `${JSON.stringify(index, null, 2)}\n`)
+console.log(
+ `Recorded ${iconSets.size} icon sets, ${google.size} Google answers, and ${fonts.size} font faces in ${fixtures}`
+)
/** Empties the fixture folder except its manifest, which holds the comparison's thresholds. */
function clearFixtures() {
@@ -225,6 +241,7 @@ function clearFixtures() {
if (entry !== 'manifest.json') rmSync(join(fixtures, entry), { recursive: true, force: true })
}
mkdirSync(join(fixtures, 'iconify'))
+ mkdirSync(join(fixtures, 'google'))
mkdirSync(join(fixtures, 'fonts'))
mkdirSync(output, { recursive: true })
}
@@ -277,21 +294,6 @@ async function exportFromPen(document: string, frameIds: string[], directory: st
}
}
-/**
- * Google's own subset of an icon font face holding only `names`, in the TrueType it serves to
- * clients that do not ask for WOFF2.
- */
-async function iconFontSubset(family: string, style: string, names: string[]): Promise<Uint8Array> {
- const query = new URLSearchParams({
- family: `${family}:wght@${styleToWeight(style)}`,
- icon_names: uniq(names).sort().join(',')
- })
- const css = await (await fetch(`${GOOGLE_FONTS_CSS}?${query}`)).text()
- const url = /src: url\((https:[^)]+)\) format\('truetype'\)/.exec(css)?.[1]
- if (!url) throw new Error(`Google Fonts has no subset of ${family} ${style}`)
- return (await fetch(url)).bytes()
-}
-
/** The Iconify sets holding `names`, each with just the icons named from it. */
async function fetchIconSets(names: readonly string[]): Promise<Map<string, IconSet>> {
const byPrefix = groupBy(