1.2.7: 6 more bundled fonts + custom-font upload + layerActiveAt parity

Built-in additions: Montserrat, Nunito, Figtree, Gabarito (sans),
Archivo Black (heavy display), Press Start 2P (pixel/retro).

Custom font upload (lib/fonts.ts):
- uploadCustomFont(file) reads .woff2/.woff/.ttf/.otf via FileReader,
  registers a FontFace early so a corrupt file fails before storage,
  then persists {id, label, dataUrl} to localStorage under
  'animatr:customFonts'. Quota errors surface a friendly message.
- removeCustomFont(id) drops the FontFace + storage entry. If the
  asset still pointed at the deleted font, the picker resets it to
  System Sans on the calling side.
- AVAILABLE_FONTS becomes a ComputedRef combining BUILTIN_FONTS with
  the reactive customFontsState. fontFamilyMapSnapshot() rebuilds the
  {id → CSS family} map per export so user-uploaded fonts make it
  into the exported runtime.

FontPicker UI:
- Two sections divided by a thin rule — built-ins on top, "Your fonts"
  below — plus an "Upload font…" entry at the bottom that opens a
  hidden file input. Custom rows show a trash button on hover.
- Auto-selects a freshly uploaded font.

Engine source becomes a function (engineSource()) instead of a const,
so each export materializes the latest FONT_FAMILY map. ENGINE_TEMPLATE
holds the static skeleton with a __FONT_FAMILY_MAP__ placeholder.

Example HTML hint:
- Built-in fonts list their .woff2 path; custom fonts get a
  "locally uploaded; @font-face below has the file inlined as a data
  URL" line. The fontFaceCss snippet inlines data URLs for custom
  entries so it's self-contained.

Bug fixes (player layerActiveAt):
- Mirrors interpolate.ts isLayerActiveAt now. The previous
  `if(total<=1) return true` short-circuit made layers with a single
  future keyframe visible at t=0; the lastHold→Infinity heuristic
  ignored end keyframes entirely. Both regressions affected the
  fullscreen preview and standalone exports. Replaced with a strict
  scan: min = earliest non-end kf, max = earliest 'end' kf or +Inf.
  Static layers (no normal kfs) stay always-visible.

Tests (5 new under "text font picker — model + render + export"):
- 6 new built-in ids in FONT_FAMILIES map.
- uploadCustomFont registers + persists + appears in AVAILABLE_FONTS;
  removeCustomFont reverses it. Stubs FontFace and document.fonts.add
  for the test environment via a stubFontFaceForTest() helper.
- uploadCustomFont rejects unsupported extensions.
- Exported runtime FONT_FAMILIES includes uploaded custom font ids.
- FontPicker popover shows the Upload font… entry.
- New "exported runtime layerActiveAt mirrors editor isLayerActiveAt"
  extracts the function from engineSource() and exercises five
  scenarios (single future kf, two normal kfs no end, end kf cuts
  off, static layer always-visible, end kf wins over separated tracks).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
thandClaude Opus 4.7 committed 2026-04-26 13:40:26 +02:00
1 parent 8c4f744afc
commit 27d6a47b72
12 files changed
+593 -81

No files matched your search

