Skip to content

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

5.4 KB
Raw Blame
import { describe, expect, test } from 'bun:test'

import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'

import { FontManager, fontManager } from '@open-pencil/core/text'
import { SceneGraph } from '@open-pencil/scene-graph'

import { isTextPictureCurrent } from '#core/canvas/renderer/fonts'
import { nodeFontReadiness } from '#core/canvas/text'
import { fontFaceDemand, fontResolver } from '#core/text/resolver'

function pageId(graph: SceneGraph): string {
  return graph.getPages()[0].id
}

describe('font lifecycle', () => {
  test('advances generation only for provider epochs and unique registrations', async () => {
    const manager = new FontManager()
    const registrations: string[] = []
    const provider = {
      registerFont(_data: ArrayBuffer, family: string) {
        registrations.push(family)
      }
    } as TypefaceFontProvider
    const data = new ArrayBuffer(12)

    expect(manager.generation()).toBe(0)
    manager.attachProvider({} as CanvasKit, provider)
    const providerGeneration = manager.generation()
    await manager.markLoaded('Generation Test', 'Regular', data)
    const registrationGeneration = manager.generation()
    await manager.markLoaded('Generation Test', 'Regular', data)

    expect(providerGeneration).toBeGreaterThan(0)
    expect(registrationGeneration).toBeGreaterThan(providerGeneration)
    expect(manager.generation()).toBe(registrationGeneration)
    expect(registrations).toEqual(['Generation Test'])
  })

  test('draws a style from the cumulative subset that replaced its file', async () => {
    const manager = new FontManager()
    const registrations: Array<{ data: ArrayBuffer; family: string }> = []
    const provider = {
      registerFont(data: ArrayBuffer, family: string) {
        registrations.push({ data, family })
      }
    } as TypefaceFontProvider

    manager.attachProvider({} as CanvasKit, provider)
    await manager.markLoaded('Subset Font', 'Regular', new ArrayBuffer(8))
    const firstGeneration = manager.generation()
    const replacement = new ArrayBuffer(12)
    await manager.markLoaded('Subset Font', 'Regular', replacement)

    // CanvasKit draws from the first file registered under a name, which is the replaced one,
    // and picks between files under one name by the weight each declares, so the name the
    // style draws under holds the replacement alone.
    const drawn = manager.renderFamily('Subset Font', 'Regular')
    expect(drawn).not.toBe('Subset Font')
    expect(manager.generation()).toBeGreaterThan(firstGeneration)
    expect(registrations.filter(({ family }) => family === drawn).map(({ data }) => data)).toEqual([
      replacement
    ])
  })

  test('tracks nodes gated by pre-render font resolution', () => {
    const manager = new FontManager()
    const graph = new SceneGraph()
    const other = new SceneGraph()
    manager.blockNodesUntilFontsResolve(graph, ['first', 'second'])
    manager.blockNodesUntilFontsResolve(graph, ['second'])
    expect(manager.isNodeBlocked(graph, 'first')).toBe(true)
    expect(manager.isNodeBlocked(other, 'first')).toBe(false)
    manager.unblockNodes(other, ['first'])
    manager.unblockNodes(graph, ['first', 'second'])
    expect(manager.isNodeBlocked(graph, 'first')).toBe(false)
    // Another preparation still holds it.
    expect(manager.isNodeBlocked(graph, 'second')).toBe(true)
    manager.unblockNodes(graph, ['second'])
    expect(manager.isNodeBlocked(graph, 'second')).toBe(false)
  })

  test('rejects a text picture observed before the font generation changed', () => {
    const graph = new SceneGraph()
    const node = graph.createNode('TEXT', pageId(graph), {
      name: 'Cached fallback',
      x: 0,
      y: 0,
      width: 100,
      height: 20,
      text: 'Hello',
      textPicture: new Uint8Array([1, 2, 3])
    })
    const renderer = {
      fontGeneration: 1,
      textFonts: {
        pictureGenerations: new Map<string, { data: Uint8Array; generation: number }>()
      }
    }

    expect(isTextPictureCurrent(renderer, node)).toBe(true)
    renderer.fontGeneration = 2
    expect(isTextPictureCurrent(renderer, node)).toBe(false)
  })

  test('keeps text visible when an unavailable italic face can use a loaded family face', async () => {
    const family = 'Missing Italic Regression'
    const demand = fontFaceDemand(family, 'Regular Italic', 'Hello')
    fontResolver.reset(demand)
    fontResolver.exhaust(demand)
    await fontManager.markLoaded(family, 'Regular', new ArrayBuffer(12))

    const graph = new SceneGraph()
    const node = graph.createNode('TEXT', pageId(graph), {
      name: 'Synthetic italic',
      x: 0,
      y: 0,
      width: 100,
      height: 20,
      text: 'Hello',
      fontFamily: family,
      italic: true
    })

    expect(nodeFontReadiness({}, node)).toBe('ready')
    fontResolver.reset(demand)
  })

  test('shares one bundled font request between concurrent loads', async () => {
    const manager = new FontManager()

    const [first, second] = await Promise.all([
      manager.fetchBundledFont('/InterVariable.ttf'),
      manager.fetchBundledFont('/InterVariable.ttf')
    ])
    expect(first).not.toBeNull()
    expect(second).toBe(first)

    // A settled request is not kept, so a later load (or a retry after a failure) reads again.
    const later = await manager.fetchBundledFont('/InterVariable.ttf')
    expect(later).not.toBe(first)
    expect(later?.byteLength).toBe(first?.byteLength)
  })
})