Skip to content

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

11.3 KB
Raw Blame
import { FLAGS, type Flag } from '#dom-css/behaviours/args'
import dedent from 'dedent'

import { es } from '@open-pencil/emit'

export const STORYBOOK_FRAMEWORKS = ['react', 'vue', 'html'] as const
export type StorybookFramework = (typeof STORYBOOK_FRAMEWORKS)[number]

/** Tells readers the file is generated; nothing parses it. */
const HEADER = '// Generated by OpenPencil. Re-export to update; edits are overwritten.'

/**
 * How a variant property is controlled. A boolean value's property becomes a boolean arg that
 * picks its on or off variant; the interaction-state property is left to each story, with
 * `disabled` and `invalid` args picking those variants when the set draws them.
 */
export type StoryControl =
  | { type: 'boolean'; name: string; on: string; off: string }
  | { type: 'state'; rest: string; disabled?: string; invalid?: string }

export interface StoryProp {
  name: string
  options: string[]
  control?: StoryControl
}

/** Everything a story module varies by; the TypeScript around it is a fixed template. */
export interface StoryModuleData {
  framework: StorybookFramework
  title: string
  /** Tags on the whole file, which its stories inherit. */
  tags: string[]
  /** Stylesheets the file imports, such as the fonts its text uses. */
  styles: string[]
  /** Group name used in the missing-variant error. */
  name: string
  props: StoryProp[]
  variants: { values: string[]; html: string }[]
  metaDesign: StoryDesign[]
  /** Import path of each design image, by variant index. */
  images: string[]
  /** Every variant laid out in one story, each with its label as escaped HTML, if a gallery. */
  gallery: { values: string[]; label: string }[] | null
  stories: {
    exportName: string
    label: string
    values: string[]
    design: StoryDesign[]
    tags: string[]
  }[]
}

export type StoryDesign =
  | { type: 'link'; url: string }
  /** Refers to the design image of the variant with this index. */
  | { type: 'image'; variant: number }

const MODULE = es.parseModule(dedent`
  import type { Meta, StoryObj } from '$storybook'

  type Args = $Args

  const variants: Record<string, string> = $variants

  function variantHTML(args: Args): string {
    const key = JSON.stringify($key)
    const html = variants[key]
    if (html === undefined) throw new Error($missing + key)
    return html
  }

  const meta = {
    title: $title,
    tags: $tags,
    parameters: $parameters,
    args: $args,
    argTypes: $argTypes,
    render: (args) => $render
  } satisfies Meta<Args>

  export default meta
  type Story = StoryObj<Args>
`)

const GALLERY = es.parseModule(dedent`
  const labels: [string, string][] = $labels

  function galleryHTML(): string {
    const items = labels.map(
      ([key, label]) =>
        '<figure style="margin: 0; display: flex; flex-direction: column; align-items: center; gap: 8px">' +
        (variants[key] ?? '') +
        '<figcaption style="font: 12px system-ui, sans-serif; color: #6b7280">' +
        label +
        '</figcaption></figure>'
    )
    return (
      '<div style="display: flex; flex-wrap: wrap; align-items: flex-end; gap: 24px">' +
      items.join('') +
      '</div>'
    )
  }

  export const Gallery: Story = { name: 'Gallery', render: () => $render }
`)

const IMAGE = es.parseModule(`const $name = new URL($path, import.meta.url).href`)
const STORY = es.parseModule(`export const $name: Story = $story`)
const STYLESHEET = es.parseModule(`import '$path'`)

/** The Storybook renderer package each framework's stories import their types from. */
export const STORYBOOK_PACKAGES: Record<StorybookFramework, string> = {
  react: '@storybook/react-vite',
  vue: '@storybook/vue3-vite',
  html: '@storybook/html-vite'
}

