### Install Dependencies and Run Development Server
Source: https://github.com/iyulab/formdown/blob/main/site/README.md
Use these commands to set up the development environment and start the local server.
```bash
npm install
npm run dev
```
--------------------------------
### Install Formdown Core Package
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/installation.md
Install the core Formdown package for framework-agnostic usage and maximum flexibility. This is the recommended starting point.
```bash
npm install @formdown/core
```
--------------------------------
### Providing Clear Placeholders
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Shows examples of using placeholders to guide users on the expected input format for various fields.
```formdown
@phone: tel:[placeholder="(555) 123-4567"]
@date: date:[placeholder="MM/DD/YYYY"]
@username: [placeholder="Letters, numbers, underscore only"]
```
--------------------------------
### Tutorial-Style Form Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
Illustrates a tutorial-style form structure in Formdown, where explanatory text is interspersed between field groups to guide the user.
```formdown
# Getting Started Guide
Let's start with your basic information:
@name: [text required]
@email: [email required]
Great! Now let's set up your preferences.
@theme{Light,Dark,Auto}: r[]
@notifications: [checkbox label="Enable notifications"]
Almost done! Choose your plan:
@plan{Free,Pro,Enterprise}: r[required]
Thank you for signing up!
```
--------------------------------
### Install @formdown/ui
Source: https://github.com/iyulab/formdown/blob/main/packages/formdown-ui/README.md
Install the @formdown/ui package using npm.
```bash
npm install @formdown/ui
```
--------------------------------
### Quick Start: FormdownFieldHelper Usage
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/field-helper.md
Demonstrates basic usage of the FormdownFieldHelper for getting, setting, adding, and checking field values. Includes necessary import statement.
```javascript
import { FormdownFieldHelper } from '@formdown/core';
// Get current field value
const priority = FormdownFieldHelper.get('priority');
// Set field value (automatically uses "other" option if needed)
FormdownFieldHelper.set('priority', 'Urgent');
// Add checkbox value
FormdownFieldHelper.add('skills', 'Rust');
// Check if field has value
const hasJS = FormdownFieldHelper.has('skills', 'JavaScript');
```
--------------------------------
### Interactive Demo Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/editor.md
An example of the Formdown editor in split mode, designed for interactive demos where users can experiment with content.
```html
```
--------------------------------
### Install Formdown Editor
Source: https://github.com/iyulab/formdown/blob/main/packages/formdown-editor/README.md
Install the @formdown/editor package using npm.
```bash
npm install @formdown/editor
```
--------------------------------
### Basic Form Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/index.md
A simple Formdown example demonstrating required name and email fields with a submit button.
```formdown
@name*: []
@email*: @[]
@submit: [submit]
```
--------------------------------
### User Registration Form Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
An example demonstrating the structure for a user registration form using FormDown, including form attributes.
```formdown
# Create Account
@form[action="/register" method="POST"]
```
--------------------------------
### Install TypeScript Definitions
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/installation.md
Install type definitions for Node.js if you encounter TypeScript errors.
```bash
# Install type definitions if missing
npm install --save-dev @types/node
```
--------------------------------
### Testing Bootstrap Theme Plugin with Formdown
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/extension-examples.md
This example demonstrates how to test a Formdown plugin using a testing framework. It includes setup for the ExtensionManager and tests for adding CSS classes and Bootstrap structure to form elements.
```typescript
import { ExtensionManager, createTestContext } from '@formdown/core'
describe('Bootstrap Theme Plugin', () => {
let extensionManager
beforeEach(() => {
extensionManager = new ExtensionManager()
extensionManager.registerPlugin(bootstrapTheme)
})
test('should add Bootstrap classes to text fields', async () => {
const context = createTestContext('css-class', {
field: { name: 'test', type: 'text', label: 'Test' }
})
const result = await extensionManager.executeHooks('css-class', context)
expect(result.field.attributes.className).toBe('form-control')
})
test('should wrap fields in Bootstrap structure', async () => {
const context = createTestContext('template-render', {
field: { name: 'test', type: 'text', label: 'Test' },
template: ''
})
const result = await extensionManager.executeHooks('template-render', context)
expect(result.template).toContain('mb-3')
expect(result.template).toContain('form-label')
})
})
```
--------------------------------
### Select Dropdown Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Shows how to create select dropdowns with options, default values, required fields, and multi-select capabilities.
```formdown
@country: [select options="USA, Canada, UK, Other"]
@country: [select options="USA, Canada, UK, Other" value="USA"]
@language: [select options="English, Spanish, French" required]
@countries: [select options="USA, Canada, UK" multiple]
```
--------------------------------
### Get Field Value Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/field-helper.md
Illustrates how to retrieve values from single-value and multi-value fields using FormdownFieldHelper.get(). Shows expected return types.
```javascript
// Single-value fields
FormdownFieldHelper.get('priority') // → "Medium" | null
FormdownFieldHelper.get('country') // → "USA" | null
FormdownFieldHelper.get('name') // → "John Doe" | null
// Multi-value fields (checkboxes)
FormdownFieldHelper.get('skills') // → ["JavaScript", "Rust"] | []
```
--------------------------------
### Button Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Demonstrates the creation of submit, reset, and generic buttons with custom values.
```formdown
@submit: [submit]
@submit: [submit value="Send Message"]
@reset: [reset]
@reset: [reset value="Clear Form"]
@cancel: [button value="Cancel"]
@preview: [button value="Preview"]
```
--------------------------------
### Adding Custom Field Types Example
Source: https://github.com/iyulab/formdown/blob/main/docs/EXTENSION_SYSTEM.md
Example demonstrating how to add a custom field type plugin to the extension system.
```APIDOC
## Adding Custom Field Types
### Description
This example shows how to create and register a custom field type plugin, specifically a 'color' picker, with its own parsing and generation logic.
### Example Code
```typescript
// Add a color picker field
const colorFieldPlugin: Plugin = {
metadata: { name: 'color-field', version: '1.0.0' },
fieldTypes: [{
type: 'color',
parser: (content) => {
const match = content.match(/@(\w+):\s*\[color\](.*)/)
if (!match) return null
return {
name: match[1],
type: 'color',
label: match[1],
defaultValue: '#ffffff'
}
},
generator: (field) => `
`
}]
}
```
```
--------------------------------
### User Registration Shorthand Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/shorthand.md
An example of using shorthand for a user registration form, including pattern validation, select options, and checkboxes.
```formdown
# Sign Up
@username{^[a-zA-Z0-9_]{3,20}$}: []
@email*: @[]
@password*: ***[minlength=8]
@confirm_password(Confirm Password)*: ***[]
@age: #[min=13 max=120]
@country: s{USA,Canada,UK,Other}[]
@interests: c{Sports,Music,Tech,Gaming}[]
@terms*: c[] I agree to terms
```
--------------------------------
### Complete Formdown Example with Reactive Handlers
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
A comprehensive example demonstrating FormManager initialization, parsing complex form content, setting up reactive event handlers for data changes and validation errors, interacting with form data, and rendering the final HTML.
```javascript
import { FormManager } from '@formdown/core';
const formContent = `
# User Registration
@name(Full Name)*: [placeholder="Enter your full name"]
@email(Email Address)*: @[placeholder="your.email@example.com"]
@age: [number min=18 max=100 value=25]
@interests{Web,Mobile,AI,*(Custom Interest)}: c[]
`;
// Create and initialize form manager
const manager = new FormManager();
manager.parse(formContent);
// Set up reactive event handlers
manager.on('data-change', ({ field, value, formData }) => {
console.log(`Field ${field} changed:`, value);
console.log('Full form data:', formData);
});
manager.on('validation-error', ({ field, errors }) => {
console.log(`Validation error in ${field}:`, errors);
});
// Interact with form data
manager.setFieldValue('name', 'Jane Smith');
manager.updateData({
email: 'jane@example.com',
interests: ['Web', 'Custom Framework']
});
// Validate and render
const validation = manager.validate();
if (validation.isValid) {
const html = manager.render();
document.body.innerHTML = html;
}
// Check for changes
console.log('Form has changes:', manager.isDirty());
console.log('Current data:', manager.getData());
```
--------------------------------
### Development Environment Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/editor.md
Demonstrates using the Formdown editor in split mode with auto-save enabled, suitable for development environments.
```html
```
--------------------------------
### Complete Formdown Field Helper Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/field-helper.md
A comprehensive example demonstrating the initialization of a form with various field types and 'other' options, followed by setting, adding, checking, and clearing field values using the FieldHelper API.
```javascript
import { FormdownFieldHelper } from '@formdown/core';
// Form with other options
const formContent = `
@priority{Low,Medium,High,*(Priority Level)}: r[required]
@skills{JavaScript,Python,Java,*(Other Skills)}: c[]
@country{USA,Canada,UK,*(Other Country)}: s[]
@name: [text required]
`;
// Set values (mix of existing and other options)
FormdownFieldHelper.set('priority', 'Critical'); // Other option
FormdownFieldHelper.set('skills', ['JavaScript', 'Rust']); // Mix
FormdownFieldHelper.set('country', 'Korea'); // Other option
FormdownFieldHelper.set('name', 'John Doe'); // Text field
// Add more checkbox values
FormdownFieldHelper.add('skills', 'Go'); // Another other option
FormdownFieldHelper.add('skills', 'Python'); // Existing option
// Check current state
console.log('Priority:', FormdownFieldHelper.get('priority')); // → "Critical"
console.log('Skills:', FormdownFieldHelper.get('skills')); // → ["JavaScript", "Rust", "Go", "Python"]
console.log('Country:', FormdownFieldHelper.get('country')); // → "Korea"
// Field information
console.log('Priority type:', FormdownFieldHelper.getFieldType('priority')); // → 'radio'
console.log('Is Critical other?', FormdownFieldHelper.isOtherValue('priority', 'Critical')); // → true
console.log('Has Rust skill?', FormdownFieldHelper.has('skills', 'Rust')); // → true
// Clear specific fields
FormdownFieldHelper.remove('skills', 'Go'); // Remove specific skill
FormdownFieldHelper.clear('priority'); // Clear priority selection
```
--------------------------------
### Complete Formdown Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
A comprehensive example demonstrating the combination of various Formdown features, including sections, required fields, radio buttons, and checkboxes.
```formdown
# Complete Example
## Personal Information
@name: [text required]
@email: [email required]
Choose your role in our community:
@role{Developer,Designer,Manager,Student,*(Your Role)}: r[required]
## Preferences
What topics interest you?
@topics{Web Dev,Mobile,AI,Data Science,*(Custom Topic)}: c[]
How would you like us to contact you?
@contact{Email,Phone,Newsletter,*(Contact Method)}: r[]
Great! You're all set.
```
--------------------------------
### Documentation Site Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/editor.md
Shows the Formdown editor in split mode, marked as read-only, ideal for tutorials on documentation sites.
```html
```
--------------------------------
### Option Patterns Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Demonstrates using custom syntax for inline options in radio, checkbox, and select fields.
```formdown
// Inline options with custom syntax
@priority{Low|Medium|High}: [radio]
@skills{JavaScript|Python|Go|Rust}: [checkbox]
// Options with commas
@status{Draft,Under Review,Published,Archived}: [select]
```
--------------------------------
### Formdown Shorthand Reference Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/reference.md
Provides examples of using shorthand type markers and content patterns for various field types and configurations.
```formdown
# Registration form with shorthand
@username*{^[a-zA-Z0-9_]{3,20}$}: [placeholder="3-20 characters"]
@email*: @[]
@password*{^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).{8,}$}: ?[]
@age: #[min=18 max=100]
@gender{male,female,other}: r[]
@interests{Web,Mobile,AI,Gaming}: c[]
@newsletter(Subscribe to updates): c[]
@submit: [submit label="Create Account"]
```
--------------------------------
### Theme Plugin Example
Source: https://github.com/iyulab/formdown/blob/main/docs/EXTENSION_SYSTEM.md
This example defines a 'dark' theme for Formdown, specifying CSS custom properties and class overrides to change the UI's appearance.
```typescript
const darkThemePlugin: Plugin = {
metadata: {
name: 'dark-theme',
version: '1.0.0'
},
themes: [{
name: 'dark',
cssProperties: {
'--form-bg': '#1a1a1a',
'--form-text': '#ffffff',
'--form-border': '#333333',
'--form-focus': '#4a9eff'
},
classOverrides: {
'form-field': 'form-field form-field--dark',
'form-button': 'form-button form-button--dark'
}
}]
}
```
--------------------------------
### Complete Registration Form Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/basics.md
An example of a user registration form with fields for username, email, password, confirmation, birth date, gender, interests, terms agreement, and submit/reset buttons.
```formdown
# User Registration
@username: [text required minlength=4 pattern="[a-zA-Z0-9_]+"]
@email: [email required]
@password: [password required minlength=8]
@confirm_password(Confirm Password): [password required]
@birth_date(Date of Birth): [date required max="2010-12-31"]
@gender: [radio options="Male,Female,Other"]
@interests: [checkbox options="Technology,Sports,Music,Travel"]
@terms(I agree to the terms and conditions): [checkbox required]
@register: [submit label="Create Account"]
@reset: [reset label="Clear Form"]
```
--------------------------------
### Real-World Example: Terms Agreement with Conditional Submit
Source: https://github.com/iyulab/formdown/blob/main/docs/SYNTAX.md
An example where the submit button is enabled only after the user agrees to the terms and conditions.
```formdown
@agree_terms: c[content="I agree to the terms and conditions"]
@submit: [submit enabled-if="agree_terms"]
```
--------------------------------
### Contact Form Shorthand Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/shorthand.md
A complex example demonstrating shorthand for a contact form, including text areas and tel input.
```formdown
# Contact Us
@name(Full Name)*: []
@email*: @[]
@phone(Phone Number): tel:[]
@subject: []
@message(Your Message)*: T5[]
@newsletter: c[] Subscribe to newsletter
```
--------------------------------
### Contact Form with Legacy Syntax
Source: https://github.com/iyulab/formdown/blob/main/docs/SYNTAX.md
A contact form example demonstrating the use of legacy syntax for submit and reset buttons. It mirrors the structure of the new syntax example.
```formdown
# Contact Us
@name(Full Name): [text required]
@email(Email Address): [email required]
@subject: [text required maxlength=100]
@message: [textarea required rows=5 placeholder="Your message..."]
@priority: [radio options="Low,Medium,High"]
@newsletter: [checkbox content="Subscribe to our weekly newsletter"]
@terms: [checkbox required content="I agree to the terms and conditions"]
@submit_form: [submit label="Send Message"]
```
--------------------------------
### Contact Form Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
A complete example of a contact form using FormDown syntax, including action, method, various input fields, and a submit button.
```formdown
# Contact Us
@form[action="/contact" method="POST"]
@name*: [placeholder="Your full name"]
@email*: @[placeholder="your@email.com"]
@subject: [placeholder="Message subject"]
@message*: T5[placeholder="Your message here..."]
@newsletter: [] Subscribe to our newsletter
@submit: [submit value="Send Message"]
```
--------------------------------
### Label Shorthand Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/shorthand.md
Shows how to use parentheses for labels and combines shorthand with other features like required fields and number ranges.
```formdown
// Using parentheses for labels
@username(Username): []
@email(Email Address)*: @[]
@age(Your Age): #[min=0 max=120]
// Combines with all other shorthand
@password(Choose Password)*: ***[minlength=8]
```
--------------------------------
### Complete Custom Plugin Example
Source: https://github.com/iyulab/formdown/blob/main/docs/EXTENSION_SYSTEM.md
This example demonstrates a comprehensive Formdown plugin that adds a custom 'rating' field type and a 'phone' validation rule. It includes metadata, initialization, cleanup, and hook registration.
```typescript
import type { Plugin, FieldTypePlugin, ValidationPlugin } from '@formdown/core'
// Custom field type for star ratings
const ratingFieldType: FieldTypePlugin = {
type: 'rating',
parser: (content: string) => {
const match = content.match(/@(\w+):\s*\[rating\](.*)/)
if (!match) return null
const [, name, rest] = match
const maxMatch = rest.match(/max=(\d+)/)
const max = maxMatch ? parseInt(maxMatch[1]) : 5
return {
name,
type: 'rating',
label: name,
attributes: { max }
}
},
validator: (field, value) => {
const rules = []
const max = field.attributes?.max || 5
if (value && (value < 1 || value > max)) {
rules.push({
type: 'custom',
message: `Rating must be between 1 and ${max}`
})
}
return rules
},
generator: (field) => {
const max = field.attributes?.max || 5
const stars = Array.from({ length: max }, (_, i) =>
`☆`
).join('')
return `
${stars}
`
}
}
// Custom validation rule
const phoneValidator: ValidationPlugin = {
name: 'phone',
validate: async (value) => {
if (!value) return true
// Can use external APIs for validation
const isValid = await validatePhoneNumber(value)
return isValid
},
getMessage: () => 'Please enter a valid phone number'
}
// Complete plugin
const customPlugin: Plugin = {
metadata: {
name: 'custom-field-plugin',
version: '1.0.0',
description: 'Adds rating fields and phone validation',
author: 'Your Name',
dependencies: ['formdown-core'] // Optional dependencies
},
// Plugin initialization
initialize: async () => {
console.log('Custom plugin initialized')
// Setup code here
},
// Plugin cleanup
destroy: async () => {
console.log('Custom plugin destroyed')
// Cleanup code here
},
// Register field types
fieldTypes: [ratingFieldType],
// Register validators
validators: [phoneValidator],
// Register hooks
hooks: [{
name: 'post-parse',
priority: 10,
handler: (context) => {
// Add custom CSS classes to all fields
if (context.parseResult?.fields) {
context.parseResult.fields.forEach(field => {
field.attributes = {
...field.attributes,
className: `form-field form-field--${field.type}`
}
})
}
}
}]
}
// Register the plugin
await registerPlugin(customPlugin)
```
--------------------------------
### Checkbox Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Illustrates checkbox usage, including checked states, custom labels, required fields, and options for multiple selections.
```formdown
@subscribe: [checkbox]
@subscribe: [checkbox checked]
@subscribe: [checkbox label="Subscribe to newsletter"]
@terms: [checkbox required label="I agree to terms"]
// Multiple checkboxes
@interests: [checkbox options="Sports, Music, Travel, Technology"]
@features: [checkbox options="Feature A, Feature B, Feature C" value="Feature A, Feature C"]
```
--------------------------------
### Complete Contact Form Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/basics.md
A comprehensive example of a contact form including fields for name, email, subject, message, priority, newsletter subscription, and a submit button.
```formdown
# Contact Us
@name(Full Name): [text required]
@email(Email Address): [email required]
@subject: [text required maxlength=100]
@message: [textarea required rows=5 placeholder="Your message..."]
@priority: [radio options="Low,Medium,High"]
@newsletter(Subscribe to newsletter): [checkbox]
@submit_form: [submit label="Send Message"]
```
--------------------------------
### Set and Get Field Values
Source: https://github.com/iyulab/formdown/blob/main/site/public/demos/field-helper-interactive.html
Demonstrates setting and getting values for different field types like radio, checkbox, and select. This is useful for programmatically controlling form states.
```javascript
FormdownFieldHelper.set('priority', 'Urgent');
FormdownFieldHelper.add('skills', 'Go');
FormdownFieldHelper.set('country', 'Korea');
console.log(FormdownFieldHelper.get('priority'));
console.log(FormdownFieldHelper.get('skills'));
```
--------------------------------
### Date and Time Input Fields
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/basics.md
Provides examples for date, time, and combined date-time local input fields with specific constraints.
```formdown
@birth_date: [date max="2010-12-31"]
@meeting_time: [time min="09:00" max="17:00"]
@appointment: [datetime-local required]
```
--------------------------------
### Inline Field Shorthand Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/shorthand.md
Demonstrates basic inline field shorthand for names, ages, required fields, and options.
```formdown
// Basic inline
My name is ___@name[] and I'm ___@age: #[] years old.
// With required
Please enter your ___@email*: @[] to continue.
// With options
I prefer ___@color: s{Red,Blue,Green}[] as my favorite color.
```
--------------------------------
### Smart Label Extension Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/extensions.md
Demonstrates how the Smart Label Extension automatically converts field names into human-readable labels.
```typescript
@first_name → "First Name"
@emailAddress → "Email Address"
```
--------------------------------
### Display Attributes Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/basics.md
Demonstrates the use of placeholder, value, disabled, and readonly attributes for text inputs.
```formdown
@name: [text placeholder="Enter your full name"]
@country: [text value="United States"]
@user_id: [text readonly value="12345"]
```
--------------------------------
### Initialization and Usage Instructions
Source: https://github.com/iyulab/formdown/blob/main/site/public/demos/field-helper-interactive.html
Logs messages to the console indicating the demo has loaded and provides instructions on how to use `FormdownFieldHelper` interactively.
```javascript
console.log('🎉 FormdownFieldHelper Interactive Demo loaded!');
console.log('Available in console: FormdownFieldHelper');
console.log('Try: FormdownFieldHelper.set("priority", "Custom Priority")');
```
--------------------------------
### Survey with Sections Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
Shows how to create a multi-section survey in Formdown, allowing for distinct parts of the survey to be presented with relevant headings and context.
```formdown
# Customer Satisfaction Survey
## About Your Experience
How would you rate our service?
@rating{1,2,3,4,5}: r[required]
What did you like most?
@liked: [textarea rows=3]
## Suggestions for Improvement
Any areas we could improve?
@improvements: [textarea rows=3]
Would you recommend us to others?
@recommend{Yes,No,Maybe}: r[required]
Thank you for your feedback!
```
--------------------------------
### Get Field Type Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/field-helper.md
Shows how to determine the type of a form field ('radio', 'checkbox', 'select', 'text') using FormdownFieldHelper.getFieldType().
```javascript
FormdownFieldHelper.getFieldType('priority') // → 'radio'
FormdownFieldHelper.getFieldType('skills') // → 'checkbox'
FormdownFieldHelper.getFieldType('country') // → 'select'
FormdownFieldHelper.getFieldType('name') // → 'text'
```
--------------------------------
### Build for Production
Source: https://github.com/iyulab/formdown/blob/main/site/README.md
Run this command to generate a static export of the site for production deployment.
```bash
npm run build
```
--------------------------------
### FormManager Initialization and Usage
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
Demonstrates two approaches to using the FormManager: a full control approach for detailed manipulation and a convenience approach for quick setup.
```javascript
import { FormManager, createFormManager } from '@formdown/core';
// Full control approach
const manager = new FormManager();
manager.parse('@name*: [placeholder="Enter name"]');
manager.setFieldValue('name', 'John Doe');
const html = manager.render();
// Convenience approach
const quickManager = createFormManager('@email*: @[]');
quickManager.updateData({ email: 'user@example.com' });
```
--------------------------------
### Purple Theme Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/styling.md
Apply a purple theme by customizing the accent color, button background gradient, and input focus ring color.
```css
formdown-ui.purple {
--formdown-accent-color: #8b5cf6;
--formdown-button-bg: linear-gradient(135deg, #8b5cf6, #7c3aed);
--formdown-input-focus-ring-color: rgba(139, 92, 246, 0.15);
}
```
--------------------------------
### Form Manager Unit Test Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/architecture.md
A sample unit test using Jest to verify the parsing functionality of the FormManager. Demonstrates basic test structure with setup and assertions.
```typescript
// Example test pattern
describe('FormManager', () => {
let manager: FormManager
beforeEach(() => {
manager = new FormManager()
})
test('should parse formdown content', () => {
const result = manager.parse('@name: [text required]')
expect(result.forms).toHaveLength(1)
expect(result.forms[0].name).toBe('name')
})
})
```
--------------------------------
### Real-World Example: Order Form with Conditional Business Fields
Source: https://github.com/iyulab/formdown/blob/main/docs/SYNTAX.md
An example of an order form where company-specific fields are shown only when the customer type is 'Business'.
```formdown
# Order Form
@customer_type{Individual,Business}: r[]
@name*: []
@company: [visible-if="customer_type=Business"]
@tax_id: [visible-if="customer_type=Business" required-if="customer_type=Business"]
```
--------------------------------
### Formdown Shorthand Syntax Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/quick-start.md
Demonstrates Formdown's recommended shorthand syntax for quick registration, highlighting concise field definitions.
```formdown
# Quick Registration
@username*: []
@email*: @[]
@password*: ?[]
@age: #[min=13]
@country{USA,Canada,UK}: s[]
@interests{Web,Mobile,AI}: c[]
@terms*: c[]
```
--------------------------------
### Get Field Value in FormDataBinding
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/api.md
Use the `get` method on `FormDataBinding` to retrieve a field's value. It prioritizes current data, then schema defaults.
```typescript
get(field: string): any
```
--------------------------------
### New Action Syntax Examples
Source: https://github.com/iyulab/formdown/blob/main/docs/SYNTAX.md
Demonstrates advanced usage of the new action syntax for buttons, including CSS classes, data attributes, and image buttons.
```formdown
@[button "Advanced Search" class="btn-primary" data-toggle="modal"]
```
```formdown
@[image "Submit Order" src="/images/submit.png" width="120" height="40"]
```
```formdown
@[submit "Complete Registration" class="btn-success btn-lg"]
```
--------------------------------
### Quick Start with CDN
Source: https://github.com/iyulab/formdown/blob/main/README.md
This snippet shows how to quickly integrate Formdown UI using a CDN link. It embeds a simple contact form directly within the HTML.
```html
@name*: []
@email*: @[]
@submit: [submit]
```
--------------------------------
### Account Settings Form Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
Demonstrates how Formdown now separates account settings into a distinct form section, improving organization and user experience compared to previous versions.
```html
Registration
Personal Details
We value your privacy.
Account Settings
```
```html
Registration
Personal Details
We value your privacy.
Account Settings
```
--------------------------------
### Best Practice: Readable Options in Shorthand
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/shorthand.md
Demonstrates readable shorthand for radio buttons and select fields using pipe separators for few options and commas for many.
```formdown
// Good - Pipe separator for few options
@size: r{S|M|L|XL}[]
// Good - Comma for many options
@country: s{USA,Canada,Mexico,UK,France,Germany,Japan,Australia}[]
```
--------------------------------
### Formdown Shorthand Syntax Examples
Source: https://github.com/iyulab/formdown/blob/main/README.md
This table provides examples of shorthand Formdown syntax for various field types, including contact, phone, inline fields, and selections.
```formdown
@name*: []
```
```formdown
@email*: @[]
```
```formdown
@phone{###-###-####}: %[]
```
```formdown
Name: ___@name*
```
```formdown
@size{S,M,L,XL}: r[]
```
--------------------------------
### Formdown Standard Syntax Examples
Source: https://github.com/iyulab/formdown/blob/main/README.md
This table provides examples of standard Formdown syntax for various field types, including contact, phone, inline fields, and selections.
```formdown
@name: [text required]
```
```formdown
@email: [email required]
```
```formdown
@phone: [tel pattern="\d{3}-\d{3}-\d{4}"]
```
```formdown
Name: ___@name[text required]
```
```formdown
@size: [radio options="S,M,L,XL"]
```
--------------------------------
### Combining Multiple Formdown Plugins
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/extension-examples.md
This example shows how to instantiate an ExtensionManager, register multiple plugins, and use them to parse and generate HTML for a complex form definition.
```typescript
const extensionManager = new ExtensionManager()
// Register all plugins
extensionManager.registerPlugin(bootstrapTheme)
extensionManager.registerPlugin(creditCardPlugin)
extensionManager.registerPlugin(fileUploadPlugin)
extensionManager.registerPlugin(analyticsPlugin)
extensionManager.registerPlugin(i18nPlugin)
extensionManager.registerPlugin(autoSavePlugin)
// Create a comprehensive form
const source = `
# Complete Registration Form
## Personal Information
@name: [text required placeholder="Full Name"]
@email: [email required]
@phone: [tel placeholder="Phone Number"]
## Payment Details
@card_number: [credit-card required]
@expiry: [text pattern="[0-9]{2}/[0-9]{2}" placeholder="MM/YY" required]
@cvv: [text pattern="[0-9]{3,4}" placeholder="CVV" required]
## Documents
@id_document: [file-upload accept="image/*,.pdf" label="ID Document"]
@proof_address: [file-upload accept=".pdf,image/*" label="Proof of Address"]
## Preferences
@language{English,Español,Français,한국어,*(Other Language)}: s[required]
@notifications{Email,SMS,Push,*(Contact Method)}: c[]
@submit: [submit label="Complete Registration"]
`
const ast = await parseForm(source, { extensionManager })
const html = await generateHTML(ast, { extensionManager })
```
--------------------------------
### Real-World Example: Payment Form with Conditional Card Fields
Source: https://github.com/iyulab/formdown/blob/main/docs/SYNTAX.md
A payment form example where credit card or bank transfer details are shown based on the selected payment method.
```formdown
@payment_method{Cash,Credit Card,Bank Transfer}: r[]
@card_number: [text visible-if="payment_method=Credit Card"]
@card_expiry: [text visible-if="payment_method=Credit Card"]
@card_cvv: [text visible-if="payment_method=Credit Card"]
@bank_name: [text visible-if="payment_method=Bank Transfer"]
@account_number: [text visible-if="payment_method=Bank Transfer"]
```
--------------------------------
### Collected Form Data Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/reference.md
An example of the JSON structure representing collected form data. Keys correspond to field names, and values are the user-submitted data, with appropriate types.
```json
{
"first_name": "John",
"email_address": "john@example.com",
"age": 25,
"interests": ["Web", "Mobile"]
}
```
--------------------------------
### Required Fields Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/basics.md
Demonstrates how to mark fields as required using the 'required' attribute, and shows examples for text, email, number, and checkbox types. Required fields are indicated with an asterisk.
```formdown
@name: [text required]
@email: [email required]
@age: [number required min=18]
@terms: [checkbox required]
```
--------------------------------
### Set Field Value Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/field-helper.md
Shows how to set values for single-value and multi-value fields using FormdownFieldHelper.set(). Demonstrates setting existing options, 'other' options, and multiple checkbox values.
```javascript
// Set existing option
FormdownFieldHelper.set('priority', 'High') // → true
// Set other option (automatically detected)
FormdownFieldHelper.set('priority', 'Urgent') // → true
// Set multiple checkbox values
FormdownFieldHelper.set('skills', ['JavaScript', 'CustomSkill']) // → true
// Set text field
FormdownFieldHelper.set('name', 'John Doe') // → true
```
--------------------------------
### Complete Survey Form Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/basics.md
A detailed example of a customer satisfaction survey form, including fields for name, email, service date, ratings, satisfaction level, improvements, comments, and recommendation.
```formdown
# Customer Satisfaction Survey
@customer_name(Your Name): [text required]
@email: [email required]
@service_date(Service Date): [date required]
@rating(Overall Rating): [radio options="1 - Poor,2 - Fair,3 - Good,4 - Very Good,5 - Excellent"]
@satisfaction: [select options="Very Dissatisfied,Dissatisfied,Neutral,Satisfied,Very Satisfied"]
@improvements: [checkbox options="Faster Service,Better Communication,Lower Prices,More Options"]
@comments: [textarea rows=4 placeholder="Additional comments..."]
@recommend(Would you recommend us?): [radio options="Yes,No,Maybe"]
@submit_survey: [submit label="Submit Survey"]
```
--------------------------------
### Option Shortcuts
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Demonstrates shorthand syntax for defining options in radio buttons, checkboxes, and select dropdowns, including default values.
```formdown
// Radio shorthand
@size: (S,M,L,XL) // Radio buttons
@size: (S,M,L,XL=L) // With default value
// Checkbox shorthand
@features: [x,y,z] // Multiple checkboxes
@features: [x,y=y,z=z] // With default checked
// Select shorthand
@country: v[USA,Canada,UK] // Select dropdown
@country: v[USA,Canada=Canada,UK] // With default
```
--------------------------------
### Range Field Markdown Examples
Source: https://github.com/iyulab/formdown/blob/main/docs/EXTENSION_SYSTEM.md
These examples show various ways to define a range field in Formdown's markdown syntax, including custom attributes like min, max, step, unit, and labels.
```markdown
# Basic range field
@volume: [range]
# Range with custom attributes
@temperature: [range min=0 max=40 step=0.5 unit="°C"]
# Range with custom label
@brightness(Display Brightness): [range max=255]
# Required range with hidden value display
@opacity: [range hideValue] required
```
--------------------------------
### Registering a Bootstrap Theme Plugin
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
Shows how to initialize the ExtensionManager and register a custom plugin, like a Bootstrap theme, to modify field attributes.
```typescript
import { ExtensionManager } from '@formdown/core'
const extensionManager = new ExtensionManager()
// Register a Bootstrap theme plugin
extensionManager.registerPlugin({
metadata: {
name: 'bootstrap-theme',
version: '1.0.0'
},
hooks: [{
name: 'css-class',
handler: (context) => {
context.field.attributes.className = 'form-control'
return context
}
}]
})
// Use with existing functions
const ast = await parseForm(source, { extensionManager })
const html = await generateHTML(ast, { extensionManager })
```
--------------------------------
### Advanced Form Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/index.md
An advanced Formdown example showcasing various field types including username with regex validation, email, age range, interests with predefined options, and a custom submit button label.
```formdown
@username*{^[a-zA-Z0-9_]{3,20}$}: [placeholder="3-20 characters"]
@email*: @[]
@age: #[min=18 max=100]
@interests{Web,Mobile,AI}: c[]
@submit: [submit label="Register"]
```
--------------------------------
### Component Creation
Source: https://github.com/iyulab/formdown/blob/main/docs/SYNTAX.md
Shows how to programmatically create FormdownUI and FormdownEditor components.
```APIDOC
## Component Creation
### Description
Programmatically create FormdownUI and FormdownEditor components with specified configurations.
### Functions
- `createFormdownUI(container: HTMLElement, formdownContent: string, options?: object)`: Creates a FormdownUI component.
- `createFormdownEditor(container: HTMLElement, formdownContent: string, options?: object)`: Creates a FormdownEditor component.
### Parameters for `createFormdownUI`
- `container`: The HTML element to mount the UI component.
- `formdownContent`: The content defining the form.
- `options`: Optional configuration object.
- `formId` (string): The ID for the form.
- `showSubmitButton` (boolean): Whether to display the submit button.
- `submitText` (string): The text for the submit button.
### Parameters for `createFormdownEditor`
- `container`: The HTML element to mount the editor component.
- `formdownContent`: The content defining the form.
- `options`: Optional configuration object.
- `mode` (string): The editor mode (e.g., 'split').
- `toolbar` (boolean): Whether to display the toolbar.
### Example Usage
```typescript
import { createFormdownUI, createFormdownEditor } from '@formdown/core'
// Create FormdownUI component
const container = document.getElementById('form-container')
const formComponent = createFormdownUI(container, formdownContent, {
formId: 'my-form',
showSubmitButton: true,
submitText: 'Submit Form'
})
// Create FormdownEditor component
const editorContainer = document.getElementById('editor-container')
const editorComponent = createFormdownEditor(editorContainer, formdownContent, {
mode: 'split',
toolbar: true
})
```
```
--------------------------------
### FormManager.createValidationManager
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/api.md
Creates a ValidationManager instance, facilitating the setup and execution of advanced validation pipelines.
```APIDOC
## FormManager.createValidationManager
### Description
Creates a ValidationManager for advanced validation pipelines.
### Method
```typescript
createValidationManager(): ValidationManager
```
### Parameters
- None
### Response
#### Success Response
- **ValidationManager** - An instance of the validation management module.
### Example
```javascript
const validator = manager.createValidationManager();
const result = await validator.validateAsync(fieldContext, value, formData);
```
```
--------------------------------
### Formdown Standard Syntax Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/quick-start.md
Illustrates Formdown's standard syntax for detailed registration, offering full control over field attributes, validation, and styling.
```formdown
# Detailed Registration
@username: [text required minlength=4 placeholder="Username"]
@email: [email required]
@password: [password required minlength=8]
@age: [number min=13 max=120]
@country: [select options="USA,Canada,UK"]
@interests: [checkbox options="Web,Mobile,AI"]
@terms: [checkbox required label="I agree to terms"]
```
--------------------------------
### Radio Button Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Defines radio buttons with options, default values, and required attributes.
```formdown
@gender: [radio options="Male, Female, Other"]
@plan: [radio options="Basic, Pro, Enterprise" value="Pro"]
@preferred_contact: [radio options="Email, Phone, SMS" required]
```
--------------------------------
### Checkboxes with Custom Others
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
Example of using custom 'other' labels with checkbox field types in Formdown.
```formdown
# Checkboxes
@interests{Web,Mobile,AI,*(Custom Topic)}: c[]
```
--------------------------------
### Best Practice: Use Shorthand for Common Patterns
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/shorthand.md
Illustrates the concise use of shorthand for common fields like email, age, and messages, contrasting with when standard syntax might be clearer.
```formdown
// Good - Clear and concise
@email*: @[]
@age: #[min=0 max=120]
@message*: T5[]
// Avoid mixing when standard is clearer
@complex_field: [text data-custom="value" aria-label="Complex"]
```
--------------------------------
### Event System for Extension Manager
Source: https://github.com/iyulab/formdown/blob/main/docs/EXTENSION_SYSTEM.md
Demonstrates how to listen for events emitted by the extension manager, such as plugin registration or hook execution.
```typescript
// Listen to extension events
extensionManager.getEventEmitter().on('plugin-registered', (event) => {
console.log('Plugin registered:', event.data.plugin)
})
// Available events:
// - plugin-registered
// - plugin-unregistered
// - plugin-initialized
// - plugin-error
// - hook-registered
// - hook-executed
// - hook-error
```
--------------------------------
### Other Option Extension Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/extensions.md
Illustrates how to define an 'other' option for selection fields, allowing custom input.
```typescript
@color: [radio options="Red,Blue,Green,*"]
```
--------------------------------
### Using Extensions with Existing Code
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
Illustrates how existing Formdown code remains compatible while new functionality can be enabled by passing an ExtensionManager.
```javascript
// Existing code (still works)
const html = generateHTML(ast)
// With extensions (new capability)
const html = generateHTML(ast, { extensionManager })
```
--------------------------------
### Field Anatomy Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/basics.md
Illustrates the complete anatomy of a Formdown field, including a custom label and placeholder.
```formdown
@first_name(Full Name): [text required placeholder="Enter your name"]
```
--------------------------------
### Implementing an Internationalization Plugin
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/new-features.md
An example of an internationalization plugin that translates field labels after parsing based on the current locale.
```typescript
const i18nPlugin = {
hooks: [{
name: 'post-parse',
handler: (context) => {
const locale = getCurrentLocale()
context.parseResult.fields.forEach(field => {
field.label = translate(field.label, locale)
})
return context
}
}]
}
```
--------------------------------
### Using Appropriate Input Types
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Illustrates how to select specific input types for better user experience, especially on mobile devices.
```formdown
@email: @[] // Email keyboard on mobile
@phone: tel:[] // Number pad on mobile
@website: http://[] // URL keyboard on mobile
@age: #[min=0 max=120] // Number spinner
```
--------------------------------
### Pattern Validation Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Illustrates pattern validation for field names and using the pattern attribute for input fields.
```formdown
// Using field name pattern
@username{^[a-zA-Z0-9_]{3,20}$}: []
@employee_id{^EMP[0-9]{6}$}: [placeholder="EMP000000"]
// Using pattern attribute
@product_code: [pattern="^[A-Z]{3}-[0-9]{4}$" placeholder="ABC-1234"]
```
--------------------------------
### Inline Field Examples
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/syntax.md
Shows how to embed form fields directly within text using triple underscores.
```formdown
My name is ___@name[text required placeholder="your name"] and
I'm ___@age[number min=1 max=120] years old.
I prefer ___@color[select options="Red, Blue, Green"] as my favorite color.
```
--------------------------------
### Import Formdown Core Components
Source: https://github.com/iyulab/formdown/blob/main/site/public/demos/field-helper-interactive.html
Illustrates how to import necessary components from the Formdown core library for local development or demonstration purposes. In production, use the official package import.
```javascript
import { parseFormdown } from '../packages/formdown-core/dist/index.js';
import { FormdownGenerator } from '../packages/formdown-core/dist/generator.js';
import { FormdownFieldHelper } from '../packages/formdown-core/dist/field-helper.js';
window.FormdownFieldHelper = FormdownFieldHelper;
```
--------------------------------
### Pattern Validation Extension Example
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/extensions.md
Shows how to use regular expressions directly in field names for pattern validation.
```typescript
@username{^[a-z0-9_]{3,20}$}: []
```
--------------------------------
### Formdown Editor Tool Usage
Source: https://github.com/iyulab/formdown/blob/main/site/content/docs/installation.md
Example of using the Formdown editor component in HTML for an enhanced development environment.
```html
@name*: []
@email*: @[]
@submit: [submit label="Send"]
```