Skip to content

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

14.8 KB
Raw Blame
/* eslint-disable max-lines -- font loading scenarios share provider and CanvasKit lifecycle fixtures */

import { describe, test, expect } from 'bun:test'

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

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

import { expectDefined } from '#tests/helpers/assert'
import { fetchStub } from '#tests/helpers/fetch'

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

function createRecordingProvider() {
  const registrations: Array<{ family: string; byteLength: number }> = []
  const provider = {
    registerFont(data: ArrayBuffer, family: string) {
      registrations.push({ family, byteLength: data.byteLength })
    }
  } as TypefaceFontProvider
  return { provider, registrations }
}

describe('FontManager loaded font cache', () => {
  test('marks and checks font', async () => {
    const family = `TestFont_${Date.now()}`
    expect(fontManager.isLoaded(family)).toBe(false)
    await fontManager.markLoaded(family, 'Regular', new ArrayBuffer(8))
    expect(fontManager.isLoaded(family)).toBe(true)
  })

  test('different styles for same family', async () => {
    const family = `MultiStyle_${Date.now()}`
    expect(fontManager.isLoaded(family)).toBe(false)
    await fontManager.markLoaded(family, 'Bold', new ArrayBuffer(8))
    expect(fontManager.isLoaded(family)).toBe(true)
    expect(fontManager.isStyleLoaded(family, 'Bold')).toBe(true)
    expect(fontManager.isStyleLoaded(family, 'Regular')).toBe(false)
  })

  test('re-registers cached fonts when provider changes', async () => {
    const manager = new FontManager()
    const canvasKit = {} as CanvasKit
    const first = createRecordingProvider()
    const second = createRecordingProvider()

    manager.attachProvider(canvasKit, first.provider)
    await manager.markLoaded('ProviderLifecycle', 'Regular', new ArrayBuffer(12))
    expect(first.registrations).toEqual([{ family: 'ProviderLifecycle', byteLength: 12 }])

    manager.attachProvider(canvasKit, second.provider)
    expect(second.registrations).toEqual([{ family: 'ProviderLifecycle', byteLength: 12 }])

    await manager.markLoaded('SharedProviderLifecycle', 'Regular', new ArrayBuffer(16))
    expect(first.registrations.at(-1)).toEqual({
      family: 'SharedProviderLifecycle',
      byteLength: 16
    })
    expect(second.registrations.at(-1)).toEqual({
      family: 'SharedProviderLifecycle',
      byteLength: 16
    })

    manager.detachProvider(first.provider)
    expect(manager.provider()).toBe(second.provider)

    manager.detachProvider(second.provider)
    expect(manager.provider()).toBeNull()
  })

  test('renders loaded faces under their source families', async () => {
    const manager = new FontManager()
    const recording = createRecordingProvider()

    manager.attachProvider({} as CanvasKit, recording.provider)
    await manager.markLoaded('Inter', 'SemiBold', new ArrayBuffer(12))

    const renderFamily = manager.renderFamily('Inter', 'SemiBold')

    expect(renderFamily).toBe('Inter')
    expect(recording.registrations).toEqual([{ family: 'Inter', byteLength: 12 }])
    expect(manager.renderFamily('Inter', 'SemiBold')).toBe(renderFamily)
    expect(recording.registrations).toHaveLength(1)
  })

  test('prefers local font data before downloaded cache', async () => {
    const manager = new FontManager()
    const recording = createRecordingProvider()
    let cacheReads = 0

    manager.attachProvider({} as CanvasKit, recording.provider)
    manager.setHostFontLoader(async () => new ArrayBuffer(20))
    manager.setDownloadedFontCache({
      async read() {
        cacheReads++
        return new ArrayBuffer(16)
      },
      async write() {
        return undefined
      }
    })

    const data = await manager.loadFont('LocalPriority', 'Regular')
    expect(data?.byteLength).toBe(20)
    expect(cacheReads).toBe(0)
  })

  test('loads downloaded cache when local sources are unavailable', async () => {
    const manager = new FontManager()
    const recording = createRecordingProvider()
    const data = new ArrayBuffer(16)
    let writes = 0

    manager.attachProvider({} as CanvasKit, recording.provider)
    manager.setDownloadedFontCache({
      async read(family, style) {
        return family === 'DownloadedCache' && style === 'Regular' ? data : null
      },
      async write() {
        writes++
      }
    })

    await expect(manager.loadFont('DownloadedCache', 'Regular')).resolves.toBe(data)
    expect(recording.registrations).toEqual([{ family: 'DownloadedCache', byteLength: 16 }])
    expect(writes).toBe(0)
  })

  test('tracks character coverage restored from downloaded cache', async () => {
    const manager = new FontManager()
    manager.attachProvider({} as CanvasKit, createRecordingProvider().provider)
    const cached = new ArrayBuffer(16)
    manager.setDownloadedFontCache({
      async read(family, style, characters) {
        return family === 'SubsetCache' && style === 'Regular' && characters === 'A' ? cached : null
      },
      async write() {
        return undefined
      }
    })

    await expect(manager.loadFont('SubsetCache', 'Regular', 'A')).resolves.toBe(cached)
    const originalLoadRemoteFont = manager.loadRemoteFont.bind(manager)
    let requested = ''
    manager.loadRemoteFont = async (_family, _style, characters) => {
      requested = characters ?? ''
      return cached
    }
    try {
      await manager.loadFont('SubsetCache', 'Regular', 'B')
    } finally {
      manager.loadRemoteFont = originalLoadRemoteFont
    }
    expect(requested).toContain('B')
  })
  test('forwards cancellation to fallback web-font requests', async () => {
    const manager = new FontManager()
    let remoteRequestStarted: (() => void) | null = null
    const started = new Promise<void>((resolve) => {
      remoteRequestStarted = resolve
    })
    const originalLoadRemoteFont = manager.loadRemoteFont.bind(manager)
    manager.loadRemoteFont = async (_family, _style, _characters, signal) => {
      remoteRequestStarted?.()
      return new Promise<ArrayBuffer | null>((_resolve, reject) => {
        signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), {
          once: true
        })
      })
    }
    const abort = new AbortController()
    const loading = manager.ensureFallbackPack(['cjk'], '字', abort.signal)

    await started
    abort.abort()

    try {
      await expect(loading).rejects.toHaveProperty('name', 'AbortError')
    } finally {
      manager.loadRemoteFont = originalLoadRemoteFont
    }
  })

  test('loads bundled Inter ExtraBold without network access', async () => {
    const manager = new FontManager()
    const recording = createRecordingProvider()
    const originalFetch = globalThis.fetch
    globalThis.fetch = fetchStub(() => {
      throw new Error('network disabled')
    })

    try {
      manager.attachProvider({} as CanvasKit, recording.provider)
      const data = expectDefined(await manager.loadFont('Inter', 'ExtraBold'), 'Inter ExtraBold')

      expect(data.byteLength).toBeGreaterThan(0)
      expect(recording.registrations).toEqual([{ family: 'Inter', byteLength: data.byteLength }])
    } finally {
      globalThis.fetch = originalFetch
    }
  })
})

