reinhardt-forms 0.1.0-rc.15

Form handling and validation
Documentation
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! WASM Compatibility Layer for Forms (Week 5 Day 1-2)
//!
//! This module provides serializable metadata structures that allow Django-style
//! Forms to be rendered on the client-side (WASM) without requiring the full
//! `Form` struct with its trait objects and non-serializable closures.
//!
//! ## Architecture
//!
//! The metadata extraction follows this pattern:
//!
//! ```mermaid
//! flowchart LR
//!     subgraph Server["Server-side"]
//!         Form["Form<br/>(traits, closures)"]
//!     end
//!
//!     subgraph Client["Client-side (WASM)"]
//!         FormMetadata["FormMetadata<br/>(plain data, serializable)"]
//!         FormComponent["FormComponent<br/>(WASM UI)"]
//!     end
//!
//!     Form -->|"to_metadata()"| FormMetadata
//!     FormMetadata --> FormComponent
//! ```
//!
//! ## Example
//!
//! ```
//! use reinhardt_forms::{Form, CharField, Field};
//! use reinhardt_forms::wasm_compat::{FormMetadata, FormExt};
//!
//! // Server-side: Create form
//! let mut form = Form::new();
//! form.add_field(Box::new(CharField::new("username".to_string())));
//!
//! // Extract metadata for client
//! let metadata: FormMetadata = form.to_metadata();
//!
//! // Serialize and send to WASM
//! let json = serde_json::to_string(&metadata).unwrap();
//! ```

use crate::field::Widget;
use crate::form::Form;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Validation rule types for client-side validation (Phase 2-A)
///
/// These rules enable client-side validation for better UX, while
/// server-side validation remains mandatory for security.
///
/// ## Security Note
///
/// Client-side validation is for UX enhancement only and MUST NOT
/// be relied upon for security. Server-side validation is always required.
///
/// ## Design Principle
///
/// All validation rules are declarative and type-safe. We do NOT use
/// JavaScript expressions to prevent arbitrary code execution vulnerabilities.
/// Instead, each rule type has specific parameters that are validated in Rust.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ValidationRule {
	/// Minimum length validation for string fields
	MinLength {
		/// Field name to validate
		field_name: String,
		/// Minimum required length
		min: usize,
		/// Error message to display when validation fails
		error_message: String,
	},
	/// Maximum length validation for string fields
	MaxLength {
		/// Field name to validate
		field_name: String,
		/// Maximum allowed length
		max: usize,
		/// Error message to display when validation fails
		error_message: String,
	},
	/// Regex pattern validation for string fields
	Pattern {
		/// Field name to validate
		field_name: String,
		/// Regex pattern to match (must be valid regex)
		pattern: String,
		/// Error message to display when validation fails
		error_message: String,
	},
	/// Minimum value validation for numeric fields
	MinValue {
		/// Field name to validate
		field_name: String,
		/// Minimum allowed value
		min: f64,
		/// Error message to display when validation fails
		error_message: String,
	},
	/// Maximum value validation for numeric fields
	MaxValue {
		/// Field name to validate
		field_name: String,
		/// Maximum allowed value
		max: f64,
		/// Error message to display when validation fails
		error_message: String,
	},
	/// Email format validation
	Email {
		/// Field name to validate
		field_name: String,
		/// Error message to display when validation fails
		error_message: String,
	},
	/// URL format validation
	Url {
		/// Field name to validate
		field_name: String,
		/// Error message to display when validation fails
		error_message: String,
	},
	/// Cross-field equality validation (e.g., password confirmation)
	FieldsEqual {
		/// Field names to compare for equality
		field_names: Vec<String>,
		/// Error message to display when validation fails
		error_message: String,
		/// Target field for error display (None = non-field error)
		target_field: Option<String>,
	},
	/// Date range validation (end_date >= start_date)
	DateRange {
		/// Start date field name
		start_field: String,
		/// End date field name
		end_field: String,
		/// Error message to display when validation fails
		error_message: String,
		/// Target field for error display
		target_field: Option<String>,
	},
	/// Numeric range validation (max >= min)
	NumericRange {
		/// Minimum value field name
		min_field: String,
		/// Maximum value field name
		max_field: String,
		/// Error message to display when validation fails
		error_message: String,
		/// Target field for error display
		target_field: Option<String>,
	},
	/// Reference to reinhardt-validators Validator
	ValidatorRef {
		/// Field name to validate
		field_name: String,
		/// Validator identifier (e.g., "email", "url", "min_length")
		validator_id: String,
		/// Validator parameters as JSON
		/// Example: {"min": 8, "max": 20} for MinMaxLengthValidator
		params: serde_json::Value,
		/// Error message to display when validation fails
		error_message: String,
	},
}

