Skip to content

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

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

import { computeAllLayouts, estimateTextSize } from '@open-pencil/core/layout'
import { fontManager } from '@open-pencil/core/text'

import { expectDefined, expectFills, getNodeOrThrow } from '#tests/helpers/assert'
import { registerTestFont } from '#tests/helpers/fonts/bundled'
import { repoPath } from '#tests/helpers/paths'
import { getTool, runTool, setupToolTest, type ToolResult } from '#tests/helpers/tools'

beforeAll(() => registerTestFont())

describe('set_fill', () => {
  test('sets solid fill', () => {
    const { figma } = setupToolTest()
    const frame = figma.createFrame()
    frame.resize(100, 100)

    const tool = getTool('set_fill')
    tool.execute(figma, { id: frame.id, color: '#ff0000' })

    const fills = expectFills(expectDefined(figma.getNodeById(frame.id), 'frame node').fills)
    expect(fills).toEqual([expect.objectContaining({ color: { r: 1, g: 0, b: 0 } })])
  })

  test('returns error for missing node', () => {
    const { figma } = setupToolTest()
    const tool = getTool('set_fill')
    const result = tool.execute(figma, { id: 'nonexistent', color: '#ff0000' }) as ToolResult
    expect(result.error).toContain('not found')
  })
})

describe('set_stroke', () => {
  test('sets stroke', () => {
    const { figma } = setupToolTest()
    const rect = figma.createRectangle()
    rect.resize(100, 100)

    const tool = getTool('set_stroke')
    tool.execute(figma, { id: rect.id, color: '#0000ff', weight: 2 })

    const node = expectDefined(figma.getNodeById(rect.id), 'rectangle node')
    expect(node.strokes).toEqual([expect.objectContaining({ color: { r: 0, g: 0, b: 1 } })])
    expect(node.strokeWeight).toBe(2)
  })
})

describe('set_effects', () => {
  test('adds drop shadow', () => {
    const { figma } = setupToolTest()
    const frame = figma.createFrame()
    frame.resize(100, 100)

    const tool = getTool('set_effects')
    tool.execute(figma, {
      id: frame.id,
      type: 'DROP_SHADOW',
      color: '#000000',
      offset_x: 0,
      offset_y: 4,
      radius: 8,
      spread: 0
    })

    const effects = expectDefined(figma.getNodeById(frame.id), 'frame node').effects
    expect(effects.length).toBe(1)
    expect(effects[0].type).toBe('DROP_SHADOW')
  })

  test('adds blur without color', () => {
    const { figma } = setupToolTest()
    const frame = figma.createFrame()
    frame.resize(100, 100)

    const tool = getTool('set_effects')
    tool.execute(figma, { id: frame.id, type: 'BACKGROUND_BLUR', radius: 10 })

    const effects = expectDefined(figma.getNodeById(frame.id), 'frame node').effects
    expect(effects.length).toBe(1)
    expect(effects[0].type).toBe('BACKGROUND_BLUR')
  })
})

describe('update_node', () => {
  test('updates position and size', () => {
    const { figma } = setupToolTest()
    const rect = figma.createRectangle()
    rect.resize(100, 100)

    const tool = getTool('update_node')
    const result = tool.execute(figma, {
      id: rect.id,
      x: 50,
      y: 75,
      width: 200,
      height: 150,
      opacity: 0.5
    }) as ToolResult

    expect(result.updated).toContain('x')
    expect(result.updated).toContain('size')
    expect(result.updated).toContain('opacity')

    const node = expectDefined(figma.getNodeById(rect.id), 'rectangle node')
    expect(node.x).toBe(50)
    expect(node.y).toBe(75)
    expect(node.width).toBe(200)
    expect(node.height).toBe(150)
    expect(node.opacity).toBe(0.5)
  })

  test('updates corner radius', () => {
    const { figma } = setupToolTest()
    const rect = figma.createRectangle()
    rect.resize(100, 100)

    const tool = getTool('update_node')
    tool.execute(figma, { id: rect.id, corner_radius: 12 })

    expect(expectDefined(figma.getNodeById(rect.id), 'rectangle node').cornerRadius).toBe(12)
  })

  test("a font size edit leaves the text's text style and keeps its fill style", () => {
    const { figma } = setupToolTest()
    const text = figma.createText()
    figma.graph.updateNode(text.id, { textStyleId: 'style:text', fillStyleId: 'style:fill' })

    getTool('update_node').execute(figma, { id: text.id, font_size: 20 })

    expect(getNodeOrThrow(figma.graph, text.id)).toMatchObject({
      fontSize: 20,
      textStyleId: null,
      fillStyleId: 'style:fill'
    })
  })
})