describe('collectFontKeys', () => {
  test('returns empty for non-text nodes', () => {
    const graph = new SceneGraph()
    const id = graph.createNode('RECTANGLE', pageId(graph), {
      name: 'Rect',
      x: 0,
      y: 0,
      width: 100,
      height: 100
    }).id
    expect(fontManager.collectFontKeys(graph, [id])).toEqual([])
  })

  test('includes default font (Inter) in collected keys', () => {
    const graph = new SceneGraph()
    const id = graph.createNode('TEXT', pageId(graph), {
      name: 'Label',
      x: 0,
      y: 0,
      width: 100,
      height: 20,
      text: 'Hello',
      fontFamily: 'Inter',
      fontWeight: 400
    }).id
    expect(fontManager.collectFontKeys(graph, [id])).toEqual([['Inter', 'Regular']])
  })

  test('collects non-default font family', () => {
    const graph = new SceneGraph()
    const id = graph.createNode('TEXT', pageId(graph), {
      name: 'Label',
      x: 0,
      y: 0,
      width: 100,
      height: 20,
      text: 'Hello',
      fontFamily: 'Roboto',
      fontWeight: 400
    }).id
    const keys = fontManager.collectFontKeys(graph, [id])
    expect(keys).toEqual([['Roboto', 'Regular']])
  })

  test('collects bold weight', () => {
    const graph = new SceneGraph()
    const id = graph.createNode('TEXT', pageId(graph), {
      name: 'Label',
      x: 0,
      y: 0,
      width: 100,
      height: 20,
      text: 'Hello',
      fontFamily: 'Roboto',
      fontWeight: 700
    }).id
    const keys = fontManager.collectFontKeys(graph, [id])
    expect(keys).toEqual([['Roboto', 'Bold']])
  })

  test('collects italic variant', () => {
    const graph = new SceneGraph()
    const id = graph.createNode('TEXT', pageId(graph), {
      name: 'Label',
      x: 0,
      y: 0,
      width: 100,
      height: 20,
      text: 'Hello',
      fontFamily: 'Roboto',
      fontWeight: 400,
      italic: true
    }).id
    const keys = fontManager.collectFontKeys(graph, [id])
    expect(keys).toEqual([['Roboto', 'Regular Italic']])
  })

  test('deduplicates same family+style', () => {
    const graph = new SceneGraph()
    const page = pageId(graph)
    graph.createNode('TEXT', page, {
      name: 'A',
      x: 0,
      y: 0,
      width: 100,
      height: 20,
      text: 'A',
      fontFamily: 'Roboto',
      fontWeight: 400
    })
    graph.createNode('TEXT', page, {
      name: 'B',
      x: 0,
      y: 30,
      width: 100,
      height: 20,
      text: 'B',
      fontFamily: 'Roboto',
      fontWeight: 400
    })
    const ids = graph.getChildren(page).map((n) => n.id)
    const keys = fontManager.collectFontKeys(graph, ids)
    expect(keys).toEqual([['Roboto', 'Regular']])
  })

  test('collects multiple families', () => {
    const graph = new SceneGraph()
    const page = pageId(graph)
    graph.createNode('TEXT', page, {
      name: 'A',
      x: 0,
      y: 0,
      width: 100,
      height: 20,
      text: 'A',
      fontFamily: 'Roboto',
      fontWeight: 400
    })
    graph.createNode('TEXT', page, {
      name: 'B',
      x: 0,
      y: 30,
      width: 100,
      height: 20,
      text: 'B',
      fontFamily: 'Open Sans',
      fontWeight: 700
    })
    const ids = graph.getChildren(page).map((n) => n.id)
    const keys = fontManager.collectFontKeys(graph, ids)
    expect(keys).toHaveLength(2)
    expect(keys).toContainEqual(['Roboto', 'Regular'])
    expect(keys).toContainEqual(['Open Sans', 'Bold'])
  })

  test('walks into nested children', () => {
    const graph = new SceneGraph()
    const page = pageId(graph)
    const frame = graph.createNode('FRAME', page, {
      name: 'Frame',
      x: 0,
      y: 0,
      width: 400,
      height: 400
    }).id
    graph.createNode('TEXT', frame, {
      name: 'Nested',
      x: 0,
      y: 0,
      width: 100,
      height: 20,
      text: 'Hello',
      fontFamily: 'Poppins',
      fontWeight: 600
    })
    const keys = fontManager.collectFontKeys(graph, [frame])
    expect(keys).toEqual([['Poppins', 'SemiBold']])
  })

  test('collects fonts from style runs', () => {
    const graph = new SceneGraph()
    const id = graph.createNode('TEXT', pageId(graph), {
      name: 'Mixed',
      x: 0,
      y: 0,
      width: 200,
      height: 20,
      text: 'Hello World',
      fontFamily: 'Roboto',
      fontWeight: 400,
      styleRuns: [
        {
          start: 0,
          length: 5,
          style: { fontFamily: 'Roboto', fontWeight: 400 }
        },
        {
          start: 6,
          length: 5,
          style: { fontFamily: 'Montserrat', fontWeight: 700 }
        }
      ]
    }).id
    const keys = fontManager.collectFontKeys(graph, [id])
    expect(keys).toHaveLength(2)
    expect(keys).toContainEqual(['Roboto', 'Regular'])
    expect(keys).toContainEqual(['Montserrat', 'Bold'])
  })

  test('style run inherits node font when not specified', () => {
    const graph = new SceneGraph()
    const id = graph.createNode('TEXT', pageId(graph), {
      name: 'Partial',
      x: 0,
      y: 0,
      width: 200,
      height: 20,
      text: 'Hello',
      fontFamily: 'Lato',
      fontWeight: 300,
      styleRuns: [
        {
          start: 0,
          length: 5,
          style: {}
        }
      ]
    }).id
    const keys = fontManager.collectFontKeys(graph, [id])
    expect(keys).toEqual([['Lato', 'Light']])
  })

  test('skips invalid node IDs', () => {
    const graph = new SceneGraph()
    expect(fontManager.collectFontKeys(graph, ['nonexistent'])).toEqual([])
  })
})