/// Serializable form metadata for client-side rendering (Week 5 Day 1)
///
/// This structure contains all information needed to render a form on the
/// client-side without requiring the full `Form` struct with its trait objects.
///
/// ## Fields
///
/// - `fields`: Metadata for each form field
/// - `initial`: Initial values for the form (form-level)
/// - `prefix`: Field name prefix (for multiple forms on same page)
/// - `is_bound`: Whether the form has been bound with data
/// - `errors`: Validation errors (if any)
/// - `validation_rules`: Client-side validation rules (Phase 2-A)
/// - `non_field_errors`: Form-level validation errors (Phase 2-A)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormMetadata {
	/// Field metadata list
	pub fields: Vec<FieldMetadata>,

	/// Initial values (form-level)
	pub initial: HashMap<String, serde_json::Value>,

	/// Field name prefix
	pub prefix: String,

	/// Whether the form has been bound with data
	pub is_bound: bool,

	/// Validation errors (field name -> error messages)
	pub errors: HashMap<String, Vec<String>>,

	/// Client-side validation rules (Phase 2-A)
	/// These rules enable immediate feedback to users without server round-trips.
	/// Server-side validation is still mandatory for security.
	#[serde(default)]
	pub validation_rules: Vec<ValidationRule>,

	/// Non-field errors (form-level errors) (Phase 2-A)
	/// These are errors that don't belong to a specific field (e.g., "Passwords don't match")
	#[serde(default)]
	pub non_field_errors: Vec<String>,
}

/// Serializable field metadata for client-side rendering (Week 5 Day 1)
///
/// This structure contains all information needed to render a single form field
/// on the client-side.
///
/// ## Fields
///
/// - `name`: Field name (used as form data key)
/// - `label`: Human-readable label (defaults to field name if None)
/// - `required`: Whether the field is required
/// - `help_text`: Help text displayed below the field
/// - `widget`: Widget type for rendering (TextInput, Select, etc.)
/// - `initial`: Initial value for this field
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldMetadata {
	/// Field name
	pub name: String,

	/// Human-readable label (optional)
	pub label: Option<String>,

	/// Whether the field is required
	pub required: bool,

	/// Help text (optional)
	pub help_text: Option<String>,

	/// Widget type for rendering
	pub widget: Widget,

	/// Initial value (optional)
	pub initial: Option<serde_json::Value>,
}

/// Extension trait for Form to extract metadata (Week 5 Day 1)
///
/// This trait provides the `to_metadata()` method that converts a `Form`
/// into a serializable `FormMetadata` structure.
pub trait FormExt {
	/// Extract serializable metadata from the form
	///
	/// This method creates a `FormMetadata` structure containing all
	/// information needed to render the form on the client-side.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::{Form, CharField, Field};
	/// use reinhardt_forms::wasm_compat::{FormMetadata, FormExt};
	///
	/// let mut form = Form::new();
	/// form.add_field(Box::new(CharField::new("email".to_string())));
	///
	/// let metadata: FormMetadata = form.to_metadata();
	/// assert_eq!(metadata.fields.len(), 1);
	/// assert_eq!(metadata.fields[0].name, "email");
	/// ```
	fn to_metadata(&self) -> FormMetadata;
}