+177 -2
View File
@@ -141,6 +141,31 @@ function tick(ms = 40): Promise<void> {
return new Promise((r) => setTimeout(r, ms))
}
/** Replaces window.FontFace and document.fonts.add with stubs so
* uploadCustomFont can run without a real woff2 parser. Returns a
* restore function — call it from a finally block. */
function stubFontFaceForTest(): () => void {
const realFontFace = (window as unknown as { FontFace?: unknown }).FontFace
class StubFontFace {
family: string
constructor(family: string) { this.family = family }
load() { return Promise.resolve(this) }
}
;(window as unknown as { FontFace: unknown }).FontFace = StubFontFace
// document.fonts.add() type-checks its argument against the real
// FontFace, which our stub fails. Replace with a no-op for the
// duration of the test.
const fontSet = document.fonts as unknown as { add: (f: unknown) => void }
const realAdd = fontSet.add
fontSet.add = () => {}
return () => {
if (realFontFace !== undefined) {
(window as unknown as { FontFace: unknown }).FontFace = realFontFace
}
fontSet.add = realAdd
}
}
export function registerAllTests(): void {
suite('scene store — defaults', () => {
test('starts with empty scene, playhead 0, not playing', () => {
@@ -15025,8 +15050,8 @@ export function registerAllTests(): void {
})
test('fontCssFamily resolves known ids and falls back to system sans', async () => {
const { fontCssFamily, AVAILABLE_FONTS, SYSTEM_SANS } = await import('@/lib/fonts')
const inter = AVAILABLE_FONTS.find(f => f.id === 'inter')!
const { fontCssFamily, BUILTIN_FONTS, SYSTEM_SANS } = await import('@/lib/fonts')
const inter = BUILTIN_FONTS.find(f => f.id === 'inter')!
expect(fontCssFamily('inter')).toBe(inter.family)
expect(fontCssFamily(undefined)).toBe(SYSTEM_SANS.family)
expect(fontCssFamily('does-not-exist')).toBe(SYSTEM_SANS.family)
@@ -15138,6 +15163,56 @@ export function registerAllTests(): void {
expect(html.includes('Fonts used in this animation')).toBe(false)
})
test('exported runtime layerActiveAt mirrors the editor isLayerActiveAt', async () => {
// Regression: the player previously short-circuited
// `if(total<=1) return true` — a layer with one keyframe at t=2
// would render at t=0 (visible too early). It also ignored
// 'end' keyframes, and dropped layers with two normal kfs after
// the last kf instead of holding them to +Infinity. Both bugs
// showed up in fullscreen-preview AND in standalone exports.
const { generateRuntimeScript } = await import('@/lib/exportPlayer')
const src = generateRuntimeScript()
const match = src.match(/function layerActiveAt\(layer,time\)\{([\s\S]*?)\n {4}\}/)
expect(!!match).toBe(true)
const body = match![1]
// Build a callable from the function body so we can poke the
// runtime's gate logic directly without mounting a player.
const layerActiveAt = new Function('layer', 'time', body) as (layer: unknown, time: number) => boolean
// (a) Single normal kf at t=2 → invisible before t=2.
const a = { keyframes: [{ time: 2, kind: 'normal' }] }
expect(layerActiveAt(a, 0)).toBe(false)
expect(layerActiveAt(a, 1.9)).toBe(false)
expect(layerActiveAt(a, 2)).toBe(true)
expect(layerActiveAt(a, 5)).toBe(true)
// (b) Two normal kfs, no end kf → visible to +Infinity.
const b = { keyframes: [{ time: 0, kind: 'normal' }, { time: 1, kind: 'normal' }] }
expect(layerActiveAt(b, 0)).toBe(true)
expect(layerActiveAt(b, 0.5)).toBe(true)
expect(layerActiveAt(b, 5)).toBe(true)
expect(layerActiveAt(b, 1000)).toBe(true)
// (c) Normal kf at t=0 + end kf at t=2 → invisible at and after t=2.
const c = { keyframes: [{ time: 0, kind: 'normal' }, { time: 2, kind: 'end' }] }
expect(layerActiveAt(c, 0)).toBe(true)
expect(layerActiveAt(c, 1)).toBe(true)
expect(layerActiveAt(c, 2)).toBe(false)
expect(layerActiveAt(c, 3)).toBe(false)
// (d) Static layer with zero keyframes → always visible.
const d = { keyframes: [] }
expect(layerActiveAt(d, 0)).toBe(true)
expect(layerActiveAt(d, 999)).toBe(true)
// (e) End kf is honored even when it's only on the main track —
// separated position kfs alone should not push max past the end.
const e = {
keyframes: [{ time: 5, kind: 'end' }],
positionKeyframes: [{ time: 0, kind: 'normal' }, { time: 4, kind: 'normal' }],
rotationKeyframes: [],
}
expect(layerActiveAt(e, 0)).toBe(true)
expect(layerActiveAt(e, 4.99)).toBe(true)
expect(layerActiveAt(e, 5)).toBe(false)
expect(layerActiveAt(e, 6)).toBe(false)
})
test('exported runtime carries a FONT_FAMILIES map and uses fontFam(asset)', async () => {
const { generateRuntimeScript } = await import('@/lib/exportPlayer')
const src = generateRuntimeScript()
@@ -15146,6 +15221,106 @@ export function registerAllTests(): void {
// Sanity: known font ids are present in the embedded map.
expect(src).toContain('"inter"')
expect(src).toContain('"playfair"')
// The 6 newly-added built-ins all show up too.
expect(src).toContain('"montserrat"')
expect(src).toContain('"nunito"')
expect(src).toContain('"archivo-black"')
expect(src).toContain('"figtree"')
expect(src).toContain('"press-start"')
expect(src).toContain('"gabarito"')
})
test('uploadCustomFont registers, persists to localStorage, and exposes the font', async () => {
const fonts = await import('@/lib/fonts')
// Reset state: nuke any leftovers from a previous test run.
const before = localStorage.getItem('animatr:customFonts')
localStorage.removeItem('animatr:customFonts')
const restore = stubFontFaceForTest()
try {
// Crude .woff2 stub: a single byte is enough since the FontFace
// stub doesn't actually parse it.
const file = new File([new Uint8Array([0])], 'MyFancy.woff2', { type: 'font/woff2' })
const def = await fonts.uploadCustomFont(file)
expect(def.custom).toBe(true)
expect(def.label).toBe('MyFancy')
expect(def.id.startsWith('custom-')).toBe(true)
// Reflected in AVAILABLE_FONTS reactively.
const list = fonts.AVAILABLE_FONTS.value
expect(list.some(f => f.id === def.id)).toBe(true)
// Persisted to localStorage in the documented blob shape.
const raw = localStorage.getItem('animatr:customFonts')!
const parsed = JSON.parse(raw)
expect(parsed.version).toBe(1)
expect(Array.isArray(parsed.fonts)).toBe(true)
expect(parsed.fonts[0].id).toBe(def.id)
expect(parsed.fonts[0].dataUrl.startsWith('data:')).toBe(true)
// removeCustomFont reverses both the live state and the
// localStorage entry.
fonts.removeCustomFont(def.id)
expect(fonts.AVAILABLE_FONTS.value.some(f => f.id === def.id)).toBe(false)
const rawAfter = localStorage.getItem('animatr:customFonts')!
expect(JSON.parse(rawAfter).fonts.length).toBe(0)
} finally {
restore()
if (before === null) localStorage.removeItem('animatr:customFonts')
else localStorage.setItem('animatr:customFonts', before)
}
})
test('uploadCustomFont rejects unsupported file extensions', async () => {
const fonts = await import('@/lib/fonts')
const file = new File([new Uint8Array([0])], 'evil.exe', { type: 'application/octet-stream' })
let caught: Error | null = null
try {
await fonts.uploadCustomFont(file)
} catch (err) {
caught = err as Error
}
expect(caught !== null).toBe(true)
expect(/Unsupported font format/.test(caught?.message ?? '')).toBe(true)
})
test('exported runtime FONT_FAMILIES map includes uploaded custom fonts', async () => {
const fonts = await import('@/lib/fonts')
const { generateRuntimeScript } = await import('@/lib/exportPlayer')
const before = localStorage.getItem('animatr:customFonts')
localStorage.removeItem('animatr:customFonts')
const restore = stubFontFaceForTest()
try {
const file = new File([new Uint8Array([0])], 'BrandFont.woff2', { type: 'font/woff2' })
const def = await fonts.uploadCustomFont(file)
const src = generateRuntimeScript()
expect(src).toContain(def.id)
expect(src).toContain('RUWIO Custom')
fonts.removeCustomFont(def.id)
} finally {
restore()
if (before === null) localStorage.removeItem('animatr:customFonts')
else localStorage.setItem('animatr:customFonts', before)
}
})
test('FontPicker popover shows an Upload font… entry', async () => {
const s = makeFreshStore()
const a = s.addAsset({
kind: 'text', name: 'T', text: 'hi', fontSize: 32, fill: '#000',
})
const layer = s.addLayer(a.id)!
s.selectedLayerId = layer.id
s.selectedLayerIds = [layer.id]
const handle = mountComponent(PropertiesPanel, {})
try {
await nextTick()
const trigger = handle.host.querySelector('.font-picker .trigger') as HTMLButtonElement
trigger.click()
await nextTick()
const upload = document.querySelector('.font-popover .upload-btn') as HTMLButtonElement | null
expect(!!upload).toBe(true)
expect((upload!.textContent ?? '').toLowerCase().includes('upload')).toBe(true)
} finally {
handle.unmount()
document.querySelectorAll('.font-popover').forEach(el => el.remove())
}
})
})
}