Okay, let's build a client-side form builder using React, React Query (though its primary use case here is limited as it's client-side building, we can include it conceptually for potential save/load operations), Jotai (as an alternative or complementary state manager, though we'll primarily use signals as requested), @preact/signals-react, and ArkType.
We'll use @preact/signals-react for the core state management of the form definition itself, as it provides fine-grained reactivity. Jotai could be used for other global states if needed (like UI state), but signals fit well for the form structure. React Query would typically manage fetching/saving the form definition to/from an API, which isn't the focus of building but we can imagine where it would fit. ArkType will define our form field structures and validate them.
1. Project Setup (Conceptual)
# Using Vite (recommended)
npm create vite@latest my-form-builder --template react-ts
cd my-form-builder
npm install
npm install @preact/signals-react @preact/signals jotai react-query arktype uuid
npm install --save-dev @types/react @types/react-dom
2. Define Schemas with ArkType (src/schema.ts)
We'll define the structure for different field types and the overall form.
// src/schema.ts
import { ark, type Static, UCS } from 'arktype';
// Base properties for all fields
const BaseField = UCS({
id: UCS.string().describe('Unique identifier for the field'),
type: UCS.literal('text', 'number', 'select', 'checkbox').describe('Type of the input field'),
label: UCS.string().describe('Label displayed for the field'),
isRequired: UCS.boolean().default(false).describe('Whether the field is mandatory'),
});
// Specific field types
const TextInput = BaseField.extend({
type: UCS.literal('text'),
placeholder: UCS.string().optional().describe('Placeholder text for the input'),
multiline: UCS.boolean().default(false).describe('Whether the input should be a textarea'),
});
const NumberInput = BaseField.extend({
type: UCS.literal('number'),
placeholder: UCS.string().optional().describe('Placeholder text for the input'),
min: UCS.number().optional().describe('Minimum allowed value'),
max: UCS.number().optional().describe('Maximum allowed value'),
});
const SelectInput = BaseField.extend({
type: UCS.literal('select'),
options: UCS.array(UCS.object({
value: UCS.string(),
label: UCS.string(),
})).describe('Array of available options for the select'),
});
const CheckboxInput = BaseField.extend({
type: UCS.literal('checkbox'),
checkedByDefault: UCS.boolean().default(false).describe('Initial checked state'),
});
// Union type for any valid field
export const FormField = UCS.union([
TextInput,
NumberInput,
SelectInput,
CheckboxInput,
]).compile(); // Compile for performance
export type FormField = Static<typeof FormField>;
// Schema for the entire form definition (an array of fields)
export const FormDefinitionSchema = UCS.array(FormField).compile();
export type FormDefinition = Static<typeof FormDefinitionSchema>;
// --- Default Field Values ---
export const defaultFieldValues: Record<FormField['type'], Omit<FormField, 'id' | 'type'>> = {
text: { label: 'New Text Field', placeholder: 'Enter text...', isRequired: false, multiline: false },
number: { label: 'New Number Field', placeholder: 'Enter number...', isRequired: false, min: undefined, max: undefined },
select: { label: 'New Select Field', isRequired: false, options: [{ value: 'option1', label: 'Option 1' }] },
checkbox: { label: 'New Checkbox Field', isRequired: false, checkedByDefault: false },
};
3. Define Signals (src/signals.ts)
We'll use signals to manage the list of fields and the currently selected field for editing.
// src/signals.ts
import { signal } from '@preact/signals-react';
import { FormField, FormDefinition } from './schema';
import { v4 as uuidv4 } from 'uuid';
// --- Signals ---
// Holds the array of form fields currently being built
export const formFields = signal<FormDefinition>([]);
// Holds the ID of the field currently selected for editing, or null
export const selectedFieldId = signal<string | null>(null);
// --- Actions ---
export const addField = (type: FormField['type']) => {
const newField: FormField = {
id: uuidv4(),
type,
...defaultFieldValues[type],
};
// Validate the new field against the schema before adding
try {
FormField.parse(newField); // Validate
formFields.value = [...formFields.value, newField];
selectedFieldId.value = newField.id; // Select the newly added field
} catch (error) {
console.error("Failed to create valid field:", error);
// Optionally show a user-facing error message
}
};
export const updateField = (id: string, updates: Partial<FormField>) => {
formFields.value = formFields.value.map(field =>
field.id === id ? FormField.parse({ ...field, ...updates }) : field
);
};
export const removeField = (id: string) => {
formFields.value = formFields.value.filter(field => field.id !== id);
// If the removed field was the selected one, deselect it
if (selectedFieldId.value === id) {
selectedFieldId.value = null;
}
};
export const setSelectedField = (id: string | null) => {
selectedFieldId.value = id;
};
// Helper to get the currently selected field object
export const getSelectedField = () => {
if (!selectedFieldId.value) return null;
return formFields.value.find(f => f.id === selectedFieldId.value);
}
// --- Potential React Query Integration ---
// Example: In a real app, you'd fetch/save formFields.value here
/*
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
// Fetch form definition
export const useFormDefinition = (formId: string) => {
return useQuery({
queryKey: ['formDefinition', formId],
queryFn: async () => {
const response = await fetch(`/api/forms/${formId}`);
const data = await response.json();
// Validate fetched data
return FormDefinitionSchema.parse(data);
},
enabled: !!formId, // Only run if formId is provided
});
}
// Save form definition
export const useUpdateFormDefinition = (formId: string) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (definition: FormDefinition) => {
// Validate before sending
const validatedDefinition = FormDefinitionSchema.parse(definition);
await fetch(`/api/forms/${formId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validatedDefinition),
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['formDefinition', formId] });
console.log('Form definition saved successfully!');
},
onError: (error) => {
console.error('Failed to save form definition:', error);
}
});
}
*/
4. Components
RenderedField.tsx: Renders a single field based on its definition and handles selection/deletion.
FormCanvas.tsx: Displays all the fields managed by the formFields signal.
FieldPalette.tsx: Shows buttons to add new field types.
FieldEditor.tsx: Displays properties of the selected field and allows editing.
App.tsx: Main component orchestrating the layout.
// src/components/RenderedField.tsx
import React from 'react';
import { useSignals } from '@preact/signals-react';
import { FormField } from '../schema';
import { setSelectedField, removeField, updateField, formFields } from '../signals';
import { useSignalsEffect } from '@preact/signals-react/runtime'; // Import for effects
interface RenderedFieldProps {
field: FormField;
isSelected: boolean;
}
export const RenderedField: React.FC<RenderedFieldProps> = ({ field, isSelected }) => {
useSignals(); // Make signals available in this component
const selectHandler = () => {
setSelectedField(field.id);
};
const deleteHandler = () => {
removeField(field.id);
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
const { name, value, type, checked } = e.target;
const parsedValue = type === 'checkbox' ? checked : (name === 'min' || name === 'max' ? parseFloat(value) : value);
// Basic validation using ArkType before updating
try {
// Create a temporary updated field object for validation
const tempField = { ...field, [name]: parsedValue };
FormField.parse(tempField); // Validate the potential change
updateField(field.id, { [name]: parsedValue });
} catch (error) {
console.warn(`Validation failed for ${name} with value ${value}:`, error);
// Optionally provide user feedback here
}
};
const handleOptionChange = (index: number, type: 'value' | 'label', value: string) => {
const currentOptions = [...field.options];
currentOptions[index] = { ...currentOptions[index], [type]: value };
updateField(field.id, { options: currentOptions });
}
const handleAddOption = () => {
const newOptions = [...field.options, { value: `option${field.options.length + 1}`, label: `Option ${field.options.length + 1}` }];
updateField(field.id, { options: newOptions });
}
const handleRemoveOption = (index: number) => {
const newOptions = field.options.filter((_, i) => i !== index);
updateField(field.id, { options: newOptions });
}
const renderInput = () => {
switch (field.type) {
case 'text':
return (
<div className="flex flex-col gap-2 p-3 border rounded-md shadow-sm" style={{ borderColor: isSelected ? 'blue' : '#ccc' }}>
{field.multiline ? (
<textarea
name="value" // Example: for potential data binding later
placeholder={field.placeholder}
value={''} // Placeholder for actual data binding
onChange={() => {}} // No data binding in builder view
className="p-2 border rounded"
/>
) : (
<input
type="text"
name="value"
placeholder={field.placeholder}
value={''} // Placeholder for actual data binding
onChange={() => {}} // No data binding in builder view
className="p-2 border rounded"
/>
)}
{isSelected && (
<>
<input
type="text"
name="label"
value={field.label}
onChange={handleInputChange}
placeholder="Field Label"
className="p-1 border rounded text-sm"
/>
<input
type="text"
name="placeholder"
value={field.placeholder ?? ''}
onChange={handleInputChange}
placeholder="Placeholder"
className="p-1 border rounded text-sm"
/>
<label className="flex items-center gap-1 text-sm">
Required:
<input
type="checkbox"
name="isRequired"
checked={field.isRequired}
onChange={handleInputChange}
className="h-4 w-4"
/>
</label>
<label className="flex items-center gap-1 text-sm">
Multiline:
<input
type="checkbox"
name="multiline"
checked={field.multiline}
onChange={handleInputChange}
className="h-4 w-4"
/>
</label>
</>
)}
</div>
);
case 'number':
return (
<div className="flex flex-col gap-2 p-3 border rounded-md shadow-sm" style={{ borderColor: isSelected ? 'blue' : '#ccc' }}>
<input
type="number"
name="value"
placeholder={field.placeholder}
value={''} // Placeholder for actual data binding
onChange={() => {}} // No data binding in builder view
className="p-2 border rounded"
/>
{isSelected && (
<>
<input
type="text"
name="label"
value={field.label}
onChange={handleInputChange}
placeholder="Field Label"
className="p-1 border rounded text-sm"
/>
<input
type="text"
name="placeholder"
value={field.placeholder ?? ''}
onChange={handleInputChange}
placeholder="Placeholder"
className="p-1 border rounded text-sm"
/>
<label className="flex items-center gap-1 text-sm">
Required:
<input
type="checkbox"
name="isRequired"
checked={field.isRequired}
onChange={handleInputChange}
className="h-4 w-4"
/>
</label>
<div className="flex items-center gap-1 text-sm">
Min: <input type="number" name="min" value={field.min ?? ''} onChange={handleInputChange} className="p-1 border rounded w-20"/>
</div>
<div className="flex items-center gap-1 text-sm">
Max: <input type="number" name="max" value={field.max ?? ''} onChange={handleInputChange} className="p-1 border rounded w-20"/>
</div>
</>
)}
</div>
);
case 'select':
return (
<div className="flex flex-col gap-2 p-3 border rounded-md shadow-sm" style={{ borderColor: isSelected ? 'blue' : '#ccc' }}>
<select name="value" onChange={() => {}} className="p-2 border rounded">
<option value="">Select an option...</option>
{field.options.map(opt => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
</select>
{isSelected && (
<>
<input
type="text"
name="label"
value={field.label}
onChange={handleInputChange}
placeholder="Field Label"
className="p-1 border rounded text-sm"
/>
<label className="flex items-center gap-1 text-sm">
Required:
<input
type="checkbox"
name="isRequired"
checked={field.isRequired}
onChange={handleInputChange}
className="h-4 w-4"
/>
</label>
<div className="text-sm font-semibold mb-1">Options:</div>
{field.options.map((opt, i) => (
<div key={i} className="flex items-center gap-1 mb-1">
<input type="text" value={opt.label} onChange={(e) => handleOptionChange(i, 'label', e.target.value)} className="p-1 border rounded flex-grow text-sm" />
{/* <input type="text" value={opt.value} onChange={(e) => handleOptionChange(i, 'value', e.target.value)} className="p-1 border rounded flex-grow text-sm" /> */}
<button onClick={() => handleRemoveOption(i)} className="bg-red-100 text-red-600 px-2 py-1 rounded text-xs">X</button>
</div>
))}
<button onClick={handleAddOption} className="bg-green-100 text-green-600 px-2 py-1 rounded text-xs">
+ Add Option
</button>
</>
)}
</div>
);
case 'checkbox':
return (
<div className="p-3 border rounded-md shadow-sm flex items-center gap-2" style={{ borderColor: isSelected ? 'blue' : '#ccc' }}>
<input
type="checkbox"
name="value"
checked={field.checkedByDefault} // Placeholder for actual data binding
onChange={() => {}} // No data binding in builder view
className="h-5 w-5"
/>
<span>{field.label}</span>
{isSelected && (
<>
<input
type="text"
name="label"
value={field.label}
onChange={handleInputChange}
placeholder="Field Label"
className="p-1 border rounded text-sm ml-auto"
/>
<label className="flex items-center gap-1 text-sm">
Required:
<input
type="checkbox"
name="isRequired"
checked={field.isRequired}
onChange={handleInputChange}
className="h-4 w-4"
/>
</label>
<label className="flex items-center gap-1 text-sm">
Checked by Default:
<input
type="checkbox"
name="checkedByDefault"
checked={field.checkedByDefault}
onChange={handleInputChange}
className="h-4 w-4"
/>
</label>
</>
)}
</div>
);
default:
return null;
}
};
return (
<div
className={`relative mb-4 cursor-pointer hover:bg-gray-50 p-1 rounded ${isSelected ? 'ring-2 ring-blue-500' : ''}`}
onClick={selectHandler}
>
{renderInput()}
{isSelected && (
<button
onClick={deleteHandler}
className="absolute top-1 right-1 bg-red-500 text-white text-xs font-bold w-6 h-6 rounded-full flex items-center justify-center"
style={{ transform: 'translate(50%, -50%)' }}
title="Delete Field"
>
×
</button>
)}
</div>
);
};
// src/components/FormCanvas.tsx
import React from 'react';
import { useSignals } from '@preact/signals-react';
import { formFields, setSelectedField, getSelectedField } from '../signals';
import { RenderedField } from './RenderedField';
export const FormCanvas: React.FC = () => {
useSignals(); // Ensure reactivity
const fields = formFields.value;
const selectedField = getSelectedField();
// Basic validation display (could be more sophisticated)
const validateFormDefinition = () => {
try {
FormDefinitionSchema.parse(fields);
return { isValid: true, error: null };
} catch (error) {
return { isValid: false, error: error };
}
}
const validationResult = validateFormDefinition();
return (
<div className="flex-1 p-4 border rounded-lg shadow-inner bg-gray-50 min-h-[400px] overflow-y-auto">
<h2 className="text-xl font-semibold mb-4 text-gray-700">Form Canvas</h2>
{fields.length === 0 && (
<p className="text-gray-400">Add fields from the palette to start building your form.</p>
)}
{fields.map((field) => (
<RenderedField
key={field.id}
field={field}
isSelected={field.id === selectedField?.id}
/>
))}
{!validationResult.isValid && (
<div className="mt-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
<h4 className="font-bold">Form Definition Invalid:</h4>
<pre className="text-xs overflow-x-auto">{validationResult.error?.message}</pre>
</div>
)}
</div>
);
};
// src/components/FieldPalette.tsx
import React from 'react';
import { useSignals } from '@preact/signals-react';
import { addField } from '../signals';
import { FormField } from '../schema';
const fieldTypes: { type: FormField['type']; label: string; icon?: string }[] = [
{ type: 'text', label: 'Text Input', icon: '📝' },
{ type: 'number', label: 'Number Input', icon: '🔢' },
{ type: 'select', label: 'Select Dropdown', icon: '▼' },
{ type: 'checkbox', label: 'Checkbox', icon: '☑' },
];
export const FieldPalette: React.FC = () => {
useSignals();
return (
<div className="w-64 p-4 border rounded-lg shadow-md bg-white">
<h2 className="text-xl font-semibold mb-4 text-gray-700">Field Palette</h2>
<div className="grid grid-cols-1 gap-3">
{fieldTypes.map((fieldType) => (
<button
key={fieldType.type}
onClick={() => addField(fieldType.type)}
className="w-full px-3 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors flex items-center justify-center gap-2"
>
{fieldType.icon} {fieldType.label}
</button>
))}
</div>
</div>
);
};
// src/components/FieldEditor.tsx
import React from 'react';
import { useSignals } from '@preact/signals-react';
import { FormField } from '../schema';
import { formFields, updateField, getSelectedField } from '../signals';
export const FieldEditor: React.FC = () => {
useSignals(); // Make signals reactive here
const field = getSelectedField(); // Get the currently selected field
if (!field) {
return (
<div className="w-72 p-4 border rounded-lg shadow-md bg-gray-100 text-gray-500">
<h2 className="text-xl font-semibold mb-4">Field Editor</h2>
<p>Select a field from the canvas to edit its properties.</p>
</div>
);
}
// Handler for common input changes
const handleCommonChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value, type, checked } = e.target;
const parsedValue = type === 'checkbox' ? checked : (name === 'min' || name === 'max' ? parseFloat(value) : value);
// Validate before updating
try {
const tempField = { ...field, [name]: parsedValue };
FormField.parse(tempField); // Validate the potential change
updateField(field.id, { [name]: parsedValue });
} catch(error) {
console.warn(`Validation failed for ${name} with value ${value}:`, error);
// Optionally provide user feedback here
}
};
// Handler for options array (Select fields)
const handleOptionChange = (index: number, prop: 'value' | 'label', e: React.ChangeEvent<HTMLInputElement>) => {
const newOptions = [...field.options];
newOptions[index] = { ...newOptions[index], [prop]: e.target.value };
// Basic validation on options
try {
// Need to construct a valid field structure again for validation
const tempField = { ...field, options: newOptions };
FormField.parse(tempField);
updateField(field.id, { options: newOptions });
} catch (error) {
console.warn(`Option validation failed for ${prop} at index ${index}:`, error);
}
};
const handleAddOption = () => {
const newOptions = [...field.options, { value: `option_${Date.now()}`, label: `New Option` }];
updateField(field.id, { options: newOptions });
};
const handleRemoveOption = (index: number) => {
const newOptions = field.options.filter((_, i) => i !== index);
updateField(field.id, { options: newOptions });
};
return (
<div className="w-72 p-4 border rounded-lg shadow-md bg-white">
<h2 className="text-xl font-semibold mb-4">
Editing: {field.label} ({field.type})
</h2>
<div className="mb-3">
<label htmlFor="label" className="block text-sm font-medium text-gray-700">
Label
</label>
<input
type="text"
id="label"
name="label"
value={field.label}
onChange={handleCommonChange}
className="mt-1 p-2 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm"
/>
</div>
{field.type !== 'checkbox' && (
<div className="mb-3">
<label htmlFor="placeholder" className="block text-sm font-medium text-gray-700">
Placeholder
</label>
<input
type="text"
id="placeholder"
name="placeholder"
value={field.placeholder ?? ''}
onChange={handleCommonChange}
className="mt-1 p-2 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm"
/>
</div>
)}
{(field.type === 'text' || field.type === 'number') && (
<div className="mb-3 flex items-center">
<label htmlFor="multiline" className="block text-sm font-medium text-gray-700 mr-2">
Multiline:
</label>
<input
type="checkbox"
id="multiline"
name="multiline"
checked={field.multiline ?? false}
onChange={handleCommonChange}
className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
</div>
)}
{(field.type === 'number') && (
<>
<div className="mb-3 flex items-center gap-2">
<label htmlFor="min" className="block text-sm font-medium text-gray-700">Min</label>
<input
type="number"
id="min"
name="min"
value={field.min ?? ''}
onChange={handleCommonChange}
className="mt-1 p-1 w-24 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm"
/>
</div>
<div className="mb-3 flex items-center gap-2">
<label htmlFor="max" className="block text-sm font-medium text-gray-700">Max</label>
<input
type="number"
id="max"
name="max"
value={field.max ?? ''}
onChange={handleCommonChange}
className="mt-1 p-1 w-24 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm"
/>
</div>
</>
)}
{field.type === 'checkbox' && (
<div className="mb-3 flex items-center">
<label htmlFor="checkedByDefault" className="block text-sm font-medium text-gray-700 mr-2">
Checked by Default:
</label>
<input
type="checkbox"
id="checkedByDefault"
name="checkedByDefault"
checked={field.checkedByDefault ?? false}
onChange={handleCommonChange}
className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
</div>
)}
<div className="mb-3 flex items-center">
<label htmlFor="isRequired" className="block text-sm font-medium text-gray-700 mr-2">
Required
</label>
<input
type="checkbox"
id="isRequired"
name="isRequired"
checked={field.isRequired}
onChange={handleCommonChange}
className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
</div>
{field.type === 'select' && (
<div className="mt-4 pt-3 border-t">
<div className="flex justify-between items-center mb-2">
<label className="block text-sm font-medium text-gray-700">Options</label>
<button onClick={handleAddOption} className="bg-green-100 text-green-600 px-2 py-1 rounded text-xs hover:bg-green-200">
+ Add
</button>
</div>
{field.options.map((option, index) => (
<div key={index} className="flex items-center mb-2 gap-1">
<input
type="text"
value={option.label}
onChange={(e) => handleOptionChange(index, 'label', e)}
className="p-1 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm flex-grow"
/>
{/* Option value is usually less critical to edit directly here */}
{/* <input
type="text"
value={option.value}
onChange={(e) => handleOptionChange(index, 'value', e)}
className="p-1 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm w-24"
/> */}
<button onClick={() => handleRemoveOption(index)} className="bg-red-100 text-red-600 px-2 py-1 rounded text-xs hover:bg-red-200">
Remove
</button>
</div>
))}
</div>
)}
</div>
);
};
// src/App.tsx
import React from 'react';
import { FormCanvas } from './components/FormCanvas';
import { FieldPalette } from './components/FieldPalette';
import { FieldEditor } from './components/FieldEditor';
import { QueryClient, QueryClientProvider } from '@react-query/react'; // Using @tanstack/react-query v4 structure
// For v5+, use: import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
// Initialize React Query
const queryClient = new QueryClient();
function App() {
// Conceptually wrap with QueryClientProvider if using React Query for API calls
// return (
// <QueryClientProvider client={queryClient}>
// <MainLayout />
// </QueryClientProvider>
// );
// For this client-side builder example, we can omit QueryClientProvider
// unless we add save/load functionality later.
return <MainLayout />;
}
function MainLayout() {
// No need to call useSignals() here if children use it.
// But it's harmless if placed here.
// useSignals();
return (
<div className="container mx-auto p-6 font-sans">
<h1 className="text-3xl font-bold mb-6 text-center text-gray-800">React Form Builder</h1>
<div className="flex flex-wrap md:flex-nowrap gap-6">
<FieldPalette />
<FormCanvas />
<FieldEditor />
</div>
{/* Example of how you might use Jotai state */}
{/* <JotaiStateDisplay /> */}
</div>
);
}
// Example Jotai component (optional)
// import { atom, useAtom } from 'jotai';
// const countAtom = atom(0);
// const JotaiStateDisplay = () => {
// const [count, setCount] = useAtom(countAtom);
// return (
// <div className="mt-4 p-4 bg-purple-50 border border-purple-300 rounded">
// <p>Jotai Counter: {count}</p>
// <button onClick={() => setCount(c => c + 1)}>Increment Jotai Count</button>
// </div>
// );
// }
export default App;
// src/main.tsx (or index.tsx)
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css' // Assuming Tailwind CSS is set up
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
3. Styling (Tailwind CSS)
Ensure you have Tailwind CSS set up in your project (tailwind.config.js, index.css). The code uses Tailwind classes for layout and basic styling.
Explanation:
- ArkType Schemas (
schema.ts): We define the structure of each field (TextInput, NumberInput, etc.) and a union type (FormField) that represents any valid field. FormDefinitionSchema represents the entire form as an array of FormField. defaultFieldValues provides initial data.
- Signals (
signals.ts):
formFields: A signal holding the array of FormField objects. Any change here triggers UI updates reactively.
selectedFieldId: A signal holding the id of the field being edited.
- Actions: Functions like
addField, updateField, removeField, setSelectedField provide a clean way to modify the signal state. They include basic ArkType validation before committing changes.
- Components:
FieldPalette: Renders buttons to add new fields. Clicking a button calls addField with the corresponding type.
FormCanvas: Maps over the formFields.value array. For each field, it renders a RenderedField, passing whether it's the currently selected one.
RenderedField: Renders the actual input based on field.type. It handles click events to set the selectedFieldId and includes a delete button. When selected, it shows edit controls directly within the canvas view for basic property adjustments (label, required).
FieldEditor: Conditionally renders based on selectedFieldId. It fetches the full field object and provides more detailed input controls for all its properties. Changes made here call updateField.
App.tsx: Sets up the main layout, containing the palette, canvas, and editor side-by-side. It conditionally wraps the app in QueryClientProvider if you were to implement data fetching/saving using React Query.
- Reactivity:
@preact/signals-react ensures that only the components that depend on a specific signal re-render when that signal's value changes. For instance, editing a label in the FieldEditor updates the formFields signal, which causes the corresponding (and potentially the itself) to re-render with the new label, without necessarily re-rendering the entire application.
How to Use:
- Run the development server (
npm run dev).
- Use the "Field Palette" to add different types of fields to the "Form Canvas".
- Click on a field in the canvas to select it.
- Use the "Field Editor" panel to modify the properties (label, placeholder, options, etc.) of the selected field.
- Use the 'x' button on a selected field in the canvas to delete it.
This provides a robust foundation for a client-side form builder, leveraging signals for efficient state updates and ArkType for clear, validated data structures.