### Clone and Setup Manifesto.io Project
Source: https://github.com/eggplantiny/manifesto-io/blob/main/CONTRIBUTING.md
Steps to clone the Manifesto.io repository, set up remotes, install dependencies, build packages, and run tests for initial setup verification.
```bash
git clone https://github.com/YOUR_USERNAME/manifesto-io.git
cd manifesto-io
git remote add upstream https://github.com/anthropics/manifesto-io.git
pnpm install
pnpm build
pnpm test
```
--------------------------------
### Install Manifesto Core Packages (pnpm)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Installs the core schema and engine packages for Manifesto.io using the pnpm package manager. These are essential for defining and processing form schemas.
```bash
pnpm add @manifesto-io/schema @manifesto-io/engine
```
--------------------------------
### Install Manifesto Core Packages (npm)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Installs the core schema and engine packages for Manifesto.io using the npm package manager. These packages provide the foundation for Manifesto's schema definition and form rendering capabilities.
```bash
npm install @manifesto-io/schema @manifesto-io/engine
```
--------------------------------
### Install Manifesto React Binding
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Adds the @manifesto-io/react package, enabling the use of Manifesto's form rendering capabilities within a React application. This package provides the FormRenderer component.
```bash
pnpm add @manifesto-io/react
```
--------------------------------
### Install Manifesto Core Packages (yarn)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Installs the core schema and engine packages for Manifesto.io using the yarn package manager. This command ensures that the necessary libraries for schema management and form processing are available.
```bash
yarn add @manifesto-io/schema @manifesto-io/engine
```
--------------------------------
### Install Manifesto Vue Binding
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Adds the @manifesto-io/vue package, allowing integration of Manifesto forms into Vue.js applications. This package provides the necessary components and utilities for Vue integration.
```bash
pnpm add @manifesto-io/vue
```
--------------------------------
### Run React Storybook Example
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/README.md
Command to launch the React Storybook for interactive UI component examples. This requires pnpm as the package manager.
```bash
pnpm storybook:react
```
--------------------------------
### Run Vue Storybook Example
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/README.md
Command to launch the Vue Storybook for interactive UI component examples. This requires pnpm as the package manager.
```bash
pnpm storybook:vue
```
--------------------------------
### Manifesto.IO Selection Component Examples
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Examples demonstrating various selection input types: dropdown select, multi-select, radio buttons, and autocomplete. These examples show how to set placeholders and component-specific props.
```typescript
viewField.select('category', 'category')
.placeholder('Select category')
.build()
viewField.multiSelect('tags', 'tags')
.placeholder('Select tags')
.build()
viewField.radio('priority', 'priority')
.props({ direction: 'horizontal' })
.build()
viewField.autocomplete('author', 'authorId')
.props({ minChars: 2, debounce: 300 })
.build()
```
--------------------------------
### API GET Request Example (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/action-schema.md
An example of configuring an API GET request step using the Manifesto schema builder. It specifies the step ID, endpoint, custom headers including authentication, and sets an output key 'products' to store the response data. Requires the 'api' function from '@manifesto-io/schema'.
```typescript
import { api } from '@manifesto-io/schema'
// GET request
api.get('fetch-products', '/api/products')
.headers({ 'Authorization': 'Bearer $context.token' })
.outputAs('products')
.build()
```
--------------------------------
### Wizard Layout Configuration Example (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Example of configuring a wizard-style layout, where each section represents a step in a sequence.
```typescript
layout: { type: 'wizard' }
// Each section becomes a step
```
--------------------------------
### Pre-populate React Form with Initial Values
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
This React example shows how to pre-fill the FormRenderer with initial data. By passing an `initialValues` prop, you can set default values for form fields like name, email, and subject, improving user experience by reducing repetitive data entry.
```tsx
```
--------------------------------
### Manifesto.IO Date/Time Component Examples
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Examples for date and date-time input components. This includes `datePicker` and `datetimePicker`, showcasing how to configure format, min date, and other relevant props.
```typescript
viewField.datePicker('birthDate', 'birthDate')
.props({ format: 'YYYY-MM-DD', minDate: '1900-01-01' })
.build()
viewField.datetimePicker('scheduledAt', 'scheduledAt')
.props({ format: 'YYYY-MM-DD HH:mm' })
.build()
```
--------------------------------
### Example: Initialize FormRuntime with Options
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/engine.md
A comprehensive example showing the creation and initialization of a FormRuntime instance with various options such as initial values, entity schema, context, and custom handlers.
```typescript
import { createFormRuntime } from '@manifesto-io/engine'
import { productView, productEntity } from './schemas'
const runtime = createFormRuntime(productView, {
initialValues: {
name: 'Sample Product',
price: 99.99,
},
entitySchema: productEntity,
context: {
user: { id: '123', role: 'admin' },
params: { mode: 'edit' },
},
fetchHandler: async (endpoint, options) => {
const response = await fetch(endpoint, {
method: options.method,
body: options.body ? JSON.stringify(options.body) : undefined,
headers: {
'Content-Type': 'application/json',
...options.headers,
},
})
return response.json()
},
navigateHandler: (path, params) => {
window.location.href = path
},
emitHandler: (event, payload) => {
console.log('Event:', event, payload)
},
debug: process.env.NODE_ENV === 'development',
})
// Initialize the runtime
const result = runtime.initialize()
if (result._tag === 'Err') {
console.error('Failed to initialize:', result.error)
}
```
--------------------------------
### Simple Static Form Example (React)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/migration/adoption-guide.md
Demonstrates a basic contact form in React that is suitable for simple, unchanging forms and does not require Manifesto. It highlights the straightforward state management and JSX for rendering.
```tsx
function ContactForm() {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
return (
)
}
```
--------------------------------
### Grid Layout Configuration Example (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Example of configuring a multi-column grid layout with a specified number of columns and item gap.
```typescript
layout: {
type: 'grid',
columns: 3, // Number of columns
gap: '1rem' // Gap between items
}
```
--------------------------------
### Development Commands (Bash)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/README.md
Provides essential bash commands for managing the Manifesto.IO project. Includes commands for installing dependencies, building all packages, running tests, and starting the Storybook development servers for both React and Vue.
```bash
# Install dependencies
pnpm install
# Build all packages
pnpm build
# Run tests
pnpm test
# Start Storybook (React)
pnpm storybook:react
# Start Storybook (Vue)
pnpm storybook:vue
```
--------------------------------
### Flex Layout Configuration Example (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Example of configuring a flexible layout with options for direction (row or column) and item gap.
```typescript
layout: {
type: 'flex',
direction: 'row', // or 'column'
gap: '1rem'
}
```
--------------------------------
### Comparison Expressions (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-authoring-guide.md
Provides examples of comparison expressions used in Manifesto DSL for conditional logic, covering equality, inequality, and numerical comparisons. Uses '@manifesto-io/schema'.
```typescript
['==', $.state('status'), 'ACTIVE']
['!=', $.state('type'), 'HIDDEN']
['>', $.state('age'), 18]
['<', $.state('count'), 100]
['>=', $.state('score'), 60]
['<=', $.state('price'), 1000]
```
--------------------------------
### Complete Manifesto IO Form Example with Vue, TypeScript, and Vue Router
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/vue.md
A comprehensive example demonstrating a product form using Vue.js, TypeScript, and Manifesto IO. It includes setup for Vue Router, API service integration, toast notifications, form submission handling, error management, and conditional rendering based on environment variables and submission status.
```vue
{{ product ? 'Edit Product' : 'New Product' }}
{{ submitError }}
```
--------------------------------
### Quick Start: Render a Contact Form with FormRenderer
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/react.md
A basic example demonstrating how to use the FormRenderer component from @manifesto-io/react to render a contact form. It includes importing the component, default styles, and defining a handleSubmit function.
```tsx
import { FormRenderer } from '@manifesto-io/react'
import '@manifesto-io/react/styles' // Import default styles
import { contactView, contactEntity } from './schemas'
function ContactForm() {
const handleSubmit = (data: Record) => {
console.log('Submitted:', data)
}
return (
)
}
```
--------------------------------
### Vue Quick Start with FormRenderer
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/vue.md
A basic Vue 3 setup demonstrating how to use the FormRenderer component to display a form based on provided view and entity schemas. It includes importing the component, its styles, defining a submit handler, and rendering the FormRenderer.
```vue
```
--------------------------------
### Form Layout Configuration Example (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Example of configuring a default single-column form layout using the LayoutConfig interface.
```typescript
layout: { type: 'form' }
```
--------------------------------
### Role-Based Field Visibility using Context in TypeScript
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/guides/dynamic-conditions.md
Demonstrates how to control field visibility based on the user's role, leveraging the '$context.user.role' state. It shows examples for single role and multiple allowed roles.
```typescript
// Admin-only field
viewField.numberInput('internalCost', 'internalCost')
.hidden(['!=', '$context.user.role', 'admin'])
.build()
// Multiple allowed roles
viewField.select('priority', 'priority')
.hidden(['NOT_IN', '$context.user.role', ['admin', 'manager', 'supervisor']])
.build()
```
--------------------------------
### Manifesto.IO Section Configuration Example
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
An example of a section configuration object, defining its ID, title, description, layout, visibility, and fields. This demonstrates how to structure a part of a form or view.
```typescript
{
id: 'shipping',
title: 'Shipping Information',
description: 'Enter shipping details',
layout: { type: 'grid', columns: 2 },
visible: ['!=', '$state.productType', 'digital'],
collapsible: true,
collapsed: false,
fields: [
viewField.numberInput('weight', 'weight').build(),
viewField.textInput('dimensions', 'dimensions').build(),
],
}
```
--------------------------------
### Traditional React Form Migration Example
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/migration/adoption-guide.md
Illustrates a traditional React form component before migration to Manifesto. It includes state management for form fields, basic validation logic, and a submit handler, showcasing the complexities Manifesto aims to simplify.
```typescript
// Before: Traditional React form
function ProductForm({ product, onSave }) {
const [name, setName] = useState(product?.name ?? '')
const [price, setPrice] = useState(product?.price ?? 0)
const [category, setCategory] = useState(product?.category ?? '')
const [errors, setErrors] = useState({})
const validate = () => {
const newErrors = {}
if (!name) newErrors.name = 'Required'
if (name.length < 3) newErrors.name = 'Too short'
if (price < 0) newErrors.price = 'Invalid'
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
const handleSubmit = (e) => {
e.preventDefault()
if (validate()) {
onSave({ name, price, category })
}
}
// ... render
}
```
--------------------------------
### Tabs Layout Configuration Example (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Example of configuring a layout using tabs, where each section is rendered as a separate tab.
```typescript
layout: { type: 'tabs' }
// Each section becomes a tab
```
--------------------------------
### Install @manifesto-io/react with Dependencies
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/react.md
Instructions for installing the @manifesto-io/react package along with its required dependencies (@manifesto-io/engine and @manifesto-io/schema) using popular package managers like pnpm, npm, and yarn.
```bash
# Using pnpm
pnpm add @manifesto-io/react @manifesto-io/engine @manifesto-io/schema
# Using npm
npm install @manifesto-io/react @manifesto-io/engine @manifesto-io/schema
# Using yarn
yarn add @manifesto-io/react @manifesto-io/engine @manifesto-io/schema
```
--------------------------------
### Manifesto.IO Numeric Input Component Examples
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Examples of configuring numeric input fields. This includes a standard number input with prefix and step customization, and a slider component with min, max, and step properties.
```typescript
viewField.numberInput('price', 'price')
.props({ min: 0, step: 0.01, prefix: '$' })
.build()
viewField.slider('quantity', 'quantity')
.props({ min: 1, max: 100, step: 1 })
.build()
```
--------------------------------
### Expose Form Runtime to AI Agents with Manifesto.IO
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
This TypeScript code demonstrates how to create a form runtime and an interoperability session using Manifesto.IO's engine and AI modules. It generates a snapshot of the form's semantic state and converts it into tool definitions suitable for AI agents like OpenAI or Claude, enabling safe automation of form interactions.
```ts
import { createFormRuntime } from '@manifesto-io/engine'
import { createInteroperabilitySession, toToolDefinitions } from '@manifesto-io/ai'
const runtime = createFormRuntime(contactView, { entitySchema: contactEntity })
const session = createInteroperabilitySession({
runtime,
viewSchema: contactView,
entitySchema: contactEntity,
})
const snapshot = session.snapshot() // semantic state for reasoning
const tools = toToolDefinitions(snapshot, { omitUnavailable: true }) // OpenAI/Claude tool schemas
```
--------------------------------
### Accordion Layout Configuration Example (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Example of configuring a layout using an accordion, where sections are collapsible.
```typescript
layout: { type: 'accordion' }
```
--------------------------------
### Manifesto.IO Boolean Component Examples
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Examples for boolean input components: checkbox and toggle switch. These demonstrate setting custom labels and toggle-specific props like `onLabel` and `offLabel`.
```typescript
viewField.checkbox('acceptTerms', 'acceptTerms')
.label('I accept the terms and conditions')
.build()
viewField.toggle('isActive', 'isActive')
.props({ onLabel: 'Active', offLabel: 'Inactive' })
.build()
```
--------------------------------
### Install Core, AI, and Framework Packages for Manifesto
Source: https://github.com/eggplantiny/manifesto-io/blob/main/README.md
Installs the core schema and engine packages for Manifesto, along with optional AI interoperability and framework-specific bindings for React or Vue.
```bash
# Core packages
pnpm add @manifesto-io/schema @manifesto-io/engine
# AI interoperability (optional)
pnpm add @manifesto-io/ai
# Framework binding (choose one)
pnpm add @manifesto-io/react # For React
pnpm add @manifesto-io/vue # For Vue
```
--------------------------------
### Install @manifesto-io/engine Package
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/engine.md
Instructions for installing the @manifesto-io/engine package using popular package managers like pnpm, npm, and yarn.
```bash
# Using pnpm
pnpm add @manifesto-io/engine
# Using npm
npm install @manifesto-io/engine
# Using yarn
yarn add @manifesto-io/engine
```
--------------------------------
### Install @manifesto-io/ai
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/ai.md
Install the @manifesto-io/ai package using pnpm. This command adds the necessary dependencies to your project for AI interoperability utilities.
```bash
pnpm add @manifesto-io/ai
```
--------------------------------
### Mount Trigger Example (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/reaction-dsl.md
Illustrates the 'mount' trigger, which executes when a field is initially rendered. This example sets options for the 'country' field from an API endpoint if the country is initially null.
```typescript
on.mount()
.when(['==', '$state.country', null])
.do(actions.setOptions('country', dataSource.api('/api/countries')))
```
--------------------------------
### Install @manifesto-io/vue Package
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/vue.md
Installs the core @manifesto-io/vue package along with its required dependencies, @manifesto-io/engine and @manifesto-io/schema, using package managers like pnpm, npm, or yarn.
```bash
# Using pnpm
pnpm add @manifesto-io/vue @manifesto-io/engine @manifesto-io/schema
# Using npm
npm install @manifesto-io/vue @manifesto-io/engine @manifesto-io/schema
# Using yarn
yarn add @manifesto-io/vue @manifesto-io/engine @manifesto-io/schema
```
--------------------------------
### FormRenderer Example with API Integration Handlers
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/react.md
This example shows how to integrate the FormRenderer with external services using custom handlers for API requests (`fetchHandler`), navigation (`navigateHandler`), and event emission (`emitHandler`).
```tsx
{
const response = await api.request(endpoint, options)
return response.data
}}
navigateHandler={(path) => {
router.push(path)
}}
emitHandler={(event, payload) => {
analytics.track(event, payload)
}}
onSubmit={handleSubmit}
/>
```
--------------------------------
### Pre-populate Vue Form with Initial Values
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
This Vue example demonstrates pre-populating the FormRenderer with initial data using the `initial-values` prop. This allows you to set default values for fields like name, email, and subject, enhancing usability by providing pre-filled information.
```vue
```
--------------------------------
### GraphQL Adapter for Creating Products
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/guides/legacy-integration.md
This snippet demonstrates how to use the GraphQL adapter to create a product. It defines a mutation with input variables and specifies a transformation to extract the created product data from the response. Assumes a GraphQL endpoint at '/graphql'.
```typescript
api.post('query', '/graphql')
.body({
query: `
mutation CreateProduct($input: ProductInput!) {
createProduct(input: $input) {
id
name
status
}
}
`,
variables: {
input: '$state'
}
})
.adapter(adapter.graphql(
undefined,
{ steps: [
transform.custom('extract', {
expression: ['GET_PATH', '$data', 'data.createProduct']
})
]})
)
.outputAs('product')
.build()
```
--------------------------------
### Manifesto.IO Text Input Component Examples
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Examples of configuring text input fields using the `viewField` helper. This includes basic text input, multi-line textarea, and a rich text editor, each with customizable props like maxLength and rows.
```typescript
viewField.textInput('title', 'title')
.placeholder('Enter title')
.props({ maxLength: 100 })
.build()
viewField.textarea('description', 'description')
.props({ rows: 5 })
.build()
viewField.richEditor('content', 'content')
.props({ toolbar: ['bold', 'italic', 'link'] })
.build()
```
--------------------------------
### Render Contact Form with React
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Renders the 'Contact' form in a React application using the FormRenderer component from @manifesto-io/react. It takes the view and entity schemas as props and includes handlers for form submission and errors.
```tsx
import { FormRenderer } from '@manifesto-io/react'
import '@manifesto-io/react/styles' // Import default styles
import { contactView } from './schemas/contact.view'
import { contactEntity } from './schemas/contact.entity'
export function ContactForm() {
const handleSubmit = (data: Record) => {
console.log('Form submitted:', data)
// Send to your API
}
const handleError = (error: unknown) => {
console.error('Form error:', error)
}
return (
Contact Us
)
}
```
--------------------------------
### Start Storybook for Manifesto.io UI Components
Source: https://github.com/eggplantiny/manifesto-io/blob/main/CONTRIBUTING.md
Commands to launch Storybook for showcasing React and Vue components developed within the Manifesto.io project.
```bash
# React Storybook
pnpm storybook:react
# Vue Storybook
pnpm storybook:vue
# Both
pnpm storybook:all
```
--------------------------------
### ViewField Builder API Example in TypeScript
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/view-schema.md
Demonstrates the fluent API of the `ViewField` builder for creating and configuring input fields. This example shows how to set the label, placeholder, help text, props, styles, disable conditions, and grid span for a text input field.
```typescript
viewField.textInput('email', 'email')
.label('Email Address')
.placeholder('user@example.com')
.helpText('We will never share your email')
.props({ type: 'email', autoComplete: 'email' })
.styles({ className: 'email-input' })
.disabled(['==', '$state.status', 'verified'])
.span(2)
.build()
```
--------------------------------
### FormRenderer Example with Initial Values
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/react.md
Shows how to pre-populate a form rendered by FormRenderer using the `initialValues` prop. This is useful for editing existing data.
```tsx
```
--------------------------------
### Define Contact Entity Schema (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Defines the structure and validation rules for contact information using Manifesto.io's schema definition language. It includes fields for name, email, phone, company, subject, and message with specific constraints.
```typescript
import { entity, field } from '@manifesto-io/schema'
export const contactEntity = entity('contact', 'Contact', '1.0.0')
.description('Contact information form')
.field(field.string('name').label('Full Name').required().min(2).max(100))
.field(field.string('email').label('Email Address').required()
.pattern('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'))
.field(field.string('phone').label('Phone Number'))
.field(field.string('company').label('Company Name'))
.field(field.enum('subject', [
{ value: 'general', label: 'General Inquiry' },
{ value: 'support', label: 'Technical Support' },
{ value: 'sales', label: 'Sales Question' },
{ value: 'feedback', label: 'Feedback' },
]).label('Subject').required())
.field(field.string('message').label('Message').required().min(10).max(1000))
.build()
```
--------------------------------
### Update Entity Schema for Conditional Field
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
This TypeScript snippet demonstrates how to add a new 'company' field to the entity schema for the contact form. This field is intended to be conditionally displayed based on user input, enabling more dynamic form behavior.
```typescript
// Add to contactEntity
.field(
field.string('company')
.label('Company Name')
)
```
--------------------------------
### Define Contact Form View Schema (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Defines the user interface for the contact form using Manifesto.io's view definition language. It structures the form into sections and specifies input field types, labels, placeholders, and conditional visibility.
```typescript
import { view, section, viewField, layout } from '@manifesto-io/schema'
export const contactView = view('contact-form', 'Contact Form', '1.0.0')
.entityRef('contact')
.mode('create')
.layout(layout.form())
.section(
section('personal')
.title('Your Information')
.field(viewField.textInput('name', 'name').placeholder('Enter your full name'))
.field(viewField.textInput('email', 'email').placeholder('your.email@example.com'))
.field(viewField.textInput('phone', 'phone').placeholder('(Optional) Your phone number'))
.field(viewField.textInput('company', 'company')
.placeholder('Your company name')
.hidden(['!=', '$state.subject', 'sales']))
)
.section(
section('inquiry')
.title('Your Message')
.field(viewField.select('subject', 'subject').placeholder('Select a subject'))
.field(viewField.textarea('message', 'message')
.placeholder('How can we help you?')
.props({ rows: 5 }))
)
.build()
```
--------------------------------
### Define Contact View Schema (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Defines the user interface and behavior for the 'Contact' form using Manifesto's view schema definition. It structures the form into sections ('Your Information', 'Your Message') and specifies input types and placeholders.
```typescript
import { view, section, viewField, layout } from '@manifesto-io/schema'
export const contactView = view('contact-form', 'Contact Form', '1.0.0')
.entityRef('contact')
.mode('create')
.layout(layout.form())
.section(
section('personal')
.title('Your Information')
.field(
viewField.textInput('name', 'name')
.placeholder('Enter your full name')
)
.field(
viewField.textInput('email', 'email')
.placeholder('your.email@example.com')
)
.field(
viewField.textInput('phone', 'phone')
.placeholder('(Optional) Your phone number')
)
)
.section(
section('inquiry')
.title('Your Message')
.field(
viewField.select('subject', 'subject')
.placeholder('Select a subject')
)
.field(
viewField.textarea('message', 'message')
.placeholder('How can we help you?')
.props({ rows: 5 })
)
)
.build()
```
--------------------------------
### Define Contact Entity Schema (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
Defines the data structure and validation rules for a 'Contact' entity using Manifesto's schema definition language. It includes fields for name, email, phone, subject, and message with specific validation constraints.
```typescript
import { entity, field } from '@manifesto-io/schema'
export const contactEntity = entity('contact', 'Contact', '1.0.0')
.description('Contact information form')
// String field with validation
.field(
field.string('name')
.label('Full Name')
.required()
.min(2)
.max(100)
)
// Email field with pattern validation
.field(
field.string('email')
.label('Email Address')
.required()
.pattern('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$')
)
// Optional phone field
.field(
field.string('phone')
.label('Phone Number')
)
// Enum field
.field(
field.enum('subject', [
{ value: 'general', label: 'General Inquiry' },
{ value: 'support', label: 'Technical Support' },
{ value: 'sales', label: 'Sales Question' },
{ value: 'feedback', label: 'Feedback' },
])
.label('Subject')
.required()
)
// Multiline text field
.field(
field.string('message')
.label('Message')
.required()
.min(10)
.max(1000)
)
.build()
```
--------------------------------
### GraphQL Adapter API
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/action-schema.md
Shows how to interact with GraphQL APIs using the GraphQL adapter. Includes setting up mutations and response transformations.
```APIDOC
## POST /graphql (GraphQL Adapter)
### Description
This endpoint is used to send GraphQL mutations or queries. It utilizes the GraphQL adapter to format requests and process responses.
### Method
POST
### Endpoint
/graphql
### Parameters
#### Request Body
- **query** (string) - The GraphQL query or mutation string.
- **variables** (object) - Variables to be used with the query/mutation.
### Request Example
```json
{
"query": "\n mutation CreateProduct($input: ProductInput!) {\n createProduct(input: $input) {\n id\n name\n }\n }\n ",
"variables": {
"input": { ... state data ... }
}
}
```
### Response
#### Success Response (200)
- **data** (object) - The data returned from the GraphQL API.
#### Response Example
```json
{
"data": {
"createProduct": {
"id": "123",
"name": "New Product"
}
}
}
```
### Adapter Configuration
- **Type**: `graphql`
- **Response Transform**: Extracts data using the expression '$data.createProduct'.
```
--------------------------------
### Custom Error Display Component (React)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/guides/validation.md
A reusable React component that displays validation errors for a given field. It uses the `useFormRuntime` hook to get field metadata and conditionally renders error messages below the field's input if any errors exist.
```tsx
function Field({ fieldId, children }) {
const { getFieldMeta } = useFormRuntime(schema, options)
const meta = getFieldMeta(fieldId)
return (
{children}
{meta?.errors.map((error, i) => (
{error}
))}
)
}
```
--------------------------------
### Adapter Helper Methods
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/action-schema.md
Lists the adapter helper methods used to configure different types of API adapters: legacy, GraphQL, and SOAP.
```markdown
**Adapter Helpers**
| Method | Description |
|--------|-------------|
| `adapter.legacy(req, res)` | Legacy REST adapter |
| `adapter.graphql(req, res)` | GraphQL adapter |
| `adapter.soap(req, res)` | SOAP/XML adapter |
```
--------------------------------
### Null Check Banner Visibility in TypeScript
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-authoring-guide.md
This example demonstrates how to display a warning banner when a specific field, 'endDate', is null. It uses the `visible` method with the `IS_NULL` condition to control the section's visibility. This is useful for alerting users about missing or unconfigured data.
```typescript
section('no-end-date-warning')
.title('No end date')
.visible(['IS_NULL', $.state('endDate')])
.fields()
.build()
```
--------------------------------
### Complete Product Form Example (React + TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/api-reference/react.md
A comprehensive example of a product form using React and TypeScript with Manifesto.io's FormRenderer. It includes state management for submission and errors, API interaction via fetch, and proper type handling.
```tsx
import { useState } from 'react';
import { FormRenderer, FormRuntimeError } from '@manifesto-io/react';
import '@manifesto-io/react/styles';
// Assuming schemas and interfaces are defined elsewhere
// import { productView, productEntity } from './schemas/product';
// interface Product { id?: string; name: string; price: number; category: string; }
// interface ProductFormProps { product?: Product; onSuccess: (product: Product) => void; }
// Placeholder definitions for compilation
const productView = {};
const productEntity = {};
interface Product { id?: string; name: string; price: number; category: string; }
interface ProductFormProps { product?: Product; onSuccess: (product: Product) => void; }
export function ProductForm({ product, onSuccess }: ProductFormProps) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState(null);
const handleSubmit = async (data: Record) => {
setIsSubmitting(true);
setError(null);
try {
const response = await fetch(
product ? `/api/products/${product.id}` : '/api/products',
{
method: product ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
}
);
if (!response.ok) {
throw new Error('Failed to save product');
}
const savedProduct = await response.json();
onSuccess(savedProduct);
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setIsSubmitting(false);
}
};
const handleError = (err: FormRuntimeError) => {
if (err.type === 'VALIDATION_ERROR') {
// Validation errors are shown inline
return;
}
setError(err.message);
};
return (
{product ? 'Edit Product' : 'New Product'}
{error && (
{error}
)}
{
const res = await fetch(endpoint, {
method: options.method,
body: options.body ? JSON.stringify(options.body) : undefined,
});
return res.json();
}}
onSubmit={handleSubmit}
onError={handleError}
debug={process.env.NODE_ENV === 'development'}
/>
{isSubmitting && (
)}
);
}
```
--------------------------------
### Manifesto Entity Schema Definition
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/migration/adoption-guide.md
Defines an entity schema for a 'Product' using Manifesto's schema builder. This example showcases how to define fields like 'name', 'price', and 'category' with their respective types, validation rules (required, min length, min value), and enum options.
```typescript
import { field, enumValue } from '@manifesto-io/schema'
export const productEntity = {
_type: 'entity' as const,
id: 'product',
name: 'Product',
version: '1.0.0',
fields: [
field.string('name', 'Name').required().min(3).build(),
field.number('price', 'Price').min(0).build(),
field.enum('category', 'Category', [
enumValue('electronics', 'Electronics'),
enumValue('clothing', 'Clothing'),
]).build(),
],
}
```
--------------------------------
### API POST Request Example (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/action-schema.md
Demonstrates how to configure an API POST request step. This example sets the step ID, endpoint, uses the current state ('$state') as the request body, and defines 'result' as the output key for the API response. Utilizes the 'api' function from '@manifesto-io/schema'.
```typescript
import { api } from '@manifesto-io/schema'
// POST request
api.post('create-product', '/api/products')
.body('$state')
.outputAs('result')
.build()
```
--------------------------------
### Enable Debug Panel in React FormRenderer
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
This React code snippet shows how to enable the debug panel for the FormRenderer component by setting the `debug` prop to `true`. The debug panel provides real-time insights into the form's state, including values, field statuses, and expression evaluations.
```tsx
```
--------------------------------
### Cross-Field Validation (TypeScript)
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/guides/validation.md
Demonstrates how to implement validation rules that depend on the values of other fields within the same form. Examples include password confirmation, date range validation, and conditional required fields based on other selections. It uses custom expressions referencing other fields via `$state.`.
```typescript
// Entity Schema
field.string('password', 'Password')
.required()
.min(8)
.build(),
field.string('confirmPassword', 'Confirm Password')
.required()
.constraint({
type: 'custom',
expression: ['==', '$value', '$state.password'],
message: 'Passwords do not match',
})
.build()
```
```typescript
field.date('startDate', 'Start Date')
.required()
.build(),
field.date('endDate', 'End Date')
.required()
.constraint({
type: 'custom',
expression: ['>=', '$value', '$state.startDate'],
message: 'End date must be after start date',
})
.build()
```
```typescript
// Tax ID required for business customers
field.string('taxId', 'Tax ID')
.constraint({
type: 'custom',
expression: ['OR',
['!=', '$state.customerType', 'business'],
['AND',
['==', '$state.customerType', 'business'],
['!=', '$value', ''],
['!=', '$value', null]
]
],
message: 'Tax ID is required for business customers',
})
.build()
```
--------------------------------
### Trigger Actions Based on Field Changes in TypeScript
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-authoring-guide.md
This example shows how to define reactions to field changes. When the 'triggerType' field changes, specific actions are performed, such as setting other field values or updating properties. It uses `on.change`, `when`, and `do` to define the trigger-action logic. Dependencies include `fieldEquals` and `actions`.
```typescript
viewField.select('triggerType', 'triggerType')
.label('Trigger type')
.reaction(
on.change()
.when(fieldEquals('triggerType', 'EMERGENCY'))
.do(
actions.setValue('smsCheckbox', true),
actions.setValue('priority', 'CRITICAL'),
actions.updateProp('smsCheckbox', 'disabled', true)
)
)
.reaction(
on.change()
.when(['!=', $.state('triggerType'), 'EMERGENCY'])
.do(actions.updateProp('smsCheckbox', 'disabled', false))
)
.build()
```
--------------------------------
### Update View Schema for Conditional Field Display
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
This TypeScript snippet shows how to update the view schema to make the 'company' field conditionally visible. It uses the `hidden` attribute with a condition to only display the 'Company Name' input field when the 'subject' field is set to 'sales', providing context-aware form elements.
```typescript
// Add to the 'personal' section
.field(
viewField.textInput('company', 'company')
.placeholder('Your company name')
.hidden(['!=', '$state.subject', 'sales']) // Only show for sales
)
```
--------------------------------
### Create Vue Contact Form with FormRenderer
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
This snippet shows how to create a contact form in Vue using the FormRenderer component. It imports necessary components and schemas, defines submission and error handlers, and renders the form within a template. The component automatically handles form rendering based on provided view and entity schemas.
```vue
Contact Us
```
--------------------------------
### Handle Form Submission in Vue with API Call
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/getting-started.md
This Vue component illustrates handling form submissions with the FormRenderer. It utilizes Vue's `ref` for managing submission and success states and implements an asynchronous `fetch` call to '/api/contact'. The template conditionally renders a success message or the form itself, providing a seamless user experience during submission.
```vue
Thank you! We'll be in touch soon.
```
--------------------------------
### GraphQL Adapter Configuration with Response Transform
Source: https://github.com/eggplantiny/manifesto-io/blob/main/docs/schema-reference/action-schema.md
Sets up a GraphQL adapter for API calls. It includes a mutation for creating a product and a response transform to extract specific data.
```typescript
api.post('query', '/graphql')
.body({
query: `
mutation CreateProduct($input: ProductInput!) {
createProduct(input: $input) {
id
name
}
}
`,
variables: { input: '$state' }
})
.adapter(adapter.graphql(
undefined,
{
steps: [
transform.map('extract', { expression: '$data.createProduct' })
]
}
))
.build()
```