Skip to content

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

876 B
Raw Blame
import { Allow, parseJSON } from 'partial-json'
import * as v from 'valibot'

const coordinateSchema = v.optional(v.pipe(v.number(), v.finite()))
const renderPreviewInputSchema = v.object({
  jsx: v.string(),
  parent_id: v.optional(v.string()),
  replace_id: v.optional(v.string()),
  insert_index: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
  x: coordinateSchema,
  y: coordinateSchema
})

export type RenderPreviewInput = v.InferOutput<typeof renderPreviewInputSchema>

export function readPreviewInput(source: string): RenderPreviewInput | null {
  try {
    // Omit unfinished numbers rather than guessing coordinates (for example x: 1e).
    const value: unknown = parseJSON(source, Allow.STR | Allow.OBJ)
    const result = v.safeParse(renderPreviewInputSchema, value)
    return result.success ? result.output : null
  } catch {
    return null
  }
}