/** How each framework renders a string of HTML, `$html`, as a story. */
const FRAMEWORKS: Record<StorybookFramework, { imports: es.SyntaxNode[]; render: es.SyntaxNode }> =
  {
    react: {
      imports: es.parseModule(`import { createElement } from 'react'`).body,
      render: es.parseExpression(
        `createElement('div', { dangerouslySetInnerHTML: { __html: $html } })`
      )
    },
    vue: {
      imports: es.parseModule(`import { h } from 'vue'`).body,
      render: es.parseExpression(`{ setup: () => () => h('div', { innerHTML: $html }) }`)
    },
    html: {
      imports: [],
      render: es.parseExpression('$html')
    }
  }

const rendered = (framework: StorybookFramework, html: string) =>
  es.fill(FRAMEWORKS[framework].render, { $html: es.parseExpression(html) })

const imageName = (variant: number) => `design${variant}`

const BOOLEAN = es.parseType('boolean')
const CONDITION = es.parseExpression('$test ? $then : $else')
const boolean = (value: boolean) => es.parseExpression(String(value))

function argRef(name: string): es.SyntaxNode {
  return {
    type: 'MemberExpression',
    object: es.identifier('args'),
    property: es.string(name),
    computed: true,
    optional: false
  }
}

/** A `disabled` or `invalid` arg that picks a value of the state property. */
interface FlagArg {
  name: Flag
  property: string
  value: string
}

/**
 * The `disabled` and `invalid` args a state property adds, disabled first, which wins when both
 * are on; a flag a boolean value already takes is left out.
 */
function flagArgs(data: StoryModuleData): FlagArg[] {
  return FLAGS.flatMap((name) => {
    if (data.props.some((prop) => prop.control?.type === 'boolean' && prop.control.name === name))
      return []
    for (const prop of data.props) {
      const value = prop.control?.type === 'state' ? prop.control[name] : undefined
      if (value !== undefined) return [{ name, property: prop.name, value }]
    }
    return []
  })
}

/** The arg a prop is set by: a boolean prop's own name, otherwise the property's. */
const argName = (prop: StoryProp) =>
  prop.control?.type === 'boolean' ? prop.control.name : prop.name

/** The variant value a prop shows, as an expression over `args`. */
function propValue(data: StoryModuleData, prop: StoryProp): es.SyntaxNode {
  const control = prop.control
  if (control?.type === 'boolean')
    return es.fill(CONDITION, {
      $test: argRef(control.name),
      $then: es.string(control.on),
      $else: es.string(control.off)
    })
  // `args.disabled ? 'Disabled' : args.invalid ? 'Invalid' : args.State`
  return flagArgs(data)
    .filter((flag) => flag.property === prop.name)
    .reduceRight<es.SyntaxNode>(
      (otherwise, flag) =>
        es.fill(CONDITION, {
          $test: argRef(flag.name),
          $then: es.string(flag.value),
          $else: otherwise
        }),
      argRef(prop.name)
    )
}

function argsObject(data: StoryModuleData, values: string[]): es.SyntaxNode {
  const flags = flagArgs(data)
  const entries = data.props.map((prop, i): [string, es.SyntaxNode] => {
    const value = values[i] ?? ''
    if (prop.control?.type === 'boolean')
      return [prop.control.name, boolean(value === prop.control.on)]
    // A disabled or invalid story says so through its flag, so clearing it shows the rest state.
    if (prop.control?.type === 'state' && flags.some((flag) => flag.value === value))
      return [prop.name, es.string(prop.control.rest)]
    return [prop.name, es.string(value)]
  })
  for (const flag of flags) {
    const index = data.props.findIndex((prop) => prop.name === flag.property)
    entries.push([flag.name, boolean(values[index] === flag.value)])
  }
  return es.object(entries)
}