describe('set_layout', () => {
  test('sets auto-layout', () => {
    const { figma } = setupToolTest()
    const frame = figma.createFrame()
    frame.resize(300, 200)

    const tool = getTool('set_layout')
    tool.execute(figma, {
      id: frame.id,
      direction: 'VERTICAL',
      spacing: 16,
      padding: 20
    })

    const node = expectDefined(figma.getNodeById(frame.id), 'frame node')
    expect(node.layoutMode).toBe('VERTICAL')
    expect(node.itemSpacing).toBe(16)
    expect(node.paddingLeft).toBe(20)
    expect(node.paddingTop).toBe(20)
  })

  test('defaults to HUG sizing when enabling auto-layout', () => {
    const { graph, figma } = setupToolTest()
    const frame = figma.createFrame()
    frame.resize(300, 200)

    const rawBefore = getNodeOrThrow(graph, frame.id)
    expect(rawBefore.layoutMode).toBe('NONE')
    // A new frame hugs along its main axis, as in Figma.
    expect(rawBefore.primaryAxisSizing).toBe('HUG')
    expect(rawBefore.counterAxisSizing).toBe('FIXED')

    const tool = getTool('set_layout')
    tool.execute(figma, { id: frame.id, direction: 'VERTICAL' })

    const rawAfter = getNodeOrThrow(graph, frame.id)
    expect(rawAfter.layoutMode).toBe('VERTICAL')
    expect(rawAfter.primaryAxisSizing).toBe('HUG')
    expect(rawAfter.counterAxisSizing).toBe('HUG')
  })

  test('preserves sizing modes when updating existing auto-layout', () => {
    const { graph, figma } = setupToolTest()
    const frame = figma.createFrame()
    frame.resize(300, 200)

    const tool = getTool('set_layout')
    tool.execute(figma, { id: frame.id, direction: 'HORIZONTAL' })

    // Manually set primary axis back to FIXED (user wants fixed width)
    graph.updateNode(frame.id, { primaryAxisSizing: 'FIXED' })
    expect(getNodeOrThrow(graph, frame.id).primaryAxisSizing).toBe('FIXED')

    // Updating spacing should NOT reset sizing modes
    tool.execute(figma, { id: frame.id, spacing: 24 })

    const raw = getNodeOrThrow(graph, frame.id)
    expect(raw.primaryAxisSizing).toBe('FIXED')
    expect(raw.counterAxisSizing).toBe('HUG')
  })

  test('HUG default enables hug-to-fit with 5 children', () => {
    const { graph, figma } = setupToolTest()
    const frame = figma.createFrame()
    frame.resize(320, 100)

    const tool = getTool('set_layout')
    tool.execute(figma, { id: frame.id, direction: 'VERTICAL', spacing: 8, padding: 16 })

    for (let i = 0; i < 5; i++) {
      const child = figma.createRectangle()
      child.resize(280, 50)
      frame.appendChild(child)
    }

    computeAllLayouts(graph)

    const node = getNodeOrThrow(graph, frame.id)
    expect(node.primaryAxisSizing).toBe('HUG')
    // 16 (top pad) + 5*50 (children) + 4*8 (gaps) + 16 (bottom pad) = 314
    expect(node.height).toBe(314)
  })
})

