1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//! Schema-driven form rendering: describe fields with [`FormField`] and [`FieldSchema`]
//! and let [`DynamicForm`] build the inputs and collect their values as JSON.
use leptos::prelude::*;
use serde_json::{Map, Value};
/// The type of a form field, which determines the control [`DynamicForm`] renders and the
/// JSON shape of its value.
#[derive(Clone)]
pub enum FieldSchema {
Number {
min: Option<f64>,
max: Option<f64>,
integer: bool,
},
Text,
Bool,
Enum(Vec<String>),
Vector(usize),
}
/// A single field in a [`DynamicForm`], pairing a JSON `key` and display `label` with its
/// [`FieldSchema`].
#[derive(Clone)]
pub struct FormField {
/// The key under which this field's value is stored in the output JSON object.
pub key: String,
/// The label shown next to the control.
pub label: String,
/// The field type describing which control to render.
pub schema: FieldSchema,
}
impl FormField {
/// Creates a [`FormField`] from a key, label, and schema.
pub fn new(key: impl Into<String>, label: impl Into<String>, schema: FieldSchema) -> Self {
Self {
key: key.into(),
label: label.into(),
schema,
}
}
}
fn default_value(schema: &FieldSchema) -> Value {
match schema {
FieldSchema::Number { .. } => Value::from(0.0),
FieldSchema::Text => Value::from(""),
FieldSchema::Bool => Value::from(false),
FieldSchema::Enum(options) => Value::from(options.first().cloned().unwrap_or_default()),
FieldSchema::Vector(size) => Value::from(vec![0.0_f64; *size]),
}
}
type FormState = RwSignal<Map<String, Value>>;
fn number_control(
key: String,
min: Option<f64>,
max: Option<f64>,
integer: bool,
state: FormState,
emit: impl Fn() + Copy + 'static,
) -> AnyView {
let read_key = key.clone();
view! {
<input
type="number"
min=min.map(|value| value.to_string())
max=max.map(|value| value.to_string())
step=if integer { "1" } else { "any" }
prop:value=move || {
state.with(|map| {
map.get(&read_key).and_then(Value::as_f64).unwrap_or(0.0).to_string()
})
}
on:input=move |event| {
if let Ok(parsed) = event_target_value(&event).parse::<f64>() {
let parsed = if integer { parsed.round() } else { parsed };
state.update(|map| {
map.insert(key.clone(), Value::from(parsed));
});
emit();
}
}
/>
}
.into_any()
}
fn vector_control(
key: String,
size: usize,
state: FormState,
emit: impl Fn() + Copy + 'static,
) -> AnyView {
let axes = (0..size)
.map(|index| {
let key = key.clone();
let read_key = key.clone();
view! {
<input
type="number"
step="any"
class="nightshade-vec-input"
prop:value=move || {
state.with(|map| {
map.get(&read_key)
.and_then(Value::as_array)
.and_then(|array| array.get(index))
.and_then(Value::as_f64)
.unwrap_or(0.0)
.to_string()
})
}
on:input=move |event| {
if let Ok(parsed) = event_target_value(&event).parse::<f64>() {
state.update(|map| {
let mut values = map
.get(&key)
.and_then(Value::as_array)
.map(|array| {
array
.iter()
.map(|value| value.as_f64().unwrap_or(0.0))
.collect::<Vec<_>>()
})
.unwrap_or_else(|| vec![0.0; size]);
if values.len() < size {
values.resize(size, 0.0);
}
values[index] = parsed;
map.insert(key.clone(), Value::from(values));
});
emit();
}
}
/>
}
})
.collect_view();
view! { <div class="nightshade-vec-field">{axes}</div> }.into_any()
}
fn field_view(field: FormField, state: FormState, emit: impl Fn() + Copy + 'static) -> AnyView {
let label = field.label.clone();
let control = match field.schema {
FieldSchema::Number { min, max, integer } => {
number_control(field.key, min, max, integer, state, emit)
}
FieldSchema::Text => {
let key = field.key.clone();
let read_key = field.key.clone();
view! {
<input
type="text"
prop:value=move || {
state.with(|map| {
map.get(&read_key)
.and_then(Value::as_str)
.unwrap_or("")
.to_string()
})
}
on:input=move |event| {
state.update(|map| {
map.insert(key.clone(), Value::from(event_target_value(&event)));
});
emit();
}
/>
}
.into_any()
}
FieldSchema::Bool => {
let key = field.key.clone();
let read_key = field.key.clone();
view! {
<input
type="checkbox"
prop:checked=move || {
state.with(|map| {
map.get(&read_key).and_then(Value::as_bool).unwrap_or(false)
})
}
on:change=move |event| {
state.update(|map| {
map.insert(key.clone(), Value::from(event_target_checked(&event)));
});
emit();
}
/>
}
.into_any()
}
FieldSchema::Enum(options) => {
let key = field.key.clone();
let read_key = field.key.clone();
view! {
<select
class="nightshade-select"
prop:value=move || {
state.with(|map| {
map.get(&read_key)
.and_then(Value::as_str)
.unwrap_or("")
.to_string()
})
}
on:change=move |event| {
state.update(|map| {
map.insert(key.clone(), Value::from(event_target_value(&event)));
});
emit();
}
>
{options
.into_iter()
.map(|option| view! { <option value=option.clone()>{option.clone()}</option> })
.collect_view()}
</select>
}
.into_any()
}
FieldSchema::Vector(size) => vector_control(field.key, size, state, emit),
};
view! {
<label class="nightshade-field">
<span class="nightshade-field-label">{label}</span>
{control}
</label>
}
.into_any()
}
/// Renders a form from a list of [`FormField`]s, maintaining the collected values as a
/// JSON object. Emits the object through `on_change` on every edit and, when an
/// `on_submit` callback is provided, shows a submit button labelled `submit_label`.
#[component]
pub fn DynamicForm(
fields: Vec<FormField>,
#[prop(optional)] on_change: Option<Callback<Value>>,
#[prop(optional)] on_submit: Option<Callback<Value>>,
#[prop(into, optional)] submit_label: String,
) -> impl IntoView {
let state: FormState = RwSignal::new({
let mut map = Map::new();
for field in &fields {
map.insert(field.key.clone(), default_value(&field.schema));
}
map
});
let emit = move || {
if let Some(callback) = on_change {
callback.run(Value::Object(state.get_untracked()));
}
};
let submit_label = if submit_label.is_empty() {
"Submit".to_string()
} else {
submit_label
};
let rows = fields
.into_iter()
.map(|field| field_view(field, state, emit))
.collect_view();
view! {
<div class="nightshade-dynamic-form">
{rows}
{on_submit
.map(|callback| {
view! {
<button
class="nightshade-button primary"
on:click=move |_| callback.run(Value::Object(state.get_untracked()))
>
{submit_label}
</button>
}
})}
</div>
}
}