function argTypes(data: StoryModuleData): es.SyntaxNode {
  const entries = data.props.map((prop): [string, es.SyntaxNode] => {
    if (prop.control?.type === 'boolean')
      return [prop.control.name, es.object([['control', es.string('boolean')]])]
    if (prop.control?.type === 'state')
      return [prop.name, es.object([['table', es.object([['disable', boolean(true)]])]])]
    return [
      prop.name,
      es.object([
        ['control', es.string('select')],
        ['options', es.array(prop.options.map(es.string))]
      ])
    ]
  })
  for (const flag of flagArgs(data))
    entries.push([flag.name, es.object([['control', es.string('boolean')]])])
  return es.object(entries)
}

function parameters(design: StoryDesign[]): es.SyntaxNode {
  const entries = design.map((entry) =>
    entry.type === 'link'
      ? es.object([
          ['name', es.string('OpenPencil')],
          ['type', es.string('link')],
          ['url', es.string(entry.url)]
        ])
      : es.object([
          ['name', es.string('Design')],
          ['type', es.string('image')],
          ['url', es.identifier(imageName(entry.variant))]
        ])
  )
  return es.object([['design', es.array(entries)]])
}

const NO_ARGS = es.parseType('Record<string, never>')

function argsType(data: StoryModuleData): es.SyntaxNode {
  if (data.props.length === 0) return NO_ARGS
  const entries = data.props.map((prop): [string, es.SyntaxNode] => [
    argName(prop),
    prop.control?.type === 'boolean' ? BOOLEAN : es.stringUnionType(prop.options)
  ])
  for (const flag of flagArgs(data)) entries.push([flag.name, BOOLEAN])
  return es.objectType(entries)
}

/** `import './fonts/kit/fonts.css'` for each stylesheet, which the bundler loads with the stories. */
export const stylesheets = (paths: readonly string[]) =>
  paths.flatMap((path) => es.fill(STYLESHEET, { $path: es.string(path) }).body)

/** Print a CSF3 story module for one component or component set. */
export function printStoryModule(data: StoryModuleData): string {
  const framework = FRAMEWORKS[data.framework]
  const [storybookImport, ...body] = es.fill(MODULE, {
    $storybook: es.string(STORYBOOK_PACKAGES[data.framework]),
    $Args: argsType(data),
    $variants: es.object(
      data.variants.map((variant) => [JSON.stringify(variant.values), es.string(variant.html)])
    ),
    $key: es.array(data.props.map((prop) => propValue(data, prop))),
    $missing: es.string(`${data.name} has no variant `),
    $title: es.string(data.title),
    $tags: es.array(data.tags.map(es.string)),
    $parameters: data.metaDesign.length > 0 ? parameters(data.metaDesign) : es.OMIT,
    $args: argsObject(data, data.variants[0]?.values ?? []),
    $argTypes: argTypes(data),
    $render: rendered(data.framework, 'variantHTML(args)')
  }).body
  const images = data.images.flatMap(
    (path, i) =>
      es.fill(IMAGE, { $name: es.identifier(imageName(i)), $path: es.string(`./${path}`) }).body
  )
  const stories = data.stories.flatMap(
    (story) =>
      es.fill(STORY, {
        $name: es.identifier(story.exportName),
        $story: es.object([
          ['name', es.string(story.label)],
          ...(story.tags.length > 0
            ? [['tags', es.array(story.tags.map(es.string))] as const]
            : []),
          ...(story.design.length > 0 ? [['parameters', parameters(story.design)] as const] : []),
          ['args', argsObject(data, story.values)]
        ])
      }).body
  )
  const gallery = data.gallery
    ? es.fill(GALLERY, {
        $labels: es.array(
          data.gallery.map((item) =>
            es.array([es.string(JSON.stringify(item.values)), es.string(item.label)])
          )
        ),
        $render: rendered(data.framework, 'galleryHTML()')
      }).body
    : []
  const module = es.printModule({
    type: 'Program',
    sourceType: 'module',
    body: [
      storybookImport,
      ...framework.imports,
      ...stylesheets(data.styles),
      ...images,
      ...body,
      ...stories,
      ...gallery
    ]
  })
  return `${HEADER}\n${module}\n`
}