describe('set_constraints', () => {
  test('sets constraints', () => {
    const { figma } = setupToolTest()
    const rect = figma.createRectangle()
    rect.resize(100, 100)

    const tool = getTool('set_constraints')
    tool.execute(figma, { id: rect.id, horizontal: 'CENTER', vertical: 'STRETCH' })

    const node = expectDefined(figma.getNodeById(rect.id), 'rectangle node')
    expect(node.constraints.horizontal).toBe('CENTER')
    expect(node.constraints.vertical).toBe('STRETCH')
  })
})

describe('set_font_range', () => {
  test('returns an empty or overlong range as an error and changes nothing', async () => {
    const { figma, graph } = setupToolTest()
    const created = getTool('create_shape').execute(figma, {
      type: 'TEXT',
      x: 0,
      y: 0,
      width: 200,
      height: 20
    }) as ToolResult
    const id = expectDefined(created.id, 'created node id')
    await runTool(figma, 'set_text', { id, text: 'Hello' })

    expect(await runTool(figma, 'set_font_range', { id, start: 2, end: 2, size: 18 })).toEqual({
      error: "in setRangeFontSize: Empty range selected. 'end' must be greater than 'start'"
    })
    expect(
      await runTool(figma, 'set_font_range', { id, start: 0, end: 9, size: 18 })
    ).toMatchObject({
      error: expect.stringContaining('Range outside of available characters')
    })
    expect(await runTool(figma, 'set_font_range', { id, start: 2, end: 2 })).toEqual({
      error: 'set_font_range needs at least one of family, size, style, variations, or color'
    })
    expect(getNodeOrThrow(graph, id).styleRuns).toEqual([])
  })

  test('sets text from Markdown, its headings and emphasis as ranges over the text’s style', async () => {
    const { figma, graph } = setupToolTest()
    const created = getTool('create_shape').execute(figma, {
      type: 'TEXT',
      x: 0,
      y: 0,
      width: 200,
      height: 20
    }) as ToolResult
    const id = expectDefined(created.id, 'created node id')
    expect(
      await runTool(figma, 'set_text', { id, text: '# Title\n- **one**', markdown: true })
    ).toEqual({ id, text: 'Title\none' })
    const node = getNodeOrThrow(graph, id)
    expect(node.textParagraphs).toEqual([
      { listType: 'NONE', indentation: 0 },
      { listType: 'UNORDERED', indentation: 1 }
    ])
    // The heading carries its size too, so it and the bold item are ranges of their own.
    expect(node.styleRuns.map((run) => [run.start, run.length, run.style.fontWeight])).toEqual([
      [0, 6, 700],
      [6, 3, 700]
    ])
  })

  test('applies font style to text range and survives serialization', async () => {
    const { figma, graph } = setupToolTest()
    const created = getTool('create_shape').execute(figma, {
      type: 'TEXT',
      x: 0,
      y: 0,
      width: 200,
      height: 20
    }) as ToolResult
    await runTool(figma, 'set_text', { id: created.id, text: 'Hello World' })
    await runTool(figma, 'set_font_range', {
      id: created.id,
      start: 0,
      end: 5,
      family: 'Inter',
      size: 18,
      style: 'Bold'
    })

    const node = getNodeOrThrow(graph, expectDefined(created.id, 'created node id'))
    expect(node.styleRuns.length).toBeGreaterThan(0)
    for (const run of node.styleRuns) {
      expect(run.style).toBeDefined()
      expect(typeof run.start).toBe('number')
      expect(typeof run.length).toBe('number')
    }
    const boldRun = node.styleRuns.find((r) => r.style.fontWeight === 700)
    expect(boldRun).toBeDefined()
    expect(expectDefined(boldRun, 'bold style run').start).toBe(0)
    expect(expectDefined(boldRun, 'bold style run').length).toBe(5)
  })

  test('applies color to text range', async () => {
    const { figma, graph } = setupToolTest()
    const created = getTool('create_shape').execute(figma, {
      type: 'TEXT',
      x: 0,
      y: 0,
      width: 200,
      height: 20
    }) as ToolResult
    await runTool(figma, 'set_text', { id: created.id, text: 'Red text' })
    await runTool(figma, 'set_font_range', { id: created.id, start: 0, end: 3, color: '#ff0000' })

    const node = getNodeOrThrow(graph, expectDefined(created.id, 'created node id'))
    const colorRun = node.styleRuns.find((r) => r.style.fills?.length)
    expect(colorRun).toBeDefined()
    expect(
      expectDefined(expectDefined(colorRun, 'color style run').style.fills, 'color style fills')[0]
        ?.color.r
    ).toBeCloseTo(1)
  })
})

