openpencil/tests/engine/text/fonts/variations.test.ts
Danila Poyarkov aa86873dd7
test: typecheck the test suites and fix what that found (#896)
* build: typecheck the test suites

Tests were in no TypeScript program: no tsconfig included tests/** or
packages/*/tests/**, and bun strips types without checking them, so a
fixture could drop a required field and keep passing until something
read it.

@types/bun moves to the root because it was installed per package only,
and #cli-tests/* joins the paths the root config already carries.

* test: fix the type errors the test suites were hiding

Typechecking the tests turned up 1123 errors. Most were ordinary
strictness, but some were real: `NodeChange` bound to Figma's plugin
typings rather than the Kiwi codec in thirteen .fig tests,
materializeInstance was called with six arguments against five so the
blobs and source children were dropped, CanvasKit pixels were written
to a plain object that never reached WASM, and assertions were made
through accessors that do not exist, so they asserted nothing.

Fixtures that had quietly lost a required field now carry it, nullable
results are narrowed through the existing expectDefined helper rather
than assumed, and stand-ins for CanvasKit and the editor go through one
named helper instead of an unexplained cast at each site.

No test was deleted, skipped, or weakened, and no `any`, non-null
assertion, or ts-expect-error was introduced.

* docs: record what typechecking the tests established

Pins the app program's global types with an assertion rather than a
note, since an unpinned types list lets any root @types package decide
which platform src/** is judged against.

The two environment faults that look like code regressions — Vite's
dependency pre-bundle outliving a package rebuild, and heavy .fig
suites failing under load — go to the development docs, where an
explanation belongs.

* fix: align @types/bun and keep node types resolvable when extended

The root manifest declared a newer @types/bun than every package, which
check:monorepo rejects, and pinning the app program's types left them
unresolvable from a config that extends this one out of tree.

* fix: fail the test typecheck when the compiler itself fails

The gate matched diagnostics by substring, so a compiler or config
failure that named no test file printed a pass while having checked
nothing. Diagnostics are now split by whether they name a file: an
unscoped one is the run failing and stops the gate, a test file's is a
finding, and a source file's stays out by design.

Also drops the parameter planComponentConstruction never read, and
makes the inner-shadow verification script exit non-zero when it
renders no image instead of logging and succeeding.

* chore: merge master into tests-typecheck
2026-10-05 12:42:38 +00:00

199 lines
6.4 KiB
TypeScript

import { describe, expect, test } from 'bun:test'
import { FontManager } from '@open-pencil/core'
import { isVariableFont, namedInstanceVariations } from '#core/text/font/variation'
interface Axis {
tag: string
min: number
max: number
}
interface Instance {
name: string
coordinates: number[]
}
function concat(parts: Uint8Array[]): Uint8Array {
const out = new Uint8Array(parts.reduce((size, part) => size + part.length, 0))
let offset = 0
for (const part of parts) {
out.set(part, offset)
offset += part.length
}
return out
}
function words(values: number[], bytes: 2 | 4): Uint8Array {
const view = new DataView(new ArrayBuffer(values.length * bytes))
values.forEach((value, index) =>
bytes === 2 ? view.setUint16(index * 2, value) : view.setInt32(index * 4, value)
)
return new Uint8Array(view.buffer)
}
function ascii(tag: string): Uint8Array {
return new TextEncoder().encode(tag)
}
function nameTable(names: string[]): Uint8Array {
const strings = names.map((name) =>
words(
Array.from(name, (character) => character.charCodeAt(0)),
2
)
)
const header = words([0, names.length, 6 + names.length * 12], 2)
let offset = 0
const records = names.map((_name, index) => {
const record = words([3, 1, 0x409, 256 + index, strings[index].length, offset], 2)
offset += strings[index].length
return record
})
return concat([header, ...records, ...strings])
}
function fvarTable(axes: Axis[], instances: Instance[]): Uint8Array {
const header = words([1, 0, 16, 2, axes.length, 20, instances.length, 4 + axes.length * 4], 2)
const axisRecords = axes.map((axis) =>
concat([
ascii(axis.tag),
words(
[axis.min, axis.min, axis.max].map((value) => value * 65536),
4
),
words([0, 0], 2)
])
)
const instanceRecords = instances.map((instance, index) =>
concat([
words([256 + index, 0], 2),
words(
instance.coordinates.map((value) => value * 65536),
4
)
])
)
return concat([header, ...axisRecords, ...instanceRecords])
}
function variableFont(axes: Axis[], instances: Instance[]): ArrayBuffer {
const tables: Array<[string, Uint8Array]> = [
['fvar', fvarTable(axes, instances)],
['name', nameTable(instances.map((instance) => instance.name))]
]
const directory = concat([
words([0x0001, 0x0000, tables.length, 0, 0, 0], 2),
...tables.map(([tag, data], index) => {
const offset =
12 + tables.length * 16 + tables.slice(0, index).reduce((size, [, t]) => size + t.length, 0)
return concat([ascii(tag), words([0, offset, data.length], 4)])
})
])
return concat([directory, ...tables.map(([, data]) => data)]).buffer as ArrayBuffer
}
const SF_PRO_LIKE = variableFont(
[
{ tag: 'wdth', min: 30, max: 150 },
{ tag: 'wght', min: 1, max: 1000 }
],
[
{ name: 'Condensed Medium', coordinates: [60, 540] },
{ name: 'Regular', coordinates: [100, 400] },
{ name: 'Medium', coordinates: [100, 510] },
{ name: 'Semibold', coordinates: [100, 590] },
{ name: 'Bold Italic', coordinates: [100, 700] }
]
)
describe('namedInstanceVariations', () => {
test('uses the coordinates of the named instance matching the style', () => {
expect(namedInstanceVariations(SF_PRO_LIKE, 'Medium')).toEqual([
{ axis: 'wdth', value: 100 },
{ axis: 'wght', value: 510 }
])
expect(namedInstanceVariations(SF_PRO_LIKE, 'Bold Italic')).toEqual([
{ axis: 'wdth', value: 100 },
{ axis: 'wght', value: 700 }
])
})
test('matches instance names regardless of case and spacing', () => {
expect(namedInstanceVariations(SF_PRO_LIKE, 'SemiBold')).toEqual([
{ axis: 'wdth', value: 100 },
{ axis: 'wght', value: 590 }
])
})
test('clamps the style weight to the wght axis without a matching instance', () => {
expect(namedInstanceVariations(SF_PRO_LIKE, 'Black')).toEqual([{ axis: 'wght', value: 900 }])
const narrow = variableFont([{ tag: 'wght', min: 300, max: 600 }], [])
expect(namedInstanceVariations(narrow, 'Bold')).toEqual([{ axis: 'wght', value: 600 }])
})
test('returns null for static fonts', () => {
const header = words([0x0001, 0x0000, 0, 0, 0, 0], 2)
expect(namedInstanceVariations(header.buffer as ArrayBuffer, 'Medium')).toBeNull()
expect(isVariableFont(header.buffer as ArrayBuffer)).toBe(false)
expect(isVariableFont(SF_PRO_LIKE)).toBe(true)
})
})
describe('namedInstanceVariations with malformed fonts', () => {
function patched(patch: (view: DataView, tableOffset: (tag: string) => number) => void) {
const data = SF_PRO_LIKE.slice(0)
const view = new DataView(data)
const tableRecord = (tag: string) => {
for (let i = 0; i < view.getUint16(4); i++) {
const record = 12 + i * 16
const recordTag = String.fromCharCode(...new Uint8Array(data, record, 4))
if (recordTag === tag) return record
}
throw new Error(`Missing ${tag}`)
}
patch(view, tableRecord)
return data
}
test('skips name records that point outside the font', () => {
const data = patched((view, tableRecord) => {
const name = view.getUint32(tableRecord('name') + 8)
view.setUint16(name + 6 + 10, 0xfff0)
})
expect(
namedInstanceVariations(data, 'Condensed Medium')?.map((variation) => variation.axis)
).toEqual(['wght'])
expect(namedInstanceVariations(data, 'Medium')).toEqual([
{ axis: 'wdth', value: 100 },
{ axis: 'wght', value: 510 }
])
})
test('ignores fvar tables shorter than their header', () => {
const data = patched((view, tableRecord) => view.setUint32(tableRecord('fvar') + 12, 10))
expect(namedInstanceVariations(data, 'Medium')).toBeNull()
})
test('ignores fvar tables with undersized axis records', () => {
const data = patched((view, tableRecord) => {
const fvar = view.getUint32(tableRecord('fvar') + 8)
view.setUint16(fvar + 10, 8)
})
expect(namedInstanceVariations(data, 'Medium')).toBeNull()
})
})
describe('FontManager.namedInstanceVariations', () => {
test('resolves variations from the face loaded for a style', () => {
const manager = new FontManager()
manager.markLoaded('SF Pro', 'Medium', SF_PRO_LIKE)
expect(manager.namedInstanceVariations('SF Pro', 'Medium')).toEqual([
{ axis: 'wdth', value: 100 },
{ axis: 'wght', value: 510 }
])
expect(manager.namedInstanceVariations('SF Pro', 'Bold')).toBeNull()
})
})