Skip to content

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

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

import { getNodeOrThrow } from '#core-tests/helpers/assert'

import { renderJSX } from '@open-pencil/core/design-jsx'
import { sceneNodeToJSX } from '@open-pencil/design-jsx'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { missingBindings, readBehaviour } from '@open-pencil/scene-graph/behaviours'

async function render(jsx: string) {
  const graph = new SceneGraph()
  const [result] = await renderJSX(graph, jsx)
  const root = getNodeOrThrow(graph, result.id)
  const behaviour = readBehaviour(root)
  if (!behaviour) throw new Error(`${root.name} has no behaviour`)
  const names = (definitions: SceneNode['componentPropertyDefinitions']) =>
    definitions.map((item) => `${item.name}:${item.type}`)
  return { graph, root, behaviour, names, missing: missingBindings(graph, root, behaviour) }
}

describe('Reka UI elements in design JSX', () => {
  test('a Switch.Root with variants is a set whose thumb is one slot across its variants', async () => {
    const { graph, root, behaviour, missing } = await render(`
      <Switch.Root name="Switch" modelValue="State" states="Interaction">
        <Component name="State=Off, Interaction=Default" w={44} h={24}>
          <Switch.Thumb x={2} y={2} w={20} h={20} />
        </Component>
        <Component name="State=On, Interaction=Default" w={44} h={24}>
          <Switch.Thumb x={22} y={2} w={20} h={20} />
        </Component>
        <Component name="State=Off, Interaction=Hover" w={44} h={24}>
          <Switch.Thumb x={2} y={2} w={20} h={20} />
        </Component>
      </Switch.Root>
    `)
    expect(root.type).toBe('COMPONENT_SET')
    expect(behaviour.kind).toBe('switch')
    expect(behaviour.booleans.value).toMatchObject({ on: 'On', off: 'Off' })
    expect(behaviour.states).toMatchObject({ rest: 'Default', hover: 'Hover' })
    const thumbs = [...graph.getAllNodes()].filter((node) => node.name === 'Thumb')
    expect(thumbs).toHaveLength(3)
    expect(
      new Set(thumbs.map((thumb) => thumb.componentPropertyReferences[0]?.propertyId))
    ).toEqual(new Set([behaviour.parts.thumb]))
    expect(missing).toEqual([])
  })

  test('a TextField.Input becomes the field’s text property', async () => {
    const { root, behaviour, names, missing } = await render(`
      <TextField.Root name="Field" w={200} h={36}>
        <TextField.Input x={10} y={10}>Email</TextField.Input>
      </TextField.Root>
    `)
    expect(names(root.componentPropertyDefinitions)).toEqual(['Text:TEXT'])
    expect(behaviour.texts.value?.propertyId).toBe(root.componentPropertyDefinitions[0]?.id)
    expect(missing).toEqual([])
  })

  test('tab triggers and panels go in their List and Panels slots, the first panel showing', async () => {
    const { graph, root, behaviour, missing } = await render(`
      <Tabs.Root name="Tabs" w={240} flex="col">
        <Tabs.List flex="row" gap={8}>
          <Tabs.Trigger><Text>Account</Text></Tabs.Trigger>
          <Tabs.Trigger><Text>Password</Text></Tabs.Trigger>
        </Tabs.List>
        <Tabs.Content><Text>Your name</Text></Tabs.Content>
        <Tabs.Content><Text>Your password</Text></Tabs.Content>
      </Tabs.Root>
    `)
    expect(graph.getChildren(root.id).map((child) => child.name)).toEqual(['List', 'Panels'])
    const panels = graph.getChildren(graph.getChildren(root.id)[1]?.id ?? '')
    expect(panels.map((panel) => panel.visible)).toEqual([true, false])
    expect(Object.keys(behaviour.parts).sort()).toEqual(['list', 'panels'])
    expect(missing).toEqual([])
  })

  test('a radio group’s items are instances of its RadioGroup.Item component in an Items slot', async () => {
    const graph = new SceneGraph()
    const [radio] = await renderJSX(
      graph,
      `<RadioGroup.Item name="Radio" modelValue="Checked">
        <Component name="Checked=Off" w={20} h={20} />
        <Component name="Checked=On" w={20} h={20} />
      </RadioGroup.Item>`
    )
    const [group] = await renderJSX(
      graph,
      `<RadioGroup.Root name="Plan">
        <RadioGroup.Item of="${radio.id}" />
        <RadioGroup.Item of="${radio.id}" />
      </RadioGroup.Root>`
    )
    const root = getNodeOrThrow(graph, group.id)
    const [items] = graph.getChildren(root.id)
    expect(items?.name).toBe('Items')
    expect(graph.getChildren(items?.id ?? '').map((item) => item.type)).toEqual([
      'INSTANCE',
      'INSTANCE'
    ])
    expect(readBehaviour(getNodeOrThrow(graph, radio.id))?.kind).toBe('radio')
    const behaviour = readBehaviour(root)
    expect(behaviour && missingBindings(graph, root, behaviour)).toEqual([])
  })

  test('a part with content and no layout of its own hugs it in a column', async () => {
    const { graph, root } = await render(`
      <Collapsible.Root name="Question" w={360} flex="col">
        <Collapsible.Trigger flex="row" gap={8}><Text>Can I cancel?</Text></Collapsible.Trigger>
        <Collapsible.Content><Text>Yes, any time from your account.</Text></Collapsible.Content>
      </Collapsible.Root>
    `)
    const [, content] = graph.getChildren(root.id)
    const [text] = graph.getChildren(content?.id ?? '')
    expect(content?.layoutMode).toBe('VERTICAL')
    expect(content?.width).toBe(text?.width)
    expect(content?.height).toBe(text?.height)

    // One sized under any name keeps its own size and no layout.
    const { graph: sizedGraph, root: sized } = await render(`
      <Collapsible.Root name="Question" w={360} flex="col">
        <Collapsible.Trigger flex="row"><Text>Can I cancel?</Text></Collapsible.Trigger>
        <Collapsible.Content width={200} height={40}><Text>Yes.</Text></Collapsible.Content>
      </Collapsible.Root>
    `)
    const [, sizedContent] = sizedGraph.getChildren(sized.id)
    expect([sizedContent?.layoutMode, sizedContent?.width, sizedContent?.height]).toEqual([
      'NONE',
      200,
      40
    ])

    // A part drawn as a shape keeps the size it is given.
    const { graph: switchGraph, root: switchRoot } = await render(`
      <Switch.Root name="Switch" w={44} h={24}><Switch.Thumb w={20} h={20} /></Switch.Root>
    `)
    const [thumb] = switchGraph.getChildren(switchRoot.id)
    expect([thumb?.layoutMode, thumb?.width, thumb?.height]).toEqual(['NONE', 20, 20])
  })

  test('an item chooses its variant by the set’s variant property, which is no unknown prop', async () => {
    const graph = new SceneGraph()
    const [radio] = await renderJSX(
      graph,
      `<RadioGroup.Item name="Radio" modelValue="Checked">
        <Component name="Checked=Off" w={20} h={20} />
        <Component name="Checked=On" w={20} h={20} />
      </RadioGroup.Item>`
    )
    const [group] = await renderJSX(
      graph,
      `<RadioGroup.Root name="Plan">
        <RadioGroup.Item of="${radio.id}" />
        <RadioGroup.Item of="${radio.id}" Checked="On" Tone="Loud" />
      </RadioGroup.Root>`
    )
    const [items] = graph.getChildren(group.id)
    const chosen = graph
      .getChildren(items?.id ?? '')
      .map((item) => graph.getNode(item.componentId ?? '')?.name)
    expect(chosen).toEqual(['Checked=Off', 'Checked=On'])
    expect(group.warnings).toEqual(['Unsupported prop "Tone" on <RadioGroup.Item> is ignored.'])
  })
})

