Compare commits

..

56 Commits

Author SHA1 Message Date
8fd601357d Add JSON UI support for progress indicators 2026-01-18 11:48:06 +00:00
fc209545c1 Merge pull request #112 from johndoe6345789/codex/add-checklist-for-json-components
Rephrase JSON compatibility refactoring checklist item
2026-01-18 11:21:46 +00:00
28a3851310 Rephrase refactoring checklist guidance 2026-01-18 11:19:42 +00:00
8465a9de5a Merge pull request #111 from johndoe6345789/codex/extend-json-schema-types-for-bindings
Add state-aware bindings for JSON renderer
2026-01-18 11:19:06 +00:00
d04333e565 Add state-aware bindings for JSON renderer 2026-01-18 11:18:40 +00:00
e210dd8bec Merge pull request #110 from johndoe6345789/codex/define-json-event-schema-and-implement-dispatcher
Add JSON event map handling in JSON UI renderer
2026-01-18 11:18:03 +00:00
39c57e9967 Add JSON event definitions and renderer support 2026-01-18 11:17:37 +00:00
9675e1f071 Merge pull request #109 from johndoe6345789/codex/fix-json-ui-framework-rendering-issues
Stabilize JSON UI: bindings, conditionals, loops, and types
2026-01-18 11:07:44 +00:00
813c36b953 Stabilize JSON UI bindings and loop rendering 2026-01-18 11:07:32 +00:00
377a95da80 Merge pull request #108 from johndoe6345789/codex/align-event/action-shape-in-renderer
Align JSON UI event handling with action arrays
2026-01-18 02:38:12 +00:00
b232c220df Merge branch 'main' into codex/align-event/action-shape-in-renderer 2026-01-18 02:38:04 +00:00
01921d4b80 Align json-ui event action handlers 2026-01-18 02:36:16 +00:00
19a26156ad Merge pull request #107 from johndoe6345789/codex/update-loop-rendering-in-renderer.tsx
Render loop container elements per item with merged props
2026-01-18 02:35:43 +00:00
5652d0222d Render loop containers with props 2026-01-18 02:35:04 +00:00
e2f128a947 Merge pull request #106 from johndoe6345789/codex/expand-conditional-rendering-in-renderer.tsx
Expand conditional rendering branches for JSON UI renderer
2026-01-18 02:34:36 +00:00
717871c673 Expand conditional rendering branches 2026-01-18 02:34:10 +00:00
53a40aa808 Merge pull request #105 from johndoe6345789/codex/refactor-data-binding-resolution-in-componentrenderer
Enhance binding resolution in json-ui component renderer
2026-01-18 02:33:00 +00:00
f7d7b9f478 Merge branch 'main' into codex/refactor-data-binding-resolution-in-componentrenderer 2026-01-18 02:32:30 +00:00
17ff0eaaea Enhance binding resolution in component renderer 2026-01-18 02:31:49 +00:00
17c91ee91b Merge pull request #104 from johndoe6345789/codex/align-binding.transform-with-string-expression
Align JSON UI binding transforms
2026-01-18 02:31:31 +00:00
94018c0e3c Align JSON UI binding transforms 2026-01-18 02:31:19 +00:00
24b0498aa2 Merge pull request #103 from johndoe6345789/codex/fix-json-rendering-library-issues
Add roadmap tasks for molecule/organism refactors and JSON UI fixes
2026-01-18 02:14:24 +00:00
c6dc49488d Add roadmap tasks for JSON UI refactors 2026-01-18 02:14:12 +00:00
88e028b54e Merge pull request #102 from johndoe6345789/codex/update-conditional-component-handling
Render `conditional.then` when condition is true in JSONUIRenderer
2026-01-18 02:06:27 +00:00
f19df2822d Adjust conditional rendering for JSON UI 2026-01-18 02:06:17 +00:00
535f712383 Merge pull request #101 from johndoe6345789/codex/update-loop-handling-in-renderer
Fix loop rendering to use children with loop context
2026-01-18 02:05:54 +00:00
1bb40e399b Fix loop rendering to use children context 2026-01-18 02:05:42 +00:00
63db390cf7 Merge pull request #100 from johndoe6345789/codex/update-resolvedatabinding-for-context-support
Resolve data bindings with context, nested paths, and transforms
2026-01-18 02:05:20 +00:00
55c81cedfa Update data binding resolution context 2026-01-18 02:05:10 +00:00
3fac67c907 Merge pull request #99 from johndoe6345789/codex/consolidate-.tsx-and-.ts-json-ui-registries
Unify orchestration component registry with JSON UI
2026-01-18 01:55:05 +00:00
1be31c49f9 Unify orchestration component registry 2026-01-18 01:54:55 +00:00
cc0cab04dc Merge pull request #98 from johndoe6345789/codex/extend-usecomponentregistry-for-ui-primitives
Align JSON UI registry with canonical atom/molecule sources
2026-01-18 01:54:03 +00:00
8864436425 Align JSON UI registry with canonical components 2026-01-18 01:53:48 +00:00
4a07737c6a Merge pull request #97 from johndoe6345789/codex/extend-usecomponentregistry-for-json-ui-icons
Unify icon registry access for schema renderer
2026-01-18 01:52:07 +00:00
463201d758 Unify icon registry access 2026-01-18 01:51:56 +00:00
7cd15ca7ba Merge pull request #96 from johndoe6345789/codex/merge-json-ui-registry-into-component-registry
Merge JSON UI registry into component hook and add registry overrides to SchemaRenderer
2026-01-18 01:43:41 +00:00
560a75cd69 Expand schema component registry 2026-01-18 01:43:31 +00:00
17f4d567c9 Merge pull request #95 from johndoe6345789/codex/merge-atom/molecule-entries-into-component-registry
Consolidate JSON UI component registry and sync ComponentType union
2026-01-18 01:42:52 +00:00
320e8a4c2c Consolidate JSON UI component registry 2026-01-18 01:42:41 +00:00
1065d62d65 Merge pull request #94 from johndoe6345789/codex/update-exports-and-documentation-for-json-ui-hooks
Re-export JSON UI hooks from public entrypoint and update docs
2026-01-18 01:41:55 +00:00
671a99d30b Re-export JSON UI hooks 2026-01-18 01:41:27 +00:00
e033b032a1 Merge pull request #93 from johndoe6345789/codex/extract-logic-into-custom-hooks
Extract data source & component binding dialog state into hooks
2026-01-18 01:27:36 +00:00
81c6ada8c1 Merge branch 'main' into codex/extract-logic-into-custom-hooks 2026-01-18 01:27:30 +00:00
9a28805791 Extract dialog state hooks 2026-01-18 01:26:34 +00:00
f3cf2883d3 Merge pull request #92 from johndoe6345789/codex/create-shared-types-module-for-global-search
Add shared global search types module
2026-01-18 01:26:18 +00:00
925adc9712 Add shared global search types 2026-01-18 01:26:08 +00:00
5d5968d87b Merge pull request #91 from johndoe6345789/codex/add-shared-types-for-nextjs-components
Add shared Next.js config props type
2026-01-18 01:25:48 +00:00
9cd0ed818a Add shared Next.js config props type 2026-01-18 01:25:37 +00:00
68f0dcbfbd Merge pull request #90 from johndoe6345789/codex/add-use-component-binding-dialog-hook
Add useComponentBindingDialog hook and refactor ComponentBindingDialog to use it
2026-01-18 01:25:16 +00:00
6700705842 Add component binding dialog hook 2026-01-18 01:25:04 +00:00
530d7d96da Merge pull request #89 from johndoe6345789/codex/create-use-data-source-editor-hook
Add useDataSourceEditor hook and refactor DataSourceEditorDialog to use it
2026-01-18 01:24:46 +00:00
4ee346c69d Add data source editor hook 2026-01-18 01:24:36 +00:00
902253a9be Merge pull request #87 from johndoe6345789/codex/create-hook-for-template-explorer-actions
Add useTemplateExplorerActions hook and refactor TemplateExplorer
2026-01-18 01:22:55 +00:00
1e0cdf034c Add template explorer actions hook 2026-01-18 01:22:45 +00:00
5c64833a3f Merge pull request #86 from johndoe6345789/codex/add-expansion-hook-for-componenttree
Add component tree expansion hook
2026-01-18 01:22:27 +00:00
104f9461bc Add component tree expansion hook 2026-01-18 01:22:18 +00:00
46 changed files with 1847 additions and 788 deletions

View File

@@ -171,6 +171,24 @@ To add a new component to the JSON UI system:
4. Update `json-components-registry.json` with metadata
5. Test the component in a JSON schema
### JSON Compatibility Checklist
Before migrating a component, confirm all required conditions are met:
- [ ] **Hooks/state are registry-safe**: hooks and internal state are acceptable when the component registry can control or expose them through JSON bindings.
- [ ] **Bindings are defined**: any required actions, event handlers, or state bindings are already supported by the JSON UI binding system.
- [ ] **Refactoring covered by PR**: JSON compatibility gaps should be resolved via refactoring as part of the same pull request.
### Step-by-Step Migration Path
Use this repeatable migration flow for planned components:
1. **Update the type union** in `src/types/json-ui.ts` to include the new component type name.
2. **Register the component** in `src/lib/json-ui/component-registry.tsx` so JSON schemas can resolve it at runtime.
3. **Define component metadata** in `src/lib/component-definitions.ts` (defaults, prop schema, and any JSON-driven constraints).
4. **Validate JSON schema usage** by rendering a sample schema that uses the new type.
5. **Update registry metadata** in `json-components-registry.json` so the CLI/listing reflects the new status.
## Migration Strategy
Components marked as "planned" are:

View File

@@ -46,7 +46,7 @@ Replaced all imports of `@github/spark/hooks` with the local `@/hooks/use-kv` im
### Config Files
- `src/config/orchestration/data-source-manager.ts`
- `src/lib/json-ui/hooks.ts`
- `src/lib/json-ui/hooks.ts` (re-exported via `@/lib/json-ui`)
## Change Pattern
All instances of:

View File

@@ -27,7 +27,7 @@ Successfully implemented a comprehensive JSON-driven UI system that allows build
- Array looping for lists
- Form rendering with validation
- **hooks.ts**: React hooks for data management
- **hooks.ts**: React hooks for data management (import from `@/lib/json-ui`)
- `useJSONDataSource`: Single data source management (KV, API, static, computed)
- `useJSONDataSources`: Multiple data sources orchestration
- `useJSONActions`: Action registration and execution

View File

