use crate::use_form::try_form_controller;
use formars_signals::FieldHandle;
use leptos::prelude::*;
pub(crate) fn sanitize_id(path: &str) -> String {
let mut core = String::with_capacity(path.len());
let mut prev_sep = false;
for ch in path.chars() {
if ch.is_alphanumeric() {
core.push(ch);
prev_sep = false;
} else if !prev_sep {
core.push('-');
prev_sep = true;
}
}
format!("formars-{}", core.trim_matches('-'))
}
pub(crate) fn ssr_initial(field: &FieldHandle) -> String {
field.display_str()
}
#[component]
#[allow(
clippy::needless_pass_by_value,
reason = "leptos typed-builder prop convention"
)]
pub fn TextField(
field: FieldHandle,
#[prop(optional)] label: Option<String>,
#[prop(optional)] id: Option<String>,
#[prop(optional)] placeholder: Option<String>,
) -> impl IntoView {
let input_id = id.unwrap_or_else(|| sanitize_id(&field.path().to_string()));
let input_ref = NodeRef::<leptos::html::Input>::new();
let controller_for_blur = try_form_controller();
let field_for_effect = field.clone();
let input_id_for_label = input_id.clone();
Effect::new(move |_| {
let sig_str = field_for_effect.display_str();
if let Some(el) = input_ref.get().filter(|el| el.value() != sig_str) {
el.set_value(&sig_str);
}
});
let field_for_input = field.clone();
let field_for_blur = field.clone();
let initial_value = ssr_initial(&field);
let visible = field.visible_errors();
view! {
<div class="formars-field">
{move || {
let for_id = input_id_for_label.clone();
label.clone().map(move |text| {
view! { <label for=for_id>{text}</label> }
})
}}
<input
type="text"
id=input_id.clone()
value=initial_value
placeholder=placeholder
node_ref=input_ref
on:input=move |ev| field_for_input.set_str(&event_target_value(&ev))
on:blur=move |_| {
if let Some(controller) = &controller_for_blur {
controller.mark_touched(field_for_blur.path());
}
}
/>
{move || {
let issues = visible.get();
(!issues.is_empty()).then(move || {
let items: Vec<_> = issues
.into_iter()
.map(|issue| {
let message = issue.message.to_string();
view! { <li>{message}</li> }
})
.collect();
view! { <ul class="formars-errors">{items}</ul> }
})
}}
</div>
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flat_key_gets_prefixed_id() {
assert_eq!(sanitize_id("email"), "formars-email");
}
#[test]
fn dotted_path_becomes_single_dashes() {
assert_eq!(sanitize_id("user.email"), "formars-user-email");
}
#[test]
fn dash_runs_collapse_to_one_dash() {
assert_eq!(sanitize_id("a--b c"), "formars-a-b-c");
}
#[test]
fn unicode_alphanumerics_pass_through() {
assert_eq!(sanitize_id("café"), "formars-café");
}
#[test]
fn colliding_paths_documented_limitation() {
assert_eq!(sanitize_id("user.email"), sanitize_id("user-email"));
}
#[test]
fn sanitize_id_collision_class_table() {
for input in ["..", "--", "?", ""] {
assert_eq!(
sanitize_id(input),
"formars-",
"class 1: {input:?} collapses to \"formars-\""
);
}
for input in [".x", "-x", "x", "x.", "x-"] {
assert_eq!(
sanitize_id(input),
"formars-x",
"class 2: {input:?} strips to \"formars-x\""
);
}
for input in ["user.email", "user-email"] {
assert_eq!(
sanitize_id(input),
"formars-user-email",
"class 3: {input:?} collapses interior runs"
);
}
}
#[test]
fn t6_same_handle_twice_duplicates_derived_id_explicit_ids_differ() {
use formars_signals::{FieldPath, FormController, ValidateOn};
let mut c = FormController::new(ValidateOn::Blur);
let h = c
.register(
FieldPath::key("email"),
Box::new(formars_core::prelude::string()),
)
.unwrap();
let resolved = |explicit: Option<String>| {
explicit.unwrap_or_else(|| sanitize_id(&h.path().to_string()))
};
assert_eq!(
resolved(None),
"formars-email",
"derived id pins the actual sanitization"
);
let with_explicit_a = resolved(Some("field-a".to_string()));
let with_explicit_b = resolved(Some("field-b".to_string()));
assert_ne!(
with_explicit_a, with_explicit_b,
"distinct explicit id props disambiguate"
);
}
#[test]
fn ssr_initial_carries_prefilled_value() {
use formars_signals::{FieldPath, FormController, ValidateOn, Value};
let mut c = FormController::new(ValidateOn::Blur);
let h = c
.register_initial(
FieldPath::key("email"),
Box::new(formars_core::prelude::string()),
Value::from("pre@filled.io"),
)
.unwrap();
assert_eq!(
ssr_initial(&h),
"pre@filled.io",
"the value attribute seam must carry the registered initial"
);
}
#[test]
fn ssr_initial_defaults_to_empty_for_plain_registration() {
use formars_signals::{FieldPath, FormController, ValidateOn};
let mut c = FormController::new(ValidateOn::Blur);
let h = c
.register(
FieldPath::key("email"),
Box::new(formars_core::prelude::string()),
)
.unwrap();
assert_eq!(ssr_initial(&h), "");
}
#[test]
fn ssr_initial_carries_numeric_initial_canonically() {
use formars_signals::{FieldPath, FormController, ValidateOn, Value};
let mut c = FormController::new(ValidateOn::Blur);
let h = c
.register_initial(
FieldPath::key("qty"),
Box::new(formars_core::prelude::coerced::<u32>()),
Value::I64(7),
)
.unwrap();
assert_eq!(
ssr_initial(&h),
"7",
"the value attribute seam must render numeric initials canonically"
);
}
}