describe('Reka UI elements in JSX export', () => {
  test('a switch set exports as Switch.Root with its thumb and renders back the same', async () => {
    const graph = new SceneGraph()
    const [first] = await renderJSX(
      graph,
      `<Switch.Root name="Switch" modelValue="State">
        <Component name="State=Off" w={44} h={24}><Switch.Thumb x={2} y={2} w={20} h={20} /></Component>
        <Component name="State=On" w={44} h={24}><Switch.Thumb x={22} y={2} w={20} h={20} /></Component>
      </Switch.Root>`
    )
    const code = sceneNodeToJSX(first.id, graph)
    expect(code).toContain('<Switch.Root')
    expect(code).toContain('modelValue={{ property: "State", on: "On", off: "Off" }}')
    expect(code.match(/<Switch\.Thumb/g)).toHaveLength(2)

    const [second] = await renderJSX(graph, code)
    const again = readBehaviour(getNodeOrThrow(graph, second.id))
    const before = readBehaviour(getNodeOrThrow(graph, first.id))
    expect(again?.kind).toBe('switch')
    expect(again?.booleans.value).toMatchObject({ on: 'On', off: 'Off' })
    expect(Object.keys(again?.parts ?? {})).toEqual(Object.keys(before?.parts ?? {}))
  })

  test('a checkbox keeps its invalid value and invalid state through export', async () => {
    const graph = new SceneGraph()
    const [first] = await renderJSX(
      graph,
      `<Checkbox.Root name="Checkbox" modelValue="Checked" invalid="Error" states="State">
        <Component name="Checked=Off, Error=Off, State=Default" w={16} h={16} />
        <Component name="Checked=On, Error=Off, State=Default" w={16} h={16} />
        <Component name="Checked=Off, Error=On, State=Default" w={16} h={16} />
        <Component name="Checked=Off, Error=Off, State=Invalid" w={16} h={16} />
      </Checkbox.Root>`
    )
    const before = readBehaviour(getNodeOrThrow(graph, first.id))
    expect(before?.booleans.invalid).toMatchObject({ on: 'On', off: 'Off' })
    expect(before?.states?.invalid).toBe('Invalid')
    const code = sceneNodeToJSX(first.id, graph)
    expect(code).toContain('invalid={{ property: "Error", on: "On", off: "Off" }}')

    const [second] = await renderJSX(graph, code)
    const again = readBehaviour(getNodeOrThrow(graph, second.id))
    expect(again?.booleans.invalid).toMatchObject({ on: 'On', off: 'Off' })
    expect(again?.states?.invalid).toBe('Invalid')
  })

  test('tabs and a radio group export their repeated parts and items as Reka writes them', async () => {
    const graph = new SceneGraph()
    const [radio] = await renderJSX(
      graph,
      `<RadioGroup.Item name="Radio" modelValue="Checked">
        <Component name="Checked=Off" w={20} h={20} />
        <Component name="Checked=On" w={20} h={20} />
      </RadioGroup.Item>`
    )
    const [group] = await renderJSX(
      graph,
      `<RadioGroup.Root name="Plan">
        <RadioGroup.Item of="${radio.id}" />
        <RadioGroup.Item of="${radio.id}" Checked="On" />
      </RadioGroup.Root>`
    )
    // Each item keeps its variant, so a checked item renders back checked.
    const exported = sceneNodeToJSX(group.id, graph)
    expect(exported).toContain('<RadioGroup.Item of="Radio" Checked="Off" />')
    expect(exported).toContain('<RadioGroup.Item of="Radio" Checked="On" />')
    const [copy] = await renderJSX(graph, exported)
    expect(sceneNodeToJSX(copy.id, graph)).toBe(exported)

    const [tabs] = await renderJSX(
      graph,
      `<Tabs.Root name="Tabs">
        <Tabs.List><Tabs.Trigger><Text>One</Text></Tabs.Trigger></Tabs.List>
        <Tabs.Content><Text>First</Text></Tabs.Content>
      </Tabs.Root>`
    )
    const code = sceneNodeToJSX(tabs.id, graph)
    expect(code).toContain('<Tabs.List')
    expect(code).toContain('<Tabs.Trigger')
    expect(code).toContain('<Tabs.Content')
    expect(code).not.toContain('name="Panels"')
  })

  test('a Tabs.Tab component draws the triggers a tab list holds as its instances', async () => {
    const graph = new SceneGraph()
    const [tab] = await renderJSX(
      graph,
      `<Tabs.Tab name="Tab" modelValue="Selected">
        <Component name="Selected=Off" w={60} h={24} />
        <Component name="Selected=On" w={60} h={24} />
      </Tabs.Tab>`
    )
    expect(readBehaviour(getNodeOrThrow(graph, tab.id))?.kind).toBe('tab')
    const [tabs] = await renderJSX(
      graph,
      `<Tabs.Root name="Tabs" flex="col">
        <Tabs.Tab of="${tab.id}" Selected="On" />
        <Tabs.Tab of="${tab.id}" />
        <Tabs.Content><Text>First</Text></Tabs.Content>
        <Tabs.Content><Text>Second</Text></Tabs.Content>
      </Tabs.Root>`
    )
    const root = getNodeOrThrow(graph, tabs.id)
    const [list] = graph.getChildren(root.id)
    expect(list?.name).toBe('List')
    expect(graph.getChildren(list?.id ?? '').map((trigger) => trigger.type)).toEqual([
      'INSTANCE',
      'INSTANCE'
    ])
    const behaviour = readBehaviour(root)
    expect(behaviour && missingBindings(graph, root, behaviour)).toEqual([])

    const exported = sceneNodeToJSX(tabs.id, graph)
    expect(exported).toContain('<Tabs.Tab of="Tab" Selected="On" />')
    expect(exported).toContain('<Tabs.Tab of="Tab" Selected="Off" />')
    const [copy] = await renderJSX(graph, exported)
    expect(sceneNodeToJSX(copy.id, graph)).toBe(exported)
  })

  test('a group item whose changes JSX cannot write is written as the layer it draws', async () => {
    const graph = new SceneGraph()
    await renderJSX(
      graph,
      `<><Component name="Mark" w={4} h={4} />
      <RadioGroup.Item name="Radio" modelValue="Checked">
        <Component name="Checked=Off" w={20} h={20}><Instance name="Dot" of="Mark" /></Component>
        <Component name="Checked=On" w={20} h={20}><Instance name="Dot" of="Mark" /></Component>
      </RadioGroup.Item></>`
    )
    const [group] = await renderJSX(
      graph,
      `<RadioGroup.Root name="Plan">
        <RadioGroup.Item of="Radio" overrides={{ 'Dot:opacity': 0.5 }} />
      </RadioGroup.Root>`
    )
    const exported = sceneNodeToJSX(group.id, graph)
    expect(exported).not.toContain('<RadioGroup.Item')
    // The item renders back as the layers it drew, its dot still half transparent.
    const [copy] = await renderJSX(graph, exported)
    const [item] = graph.getChildren(copy.id)
    const [dot] = graph.getChildren(item?.id ?? '')
    expect([item?.type, item?.name]).toEqual(['FRAME', 'Checked=Off'])
    expect([dot?.type, dot?.name, dot?.opacity]).toEqual(['INSTANCE', 'Dot', 0.5])
  })

  test('a group item exports the property values and layer overrides it gives its component', async () => {
    const graph = new SceneGraph()
    await renderJSX(
      graph,
      `<RadioGroup.Item name="Radio" modelValue="Checked">
        <Component name="Checked=Off" w={20} h={20}>
          <Frame name="Dot" w={4} h={4} /><Text name="Label" text={property('Label', 'Plan')} />
        </Component>
        <Component name="Checked=On" w={20} h={20}>
          <Frame name="Dot" w={4} h={4} /><Text name="Label" text={property('Label', 'Plan')} />
        </Component>
      </RadioGroup.Item>`
    )
    const [group] = await renderJSX(
      graph,
      `<RadioGroup.Root name="Plan">
        <RadioGroup.Item of="Radio" Checked="On" Label="Pro" overrides={{ 'Dot:opacity': 0.5 }} />
        <RadioGroup.Item of="Radio" visible={false} />
        <RadioGroup.Item of="Radio" opacity={0.4} />
      </RadioGroup.Root>`
    )
    const exported = sceneNodeToJSX(group.id, graph)
    expect(exported).toContain(
      '<RadioGroup.Item of="Radio" Checked="On" Label="Pro" overrides={{ "Dot:opacity": 0.5 }} />'
    )
    expect(exported).toContain('<RadioGroup.Item of="Radio" Checked="Off" visible={false} />')
    expect(exported).toContain('<RadioGroup.Item of="Radio" Checked="Off" opacity={0.4} />')
    const [copy] = await renderJSX(graph, exported)
    expect(sceneNodeToJSX(copy.id, graph)).toBe(exported)
  })
})