npm package: @msaadh-synapse/form-builder
Description: A powerful drag-and-drop form builder for React with support for headings, paragraphs, tables, and form inputs
Latest version: 1.0.1

# Custom Form Builder

A powerful, drag-and-drop form builder for React with support for headings, paragraphs, tables, and various form inputs. Build beautiful forms with an intuitive visual interface.

## Features

- 🎨 **Drag & Drop Interface** - Intuitive drag-and-drop builder
- 📝 **Rich Content Elements** - Headings, paragraphs, and tables
- 📋 **Form Inputs** - Text, number, select, and checkbox inputs
- 🎯 **Real-time Preview** - See your form as you build it
- 💾 **Schema Export** - Export and import form schemas as JSON
- 🔄 **Undo/Redo** - Full history support for your changes
- 📱 **Responsive Design** - Works seamlessly on mobile and desktop
- 🎨 **Tailwind CSS** - Beautiful, modern styling out of the box

## Installation

```bash
npm install @msaadh-synapse/form-builder
```

or

```bash
yarn add @msaadh-synapse/form-builder
```

or

```bash
pnpm add @msaadh-synapse/form-builder
```

## Peer Dependencies

This package requires React 18+ or 19+ and React DOM. Make sure you have these installed:

```bash
npm install react react-dom
```

The package also requires these dependencies (they will be installed automatically):

- `@dnd-kit/core`
- `@dnd-kit/sortable`
- `@dnd-kit/utilities`
- `react-hook-form`

## Quick Start

### Basic Usage

```tsx
import { FormBuilder } from '@msaadh-synapse/form-builder'
import '@msaadh-synapse/form-builder/styles'

function App() {
  return <FormBuilder />
}
```

### With Schema Management

```tsx
import { FormBuilder, useFormBuilder } from '@msaadh-synapse/form-builder'
import '@msaadh-synapse/form-builder/styles'
import { useState } from 'react'

function App() {
  const [schema, setSchema] = useState([])

  return (
    <FormBuilder
      initialSchema={schema}
      onSchemaChange={(newSchema) => {
        setSchema(newSchema)
        // Save to your backend or localStorage
      }}
    />
  )
}
```

### Using the Hook Directly

For more control, you can use the `useFormBuilder` hook directly:

```tsx
import { useFormBuilder, Canvas, Sidebar, PropertiesPanel } from '@msaadh-synapse/form-builder'
import '@msaadh-synapse/form-builder/styles'
import { DndContext } from '@dnd-kit/core'

function CustomFormBuilder() {
  const {
    elements,
    selectedId,
    selectElement,
    addElement,
    deleteElement,
    updateElementConfig,
    exportSchema,
  } = useFormBuilder()

  return (
    <DndContext>
      <div style={{ display: 'flex' }}>
        <Sidebar onAdd={addElement} />
        <Canvas
          elements={elements}
          selectedId={selectedId}
          onSelect={selectElement}
          onDelete={deleteElement}
          onUpdate={updateElementConfig}
        />
        <PropertiesPanel
          element={elements.find((e) => e.id === selectedId) || null}
          onUpdate={updateElementConfig}
          onDelete={deleteElement}
        />
      </div>
    </DndContext>
  )
}
```

## API Reference

### FormBuilder Component

The main component that provides a complete form builder interface.

#### Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `initialSchema` | `AnyFormElement[]` | `undefined` | Initial form schema to load |
| `onSchemaChange` | `(schema: AnyFormElement[]) => void` | `undefined` | Callback when schema changes |
| `persistToLocalStorage` | `boolean` | `true` | Whether to persist schema to localStorage |
| `storageKey` | `string` | `'custom-form-builder-schema'` | Custom storage key for localStorage |
| `defaultPreviewMode` | `boolean` | `false` | Show preview mode by default |
| `className` | `string` | `undefined` | Custom className for root container |

### useFormBuilder Hook

Returns an object with the following properties and methods:

- `elements: AnyFormElement[]` - Current form elements
- `selectedId: string | null` - ID of currently selected element
- `selectedElement: AnyFormElement | null` - Currently selected element
- `selectElement: (id: string | null) => void` - Select an element
- `addElement: (type: BuilderElementType, index?: number) => AnyFormElement` - Add a new element
- `updateElementConfig: <T>(id: string, producer: (config: FormElementConfigMap[T]) => FormElementConfigMap[T]) => void` - Update element configuration
- `deleteElement: (id: string) => void` - Delete an element
- `duplicateElement: (id: string) => AnyFormElement | null` - Duplicate an element
- `moveElement: (activeId: string, overId: string) => void` - Move an element
- `clearCanvas: () => void` - Clear all elements
- `undo: () => void` - Undo last change
- `redo: () => void` - Redo last undone change
- `canUndo: boolean` - Whether undo is available
- `canRedo: boolean` - Whether redo is available
- `exportSchema: () => AnyFormElement[]` - Export current schema
- `loadSchema: (schema: AnyFormElement[]) => void` - Load a schema

### Types

```typescript
type BuilderElementType = 
  | 'heading'
  | 'paragraph'
  | 'table'
  | 'text'
  | 'number'
  | 'select'
  | 'checkbox'

interface AnyFormElement {
  id: string
  type: BuilderElementType
  config: FormElementConfigMap[BuilderElementType]
}
```

## Styling

The package uses Tailwind CSS. Make sure to import the styles:

```tsx
import '@msaadh-synapse/form-builder/styles'
```

If you're using Tailwind CSS in your project, you may need to configure it to include the package's styles. Add this to your `tailwind.config.js`:

```js
module.exports = {
  content: [
    './src/**/*.{js,jsx,ts,tsx}',
    './node_modules/@msaadh-synapse/form-builder/dist/**/*.{js,jsx,ts,tsx}',
  ],
  // ... rest of your config
}
```

## Examples

### Export Schema

```tsx
import { FormBuilder, useFormBuilder } from '@msaadh-synapse/form-builder'

function App() {
  const { exportSchema } = useFormBuilder()
  
  const handleExport = () => {
    const schema = exportSchema()
    console.log(JSON.stringify(schema, null, 2))
    // Send to your backend or save to file
  }

  return <FormBuilder />
}
```

### Load Schema

```tsx
import { FormBuilder } from '@msaadh-synapse/form-builder'

function App() {
  const savedSchema = [
    {
      id: '1',
      type: 'heading',
      config: {
        text: 'Welcome',
        level: 'h1',
        align: 'center',
      },
    },
    // ... more elements
  ]

  return <FormBuilder initialSchema={savedSchema} />
}
```

## Development

To contribute or develop locally:

```bash
# Install dependencies
npm install

# Run development server
npm run dev

# Build for production
npm run build

# Preview production build
npm run preview
```

## License

MIT

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.