impl FormExt for Form {
	fn to_metadata(&self) -> FormMetadata {
		// Extract field metadata
		let fields = self
			.fields()
			.iter()
			.map(|field| FieldMetadata {
				name: field.name().to_string(),
				label: field.label().map(|s| s.to_string()),
				required: field.required(),
				help_text: field.help_text().map(|s| s.to_string()),
				widget: field.widget().clone(),
				initial: field.initial().cloned(),
			})
			.collect();

		FormMetadata {
			fields,
			initial: self.initial().clone(),
			prefix: self.prefix().to_string(),
			is_bound: self.is_bound(),
			errors: self.errors().clone(),
			// Phase 2-A: Clone validation rules from Form
			validation_rules: self.validation_rules().to_vec(),
			non_field_errors: self
				.errors()
				.get(crate::form::ALL_FIELDS_KEY)
				.cloned()
				.unwrap_or_default(),
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::fields::CharField;

	#[test]
	fn test_form_metadata_extraction() {
		let mut form = Form::new();
		form.add_field(Box::new(CharField::new("username".to_string())));
		form.add_field(Box::new(CharField::new("email".to_string())));

		let metadata = form.to_metadata();

		assert_eq!(metadata.fields.len(), 2);
		assert_eq!(metadata.fields[0].name, "username");
		assert_eq!(metadata.fields[1].name, "email");
		assert!(!metadata.is_bound);
	}

	#[test]
	fn test_form_metadata_with_prefix() {
		let mut form = Form::with_prefix("user".to_string());
		form.add_field(Box::new(CharField::new("name".to_string())));

		let metadata = form.to_metadata();

		assert_eq!(metadata.prefix, "user");
		assert_eq!(metadata.fields.len(), 1);
	}

	#[test]
	fn test_form_metadata_serialization() {
		let mut form = Form::new();
		form.add_field(Box::new(CharField::new("test".to_string())));

		let metadata = form.to_metadata();

		// Test JSON serialization
		let json = serde_json::to_string(&metadata).expect("Failed to serialize");
		assert!(json.contains("\"name\":\"test\""));

		// Test deserialization
		let deserialized: FormMetadata =
			serde_json::from_str(&json).expect("Failed to deserialize");
		assert_eq!(deserialized.fields[0].name, "test");
	}

	#[test]
	fn test_field_metadata_with_all_attributes() {
		use crate::fields::CharField;

		let field = CharField::new("bio".to_string())
			.with_label("Biography")
			.with_help_text("Tell us about yourself")
			.required();

		let mut form = Form::new();
		form.add_field(Box::new(field));

		let metadata = form.to_metadata();
		let field_meta = &metadata.fields[0];

		assert_eq!(field_meta.name, "bio");
		assert_eq!(field_meta.label, Some("Biography".to_string()));
		assert_eq!(
			field_meta.help_text,
			Some("Tell us about yourself".to_string())
		);
		assert!(field_meta.required);
	}

	#[test]
	fn test_form_metadata_with_initial_values() {
		use serde_json::json;

		let mut initial = HashMap::new();
		initial.insert("username".to_string(), json!("john_doe"));
		initial.insert("age".to_string(), json!(25));

		let mut form = Form::with_initial(initial);
		form.add_field(Box::new(CharField::new("username".to_string())));

		let metadata = form.to_metadata();

		assert_eq!(metadata.initial.get("username"), Some(&json!("john_doe")));
		assert_eq!(metadata.initial.get("age"), Some(&json!(25)));
	}

	#[test]
	fn test_form_metadata_with_errors() {
		use serde_json::json;

		let mut form = Form::new();
		// Create a required field - empty value should fail validation
		form.add_field(Box::new(CharField::new("email".to_string()).required()));

		// Bind with invalid data to generate errors (empty string for required field)
		let mut data = HashMap::new();
		data.insert("email".to_string(), json!("")); // Empty required field should fail
		form.bind(data);

		// Validate to populate errors
		let is_valid = form.is_valid();

		let metadata = form.to_metadata();

		// Should have validation error for the required email field
		assert!(!is_valid);
		assert!(!metadata.errors.is_empty());
		assert!(metadata.errors.contains_key("email"));
	}
}