@@ -275,6 +275,12 @@ registerComponent('MyCustom', MyCustomComponent)
### Add Custom Data Source Types
Use the public entrypoint when consuming JSON UI hooks:
```typescript
import { useJSONDataSource, useJSONDataSources, useJSONActions } from '@/lib/json-ui'
```
Edit `/src/lib/json-ui/hooks.ts` to add new data source handlers.
### Add Custom Actions
@@ -296,7 +302,7 @@ const handleAction = (handler: EventHandler, event?: any) => {
- **Schema Definitions**: `/src/lib/json-ui/schema.ts`
- **Component Registry**: `/src/lib/json-ui/component-registry.ts`
- **Renderer**: `/src/lib/json-ui/renderer.tsx`
- **Hooks**: `/src/lib/json-ui/hooks.ts`
- **Hooks**: Import from `@/lib/json-ui` (source: `/src/lib/json-ui/hooks.ts`)
- **Utils**: `/src/lib/json-ui/utils.ts`
- **Examples**: `/src/config/ui-examples/`
- **Demo Page**: `/src/components/JSONUIShowcase.tsx`

View File

@@ -645,6 +645,19 @@ CodeForge is a comprehensive low-code development platform for building producti
- [ ] Migration guides
- [ ] Best practices guide
#### Molecule/Organism Refactors
- [ ] Identify 3-5 molecule components that can be expressed as JSON schemas with hooks, types, and actions (target: ComponentTree, PropertyEditor, DataSourceCard, SchemaEditorCanvas, NavigationMenu).
- [ ] Create JSON schemas for selected molecules and wire them through `JSONUIRenderer` while keeping existing props contracts stable.
- [ ] Convert at least one organism (e.g., DataSourceManager) into JSON-driven layout with nested molecule schemas.
- [ ] Document the JSON schema patterns for molecule/organism composition (bindings, events, actions) with real examples.
#### JSON UI Framework Improvements
- [ ] Fix conditional rendering to honor `conditional.then` when conditions pass.
- [ ] Fix loop rendering to avoid self-recursion and render loop children templates.
- [ ] Add data binding support for dot-path string bindings and loop context variables.
- [ ] Apply data binding transforms consistently (support `transform` in JSON schemas).
- [ ] Align JSON UI event/action typings across `src/lib/json-ui` and `src/types/json-ui.ts`.
#### Security
- [ ] Regular dependency updates
- [ ] Security audit with npm audit

View File

@@ -1,20 +0,0 @@
# React Hook Extraction Tasks
## Component candidates
- [ ] **Extract data source editor state logic into a hook.**
- **Component:** `src/components/molecules/DataSourceEditorDialog.tsx`
- **Why:** Manages editing state, sync with props, and dependency add/remove logic in the component body.
- **Proposed hook:** `useDataSourceEditor` (or similar) to own `editingSource`, `updateField`, and dependency helpers, plus derived dependency lists.
- [ ] **Extract component binding dialog state into a hook.**
- **Component:** `src/components/molecules/ComponentBindingDialog.tsx`
- **Why:** Holds editable component state and binding update handlers inline.
- **Proposed hook:** `useComponentBindingDialog` to sync `editingComponent` with props and expose `updateBindings`/`handleSave`.
- [ ] **Extract template export/copy/download actions into a hook.**
- **Component:** `src/components/TemplateExplorer.tsx`
- **Why:** Clipboard interactions, blob creation, and KV export are embedded in the view component.
- **Proposed hook:** `useTemplateExplorerActions` to return `copyToClipboard`, `downloadJSON`, and `exportCurrentData` handlers.
- [ ] **Extract component tree expansion state into a hook.**
- **Component:** `src/components/molecules/ComponentTree.tsx`
- **Why:** Expansion state, “expand all,” and “collapse all” logic are in the component, but reusable across tree UIs.
- **Proposed hook:** `useComponentTreeExpansion` to compute expandable IDs and manage `expandedIds` with expand/collapse/toggle functions.

View File

@@ -611,7 +611,7 @@
"category": "display",
"canHaveChildren": false,
"description": "Circular progress indicator",
"status": "planned",
"status": "supported",
"source": "atoms"
},
{
@@ -629,7 +629,7 @@
"category": "display",
"canHaveChildren": false,
"description": "Visual section divider",
"status": "planned",
"status": "supported",
"source": "atoms"
},
{
@@ -719,7 +719,7 @@
"category": "display",
"canHaveChildren": false,
"description": "Linear progress bar",
"status": "planned",
"status": "supported",
"source": "atoms"
},
{

View File

@@ -0,0 +1,82 @@
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const registryPath = path.join(process.cwd(), 'json-components-registry.json')
const schemaPath = path.join(process.cwd(), 'src', 'schemas', 'registry-validation.json')
if (!fs.existsSync(registryPath)) {
console.error('❌ Could not find json-components-registry.json')
process.exit(1)
}
if (!fs.existsSync(schemaPath)) {
console.error('❌ Could not find src/schemas/registry-validation.json')
process.exit(1)
}
const registry = JSON.parse(fs.readFileSync(registryPath, 'utf8'))
const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'))
const primitiveTypes = new Set([
'div',
'span',
'p',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'section',
'article',
'header',
'footer',
'main',
'aside',
'nav',
])
const registryTypes = new Set()
for (const entry of registry.components || []) {
if (entry.source === 'atoms' || entry.source === 'molecules') {
const name = entry.export || entry.name || entry.type
if (name) {
registryTypes.add(name)
}
}
}
const schemaTypes = new Set()
const collectTypes = (components) => {
if (!components) return
if (Array.isArray(components)) {
components.forEach(collectTypes)
return
}
if (components.type) {
schemaTypes.add(components.type)
}
if (components.children) {
collectTypes(components.children)
}
}
collectTypes(schema.components || [])
const missing = []
for (const type of schemaTypes) {
if (!primitiveTypes.has(type) && !registryTypes.has(type)) {
missing.push(type)
}
}
if (missing.length) {
console.error(`❌ Missing registry entries for: ${missing.join(', ')}`)
process.exit(1)
}
console.log('✅ JSON UI registry validation passed for primitives and atom/molecule components.')

View File

@@ -3,45 +3,50 @@ import { toast } from 'sonner'
import { useKV } from '@/hooks/use-kv'
import { useState } from 'react'
import { buildDemoPageSchema, demoCopy, demoInitialTodos } from '@/components/json-demo/schema'
import { Action } from '@/lib/json-ui/schema'
export function JSONDemoPage() {
const [todos, setTodos] = useKV('json-demo-todos', demoInitialTodos)
const [newTodo, setNewTodo] = useState('')
const handleAction = (handler: any, event?: any) => {
switch (handler.action) {
case 'add-todo':
if (newTodo.trim()) {
setTodos((current: any) => [
...current,
{ id: Date.now(), text: newTodo, completed: false },
])
setNewTodo('')
toast.success(demoCopy.toastAdded)
}
break
const handleAction = (actions: Action[], event?: any) => {
actions.forEach((action) => {
const actionKey = action.type === 'custom' ? action.id : action.type
case 'toggle-todo':
setTodos((current: any) =>
current.map((todo: any) =>
todo.id === handler.params?.id
? { ...todo, completed: !todo.completed }
: todo
switch (actionKey) {
case 'add-todo':
if (newTodo.trim()) {
setTodos((current: any) => [
...current,
{ id: Date.now(), text: newTodo, completed: false },
])
setNewTodo('')
toast.success(demoCopy.toastAdded)
}
break
case 'toggle-todo':
setTodos((current: any) =>
current.map((todo: any) =>
todo.id === action.params?.id
? { ...todo, completed: !todo.completed }
: todo
)
)
)
break
break
case 'delete-todo':
setTodos((current: any) =>
current.filter((todo: any) => todo.id !== handler.params?.id)
)
toast.success(demoCopy.toastDeleted)
break
case 'delete-todo':
setTodos((current: any) =>
current.filter((todo: any) => todo.id !== action.params?.id)
)
toast.success(demoCopy.toastDeleted)
break
case 'update-input':
setNewTodo(event.target.value)
break
}
case 'update-input':
setNewTodo(event.target.value)
break
}
})
}
const pageSchema = buildDemoPageSchema(todos, newTodo)

View File

@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react'
import { JSONUIRenderer } from '@/lib/json-ui/renderer'
import { UIComponent, EventHandler, Layout } from '@/lib/json-ui/schema'
import { Action, UIComponent, Layout } from '@/lib/json-ui/schema'
import { toast } from 'sonner'
interface JSONUIPageProps {
@@ -34,88 +34,91 @@ export function JSONUIPage({ jsonConfig }: JSONUIPageProps) {
}))
}
const handleAction = (handler: EventHandler, event?: any) => {
console.log('Action triggered:', handler.action, handler.params, event)
switch (handler.action) {
case 'refresh-data':
toast.success('Data refreshed')
break
case 'create-project':
toast.info('Create project clicked')
break
case 'deploy':
toast.info('Deploy clicked')
break
case 'view-logs':
toast.info('View logs clicked')
break
case 'settings':
toast.info('Settings clicked')
break
case 'add-project':
toast.info('Add project clicked')
break
case 'view-project':
toast.info(`View project: ${handler.params?.projectId}`)
break
case 'edit-project':
toast.info(`Edit project: ${handler.params?.projectId}`)
break
case 'delete-project':
toast.error(`Delete project: ${handler.params?.projectId}`)
break
case 'update-field':
if (event?.target) {
const { name, value } = event.target
updateDataField('formData', name, value)
}
break
case 'update-checkbox':
if (handler.params?.field) {
updateDataField('formData', handler.params.field, event)
}
break
case 'submit-form':
toast.success('Form submitted!')
console.log('Form data:', dataMap.formData)
break
case 'cancel-form':
toast.info('Form cancelled')
break
case 'toggle-dark-mode':
updateDataField('settings', 'darkMode', event)
toast.success(`Dark mode ${event ? 'enabled' : 'disabled'}`)
break
case 'toggle-auto-save':
updateDataField('settings', 'autoSave', event)
toast.success(`Auto-save ${event ? 'enabled' : 'disabled'}`)
break
case 'toggle-email-notifications':
updateDataField('notifications', 'email', event)
toast.success(`Email notifications ${event ? 'enabled' : 'disabled'}`)
break
case 'toggle-push-notifications':
updateDataField('notifications', 'push', event)
toast.success(`Push notifications ${event ? 'enabled' : 'disabled'}`)
break
case 'toggle-2fa':
updateDataField('security', 'twoFactor', event)
toast.success(`Two-factor auth ${event ? 'enabled' : 'disabled'}`)
break
case 'logout-all-sessions':
toast.success('All other sessions logged out')
break
case 'save-settings':
toast.success('Settings saved successfully')
console.log('Settings:', dataMap)
break
case 'reset-settings':
toast.info('Settings reset to defaults')
break
default:
console.log('Unhandled action:', handler.action)
}
const handleAction = (actions: Action[], event?: any) => {
actions.forEach((action) => {
const actionKey = action.type === 'custom' ? action.id : action.type
console.log('Action triggered:', actionKey, action.params, event)
switch (actionKey) {
case 'refresh-data':
toast.success('Data refreshed')
break
case 'create-project':
toast.info('Create project clicked')
break
case 'deploy':
toast.info('Deploy clicked')
break
case 'view-logs':
toast.info('View logs clicked')
break
case 'settings':
toast.info('Settings clicked')
break
case 'add-project':
toast.info('Add project clicked')
break
case 'view-project':
toast.info(`View project: ${action.params?.projectId}`)
break
case 'edit-project':
toast.info(`Edit project: ${action.params?.projectId}`)
break
case 'delete-project':
toast.error(`Delete project: ${action.params?.projectId}`)
break
case 'update-field':
if (event?.target) {
const { name, value } = event.target
updateDataField('formData', name, value)
}
break
case 'update-checkbox':
if (action.params?.field) {
updateDataField('formData', action.params.field, event)
}
break
case 'submit-form':
toast.success('Form submitted!')
console.log('Form data:', dataMap.formData)
break
case 'cancel-form':
toast.info('Form cancelled')
break
case 'toggle-dark-mode':
updateDataField('settings', 'darkMode', event)
toast.success(`Dark mode ${event ? 'enabled' : 'disabled'}`)
break
case 'toggle-auto-save':
updateDataField('settings', 'autoSave', event)
toast.success(`Auto-save ${event ? 'enabled' : 'disabled'}`)
break
case 'toggle-email-notifications':
updateDataField('notifications', 'email', event)
toast.success(`Email notifications ${event ? 'enabled' : 'disabled'}`)
break
case 'toggle-push-notifications':
updateDataField('notifications', 'push', event)
toast.success(`Push notifications ${event ? 'enabled' : 'disabled'}`)
break
case 'toggle-2fa':
updateDataField('security', 'twoFactor', event)
toast.success(`Two-factor auth ${event ? 'enabled' : 'disabled'}`)
break
case 'logout-all-sessions':
toast.success('All other sessions logged out')
break
case 'save-settings':
toast.success('Settings saved successfully')
console.log('Settings:', dataMap)
break
case 'reset-settings':
toast.info('Settings reset to defaults')
break
default:
console.log('Unhandled action:', actionKey)
}
})
}
if (!jsonConfig.layout) {

View File

@@ -8,8 +8,8 @@ import { ScrollArea } from '@/components/ui/scroll-area'
import { Badge } from '@/components/ui/badge'
import { useSeedTemplates } from '@/hooks/data/use-seed-templates'
import { Copy, Download } from '@phosphor-icons/react'
import { toast } from 'sonner'
import templateUi from '@/config/template-ui.json'
import { useTemplateExplorerActions } from '@/hooks/use-template-explorer-actions'
const ui = templateUi.explorer
@@ -185,49 +185,11 @@ export function TemplateExplorer() {
const currentTemplate = templates.find(t => t.id === selectedTemplate)
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text)
toast.success(ui.toasts.copySuccess)
}
const downloadJSON = () => {
if (!currentTemplate) return
const dataStr = JSON.stringify(currentTemplate.data, null, 2)
const blob = new Blob([dataStr], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `${currentTemplate.id}-template.json`
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
toast.success(ui.toasts.downloadSuccess)
}
const exportCurrentData = async () => {
const keys = await window.spark.kv.keys()
const data: Record<string, any> = {}
for (const key of keys) {
data[key] = await window.spark.kv.get(key)
}
const dataStr = JSON.stringify(data, null, 2)
const blob = new Blob([dataStr], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = 'current-project-data.json'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
toast.success(ui.toasts.exportSuccess)
}
const {
copyToClipboard,
downloadJSON,
exportCurrentData
} = useTemplateExplorerActions(currentTemplate)
if (!currentTemplate) return null

View File

@@ -2,25 +2,7 @@ import { ClockCounterClockwise, X } from '@phosphor-icons/react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { CommandGroup, CommandItem, CommandSeparator } from '@/components/ui/command'
interface SearchHistoryItem {
id: string
query: string
timestamp: number
resultId?: string
resultTitle?: string
resultCategory?: string
}
interface SearchResult {
id: string
title: string
subtitle?: string
category: string
icon: React.ReactNode
action: () => void
tags?: string[]
}
import type { SearchHistoryItem, SearchResult } from './types'
interface RecentSearchesProps {
recentSearches: Array<{ historyItem: SearchHistoryItem; result?: SearchResult }>

View File

@@ -1,15 +1,6 @@
import { Badge } from '@/components/ui/badge'
import { CommandGroup, CommandItem, CommandSeparator } from '@/components/ui/command'
interface SearchResult {
id: string
title: string
subtitle?: string
category: string
icon: React.ReactNode
action: () => void
tags?: string[]
}
import type { SearchResult } from './types'
interface SearchResultsProps {
groupedResults: Record<string, SearchResult[]>

View File

@@ -0,0 +1,18 @@
export interface SearchResult {
id: string
title: string
subtitle?: string
category: string
icon: React.ReactNode
action: () => void
tags?: string[]
}
export interface SearchHistoryItem {
id: string
query: string
timestamp: number
resultId?: string
resultTitle?: string
resultCategory?: string
}

View File

@@ -33,25 +33,7 @@ import {
Workflow,
} from '@/types/project'
import navigationData from '@/data/global-search.json'
export interface SearchResult {
id: string
title: string
subtitle?: string
category: string
icon: React.ReactNode
action: () => void
tags?: string[]
}
export interface SearchHistoryItem {
id: string
query: string
timestamp: number
resultId?: string
resultTitle?: string
resultCategory?: string
}
import type { SearchHistoryItem, SearchResult } from './types'
const navigationIconMap = {
BookOpen,

View File

@@ -49,12 +49,18 @@ const buildTodoItem = (todo: TodoItem, copy: DemoCopy): UIComponent => ({
props: {
checked: todo.completed,
},
events: {
onCheckedChange: {
action: 'toggle-todo',
params: { id: todo.id },
events: [
{
event: 'checkedChange',
actions: [
{
id: 'toggle-todo',
type: 'custom',
params: { id: todo.id },
},
],
},
},
],
},
{
id: `text-${todo.id}`,
@@ -72,12 +78,18 @@ const buildTodoItem = (todo: TodoItem, copy: DemoCopy): UIComponent => ({
size: 'sm',
children: copy.deleteButtonLabel,
},
events: {
onClick: {
action: 'delete-todo',
params: { id: todo.id },
events: [
{
event: 'click',
actions: [
{
id: 'delete-todo',
type: 'custom',
params: { id: todo.id },
},
],
},
},
],
},
],
})

View File

@@ -1,10 +1,10 @@
import { useState } from 'react'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { BindingEditor } from '@/components/molecules/BindingEditor'
import { DataSource, UIComponent } from '@/types/json-ui'
import { Link } from '@phosphor-icons/react'
import { useComponentBindingDialog } from '@/hooks/use-component-binding-dialog'
interface ComponentBindingDialogProps {
open: boolean
@@ -21,18 +21,12 @@ export function ComponentBindingDialog({
onOpenChange,
onSave,
}: ComponentBindingDialogProps) {
const [editingComponent, setEditingComponent] = useState<UIComponent | null>(component)
const handleSave = () => {
if (!editingComponent) return
onSave(editingComponent)
onOpenChange(false)
}
const updateBindings = (bindings: Record<string, any>) => {
if (!editingComponent) return
setEditingComponent({ ...editingComponent, bindings })
}
const { editingComponent, handleSave, updateBindings } = useComponentBindingDialog({
component,
open,
onOpenChange,
onSave,
})
if (!editingComponent) return null

View File

@@ -1,9 +1,9 @@
import { useState, useCallback } from 'react'
import { UIComponent } from '@/types/json-ui'
import { ScrollArea } from '@/components/ui/scroll-area'
import { ComponentTreeHeader } from '@/components/molecules/component-tree/ComponentTreeHeader'
import { ComponentTreeEmptyState } from '@/components/molecules/component-tree/ComponentTreeEmptyState'
import { ComponentTreeNodes } from '@/components/molecules/component-tree/ComponentTreeNodes'
import { useComponentTreeExpansion } from '@/hooks/use-component-tree-expansion'
interface ComponentTreeProps {
components: UIComponent[]
@@ -34,42 +34,8 @@ export function ComponentTree({
onDragLeave,
onDrop,
}: ComponentTreeProps) {
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set())
const getAllComponentIds = useCallback((comps: UIComponent[]): string[] => {
const ids: string[] = []
const traverse = (nodes: UIComponent[]) => {
nodes.forEach((comp) => {
if (Array.isArray(comp.children) && comp.children.length > 0) {
ids.push(comp.id)
traverse(comp.children)
}
})
}
traverse(comps)
return ids
}, [])
const handleExpandAll = useCallback(() => {
const allIds = getAllComponentIds(components)
setExpandedIds(new Set(allIds))
}, [components, getAllComponentIds])
const handleCollapseAll = useCallback(() => {
setExpandedIds(new Set())
}, [])
const toggleExpand = useCallback((id: string) => {
setExpandedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) {
next.delete(id)
} else {
next.add(id)
}
return next
})
}, [])
const { expandedIds, handleExpandAll, handleCollapseAll, toggleExpand } =
useComponentTreeExpansion(components)
return (
<div className="h-full flex flex-col">

View File

@@ -1,4 +1,3 @@
import { useEffect, useState } from 'react'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { DataSource } from '@/types/json-ui'
@@ -7,7 +6,9 @@ import { DataSourceIdField } from '@/components/molecules/data-source-editor/Dat
import { KvSourceFields } from '@/components/molecules/data-source-editor/KvSourceFields'
import { StaticSourceFields } from '@/components/molecules/data-source-editor/StaticSourceFields'
import { ComputedSourceFields } from '@/components/molecules/data-source-editor/ComputedSourceFields'
import { useDataSourceEditor } from '@/hooks/data/use-data-source-editor'
import dataSourceEditorCopy from '@/data/data-source-editor-dialog.json'
import { useDataSourceEditor } from '@/hooks/use-data-source-editor'
interface DataSourceEditorDialogProps {
open: boolean
@@ -24,11 +25,15 @@ export function DataSourceEditorDialog({
onOpenChange,
onSave,
}: DataSourceEditorDialogProps) {
const [editingSource, setEditingSource] = useState<DataSource | null>(dataSource)
useEffect(() => {
setEditingSource(dataSource)
}, [dataSource])
const {
editingSource,
updateField,
addDependency,
removeDependency,
availableDeps,
selectedDeps,
unselectedDeps,
} = useDataSourceEditor(dataSource, allDataSources)
const handleSave = () => {
if (!editingSource) return
@@ -36,34 +41,8 @@ export function DataSourceEditorDialog({
onOpenChange(false)
}
const updateField = <K extends keyof DataSource>(field: K, value: DataSource[K]) => {
if (!editingSource) return
setEditingSource({ ...editingSource, [field]: value })
}
const addDependency = (depId: string) => {
if (!editingSource || editingSource.type !== 'computed') return
const deps = editingSource.dependencies || []
if (!deps.includes(depId)) {
updateField('dependencies', [...deps, depId])
}
}
const removeDependency = (depId: string) => {
if (!editingSource || editingSource.type !== 'computed') return
const deps = editingSource.dependencies || []
updateField('dependencies', deps.filter(d => d !== depId))
}
if (!editingSource) return null
const availableDeps = allDataSources.filter(
ds => ds.id !== editingSource.id && ds.type !== 'computed',
)
const selectedDeps = editingSource.dependencies || []
const unselectedDeps = availableDeps.filter(ds => !selectedDeps.includes(ds.id))
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">

View File

@@ -1,24 +1,6 @@
import { ReactNode } from 'react'
import { ComponentSchema as ComponentSchemaType } from '@/types/page-schema'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
const COMPONENT_MAP: Record<string, any> = {
Button,
Card,
Input,
Badge,
Textarea,
div: 'div',
span: 'span',
h1: 'h1',
h2: 'h2',
h3: 'h3',
p: 'p',
}
import { getUIComponent } from '@/lib/json-ui/component-registry'
interface ComponentRendererProps {
schema: ComponentSchemaType
@@ -27,7 +9,7 @@ interface ComponentRendererProps {
}
export function ComponentRenderer({ schema, context, onEvent }: ComponentRendererProps) {
const Component = COMPONENT_MAP[schema.type]
const Component = getUIComponent(schema.type)
if (!Component) {
console.warn(`Component type "${schema.type}" not found`)

View File

@@ -1,18 +1,13 @@
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { NextJsConfig } from '@/types/project'
import projectSettingsCopy from '@/data/project-settings.json'
interface NextJsApplicationCardProps {
nextjsConfig: NextJsConfig
onNextjsConfigChange: (config: NextJsConfig | ((current: NextJsConfig) => NextJsConfig)) => void
}
import { NextJsConfigSectionProps } from '@/components/project-settings/types'
export function NextJsApplicationCard({
nextjsConfig,
onNextjsConfigChange,
}: NextJsApplicationCardProps) {
}: NextJsConfigSectionProps) {
const { application } = projectSettingsCopy.nextjs
return (

View File

@@ -1,16 +1,11 @@
import { NextJsConfig } from '@/types/project'
import { NextJsApplicationCard } from '@/components/project-settings/NextJsApplicationCard'
import { NextJsFeaturesCard } from '@/components/project-settings/NextJsFeaturesCard'
interface NextJsConfigTabProps {
nextjsConfig: NextJsConfig
onNextjsConfigChange: (config: NextJsConfig | ((current: NextJsConfig) => NextJsConfig)) => void
}
import { NextJsConfigSectionProps } from '@/components/project-settings/types'
export function NextJsConfigTab({
nextjsConfig,
onNextjsConfigChange,
}: NextJsConfigTabProps) {
}: NextJsConfigSectionProps) {
return (
<div className="max-w-2xl space-y-6">
<NextJsApplicationCard

View File

@@ -1,18 +1,13 @@
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { NextJsConfig } from '@/types/project'
import projectSettingsCopy from '@/data/project-settings.json'
interface NextJsFeaturesCardProps {
nextjsConfig: NextJsConfig
onNextjsConfigChange: (config: NextJsConfig | ((current: NextJsConfig) => NextJsConfig)) => void
}
import { NextJsConfigSectionProps } from '@/components/project-settings/types'
export function NextJsFeaturesCard({
nextjsConfig,
onNextjsConfigChange,
}: NextJsFeaturesCardProps) {
}: NextJsConfigSectionProps) {
const { features } = projectSettingsCopy.nextjs
return (

View File

@@ -0,0 +1,6 @@
import { NextJsConfig } from '@/types/project'
export type NextJsConfigSectionProps = {
nextjsConfig: NextJsConfig
onNextjsConfigChange: (config: NextJsConfig | ((current: NextJsConfig) => NextJsConfig)) => void
}

View File

@@ -0,0 +1,58 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { DataSource } from '@/types/json-ui'
export function useDataSourceEditor(
dataSource: DataSource | null,
allDataSources: DataSource[],
) {
const [editingSource, setEditingSource] = useState<DataSource | null>(dataSource)
useEffect(() => {
setEditingSource(dataSource)
}, [dataSource])
const updateField = useCallback(<K extends keyof DataSource>(field: K, value: DataSource[K]) => {
setEditingSource(prev => (prev ? { ...prev, [field]: value } : prev))
}, [])
const addDependency = useCallback((depId: string) => {
setEditingSource(prev => {
if (!prev || prev.type !== 'computed') return prev
const deps = prev.dependencies || []
if (deps.includes(depId)) return prev
return { ...prev, dependencies: [...deps, depId] }
})
}, [])
const removeDependency = useCallback((depId: string) => {
setEditingSource(prev => {
if (!prev || prev.type !== 'computed') return prev
const deps = prev.dependencies || []
return { ...prev, dependencies: deps.filter(dep => dep !== depId) }
})
}, [])
const availableDeps = useMemo(() => {
if (!editingSource) return []
return allDataSources.filter(
ds => ds.id !== editingSource.id && ds.type !== 'computed',
)
}, [allDataSources, editingSource])
const selectedDeps = useMemo(() => editingSource?.dependencies || [], [editingSource])
const unselectedDeps = useMemo(
() => availableDeps.filter(ds => !selectedDeps.includes(ds.id)),
[availableDeps, selectedDeps],
)
return {
editingSource,
updateField,
addDependency,
removeDependency,
availableDeps,
selectedDeps,
unselectedDeps,
}
}

View File

@@ -1,11 +1,5 @@
import { useMemo } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import { Progress } from '@/components/ui/progress'
import { createElement, useMemo } from 'react'
import { uiComponentRegistry, iconComponents } from '@/lib/json-ui/component-registry'
import * as Icons from '@phosphor-icons/react'
interface ComponentRegistryOptions {
@@ -15,17 +9,7 @@ interface ComponentRegistryOptions {
export function useComponentRegistry({ customComponents = {} }: ComponentRegistryOptions = {}) {
const registry = useMemo(
() => ({
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
Button,
Badge,
Input,
Label,
Separator,
Progress,
...uiComponentRegistry,
...customComponents,
}),
[customComponents]
@@ -36,9 +20,13 @@ export function useComponentRegistry({ customComponents = {} }: ComponentRegistr
}
const getIcon = (iconName: string, props?: any): React.ReactElement | null => {
const IconComponent = (Icons as any)[iconName]
if (!IconComponent) return null
return IconComponent({ size: 24, weight: "duotone", ...props })
const registryIcon = registry[iconName as keyof typeof registry]
const IconComponent =
(registryIcon && typeof registryIcon !== 'string' ? registryIcon : null) ||
iconComponents[iconName as keyof typeof iconComponents] ||
(Icons as any)[iconName]
if (!IconComponent || typeof IconComponent === 'string') return null
return createElement(IconComponent, { size: 24, weight: "duotone", ...props })
}
return {

View File

@@ -0,0 +1,40 @@
import { useCallback, useEffect, useState } from 'react'
import { UIComponent } from '@/types/json-ui'
interface UseComponentBindingDialogOptions {
component: UIComponent | null
open: boolean
onOpenChange: (open: boolean) => void
onSave: (component: UIComponent) => void
}
export function useComponentBindingDialog({
component,
open,
onOpenChange,
onSave,
}: UseComponentBindingDialogOptions) {
const [editingComponent, setEditingComponent] = useState<UIComponent | null>(component)
useEffect(() => {
if (open) {
setEditingComponent(component)
}
}, [component, open])
const updateBindings = useCallback((bindings: Record<string, any>) => {
setEditingComponent(prev => (prev ? { ...prev, bindings } : prev))
}, [])
const handleSave = useCallback(() => {
if (!editingComponent) return
onSave(editingComponent)
onOpenChange(false)
}, [editingComponent, onOpenChange, onSave])
return {
editingComponent,
handleSave,
updateBindings,
}
}

View File

@@ -0,0 +1,58 @@
import { useCallback, useMemo, useState } from 'react'
import { UIComponent } from '@/types/json-ui'
interface ComponentTreeExpansionState {
expandedIds: Set<string>
handleExpandAll: () => void
handleCollapseAll: () => void
toggleExpand: (id: string) => void
}
const getExpandableIds = (components: UIComponent[]): string[] => {
const ids: string[] = []
const traverse = (nodes: UIComponent[]) => {
nodes.forEach((component) => {
if (Array.isArray(component.children) && component.children.length > 0) {
ids.push(component.id)
traverse(component.children)
}
})
}
traverse(components)
return ids
}
export function useComponentTreeExpansion(
components: UIComponent[],
): ComponentTreeExpansionState {
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set())
const expandableIds = useMemo(() => getExpandableIds(components), [components])
const handleExpandAll = useCallback(() => {
setExpandedIds(new Set(expandableIds))
}, [expandableIds])
const handleCollapseAll = useCallback(() => {
setExpandedIds(new Set())
}, [])
const toggleExpand = useCallback((id: string) => {
setExpandedIds((prev) => {
const next = new Set(prev)
if (next.has(id)) {
next.delete(id)
} else {
next.add(id)
}
return next
})
}, [])
return {
expandedIds,
handleExpandAll,
handleCollapseAll,
toggleExpand,
}
}

View File

@@ -0,0 +1,77 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { DataSource } from '@/types/json-ui'
interface UseDataSourceEditorParams {
dataSource: DataSource | null
allDataSources: DataSource[]
onSave: (dataSource: DataSource) => void
onOpenChange: (open: boolean) => void
}
export function useDataSourceEditor({
dataSource,
allDataSources,
onSave,
onOpenChange,
}: UseDataSourceEditorParams) {
const [editingSource, setEditingSource] = useState<DataSource | null>(dataSource)
useEffect(() => {
setEditingSource(dataSource)
}, [dataSource])
const updateField = useCallback(<K extends keyof DataSource>(field: K, value: DataSource[K]) => {
setEditingSource((prev) => {
if (!prev) return prev
return { ...prev, [field]: value }
})
}, [])
const addDependency = useCallback((depId: string) => {
setEditingSource((prev) => {
if (!prev || prev.type !== 'computed') return prev
const deps = prev.dependencies || []
if (deps.includes(depId)) return prev
return { ...prev, dependencies: [...deps, depId] }
})
}, [])
const removeDependency = useCallback((depId: string) => {
setEditingSource((prev) => {
if (!prev || prev.type !== 'computed') return prev
const deps = prev.dependencies || []
return { ...prev, dependencies: deps.filter((id) => id !== depId) }
})
}, [])
const handleSave = useCallback(() => {
if (!editingSource) return
onSave(editingSource)
onOpenChange(false)
}, [editingSource, onOpenChange, onSave])
const availableDeps = useMemo(() => {
if (!editingSource) return []
return allDataSources.filter(
(ds) => ds.id !== editingSource.id && ds.type !== 'computed',
)
}, [allDataSources, editingSource])
const selectedDeps = useMemo(() => editingSource?.dependencies || [], [editingSource])
const unselectedDeps = useMemo(() => {
if (!editingSource) return []
return availableDeps.filter((ds) => !selectedDeps.includes(ds.id))
}, [availableDeps, editingSource, selectedDeps])
return {
editingSource,
updateField,
addDependency,
removeDependency,
handleSave,
availableDeps,
selectedDeps,
unselectedDeps,
}
}

View File

@@ -0,0 +1,55 @@
/// <reference path="../global.d.ts" />
import { useCallback } from 'react'
import { toast } from 'sonner'
import templateUi from '@/config/template-ui.json'
import type { Template } from '@/hooks/data/use-seed-templates'
const ui = templateUi.explorer
type TemplateData = Record<string, any>
const triggerJsonDownload = (data: TemplateData, filename: string) => {
const dataStr = JSON.stringify(data, null, 2)
const blob = new Blob([dataStr], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = filename
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
}
export function useTemplateExplorerActions(selectedTemplate?: Template) {
const copyToClipboard = useCallback((text: string) => {
navigator.clipboard.writeText(text)
toast.success(ui.toasts.copySuccess)
}, [])
const downloadJSON = useCallback(() => {
if (!selectedTemplate) return
triggerJsonDownload(selectedTemplate.data, `${selectedTemplate.id}-template.json`)
toast.success(ui.toasts.downloadSuccess)
}, [selectedTemplate])
const exportCurrentData = useCallback(async () => {
const keys = await window.spark.kv.keys()
const data: Record<string, any> = {}
for (const key of keys) {
data[key] = await window.spark.kv.get(key)
}
triggerJsonDownload(data, 'current-project-data.json')
toast.success(ui.toasts.exportSuccess)
}, [])
return {
copyToClipboard,
downloadJSON,
exportCurrentData
}
}

View File

@@ -6,9 +6,16 @@ export interface ComponentDefinition {
category: 'layout' | 'input' | 'display' | 'navigation' | 'feedback' | 'data' | 'custom'
icon: string
defaultProps?: Record<string, any>
propSchema?: Record<string, ComponentPropSchema>
canHaveChildren?: boolean
}
export interface ComponentPropSchema {
type: 'string' | 'number' | 'boolean' | 'enum'
description?: string
options?: string[]
}
export const componentDefinitions: ComponentDefinition[] = [
// Layout Components
{
@@ -194,6 +201,40 @@ export const componentDefinitions: ComponentDefinition[] = [
icon: 'CircleNotch',
defaultProps: { value: 50 }
},
{
type: 'ProgressBar',
label: 'Progress Bar',
category: 'display',
icon: 'ChartBar',
defaultProps: { value: 60, max: 100, size: 'md', variant: 'default', showLabel: false },
propSchema: {
value: { type: 'number', description: 'Current progress value.' },
max: { type: 'number', description: 'Maximum progress value.' },
size: { type: 'enum', options: ['sm', 'md', 'lg'], description: 'Height size of the bar.' },
variant: {
type: 'enum',
options: ['default', 'accent', 'destructive'],
description: 'Color variant for the progress fill.',
},
showLabel: { type: 'boolean', description: 'Show percentage text below the bar.' },
className: { type: 'string', description: 'Additional class names for the container.' },
},
},
{
type: 'CircularProgress',
label: 'Circular Progress',
category: 'display',
icon: 'CircleNotch',
defaultProps: { value: 72, max: 100, size: 'md', showLabel: true },
propSchema: {
value: { type: 'number', description: 'Current progress value.' },
max: { type: 'number', description: 'Maximum progress value.' },
size: { type: 'enum', options: ['sm', 'md', 'lg', 'xl'], description: 'Rendered size.' },
showLabel: { type: 'boolean', description: 'Show percentage label in the center.' },
strokeWidth: { type: 'number', description: 'Override the default stroke width.' },
className: { type: 'string', description: 'Additional class names for the wrapper.' },
},
},
{
type: 'Spinner',
label: 'Spinner',
@@ -215,6 +256,22 @@ export const componentDefinitions: ComponentDefinition[] = [
icon: 'Minus',
defaultProps: {}
},
{
type: 'Divider',
label: 'Divider',
category: 'display',
icon: 'Minus',
defaultProps: { orientation: 'horizontal', decorative: true },
propSchema: {
orientation: {
type: 'enum',
options: ['horizontal', 'vertical'],
description: 'Divider orientation.',
},
decorative: { type: 'boolean', description: 'Whether the divider is decorative.' },
className: { type: 'string', description: 'Additional class names for the divider.' },
},
},
// Navigation Components
{
type: 'Link',

View File

@@ -91,16 +91,49 @@ Connect UI to data sources:
### Event Handling
Respond to user interactions:
Respond to user interactions using a JSON event map. Each entry maps an event name to an action definition:
```json
{
"events": {
"onClick": "save-data"
"onClick": {
"action": "save-data",
"payload": {
"source": "profile"
}
}
}
}
```
You can also pass full action arrays when needed:
```json
{
"events": {
"change": {
"actions": [
{ "id": "set-name", "type": "set-value", "target": "userName" }
]
}
}
}
```
#### Supported events
Events map directly to React handler props, so common values include:
- `click` / `onClick`
- `change` / `onChange`
- `submit` / `onSubmit`
- `focus` / `onFocus`
- `blur` / `onBlur`
- `keyDown` / `onKeyDown`
- `keyUp` / `onKeyUp`
- `mouseEnter` / `onMouseEnter`
- `mouseLeave` / `onMouseLeave`
### Looping
Render lists from arrays:
@@ -109,7 +142,8 @@ Render lists from arrays:
{
"loop": {
"source": "items",
"itemVar": "item"
"itemVar": "item",
"indexVar": "index"
},
"children": [...]
}
@@ -129,6 +163,107 @@ Show/hide based on conditions:
}
```
## 🧭 Schema Patterns & Examples
### Conditional Branches
Conditionals can return a single component, an array of components, or a string payload:
```json
{
"id": "admin-greeting",
"type": "div",
"conditional": {
"if": "user.isAdmin",
"then": [
{ "id": "admin-title", "type": "h2", "children": "Welcome, Admin!" },
{ "id": "admin-subtitle", "type": "p", "children": "You have full access." }
],
"else": "You do not have access."
}
}
```
### Loop Templates (itemVar/indexVar)
Loop containers render once and repeat their children as the template. The `itemVar` and
`indexVar` values are available in bindings and expressions inside the loop:
```json
{
"id": "activity-list",
"type": "div",
"className": "space-y-2",
"loop": {
"source": "activities",
"itemVar": "activity",
"indexVar": "idx"
},
"children": [
{
"id": "activity-row",
"type": "div",
"children": [
{ "id": "activity-index", "type": "span", "dataBinding": "idx" },
{ "id": "activity-text", "type": "span", "dataBinding": "activity.text" }
]
}
]
}
```
### Dot-Path Bindings
Bindings support `foo.bar` access for both `dataBinding` and `bindings`:
```json
{
"id": "profile-name",
"type": "p",
"dataBinding": "user.profile.fullName"
}
```
```json
{
"id": "profile-avatar",
"type": "Avatar",
"bindings": {
"src": { "source": "user", "path": "profile.avatarUrl" },
"alt": { "source": "user.profile.fullName" }
}
}
```
### Transforms
Transforms can be applied to bindings for light formatting in JSON:
```json
{
"id": "user-score",
"type": "span",
"dataBinding": {
"source": "user",
"path": "score",
"transform": "data ?? 0"
}
}
```
```json
{
"id": "user-initials",
"type": "Badge",
"bindings": {
"children": {
"source": "user.profile.fullName",
"transform": "data.split(' ').map(part => part[0]).join('')"
}
}
}
```
## 🧩 Available Components
### Layout
@@ -226,6 +361,14 @@ const component: UIComponent = {
}
```
### Hooks
Consume JSON UI data hooks from the public entrypoint:
```typescript
import { useJSONDataSource, useJSONDataSources, useJSONActions } from '@/lib/json-ui'
```
## 📦 Exports
```typescript

View File

@@ -6,25 +6,20 @@ import { Label } from '@/components/ui/label'
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Alert as ShadcnAlert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Switch } from '@/components/ui/switch'
import { Checkbox } from '@/components/ui/checkbox'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Table as ShadcnTable, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Skeleton } from '@/components/ui/skeleton'
import { Skeleton as ShadcnSkeleton } from '@/components/ui/skeleton'
import { Progress } from '@/components/ui/progress'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Heading } from '@/components/atoms/Heading'
import { Text } from '@/components/atoms/Text'
import { List as ListComponent } from '@/components/atoms/List'
import { Grid } from '@/components/atoms/Grid'
import { StatusBadge } from '@/components/atoms/StatusBadge'
import { DataCard } from '@/components/molecules/DataCard'
import { SearchInput } from '@/components/molecules/SearchInput'
import { ActionBar } from '@/components/molecules/ActionBar'
import { Avatar as ShadcnAvatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import * as AtomComponents from '@/components/atoms'
import * as MoleculeComponents from '@/components/molecules'
import jsonComponentsRegistry from '../../../json-components-registry.json'
import {
ArrowLeft, ArrowRight, Check, X, Plus, Minus, MagnifyingGlass,
Funnel, Download, Upload, PencilSimple, Trash, Eye, EyeClosed,
@@ -38,6 +33,42 @@ export interface UIComponentRegistry {
[key: string]: ComponentType<any>
}
interface JsonRegistryEntry {
name?: string
type?: string
export?: string
source?: string
}
interface JsonComponentRegistry {
components?: JsonRegistryEntry[]
}
const jsonRegistry = jsonComponentsRegistry as JsonComponentRegistry
const buildRegistryFromNames = (
names: string[],
components: Record<string, ComponentType<any>>
): UIComponentRegistry => {
return names.reduce<UIComponentRegistry>((registry, name) => {
const component = components[name]
if (component) {
registry[name] = component
}
return registry
}, {})
}
const jsonRegistryEntries = jsonRegistry.components ?? []
const atomRegistryNames = jsonRegistryEntries
.filter((entry) => entry.source === 'atoms')
.map((entry) => entry.export ?? entry.name ?? entry.type)
.filter((name): name is string => Boolean(name))
const moleculeRegistryNames = jsonRegistryEntries
.filter((entry) => entry.source === 'molecules')
.map((entry) => entry.export ?? entry.name ?? entry.type)
.filter((name): name is string => Boolean(name))
export const primitiveComponents: UIComponentRegistry = {
div: 'div' as any,
span: 'span' as any,
@@ -70,7 +101,7 @@ export const shadcnComponents: UIComponentRegistry = {
CardFooter,
Badge,
Separator,
Alert,
Alert: ShadcnAlert,
AlertDescription,
AlertTitle,
Switch,
@@ -82,7 +113,7 @@ export const shadcnComponents: UIComponentRegistry = {
SelectItem,
SelectTrigger,
SelectValue,
Table,
Table: ShadcnTable,
TableBody,
TableCell,
TableHead,
@@ -98,24 +129,28 @@ export const shadcnComponents: UIComponentRegistry = {
DialogFooter,
DialogHeader,
DialogTitle,
Skeleton,
Skeleton: ShadcnSkeleton,
Progress,
Avatar,
Avatar: ShadcnAvatar,
AvatarFallback,
AvatarImage,
}
export const customComponents: UIComponentRegistry = {
Heading,
Text,
List: ListComponent,
Grid,
StatusBadge,
DataCard,
SearchInput,
ActionBar,
export const atomComponents: UIComponentRegistry = {
...buildRegistryFromNames(
atomRegistryNames,
AtomComponents as Record<string, ComponentType<any>>
),
CircularProgress: AtomComponents.CircularProgress,
Divider: AtomComponents.Divider,
ProgressBar: AtomComponents.ProgressBar,
}
export const moleculeComponents: UIComponentRegistry = buildRegistryFromNames(
moleculeRegistryNames,
MoleculeComponents as Record<string, ComponentType<any>>
)
export const iconComponents: UIComponentRegistry = {
ArrowLeft,
ArrowRight,
@@ -160,7 +195,8 @@ export const iconComponents: UIComponentRegistry = {
export const uiComponentRegistry: UIComponentRegistry = {
...primitiveComponents,
...shadcnComponents,
...customComponents,
...atomComponents,
...moleculeComponents,
...iconComponents,
}

View File

@@ -1,157 +0,0 @@
import { ComponentType } from '@/types/json-ui'
import { Button } from '@/components/ui/button'
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select } from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Separator } from '@/components/ui/separator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Heading } from '@/components/atoms/Heading'
import { Text } from '@/components/atoms/Text'
import { TextArea } from '@/components/atoms/TextArea'
import { List } from '@/components/atoms/List'
import { Grid } from '@/components/atoms/Grid'
import { Stack } from '@/components/atoms/Stack'
import { Flex } from '@/components/atoms/Flex'
import { Container } from '@/components/atoms/Container'
import { Link } from '@/components/atoms/Link'
import { Image } from '@/components/atoms/Image'
import { Avatar } from '@/components/atoms/Avatar'
import { Code } from '@/components/atoms/Code'
import { Tag } from '@/components/atoms/Tag'
import { Spinner } from '@/components/atoms/Spinner'
import { Skeleton } from '@/components/atoms/Skeleton'
import { Slider } from '@/components/atoms/Slider'
import { NumberInput } from '@/components/atoms/NumberInput'
import { Radio } from '@/components/atoms/Radio'
import { Alert } from '@/components/atoms/Alert'
import { InfoBox } from '@/components/atoms/InfoBox'
import { EmptyState } from '@/components/atoms/EmptyState'
import { Table } from '@/components/atoms/Table'
import { KeyValue } from '@/components/atoms/KeyValue'
import { StatCard } from '@/components/atoms/StatCard'
import { StatusBadge } from '@/components/atoms/StatusBadge'
import { DataCard } from '@/components/molecules/DataCard'
import { SearchInput } from '@/components/molecules/SearchInput'
import { ActionBar } from '@/components/molecules/ActionBar'
import { AppBranding } from '@/components/molecules/AppBranding'
import { LabelWithBadge } from '@/components/molecules/LabelWithBadge'
import { EmptyEditorState } from '@/components/molecules/EmptyEditorState'
import { LoadingFallback } from '@/components/molecules/LoadingFallback'
import { LoadingState } from '@/components/molecules/LoadingState'
import { NavigationGroupHeader } from '@/components/molecules/NavigationGroupHeader'
export const componentRegistry: Record<ComponentType, any> = {
'div': 'div',
'section': 'section',
'article': 'article',
'header': 'header',
'footer': 'footer',
'main': 'main',
'Button': Button,
'Card': Card,
'Input': Input,
'TextArea': TextArea,
'Select': Select,
'Checkbox': Checkbox,
'Radio': Radio,
'Switch': Switch,
'Slider': Slider,
'NumberInput': NumberInput,
'Badge': Badge,
'Tag': Tag,
'Progress': Progress,
'Separator': Separator,
'Tabs': Tabs,
'Dialog': 'div',
'Text': Text,
'Heading': Heading,
'Label': Label,
'Link': Link,
'Image': Image,
'Avatar': Avatar,
'Code': Code,
'Spinner': Spinner,
'Skeleton': Skeleton,
'List': List,
'Grid': Grid,
'Stack': Stack,
'Flex': Flex,
'Container': Container,
'Alert': Alert,
'InfoBox': InfoBox,
'EmptyState': EmptyState,
'StatusBadge': StatusBadge,
'Table': Table,
'KeyValue': KeyValue,
'StatCard': StatCard,
'DataCard': DataCard,
'SearchInput': SearchInput,
'ActionBar': ActionBar,
'AppBranding': AppBranding,
'LabelWithBadge': LabelWithBadge,
'EmptyEditorState': EmptyEditorState,
'LoadingFallback': LoadingFallback,
'LoadingState': LoadingState,
'NavigationGroupHeader': NavigationGroupHeader,
}
export const cardSubComponents = {
'CardHeader': CardHeader,
'CardTitle': CardTitle,
'CardDescription': CardDescription,
'CardContent': CardContent,
'CardFooter': CardFooter,
}
export const tabsSubComponents = {
'TabsContent': TabsContent,
'TabsList': TabsList,
'TabsTrigger': TabsTrigger,
}
export const customComponents = {
'StatusBadge': StatusBadge,
'DataCard': DataCard,
'SearchInput': SearchInput,
'ActionBar': ActionBar,
'StatCard': StatCard,
'KeyValue': KeyValue,
'Table': Table,
'Alert': Alert,
'InfoBox': InfoBox,
'EmptyState': EmptyState,
'AppBranding': AppBranding,
'LabelWithBadge': LabelWithBadge,
'EmptyEditorState': EmptyEditorState,
'LoadingFallback': LoadingFallback,
'LoadingState': LoadingState,
'NavigationGroupHeader': NavigationGroupHeader,
}
export function getComponent(type: ComponentType | string): any {
if (type in componentRegistry) {
return componentRegistry[type as ComponentType]
}
if (type in cardSubComponents) {
return cardSubComponents[type as keyof typeof cardSubComponents]
}
if (type in tabsSubComponents) {
return tabsSubComponents[type as keyof typeof tabsSubComponents]
}
if (type in customComponents) {
return customComponents[type as keyof typeof customComponents]
}
return 'div'
}
export const getUIComponent = getComponent

View File

@@ -1,51 +1,125 @@
import { createElement, useMemo } from 'react'
import { UIComponent, Binding, ComponentRendererProps } from '@/types/json-ui'
import { createElement, useMemo, Fragment } from 'react'
import { UIComponent, Binding, ComponentRendererProps, EventHandler, JSONEventDefinition, JSONEventMap } from '@/types/json-ui'
import { getUIComponent } from './component-registry'
import { resolveDataBinding, evaluateCondition } from './utils'
function resolveBinding(binding: Binding, data: Record<string, unknown>): unknown {
let value: unknown = data[binding.source]
if (binding.path) {
const keys = binding.path.split('.')
for (const key of keys) {
if (value && typeof value === 'object') {
value = (value as Record<string, unknown>)[key]
} else {
value = undefined
break
}
}
}
if (binding.transform) {
value = binding.transform(value)
}
return value
function resolveBinding(
binding: Binding,
data: Record<string, unknown>,
context: Record<string, unknown>,
state?: Record<string, unknown>
): unknown {
return resolveDataBinding(binding, data, context, { state, bindings: context })
}
export function ComponentRenderer({ component, data, onEvent }: ComponentRendererProps) {
export function ComponentRenderer({ component, data, context = {}, state, onEvent }: ComponentRendererProps) {
const mergedData = useMemo(() => ({ ...data, ...context }), [data, context])
const resolvedEventHandlers = useMemo(() => {
const normalizeEventName = (eventName: string) =>
eventName.startsWith('on') && eventName.length > 2
? `${eventName.charAt(2).toLowerCase()}${eventName.slice(3)}`
: eventName
const normalizeDefinition = (eventName: string, definition: JSONEventDefinition | string): EventHandler | null => {
if (!definition) return null
const normalizedEventName = normalizeEventName(eventName)
if (typeof definition === 'string') {
return {
event: normalizedEventName,
actions: [{ id: definition, type: 'custom' }],
}
}
if (definition.actions?.length) {
const actions = definition.payload
? definition.actions.map((action) => ({
...action,
params: action.params ?? definition.payload,
}))
: definition.actions
return {
event: normalizedEventName,
actions,
condition: definition.condition,
}
}
if (definition.action) {
return {
event: normalizedEventName,
actions: [{ id: definition.action, type: 'custom', params: definition.payload }],
condition: definition.condition,
}
}
return null
}
if (!component.events) {
return [] as EventHandler[]
}
if (Array.isArray(component.events)) {
return component.events.map((handler) => ({
...handler,
event: normalizeEventName(handler.event),
}))
}
const eventMap = component.events as JSONEventMap
return Object.entries(eventMap).flatMap(([eventName, definition]) => {
if (Array.isArray(definition)) {
return definition
.map((entry) => normalizeDefinition(eventName, entry))
.filter(Boolean) as EventHandler[]
}
const normalized = normalizeDefinition(eventName, definition)
return normalized ? [normalized] : []
})
}, [component.events])
const resolvedProps = useMemo(() => {
const resolved: Record<string, unknown> = { ...component.props }
if (component.bindings) {
Object.entries(component.bindings).forEach(([propName, binding]) => {
resolved[propName] = resolveBinding(binding, data)
resolved[propName] = resolveBinding(binding, data, context, state)
})
}
if (component.dataBinding) {
const boundData = resolveDataBinding(component.dataBinding, data, context, { state, bindings: context })
if (boundData !== undefined) {
resolved.value = boundData
resolved.data = boundData
}
}
if (component.events && onEvent) {
component.events.forEach(handler => {
if (resolvedEventHandlers.length > 0 && onEvent) {
resolvedEventHandlers.forEach(handler => {
resolved[`on${handler.event.charAt(0).toUpperCase()}${handler.event.slice(1)}`] = (e: unknown) => {
if (!handler.condition || handler.condition(data)) {
onEvent(component.id, handler.event, e)
const conditionMet = !handler.condition
|| (typeof handler.condition === 'function'
? handler.condition(mergedData as Record<string, any>)
: evaluateCondition(handler.condition, mergedData as Record<string, any>))
if (conditionMet) {
onEvent(component.id, handler, e)
}
}
})
}
if (component.className) {
resolved.className = resolved.className
? `${resolved.className} ${component.className}`
: component.className
}
if (component.style) {
resolved.style = { ...(resolved.style as Record<string, unknown>), ...component.style }
}
return resolved
}, [component, data, onEvent])
}, [component, data, context, state, mergedData, onEvent])
const Component = getUIComponent(component.type)
@@ -54,21 +128,131 @@ export function ComponentRenderer({ component, data, onEvent }: ComponentRendere
return null
}
const renderChildren = (
children: UIComponent[] | string | undefined,
renderContext: Record<string, unknown>
) => {
if (!children) return null
if (typeof children === 'string') {
return children
}
return children.map((child, index) => (
<Fragment key={typeof child === 'string' ? `text-${index}` : child.id || index}>
{typeof child === 'string'
? child
: (
<ComponentRenderer
component={child}
data={data}
context={renderContext}
state={state}
onEvent={onEvent}
/>
)}
</Fragment>
))
}
const renderBranch = (
branch: UIComponent | (UIComponent | string)[] | string | undefined,
renderContext: Record<string, unknown>
) => {
if (branch === undefined) return null
if (typeof branch === 'string') {
return branch
}
if (Array.isArray(branch)) {
return branch.map((child, index) => (
<Fragment key={typeof child === 'string' ? `text-${index}` : child.id || index}>
{typeof child === 'string'
? child
: (
<ComponentRenderer
component={child}
data={data}
context={renderContext}
state={state}
onEvent={onEvent}
/>
)}
</Fragment>
))
}
return (
<ComponentRenderer
component={branch}
data={data}
context={renderContext}
state={state}
onEvent={onEvent}
/>
)
}
const renderConditionalContent = (renderContext: Record<string, unknown>) => {
if (!component.conditional) return undefined
const conditionMet = evaluateCondition(component.conditional.if, { ...data, ...renderContext } as Record<string, any>)
if (conditionMet) {
if (component.conditional.then !== undefined) {
return renderBranch(component.conditional.then as UIComponent | (UIComponent | string)[] | string, renderContext)
}
return undefined
}
if (component.conditional.else !== undefined) {
return renderBranch(component.conditional.else as UIComponent | (UIComponent | string)[] | string, renderContext)
}
return null
}
if (component.loop) {
const items = resolveDataBinding(component.loop.source, data, context, { state, bindings: context }) || []
const loopChildren = items.map((item: unknown, index: number) => {
const loopContext = {
...context,
[component.loop!.itemVar]: item,
...(component.loop!.indexVar ? { [component.loop!.indexVar]: index } : {}),
}
if (component.conditional) {
const conditionalContent = renderConditionalContent(loopContext)
if (conditionalContent !== undefined) {
return (
<Fragment key={`${component.id}-${index}`}>{conditionalContent}</Fragment>
)
}
}
if (component.condition) {
const conditionValue = resolveBinding(component.condition, data, loopContext, state)
if (!conditionValue) {
return null
}
}
return (
<Fragment key={`${component.id}-${index}`}>
{renderChildren(component.children, loopContext)}
</Fragment>
)
})
return createElement(Component, resolvedProps, loopChildren)
}
if (component.conditional) {
const conditionalContent = renderConditionalContent(mergedData)
if (conditionalContent !== undefined) {
return conditionalContent
}
}
if (component.condition) {
const conditionValue = resolveBinding(component.condition, data)
const conditionValue = resolveBinding(component.condition, data, context, state)
if (!conditionValue) {
return null
}
}
const children = component.children?.map((child, index) => (
<ComponentRenderer
key={child.id || index}
component={child}
data={data}
onEvent={onEvent}
/>
))
return createElement(Component, resolvedProps, children)
return createElement(Component, resolvedProps, renderChildren(component.children, context))
}

View File

@@ -1,5 +1,6 @@
export { JSONUIRenderer, JSONFormRenderer } from './renderer'
export { getUIComponent, uiComponentRegistry, registerComponent } from './component-registry'
export * from './hooks'
export * from './schema'
export * from './utils'
export * from './validator'

View File

@@ -2,6 +2,7 @@ import { useCallback } from 'react'
import { PageSchema } from '@/types/json-ui'
import { useDataSources } from '@/hooks/data/use-data-sources'
import { useActionExecutor } from '@/hooks/ui/use-action-executor'
import { useAppSelector } from '@/store'
import { ComponentRenderer } from './component-renderer'
interface PageRendererProps {
@@ -11,6 +12,7 @@ interface PageRendererProps {
export function PageRenderer({ schema, onCustomAction }: PageRendererProps) {
const { data, updateData, updatePath } = useDataSources(schema.dataSources)
const state = useAppSelector((rootState) => rootState)
const context = {
data,
@@ -20,17 +22,10 @@ export function PageRenderer({ schema, onCustomAction }: PageRendererProps) {
const { executeActions } = useActionExecutor(context)
const handleEvent = useCallback((componentId: string, event: string, eventData: any) => {
const component = findComponentById(schema.components, componentId)
if (!component) return
const handler = component.events?.find(h => h.event === event)
if (!handler) return
if (handler.condition && !handler.condition(data)) return
const handleEvent = useCallback((_componentId: string, handler: { actions: any[] }, eventData: any) => {
if (!handler?.actions?.length) return
executeActions(handler.actions, eventData)
}, [schema.components, data, executeActions])
}, [executeActions])
return (
<div className="h-full w-full">
@@ -39,20 +34,10 @@ export function PageRenderer({ schema, onCustomAction }: PageRendererProps) {
key={component.id || index}
component={component}
data={data}
state={state}
onEvent={handleEvent}
/>
))}
</div>
)
}
function findComponentById(components: any[], id: string): any {
for (const component of components) {
if (component.id === id) return component
if (component.children) {
const found = findComponentById(component.children, id)
if (found) return found
}
}
return null
}

View File

@@ -1,7 +1,15 @@
import React, { useCallback } from 'react'
import type { EventHandler, JSONFormRendererProps, JSONUIRendererProps, UIComponent } from './types'
import type {
Action,
EventHandler,
JSONEventDefinition,
JSONEventMap,
JSONFormRendererProps,
JSONUIRendererProps,
UIComponent,
} from './types'
import { getUIComponent } from './component-registry'
import { resolveDataBinding, evaluateCondition, mergeClassNames } from './utils'
import { resolveDataBinding, evaluateCondition } from './utils'
import { cn } from '@/lib/utils'
export function JSONUIRenderer({
@@ -10,110 +18,282 @@ export function JSONUIRenderer({
onAction,
context = {}
}: JSONUIRendererProps) {
if (component.conditional) {
const conditionMet = evaluateCondition(component.conditional.if, { ...dataMap, ...context })
if (!conditionMet) {
return component.conditional.else ? (
<JSONUIRenderer
component={component.conditional.else as UIComponent}
dataMap={dataMap}
onAction={onAction}
context={context}
/>
) : null
const renderChildren = (
children: UIComponent[] | string | undefined,
renderContext: Record<string, unknown>
) => {
if (!children) return null
if (typeof children === 'string') {
return children
}
}
if (component.loop) {
const items = resolveDataBinding(component.loop.source, dataMap) || []
return (
<>
{items.map((item: any, index: number) => {
const loopContext = {
...context,
[component.loop!.itemVar]: item,
...(component.loop!.indexVar ? { [component.loop!.indexVar]: index } : {}),
}
return (
<JSONUIRenderer
key={`${component.id}-${index}`}
component={component}
dataMap={dataMap}
onAction={onAction}
context={loopContext}
/>
)}
})}
</>
)
}
const Component = getUIComponent(component.type)
if (!Component) {
console.warn(`Component type "${component.type}" not found in registry`)
return null
}
const props: Record<string, any> = { ...component.props }
if (component.dataBinding) {
const boundData = resolveDataBinding(component.dataBinding, dataMap)
if (boundData !== undefined) {
props.value = boundData
props.data = boundData
}
}
if (component.events) {
Object.entries(component.events).forEach(([eventName, handler]) => {
props[eventName] = (event?: any) => {
if (onAction) {
const eventHandler = typeof handler === 'string'
? { action: handler } as EventHandler
: handler as EventHandler
onAction(eventHandler, event)
}
}
})
}
if (component.className) {
props.className = cn(props.className, component.className)
}
if (component.style) {
props.style = { ...props.style, ...component.style }
}
const renderChildren = () => {
if (!component.children) return null
if (typeof component.children === 'string') {
return component.children
}
return component.children.map((child, index) => (
<JSONUIRenderer
key={child.id || `child-${index}`}
component={child}
dataMap={dataMap}
onAction={onAction}
context={context}
/>
return children.map((child, index) => (
<React.Fragment key={child.id || `child-${index}`}>
{renderNode(child, renderContext)}
</React.Fragment>
))
}
if (typeof Component === 'string') {
return React.createElement(Component, props, renderChildren())
const renderNode = (
node: UIComponent | string,
renderContext: Record<string, unknown>
) => {
if (typeof node === 'string') {
return node
}
return (
<JSONUIRenderer
component={node}
dataMap={dataMap}
onAction={onAction}
context={renderContext}
/>
)
}
return (
<Component {...props}>
{renderChildren()}
</Component>
)
const renderBranch = (
branch: UIComponent | (UIComponent | string)[] | string | undefined,
renderContext: Record<string, unknown>
) => {
if (branch === undefined) return null
if (Array.isArray(branch)) {
return branch.map((item, index) => (
<React.Fragment key={typeof item === 'string' ? `text-${index}` : item.id || `branch-${index}`}>
{renderNode(item, renderContext)}
</React.Fragment>
))
}
return renderNode(branch, renderContext)
}
const renderConditionalBranch = (
branch: UIComponent | (UIComponent | string)[] | string | undefined,
renderContext: Record<string, unknown>
) => {
return renderBranch(branch, renderContext)
}
const normalizeEventName = (eventName: string) =>
eventName.startsWith('on') && eventName.length > 2
? `${eventName.charAt(2).toLowerCase()}${eventName.slice(3)}`
: eventName
const getEventPropName = (eventName: string) =>
eventName.startsWith('on')
? eventName
: `on${eventName.charAt(0).toUpperCase()}${eventName.slice(1)}`
const normalizeEventDefinition = (
eventName: string,
definition: JSONEventDefinition | string
): EventHandler | null => {
if (!definition) return null
const normalizedEvent = normalizeEventName(eventName)
if (typeof definition === 'string') {
return {
event: normalizedEvent,
actions: [{ id: definition, type: 'custom' }],
}
}
if (definition.actions && Array.isArray(definition.actions)) {
const actions = definition.payload
? definition.actions.map((action) => ({
...action,
params: action.params ?? definition.payload,
}))
: definition.actions
return {
event: normalizedEvent,
actions,
condition: definition.condition,
}
}
if (definition.action) {
return {
event: normalizedEvent,
actions: [{ id: definition.action, type: 'custom', params: definition.payload }],
condition: definition.condition,
}
}
return null
}
const applyEventHandlers = (
props: Record<string, any>,
renderContext: Record<string, unknown>
) => {
const eventHandlers: EventHandler[] = Array.isArray(component.events)
? component.events.map((handler) => ({
...handler,
event: normalizeEventName(handler.event),
}))
: component.events
? Object.entries(component.events as JSONEventMap).flatMap(([eventName, handler]) => {
if (Array.isArray(handler)) {
return handler
.map((entry) => normalizeEventDefinition(eventName, entry))
.filter(Boolean) as EventHandler[]
}
const normalized = normalizeEventDefinition(eventName, handler)
return normalized ? [normalized] : []
})
: []
if (eventHandlers.length > 0) {
eventHandlers.forEach((handler) => {
const propName = getEventPropName(handler.event)
props[propName] = (event?: any) => {
if (handler.condition) {
const conditionMet = typeof handler.condition === 'function'
? handler.condition({ ...dataMap, ...renderContext })
: evaluateCondition(handler.condition, { ...dataMap, ...renderContext })
if (!conditionMet) return
}
onAction?.(handler.actions, event)
}
})
}
}
const resolveProps = (renderContext: Record<string, unknown>) => {
const props: Record<string, any> = { ...component.props }
if (component.bindings) {
Object.entries(component.bindings).forEach(([propName, binding]) => {
props[propName] = resolveDataBinding(binding, dataMap, renderContext)
})
}
if (component.dataBinding) {
const boundData = resolveDataBinding(component.dataBinding, dataMap, renderContext)
if (boundData !== undefined) {
props.value = boundData
props.data = boundData
}
}
if (component.className) {
props.className = cn(props.className, component.className)
}
if (component.style) {
props.style = { ...props.style, ...component.style }
}
return props
}
const renderWithContext = (renderContext: Record<string, unknown>) => {
if (component.conditional) {
const conditionMet = evaluateCondition(component.conditional.if, { ...dataMap, ...renderContext })
if (conditionMet) {
if (component.conditional.then !== undefined) {
return renderConditionalBranch(
component.conditional.then as UIComponent | (UIComponent | string)[] | string,
renderContext
)
}
} else {
if (component.conditional.else !== undefined) {
return renderConditionalBranch(
component.conditional.else as UIComponent | (UIComponent | string)[] | string,
renderContext
)
}
return null
}
}
const Component = getUIComponent(component.type)
if (!Component) {
console.warn(`Component type "${component.type}" not found in registry`)
return null
}
const props = resolveProps(renderContext)
applyEventHandlers(props, renderContext)
if (typeof Component === 'string') {
return React.createElement(Component, props, renderChildren(component.children, renderContext))
}
return (
<Component {...props}>
{renderChildren(component.children, renderContext)}
</Component>
)
}
if (component.loop) {
const items = resolveDataBinding(component.loop.source, dataMap, context) || []
const Component = getUIComponent(component.type)
if (!Component) {
console.warn(`Component type "${component.type}" not found in registry`)
return null
}
const containerProps = resolveProps(context)
applyEventHandlers(containerProps, context)
const loopChildren = items.map((item: any, index: number) => {
const loopContext = {
...context,
[component.loop!.itemVar]: item,
...(component.loop!.indexVar ? { [component.loop!.indexVar]: index } : {}),
}
let content = renderChildren(component.children, loopContext)
if (component.conditional) {
const conditionMet = evaluateCondition(component.conditional.if, { ...dataMap, ...loopContext })
if (conditionMet) {
if (component.conditional.then !== undefined) {
content = renderConditionalBranch(
component.conditional.then as UIComponent | (UIComponent | string)[] | string,
loopContext
)
}
} else {
if (component.conditional.else !== undefined) {
content = renderConditionalBranch(
component.conditional.else as UIComponent | (UIComponent | string)[] | string,
loopContext
)
} else {
content = null
}
}
}
return (
<React.Fragment key={`${component.id}-${index}`}>
{content}
</React.Fragment>
)
})
if (typeof Component === 'string') {
return React.createElement(Component, containerProps, loopChildren)
}
return (
<Component {...containerProps}>
{loopChildren}
</Component>
)
}
return renderWithContext(context)
}
export function JSONFormRenderer({ formData, fields, onSubmit, onChange }: JSONFormRendererProps) {
@@ -140,12 +320,18 @@ export function JSONFormRenderer({ formData, fields, onSubmit, onChange }: JSONF
type: field.type,
value: formData[field.name] || field.defaultValue || '',
},
events: {
onChange: {
action: 'field-change',
params: { field: field.name },
events: [
{
event: 'change',
actions: [
{
id: `field-change-${field.name}`,
type: 'set-value',
target: field.name,
},
],
},
},
],
}
return (
@@ -159,11 +345,13 @@ export function JSONFormRenderer({ formData, fields, onSubmit, onChange }: JSONF
<JSONUIRenderer
component={fieldComponent}
dataMap={{}}
onAction={(handler, event) => {
if (handler.action === 'field-change') {
const targetValue = (event as { target?: { value?: unknown } } | undefined)?.target?.value
handleFieldChange(field.name, targetValue)
}
onAction={(actions, event) => {
actions.forEach((action) => {
if (action.type === 'set-value' && action.target === field.name) {
const targetValue = (event as { target?: { value?: unknown } } | undefined)?.target?.value
handleFieldChange(field.name, targetValue)
}
})
}}
/>
</div>

View File

@@ -15,12 +15,55 @@ export const DataBindingSchema = z.object({
transform: z.string().optional(),
})
export const EventHandlerSchema = z.object({
action: z.string(),
export const ActionSchema = z.object({
id: z.string(),
type: z.enum([
'create',
'update',
'delete',
'navigate',
'show-toast',
'open-dialog',
'close-dialog',
'set-value',
'toggle-value',
'increment',
'decrement',
'custom',
]),
target: z.string().optional(),
path: z.string().optional(),
value: z.any().optional(),
params: z.record(z.string(), z.any()).optional(),
compute: z.any().optional(),
expression: z.string().optional(),
valueTemplate: z.record(z.string(), z.any()).optional(),
message: z.string().optional(),
variant: z.enum(['success', 'error', 'info', 'warning']).optional(),
})
export const EventHandlerSchema = z.object({
event: z.string(),
actions: z.array(ActionSchema),
condition: z.any().optional(),
})
export const JSONEventDefinitionSchema = z.object({
action: z.string().optional(),
actions: z.array(ActionSchema).optional(),
payload: z.record(z.string(), z.any()).optional(),
condition: z.any().optional(),
})
export const JSONEventMapSchema = z.record(
z.string(),
z.union([
z.string(),
JSONEventDefinitionSchema,
z.array(JSONEventDefinitionSchema),
])
)
export const ConditionalSchema = z.object({
if: z.string(),
then: z.any().optional(),
@@ -33,6 +76,7 @@ export const UIComponentSchema: any = z.object({
props: z.record(z.string(), z.any()).optional(),
className: z.string().optional(),
style: z.record(z.string(), z.any()).optional(),
bindings: z.record(z.string(), DataBindingSchema).optional(),
children: z.union([
z.string(),
z.array(z.lazy(() => UIComponentSchema)),
@@ -41,10 +85,7 @@ export const UIComponentSchema: any = z.object({
z.string(),
DataBindingSchema,
]).optional(),
events: z.record(z.string(), z.union([
z.string(),
EventHandlerSchema,
])).optional(),
events: z.union([z.array(EventHandlerSchema), JSONEventMapSchema]).optional(),
conditional: ConditionalSchema.optional(),
loop: z.object({
source: z.string(),
@@ -215,7 +256,10 @@ export type DataSourceConfig<T = unknown> =
export type UIValue = z.infer<typeof UIValueSchema>
export type DataBinding = z.infer<typeof DataBindingSchema>
export type Action = z.infer<typeof ActionSchema>
export type EventHandler = z.infer<typeof EventHandlerSchema>
export type JSONEventDefinition = z.infer<typeof JSONEventDefinitionSchema>
export type JSONEventMap = z.infer<typeof JSONEventMapSchema>
export type Conditional = z.infer<typeof ConditionalSchema>
export type UIComponent = z.infer<typeof UIComponentSchema>
export type FormField = z.infer<typeof FormFieldSchema>

View File

@@ -1,11 +1,11 @@
import type { EventHandler, FormField, UIComponent } from './schema'
import type { Action, EventHandler, FormField, JSONEventDefinition, JSONEventMap, UIComponent } from './schema'
export type { EventHandler, FormField, UIComponent }
export type { Action, EventHandler, FormField, JSONEventDefinition, JSONEventMap, UIComponent }
export interface JSONUIRendererProps {
component: UIComponent
dataMap?: Record<string, unknown>
onAction?: (handler: EventHandler, event?: unknown) => void
onAction?: (actions: Action[], event?: unknown) => void
context?: Record<string, unknown>
}

View File

@@ -1,14 +1,58 @@
export function resolveDataBinding(binding: string | { source: string; path?: string }, dataMap: Record<string, any>): any {
type BindingTransform = string | ((data: unknown) => unknown)
interface BindingSourceOptions {
state?: Record<string, any>
bindings?: Record<string, any>
}
export function resolveDataBinding(
binding: string | { source: string; sourceType?: 'data' | 'bindings' | 'state'; path?: string; transform?: BindingTransform },
dataMap: Record<string, any>,
context: Record<string, any> = {},
options: BindingSourceOptions = {},
): any {
const mergedContext = { ...dataMap, ...context }
const stateSource = options.state ?? {}
const bindingsSource = options.bindings ?? context
if (typeof binding === 'string') {
return dataMap[binding]
if (binding.startsWith('state.')) {
return getNestedValue(stateSource, binding.slice('state.'.length))
}
if (binding.startsWith('bindings.')) {
return getNestedValue(bindingsSource, binding.slice('bindings.'.length))
}
if (binding.includes('.')) {
return getNestedValue(mergedContext, binding)
}
return mergedContext[binding]
}
const { source, path } = binding
const data = dataMap[source]
if (!path) return data
return getNestedValue(data, path)
const { source, sourceType, path, transform } = binding
const sourceContext =
sourceType === 'state'
? stateSource
: sourceType === 'bindings'
? bindingsSource
: mergedContext
const sourceValue = source.includes('.')
? getNestedValue(sourceContext, source)
: sourceContext[source]
const resolvedValue = path ? getNestedValue(sourceValue, path) : sourceValue
return applyTransform(resolvedValue, transform)
}
function applyTransform(value: unknown, transform?: BindingTransform) {
if (!transform) {
return value
}
if (typeof transform === 'function') {
return transform(value)
}
return transformData(value, transform)
}
export function getNestedValue(obj: any, path: string): any {

View File

@@ -83,11 +83,11 @@ function checkComponentTree(
seenIds.add(component.id)
}
if (component.dataBinding && !component.dataBinding.source) {
if (component.dataBinding) {
const bindingPath = typeof component.dataBinding === 'string'
? component.dataBinding.split('.')[0]
: ''
: component.dataBinding.source?.split('.')[0]
if (bindingPath) {
result.warnings.push({
path: `${path}.${component.id}`,

View File

@@ -1,4 +1,4 @@
import { ReactNode } from 'react'
import { createElement, type ComponentType, type ReactNode } from 'react'
import { cn } from '@/lib/utils'
import { Component as ComponentSchema, Layout } from '@/schemas/ui-schema'
import { useDataBinding, useEventHandlers, useComponentRegistry } from '@/hooks/ui'
@@ -7,6 +7,7 @@ interface SchemaRendererProps {
schema: ComponentSchema
data: Record<string, any>
functions?: Record<string, (...args: any[]) => any>
componentRegistry?: Record<string, ComponentType<any>>
}
interface LayoutRendererProps {
@@ -51,10 +52,10 @@ function LayoutRenderer({ layout, children }: LayoutRendererProps) {
return <div className={getLayoutClasses()}>{children}</div>
}
export function SchemaRenderer({ schema, data, functions = {} }: SchemaRendererProps) {
export function SchemaRenderer({ schema, data, functions = {}, componentRegistry }: SchemaRendererProps) {
const { resolveCondition, resolveProps, resolveBinding } = useDataBinding({ data })
const { resolveEvents } = useEventHandlers({ functions })
const { getComponent, getIcon } = useComponentRegistry()
const { getComponent, getIcon } = useComponentRegistry({ customComponents: componentRegistry })
if (schema.condition && !resolveCondition(schema.condition)) {
return null
@@ -76,6 +77,7 @@ export function SchemaRenderer({ schema, data, functions = {} }: SchemaRendererP
schema={{ ...schema, repeat: undefined }}
data={itemData}
functions={functions}
componentRegistry={componentRegistry}
/>
)
})}
@@ -83,6 +85,21 @@ export function SchemaRenderer({ schema, data, functions = {} }: SchemaRendererP
)
}
const props = resolveProps(schema.props || {})
const events = resolveEvents(schema.events)
const combinedProps = { ...props, ...events }
if (schema.binding) {
const iconName = resolveBinding(schema.binding)
if (typeof iconName === 'string' && schema.type === 'Icon') {
const IconComponent = getComponent(iconName)
if (IconComponent) {
return createElement(IconComponent, combinedProps)
}
return getIcon(iconName, combinedProps)
}
}
const Component = getComponent(schema.type)
if (!Component) {
@@ -96,23 +113,13 @@ export function SchemaRenderer({ schema, data, functions = {} }: SchemaRendererP
)
}
const props = resolveProps(schema.props || {})
const events = resolveEvents(schema.events)
const combinedProps = { ...props, ...events }
if (schema.binding) {
const iconName = resolveBinding(schema.binding)
if (iconName && schema.type === 'Icon') {
return getIcon(iconName, props)
}
}
const children = schema.children?.map((child, index) => (
<SchemaRenderer
key={child.id || index}
schema={child}
data={data}
functions={functions}
componentRegistry={componentRegistry}
/>
))
@@ -129,9 +136,10 @@ interface PageRendererProps {
}
data: Record<string, any>
functions?: Record<string, (...args: any[]) => any>
componentRegistry?: Record<string, ComponentType<any>>
}
export function PageRenderer({ schema, data, functions = {} }: PageRendererProps) {
export function PageRenderer({ schema, data, functions = {}, componentRegistry }: PageRendererProps) {
return (
<LayoutRenderer layout={schema.layout}>
{schema.components.map((component) => (
@@ -140,6 +148,7 @@ export function PageRenderer({ schema, data, functions = {} }: PageRendererProps
schema={component}
data={data}
functions={functions}
componentRegistry={componentRegistry}
/>
))}
</LayoutRenderer>

178
src/schemas/page-schemas.ts Normal file
View File

@@ -0,0 +1,178 @@
import type { PageSchema } from '@/types/json-ui'
export const stateBindingsDemoSchema: PageSchema = {
id: 'state-bindings-demo',
name: 'State & Bindings Demo',
layout: {
type: 'single',
},
dataSources: [
{
id: 'statusItems',
type: 'static',
defaultValue: ['KV Ready', 'Components Loaded', 'Sync Enabled'],
},
],
components: [
{
id: 'state-demo-root',
type: 'div',
props: {
className: 'space-y-4 rounded-lg border border-border bg-card p-6',
},
children: [
{
id: 'state-demo-title',
type: 'Heading',
props: {
className: 'text-xl font-semibold',
children: 'Renderer State Binding Demo',
},
},
{
id: 'state-demo-theme',
type: 'Text',
props: {
className: 'text-sm text-muted-foreground',
},
bindings: {
children: {
sourceType: 'state',
source: 'settings',
path: 'settings.theme',
},
},
},
{
id: 'state-demo-list',
type: 'div',
props: {
className: 'space-y-2',
},
loop: {
source: 'statusItems',
itemVar: 'statusItem',
},
children: [
{
id: 'state-demo-list-item',
type: 'Text',
props: {
className: 'text-sm',
},
bindings: {
children: {
sourceType: 'bindings',
source: 'statusItem',
},
},
},
],
},
],
},
],
}
export const progressIndicatorsDemoSchema: PageSchema = {
id: 'progress-indicators-demo',
name: 'Progress Indicators Demo',
layout: {
type: 'single',
},
dataSources: [],
components: [
{
id: 'progress-demo-root',
type: 'div',
props: {
className: 'space-y-6 rounded-lg border border-border bg-card p-6',
},
children: [
{
id: 'progress-demo-title',
type: 'Heading',
props: {
className: 'text-xl font-semibold',
children: 'Progress Indicators',
},
},
{
id: 'progress-demo-subtitle',
type: 'Text',
props: {
className: 'text-sm text-muted-foreground',
children: 'Circular and linear progress components with JSON-friendly props.',
},
},
{
id: 'progress-demo-circular-row',
type: 'div',
props: {
className: 'flex flex-wrap items-center gap-6',
},
children: [
{
id: 'progress-demo-circular-primary',
type: 'CircularProgress',
props: {
value: 72,
size: 'md',
showLabel: true,
},
},
{
id: 'progress-demo-circular-large',
type: 'CircularProgress',
props: {
value: 45,
size: 'lg',
showLabel: true,
},
},
],
},
{
id: 'progress-demo-divider',
type: 'Divider',
props: {
orientation: 'horizontal',
decorative: true,
className: 'my-2',
},
},
{
id: 'progress-demo-linear-stack',
type: 'div',
props: {
className: 'space-y-4',
},
children: [
{
id: 'progress-demo-linear-accent',
type: 'ProgressBar',
props: {
value: 60,
max: 100,
size: 'md',
variant: 'accent',
showLabel: true,
},
},
{
id: 'progress-demo-linear-compact',
type: 'ProgressBar',
props: {
value: 35,
max: 100,
size: 'sm',
variant: 'default',
showLabel: false,
},
},
],
},
],
},
],
}

View File

@@ -0,0 +1,74 @@
{
"id": "registry-validation",
"name": "Registry Validation",
"layout": {
"type": "single"
},
"dataSources": [],
"components": [
{
"id": "root",
"type": "div",
"props": {
"className": "p-6 space-y-6"
},
"children": [
{
"id": "branding",
"type": "AppBranding",
"props": {
"title": "Registry Validation",
"subtitle": "Atoms, molecules, and primitives"
}
},
{
"id": "stack",
"type": "Stack",
"props": {
"direction": "horizontal",
"spacing": "lg",
"className": "items-stretch"
},
"children": [
{
"id": "stat-card",
"type": "StatCard",
"props": {
"title": "Active Users",
"value": "128",
"description": "Past 24 hours"
}
},
{
"id": "flex",
"type": "Flex",
"props": {
"direction": "col",
"gap": "sm",
"className": "rounded-md border p-4"
},
"children": [
{
"id": "flex-title",
"type": "Heading",
"props": {
"level": 4,
"children": "Flex Container"
}
},
{
"id": "flex-text",
"type": "Text",
"props": {
"children": "Ensures primitives and atom components resolve."
}
}
]
}
]
}
]
}
],
"globalActions": []
}

View File

@@ -1,10 +1,8 @@
import { ReactNode } from 'react'
export type ComponentType =
| 'div' | 'section' | 'article' | 'header' | 'footer' | 'main'
| 'Button' | 'Card' | 'CardHeader' | 'CardTitle' | 'CardDescription' | 'CardContent' | 'CardFooter'
| 'Input' | 'TextArea' | 'Select' | 'Checkbox' | 'Radio' | 'Switch' | 'Slider' | 'NumberInput'
| 'Badge' | 'Progress' | 'Separator' | 'Tabs' | 'Dialog'
| 'Input' | 'TextArea' | 'Textarea' | 'Select' | 'Checkbox' | 'Radio' | 'Switch' | 'Slider' | 'NumberInput'
| 'Badge' | 'CircularProgress' | 'Divider' | 'Progress' | 'ProgressBar' | 'Separator' | 'Tabs' | 'TabsContent' | 'TabsList' | 'TabsTrigger' | 'Dialog'
| 'Text' | 'Heading' | 'Label' | 'List' | 'Grid' | 'Stack' | 'Flex' | 'Container'
| 'Link' | 'Image' | 'Avatar' | 'Code' | 'Tag' | 'Spinner' | 'Skeleton'
| 'Alert' | 'InfoBox' | 'EmptyState' | 'StatusBadge'
@@ -20,6 +18,9 @@ export type ActionType =
export type DataSourceType =
| 'kv' | 'computed' | 'static'
export type BindingSourceType =
| 'data' | 'bindings' | 'state'
export interface DataSource {
id: string
type: DataSourceType
@@ -35,8 +36,9 @@ export interface Action {
target?: string
path?: string
value?: any
params?: Record<string, any>
// Legacy: function-based compute
compute?: (data: Record<string, any>, event?: any) => any
compute?: ((data: Record<string, any>, event?: any) => any) | string
// New: JSON-friendly expression (e.g., "event.target.value", "data.fieldName")
expression?: string
// New: JSON template with dynamic values
@@ -47,24 +49,51 @@ export interface Action {
export interface Binding {
source: string
sourceType?: BindingSourceType
path?: string
transform?: (value: any) => any
transform?: string | ((value: any) => any)
}
export interface EventHandler {
event: string
actions: Action[]
condition?: (data: Record<string, any>) => boolean
condition?: string | ((data: Record<string, any>) => boolean)
}
export interface JSONEventDefinition {
action?: string
actions?: Action[]
payload?: Record<string, any>
condition?: string | ((data: Record<string, any>) => boolean)
}
export type JSONEventMap = Record<string, JSONEventDefinition | JSONEventDefinition[] | string>
export interface Conditional {
if: string
then?: UIComponent | (UIComponent | string)[] | string
else?: UIComponent | (UIComponent | string)[] | string
}
export interface Loop {
source: string
itemVar: string
indexVar?: string
}
export interface UIComponent {
id: string
type: ComponentType
props?: Record<string, any>
className?: string
style?: Record<string, any>
bindings?: Record<string, Binding>
events?: EventHandler[]
children?: UIComponent[]
dataBinding?: string | Binding
events?: EventHandler[] | JSONEventMap
children?: UIComponent[] | string
condition?: Binding
conditional?: Conditional
loop?: Loop
}
export interface Layout {
@@ -98,7 +127,9 @@ export interface JSONUIContext {
export interface ComponentRendererProps {
component: UIComponent
data: Record<string, unknown>
onEvent?: (componentId: string, event: string, eventData: unknown) => void
context?: Record<string, unknown>
state?: Record<string, unknown>
onEvent?: (componentId: string, handler: EventHandler, eventData: unknown) => void
}
export type ComponentSchema = UIComponent