Skip to main content

ferro_json_ui/
lib.rs

1//! # Ferro JSON-UI
2//!
3//! Stable JSON-based server-driven UI schema types for the Ferro framework.
4//!
5//! This crate defines the typed foundation for JSON-UI: a declarative
6//! component system where the server sends JSON descriptions that are
7//! rendered to HTML. Components, actions, and visibility rules are all
8//! defined as Rust types with serde serialization and JSON Schema generation.
9//!
10//! ## Schema Structure
11//!
12//! A JSON-UI view consists of:
13//! - **Components** - UI elements (Card, Table, Form, Button, etc.)
14//! - **Actions** - Handler references with confirmations and outcomes
15//! - **Visibility** - Conditional rendering based on data conditions
16//! - **View** - Top-level container with layout and title
17//!
18//! ## Example
19//!
20//! ```rust
21//! use ferro_json_ui::{JsonUiView, ComponentNode, Component, CardProps};
22//!
23//! let view = JsonUiView::new()
24//!     .title("Users")
25//!     .component(ComponentNode {
26//!         key: "header".to_string(),
27//!         component: Component::Card(CardProps {
28//!             title: "User Management".to_string(),
29//!             description: None,
30//!             children: vec![],
31//!             max_width: None,
32//!             footer: vec![],
33//!         }),
34//!         action: None,
35//!         visibility: None,
36//!     });
37//!
38//! let json = view.to_json().unwrap();
39//! assert!(json.contains("\"$schema\":\"ferro-json-ui/v1\""));
40//! ```
41
42pub mod action;
43pub mod assets;
44pub mod component;
45pub mod config;
46pub mod data;
47pub mod layout;
48pub mod plugin;
49pub mod plugins;
50pub mod render;
51pub mod resolve;
52pub mod view;
53pub mod visibility;
54
55pub(crate) mod runtime;
56
57pub use action::{Action, ActionOutcome, ConfirmDialog, DialogVariant, HttpMethod, NotifyVariant};
58pub use assets::FERRO_BASE_CSS;
59pub use component::{
60    ActionCardProps, ActionCardVariant, AlertProps, AlertVariant, AvatarProps, BadgeProps,
61    BadgeVariant, BreadcrumbItem, BreadcrumbProps, ButtonGroupProps, ButtonProps, ButtonType,
62    ButtonVariant, CardProps, CheckboxProps, ChecklistItem, ChecklistProps, CollapsibleProps,
63    Column, ColumnFormat, Component, ComponentNode, DataTableProps, DescriptionItem,
64    DescriptionListProps, DropdownMenuAction, DropdownMenuProps, EmptyStateProps, FormMaxWidth,
65    FormProps, FormSectionProps, GapSize, GridProps, HeaderProps, IconPosition, ImageProps,
66    InputProps, InputType, KanbanBoardProps, KanbanColumnProps, KeyValueEditorProps, ModalProps,
67    NotificationDropdownProps, NotificationItem, Orientation, PageHeaderProps, PaginationProps,
68    PluginProps, ProductTileProps, ProgressProps, SelectOption, SelectProps, SeparatorProps,
69    SidebarGroup, SidebarNavItem, SidebarProps, Size, SkeletonProps, SortDirection, StatCardProps,
70    SwitchProps, Tab, TableProps, TabsProps, TextElement, TextProps, ToastProps, ToastVariant,
71};
72pub use config::JsonUiConfig;
73// resolve_path and resolve_path_string are pub(crate) — internal render pipeline helpers
74pub use layout::{
75    register_layout, render_layout, DashboardLayout, DashboardLayoutConfig, Layout, LayoutContext,
76    LayoutRegistry, NavItem, SidebarSection,
77};
78// AppLayout, AuthLayout, DefaultLayout are pub in layout.rs but not user-facing — users select
79// layouts by name string ("dashboard", "app", "auth"), not by struct.
80// navigation, sidebar, footer, global_registry are framework-internal.
81pub use plugin::{
82    collect_plugin_assets, global_plugin_registry, register_plugin, registered_plugin_types,
83    with_plugin, Asset, CollectedAssets, JsonUiPlugin, PluginRegistry,
84};
85pub use plugins::{register_built_in_plugins, MapPlugin};
86pub use render::{render_to_html, render_to_html_with_plugins, RenderResult};
87// collect_plugin_types is pub(crate) — internal render pipeline helper
88pub use resolve::{resolve_actions, resolve_actions_strict, resolve_errors, resolve_errors_all};
89pub use view::{JsonUiView, SCHEMA_VERSION};
90pub use visibility::{Visibility, VisibilityCondition, VisibilityOperator};
91
92#[cfg(feature = "projections")]
93pub mod projection;
94
95#[cfg(feature = "projections")]
96pub use projection::{JsonUiRenderer, RenderMode, VisualContext};
97
98/// Concise reference of all JSON-UI components for AI generation prompts.
99///
100/// Used by ferro-cli (AI view generation) and ferro-mcp (json_ui_generate tool)
101/// as shared context for LLM-based code generation.
102pub const COMPONENT_CATALOG: &str = r#"## Component Catalog
103
104### Text
105Props: content (String), element (h1|h2|h3|span|div|section|p)
106
107### Button
108Props: label (String), variant (default|secondary|destructive|outline|ghost|link), size (xs|sm|default|lg), disabled (Option<bool>), icon (Option<String>), icon_position (Option<left|right>)
109
110### Card
111Props: title (String), description (Option<String>), children (Vec<ComponentNode>), footer (Vec<ComponentNode>)
112
113### Table
114Props: columns (Vec<Column {key, label, format?}>), data_path (String), row_actions (Option<Vec<Action>>), empty_message (Option<String>), sortable (Option<bool>), sort_column (Option<String>), sort_direction (Option<asc|desc>)
115
116### Form
117Props: action (Action), fields (Vec<ComponentNode>), method (Option<GET|POST|PUT|PATCH|DELETE>)
118
119### Input
120Props: field (String), label (String), input_type (text|email|password|number|textarea|hidden|date|time|url|tel|search), placeholder (Option<String>), required (Option<bool>), disabled (Option<bool>), error (Option<String>), description (Option<String>), default_value (Option<String>), data_path (Option<String>), step (Option<String>)
121
122### Select
123Props: field (String), label (String), options (Vec<SelectOption {value, label}>), placeholder (Option<String>), required (Option<bool>), disabled (Option<bool>), error (Option<String>), description (Option<String>), default_value (Option<String>), data_path (Option<String>)
124
125### Alert
126Props: message (String), variant (info|success|warning|error), title (Option<String>)
127
128### Badge
129Props: label (String), variant (default|secondary|destructive|outline)
130
131### Modal
132Props: title (String), description (Option<String>), children (Vec<ComponentNode>), footer (Vec<ComponentNode>), trigger_label (Option<String>)
133
134### Checkbox
135Props: field (String), label (String), description (Option<String>), checked (Option<bool>), data_path (Option<String>), required (Option<bool>), disabled (Option<bool>), error (Option<String>)
136
137### Switch
138Props: field (String), label (String), description (Option<String>), checked (Option<bool>), data_path (Option<String>), required (Option<bool>), disabled (Option<bool>), error (Option<String>)
139
140### KeyValueEditor
141Props: field (String), label (Option<String>), suggested_keys (Vec<String>), allow_custom_keys (bool, default true), data_path (Option<String> — must resolve to a JSON object), error (Option<String>)
142Serializes to hidden `<input name="{field}" type="hidden" value="{...json...}">`. When `allow_custom_keys` is true, the key input is a text field with a `<datalist>` from `suggested_keys`; when false, the key input is a `<select>` restricted to `suggested_keys`. Runtime syncs the hidden field on every add/delete/input event.
143
144### Separator
145Props: orientation (Option<horizontal|vertical>)
146
147### DescriptionList
148Props: items (Vec<DescriptionItem {label, value, format?}>), columns (Option<u8>)
149
150### Tabs
151Props: default_tab (String), tabs (Vec<Tab {value, label, children}>)
152
153### Breadcrumb
154Props: items (Vec<BreadcrumbItem {label, url?}>)
155
156### Pagination
157Props: current_page (u32), per_page (u32), total (u32), base_url (Option<String>)
158
159### Progress
160Props: value (u8 0-100), max (Option<u8>), label (Option<String>)
161
162### Avatar
163Props: src (Option<String>), alt (String), fallback (Option<String>), size (Option<xs|sm|default|lg>)
164
165### Skeleton
166Props: width (Option<String>), height (Option<String>), rounded (Option<bool>)
167
168## Plugin Components
169
170Plugin components use the same JSON syntax as built-in components. Their JS/CSS assets are loaded automatically.
171
172### Map
173Props: center (Option<[f64; 2]>), zoom (u8 0-18, default 13), height (String, default "400px"), fit_bounds (Option<bool>), markers (Vec<{lat, lng, popup?, color?, popup_html?, href?}>), tile_url (Option<String>), attribution (Option<String>), max_zoom (Option<u8>)
174Example JSON: {"type": "Map", "fit_bounds": true, "markers": [{"lat": 51.5, "lng": -0.09, "popup": "Hello"}]}
175Note: Leaflet CSS/JS loaded via CDN automatically. Works inside Tabs/Modals (IntersectionObserver handles resize).
176
177## Action
178Props: handler (String "controller.method" format), method (GET|POST|PUT|PATCH|DELETE), confirm (Option<ConfirmDialog {title, message?, variant: default|danger}>), on_success (Option<ActionOutcome>), on_error (Option<ActionOutcome>)
179Builders: Action::new("handler") (POST), Action::get("handler"), Action::delete("handler"), .confirm("title"), .confirm_danger("title")
180
181## ComponentNode
182Wraps every component: key (String), component (Component variant), action (Option<Action>), visibility (Option<Visibility>)
183
184## JsonUiView Builder
185JsonUiView::new().title("Title").layout("app").data(json).component(node).components(vec_of_nodes)
186"#;