Skip to content

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

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

import {
  exportFigFile,
  parseFigFile,
  populateAllFigPages,
  populateFigPage
} from '@open-pencil/core/io/formats/fig'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'

async function createLazyGraph() {
  await initCodec()
  const source = new SceneGraph()
  source.createNode('RECTANGLE', source.getPages()[0].id, { name: 'First' })
  source.createNode('RECTANGLE', source.addPage('Page 2').id, { name: 'Second' })
  const bytes = await exportFigFile(source)
  return parseFigFile(bytes.slice().buffer as ArrayBuffer, { populate: 'none' })
}

test('replacement session populates an unvisited page exactly once', async () => {
  const graph = await createLazyGraph()
  const [first, second] = graph.getPages()
  expect(graph.getChildren(first.id)).toHaveLength(0)
  expect(populateFigPage(graph, second.id)).toBe(true)
  expect(graph.getChildren(first.id)).toHaveLength(0)
  expect(graph.getChildren(second.id).map((node) => node.name)).toEqual(['Second'])
  const count = graph.nodes.size
  expect(populateFigPage(graph, second.id)).toBe(false)
  expect(graph.nodes.size).toBe(count)
})

test('replacement session populates all remaining pages once', async () => {
  const graph = await createLazyGraph()
  expect(populateAllFigPages(graph)).toBe(true)
  expect(graph.getPages().map((page) => graph.getChildren(page.id).length)).toEqual([1, 1])
  expect(populateAllFigPages(graph)).toBe(false)
})

test('loading a page keeps saving the opened bytes; an edit encodes the document again', async () => {
  await initCodec()
  const source = new SceneGraph()
  source.createNode('RECTANGLE', source.getPages()[0].id, { name: 'First' })
  source.createNode('RECTANGLE', source.addPage('Page 2').id, { name: 'Second' })
  const bytes = await exportFigFile(source)
  const graph = await parseFigFile(bytes.slice().buffer as ArrayBuffer, { populate: 'first-page' })

  expect(populateFigPage(graph, graph.getPages()[1].id)).toBe(true)
  expect(await exportFigFile(graph)).toEqual(bytes)

  const [second] = graph.getChildren(graph.getPages()[1].id)
  graph.updateNode(second.id, { name: 'Renamed' })
  expect(await exportFigFile(graph)).not.toEqual(bytes)
})