describe('isVariableFont', () => {
  function makeFontBuffer(tables: string[]): ArrayBuffer {
    const numTables = tables.length
    const headerSize = 12
    const tableRecordSize = 16
    const totalSize = headerSize + numTables * tableRecordSize
    const buf = new ArrayBuffer(totalSize)
    const view = new DataView(buf)
    view.setUint32(0, 0x00010000)
    view.setUint16(4, numTables)
    for (let i = 0; i < numTables; i++) {
      const offset = headerSize + i * tableRecordSize
      for (let c = 0; c < 4; c++) {
        view.setUint8(offset + c, tables[i].charCodeAt(c))
      }
    }
    return buf
  }

  test('detects fvar table', () => {
    expect(isVariableFont(makeFontBuffer(['head', 'fvar', 'glyf']))).toBe(true)
  })

  test('returns false without fvar', () => {
    expect(isVariableFont(makeFontBuffer(['head', 'glyf', 'cmap']))).toBe(false)
  })

  test('returns false for empty buffer', () => {
    expect(isVariableFont(new ArrayBuffer(0))).toBe(false)
  })

  test('returns false for too-small buffer', () => {
    expect(isVariableFont(new ArrayBuffer(8))).toBe(false)
  })

  test('fvar as only table', () => {
    expect(isVariableFont(makeFontBuffer(['fvar']))).toBe(true)
  })
})

describe('fetchBundledFont', () => {
  test('loads InterVariable.ttf from assets in headless', async () => {
    const buffer = await fontManager.fetchBundledFont('/InterVariable.ttf')
    expect(buffer).toBeInstanceOf(ArrayBuffer)
    expect(expectDefined(buffer, 'Inter font buffer').byteLength).toBeGreaterThan(100_000)
  })

  test('loads InterVariable.ttf from assets in headless', async () => {
    const buffer = await fontManager.fetchBundledFont('/InterVariable.ttf')
    expect(buffer).toBeInstanceOf(ArrayBuffer)
    expect(expectDefined(buffer, 'Inter bold font buffer').byteLength).toBeGreaterThan(100_000)
  })

  test('returns valid TTF data', async () => {
    const buffer = await fontManager.fetchBundledFont('/InterVariable.ttf')
    const view = new DataView(expectDefined(buffer, 'Inter font buffer'))
    // TrueType magic: 0x00010000
    expect(view.getUint32(0)).toBe(0x00010000)
  })

  test('throws for nonexistent font', async () => {
    expect(fontManager.fetchBundledFont('/Nonexistent-Font.ttf')).rejects.toThrow()
  })
})