# Schema Reference

Complete reference for Form Builder JSON Schema v0.3 format.

## Schema Structure

```typescript
interface FormSchema {
  version: "0.3"; // Required: Schema version
  title: string; // Form title
  elements: FormElement[]; // Array of form elements
}
```

## Field Types

### Text Field

Single line text input with validation.

```json
{
  "type": "text",
  "key": "name",
  "label": "Full Name",
  "required": true,
  "minLength": 2,
  "maxLength": 50,
  "pattern": "^[A-Za-z ]+$",
  "default": ""
}
```

**Properties:**

- `minLength` - Minimum character count
- `maxLength` - Maximum character count
- `pattern` - Regular expression for validation
- `default` - Default value

### Textarea Field

Multi-line text input.

```json
{
  "type": "textarea",
  "key": "description",
  "label": "Description",
  "required": false,
  "minLength": 0,
  "maxLength": 1000,
  "default": ""
}
```

**Properties:** Same as text field

### Number Field

Numeric input with constraints.

```json
{
  "type": "number",
  "key": "age",
  "label": "Age",
  "required": true,
  "min": 0,
  "max": 120,
  "decimals": 0,
  "step": 1,
  "default": 0
}
```

**Properties:**

- `min` - Minimum value
- `max` - Maximum value
- `decimals` - Number of decimal places (0-8)
- `step` - Step increment for input

### Select Field

Dropdown selection with predefined options.

```json
{
  "type": "select",
  "key": "country",
  "label": "Country",
  "required": true,
  "options": [
    { "value": "us", "label": "United States" },
    { "value": "ca", "label": "Canada" },
    { "value": "uk", "label": "United Kingdom" }
  ],
  "default": "us"
}
```

**Properties:**

- `options` - Array of value/label pairs

### File Field

Single file upload with preview.

```json
{
  "type": "file",
  "key": "avatar",
  "label": "Profile Picture",
  "required": true,
  "accept": {
    "extensions": ["jpg", "jpeg", "png"],
    "mime": ["image/jpeg", "image/png"]
  },
  "maxSizeMB": 5
}
```

**Properties:**

- `accept.extensions` - Allowed file extensions
- `accept.mime` - Allowed MIME types
- `maxSizeMB` - Maximum file size in megabytes

### Files Field

Multiple file upload with count limits.

```json
{
  "type": "files",
  "key": "documents",
  "label": "Documents",
  "required": false,
  "accept": {
    "extensions": ["pdf", "doc", "docx"],
    "mime": ["application/pdf"]
  },
  "minCount": 0,
  "maxCount": 5,
  "maxSizeMB": 10
}
```

**Properties:**

- `minCount` - Minimum number of files
- `maxCount` - Maximum number of files
- All `file` type properties

### Group Field

Nested object structure with optional repetition.

```json
{
  "type": "group",
  "key": "address",
  "label": "Address",
  "elements": [
    {
      "type": "text",
      "key": "street",
      "label": "Street Address",
      "required": true
    },
    {
      "type": "text",
      "key": "city",
      "label": "City",
      "required": true
    }
  ]
}
```

**With Repetition and Custom Element Titles:**

```json
{
  "type": "group",
  "key": "slides",
  "label": "Video Slides",
  "element_label": "Slide $index",
  "repeat": {
    "min": 1,
    "max": 5
  },
  "elements": [
    {
      "type": "file",
      "key": "image",
      "label": "Slide Image",
      "required": true
    },
    {
      "type": "text",
      "key": "title",
      "label": "Slide Title",
      "required": true
    }
  ]
}
```

**Properties:**

- `elements` - Array of nested form elements
- `element_label` - Optional custom title for each group item (supports `$index` placeholder)
- `repeat.min` - Minimum number of repetitions
- `repeat.max` - Maximum number of repetitions

## Common Properties

All field types support these properties:

```typescript
interface BaseElement {
  type: string; // Field type
  key: string; // Unique identifier
  label: string; // Display label
  required?: boolean; // Required validation (default: false)
  default?: any; // Default value (not allowed for file types)
}
```

## Complete Example

Based on the sample from `docs/13_form_builder.html`:

```json
{
  "version": "0.3",
  "title": "Asset Uploader with Slides",
  "elements": [
    {
      "type": "file",
      "key": "cover",
      "label": "Cover image",
      "required": true,
      "accept": {
        "extensions": ["png", "jpg", "jpeg"],
        "mime": ["image/png", "image/jpeg"]
      },
      "maxSizeMB": 25
    },
    {
      "type": "files",
      "key": "assets",
      "label": "Additional images",
      "required": false,
      "accept": {
        "extensions": ["png", "jpg"],
        "mime": ["image/png", "image/jpeg"]
      },
      "minCount": 0,
      "maxCount": 10,
      "maxSizeMB": 25
    },
    {
      "type": "text",
      "key": "title",
      "label": "Project title",
      "required": true,
      "minLength": 1,
      "maxLength": 120,
      "pattern": "^[A-Za-z0-9 _-]+$",
      "default": "My Project"
    },
    {
      "type": "textarea",
      "key": "description",
      "label": "Description",
      "required": false,
      "minLength": 0,
      "maxLength": 2000,
      "default": ""
    },
    {
      "type": "select",
      "key": "theme",
      "label": "Theme",
      "required": true,
      "options": [
        { "value": "light", "label": "Light" },
        { "value": "dark", "label": "Dark" }
      ],
      "default": "dark"
    },
    {
      "type": "number",
      "key": "opacity",
      "label": "Opacity",
      "required": true,
      "min": 0,
      "max": 1,
      "decimals": 2,
      "step": 0.01,
      "default": 0.85
    },
    {
      "type": "group",
      "key": "slides",
      "label": "Slides",
      "repeat": {
        "min": 1,
        "max": 5
      },
      "elements": [
        {
          "type": "text",
          "key": "title",
          "label": "Slide title",
          "required": true,
          "minLength": 1,
          "maxLength": 80,
          "default": ""
        },
        {
          "type": "textarea",
          "key": "body",
          "label": "Slide text",
          "required": true,
          "minLength": 1,
          "maxLength": 1000,
          "default": ""
        }
      ]
    }
  ]
}
```

## Output Format

Form submission produces structured JSON data:

```json
{
  "cover": "res_abc123def456",
  "assets": ["res_def456ghi789", "res_ghi789jkl012"],
  "title": "My Amazing Project",
  "description": "A detailed description of the project...",
  "theme": "dark",
  "opacity": 0.85,
  "slides": [
    {
      "title": "Introduction",
      "body": "Welcome to our presentation..."
    },
    {
      "title": "Features",
      "body": "Here are the key features..."
    }
  ]
}
```

**Key Points:**

- File fields return resource IDs (e.g., `res_abc123def456`)
- Files fields return arrays of resource IDs
- Group fields return objects or arrays of objects
- All other fields return their literal values

## Validation Rules

### Schema Validation

The form builder validates schemas before rendering:

- `version` must be `"0.3"`
- `elements` must be an array
- Each element must have `type` and `key`
- No duplicate keys within the same scope
- File fields cannot have `default` values
- Select fields' `default` must be in `options`
- Numeric constraints must be logical (min ≤ max)

### Field Validation

During form interaction:

- **Required fields**: Must have values
- **Text/Textarea**: Length constraints and pattern matching
- **Number**: Range constraints and decimal places
- **File/Files**: Type restrictions, size limits, count limits
- **Select**: Value must be in options list

### Custom Validation

For advanced validation, handle the `formSubmit` event:

```javascript
window.addEventListener("message", (event) => {
  if (event.data.type === "formSubmit") {
    const { data, schema } = event.data;

    // Custom validation logic
    if (data.email && !isValidEmail(data.email)) {
      // Handle validation error
      return;
    }

    // Process valid submission
    handleFormSubmission(data);
  }
});
```

## Schema Evolution

### Version History

- **v0.3**: Current version with file upload support
- Future versions will maintain backwards compatibility within the same major version

### Migration Guidelines

When updating schemas:

1. Always specify the correct version
2. Test with the form builder before deployment
3. Use schema validation to catch errors early
4. Provide migration paths for breaking changes

This schema reference provides complete documentation for creating effective forms with the Form Builder library.