describe('set_font', () => {
  test('sets variable font axes, picking the nearest named style when none is given', async () => {
    const family = 'Tool Variations'
    await fontManager.markLoaded(
      family,
      'Regular',
      await Bun.file(repoPath('tests/fixtures/fonts/InterVariable-Latin.ttf')).arrayBuffer()
    )
    const { figma } = setupToolTest()
    const text = figma.createText()
    text.characters = 'Hello'
    expect(
      await runTool(figma, 'set_font', { id: text.id, family, variations: { wght: 650 } })
    ).toMatchObject({
      fontName: { family, style: 'Bold', variationSettings: { wght: 650 } }
    })
    expect(
      await runTool(figma, 'set_font', { id: text.id, style: 'Regular', variations: { wght: 450 } })
    ).toMatchObject({ fontName: { style: 'Regular', variationSettings: { wght: 450 } } })
    expect(await runTool(figma, 'set_font', { id: text.id, variations: { slnt: -10 } })).toEqual({
      error:
        'in setRangeFontName: "slnt" is not a valid variation setting. Valid settings are ["opsz","wght"].'
    })
  })
})

describe('text tools load fonts first', () => {
  test('a new font loads before it is set, so auto-width text takes its width', async () => {
    const family = 'Tool Load Sans'
    const data = await Bun.file(
      repoPath('tests/fixtures/fonts/NotoSansSC-Regular.ttf')
    ).arrayBuffer()
    fontManager.setHostFontLoader(async (requested, style) =>
      requested === family && style === 'Regular' ? data : null
    )
    try {
      const { figma, graph } = setupToolTest()
      const text = figma.createText()
      text.characters = 'Wide lettering'
      const before = text.width

      await runTool(figma, 'set_font', { id: text.id, family, style: 'Regular' })
      expect(fontManager.isStyleLoaded(family, 'Regular')).toBe(true)
      // Measured in the font it was given, not estimated while that font loaded.
      const measured = estimateTextSize(getNodeOrThrow(graph, text.id))
      expect([text.width, text.height]).toEqual([measured.width, measured.height])
      expect(text.width).not.toBe(before)
    } finally {
      fontManager.setHostFontLoader(null)
    }
  })

  test('a font that cannot load is reported and the text is left as it was', async () => {
    const { figma, graph } = setupToolTest()
    const text = figma.createText()
    text.characters = 'Label'
    const before = structuredClone(getNodeOrThrow(graph, text.id))

    expect(
      await runTool(figma, 'set_font', { id: text.id, family: 'Nowhere Sans', style: 'Bold' })
    ).toEqual({ error: 'The font "Nowhere Sans Bold" could not be loaded' })
    expect(getNodeOrThrow(graph, text.id)).toEqual(before)
  })

  test('a range colour needs no font, so text in a missing font can be recoloured', async () => {
    const { figma, graph } = setupToolTest()
    const text = figma.createText()
    text.characters = 'Label'
    graph.updateNode(text.id, { fontFamily: 'Nowhere Sans' })

    expect(
      await runTool(figma, 'set_font_range', { id: text.id, start: 0, end: 2, color: '#ff0000' })
    ).toEqual({ id: text.id, range: { start: 0, end: 2 } })
    expect(
      await runTool(figma, 'set_font_range', { id: text.id, start: 0, end: 2, size: 20 })
    ).toEqual({ error: 'The font "Nowhere Sans Regular" could not be loaded' })
  })
})