1use next_rust_view::{Attr, Element, Node, View};
5
6use crate::icons::{self, icon};
7use crate::{
8 Color, Extra, FieldVariant, MaybeText, Radius, Size, apply, attr, flag, next_id, part_class, root, styled,
9};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum LabelPlacement {
14 #[default]
16 Inside,
17 Outside,
19 OutsideLeft,
21}
22
23#[derive(Default)]
25pub(crate) struct Field {
26 pub label: Option<String>,
27 pub placeholder: Option<String>,
28 pub description: Option<String>,
29 pub error_message: Option<String>,
30 pub invalid: bool,
31 pub name: Option<String>,
32 pub id: Option<String>,
33 pub value: Option<String>,
34 pub required: bool,
35 pub disabled: bool,
36 pub readonly: bool,
37 pub color: Color,
38 pub size: Size,
39 pub variant: FieldVariant,
40 pub radius: Option<Radius>,
41 pub label_placement: LabelPlacement,
42 pub start_content: Option<Node>,
43 pub end_content: Option<Node>,
44 pub full_width: Option<bool>,
45 pub label_class: Option<String>,
46 pub wrapper_class: Option<String>,
47 pub input_class: Option<String>,
48 pub description_class: Option<String>,
49 pub error_class: Option<String>,
50 pub unstyled: bool,
51 pub extra: Extra,
52}
53
54macro_rules! field_methods {
56 () => {
57 pub fn label(mut self, v: impl Into<String>) -> Self {
59 self.field.label = Some(v.into());
60 self
61 }
62 pub fn placeholder(mut self, v: impl Into<String>) -> Self {
63 self.field.placeholder = Some(v.into());
64 self
65 }
66 pub fn description(mut self, v: impl crate::MaybeText) -> Self {
68 self.field.description = v.into_text();
69 self
70 }
71 pub fn error_message(mut self, v: impl crate::MaybeText) -> Self {
74 self.field.error_message = v.into_text();
75 self
76 }
77 pub fn invalid(mut self, v: bool) -> Self {
79 self.field.invalid = v;
80 self
81 }
82 pub fn name(mut self, v: impl Into<String>) -> Self {
85 self.field.name = Some(v.into());
86 self
87 }
88 pub fn id(mut self, v: impl Into<String>) -> Self {
90 self.field.id = Some(v.into());
91 self
92 }
93 pub fn value(mut self, v: impl crate::MaybeText) -> Self {
95 self.field.value = v.into_text();
96 self
97 }
98 pub fn required(mut self, v: bool) -> Self {
99 self.field.required = v;
100 self
101 }
102 pub fn disabled(mut self, v: bool) -> Self {
103 self.field.disabled = v;
104 self
105 }
106 pub fn readonly(mut self, v: bool) -> Self {
107 self.field.readonly = v;
108 self
109 }
110 pub fn color(mut self, v: crate::Color) -> Self {
112 self.field.color = v;
113 self
114 }
115 pub fn size(mut self, v: crate::Size) -> Self {
116 self.field.size = v;
117 self
118 }
119 pub fn variant(mut self, v: crate::FieldVariant) -> Self {
120 self.field.variant = v;
121 self
122 }
123 pub fn radius(mut self, v: crate::Radius) -> Self {
124 self.field.radius = Some(v);
125 self
126 }
127 pub fn label_placement(mut self, v: crate::LabelPlacement) -> Self {
128 self.field.label_placement = v;
129 self
130 }
131 pub fn start_content(mut self, v: impl next_rust_view::View) -> Self {
133 self.field.start_content = Some(v.into_node());
134 self
135 }
136 pub fn end_content(mut self, v: impl next_rust_view::View) -> Self {
138 self.field.end_content = Some(v.into_node());
139 self
140 }
141 pub fn full_width(mut self, v: bool) -> Self {
143 self.field.full_width = Some(v);
144 self
145 }
146 pub fn label_class(mut self, v: impl Into<String>) -> Self {
148 self.field.label_class = Some(v.into());
149 self
150 }
151 pub fn wrapper_class(mut self, v: impl Into<String>) -> Self {
153 self.field.wrapper_class = Some(v.into());
154 self
155 }
156 pub fn input_class(mut self, v: impl Into<String>) -> Self {
158 self.field.input_class = Some(v.into());
159 self
160 }
161 pub fn description_class(mut self, v: impl Into<String>) -> Self {
162 self.field.description_class = Some(v.into());
163 self
164 }
165 pub fn error_class(mut self, v: impl Into<String>) -> Self {
166 self.field.error_class = Some(v.into());
167 self
168 }
169 pub fn class(mut self, v: impl Into<String>) -> Self {
171 self.field.extra.push(next_rust_view::attrs::class(v.into()));
172 self
173 }
174 pub fn unstyled(mut self, v: bool) -> Self {
176 self.field.unstyled = v;
177 self
178 }
179 };
180}
181pub(crate) use field_methods;
182
183pub(crate) struct Frame {
185 pub kind: &'static str,
187 pub floats: bool,
189 pub after_box: Vec<Node>,
191 pub root_attrs: Vec<Attr>,
193 pub end: Vec<Node>,
195}
196
197impl Field {
198 pub fn control_id(&mut self) -> String {
200 self.id.get_or_insert_with(|| next_id("nr-field")).clone()
201 }
202
203 pub fn is_invalid(&self) -> bool {
204 self.invalid || self.error_message.is_some()
205 }
206
207 pub fn control_attrs(&mut self) -> Vec<Attr> {
209 let id = self.control_id();
210 let mut attrs = vec![attr("id", id.clone())];
211 if let Some(name) = &self.name {
212 attrs.push(attr("name", name.clone()));
213 }
214 attrs.push(flag("required", self.required));
215 attrs.push(flag("disabled", self.disabled));
216 let mut described = Vec::new();
217 if self.description.is_some() {
218 described.push(format!("{id}-description"));
219 }
220 if self.error_message.is_some() || self.name.is_some() {
221 described.push(format!("{id}-error"));
222 }
223 if !described.is_empty() {
224 attrs.push(attr("aria-describedby", described.join(" ")));
225 }
226 if self.is_invalid() {
227 attrs.push(attr("aria-invalid", "true"));
228 }
229 attrs
230 }
231
232 fn label_node(&self, id: &str) -> Option<Node> {
233 let label = self.label.as_ref()?;
234 let mut el = Element::new("label")
235 .with(part_class("nr-field-label", &self.label_class))
236 .with(attr("for", id.to_owned()))
237 .with(attr("id", format!("{id}-label")))
238 .with(label.clone());
239 if self.required {
240 el = el.with(
241 Element::new("span")
242 .with(attr("class", "nr-field-required"))
243 .with(attr("aria-hidden", "true"))
244 .with("*"),
245 );
246 }
247 Some(el.into_node())
248 }
249
250 pub fn render(mut self, control: Node, frame: Frame) -> Node {
252 let id = self.control_id();
253 let (class, attrs, _) = std::mem::take(&mut self.extra).split();
254 let size = format!("nr-field-{}", self.size.suffix());
255 let placement = match self.label_placement {
256 LabelPlacement::Inside => "nr-label-inside",
257 LabelPlacement::Outside => "nr-label-outside",
258 LabelPlacement::OutsideLeft => "nr-label-left",
259 };
260 let has_label = self.label.is_some();
261 let classes = [
262 "nr-field",
263 frame.kind,
264 self.variant.class(),
265 self.color.class(),
266 &size,
267 if has_label { placement } else { "nr-label-none" },
268 self.radius.map(Radius::class).unwrap_or(""),
269 if self.full_width.unwrap_or(true) { "nr-field-full" } else { "" },
270 ];
271 let mut el = root("div", &classes, self.unstyled, class);
272 el.set_attr(flag("data-invalid", self.is_invalid()));
273 el.set_attr(flag("data-disabled", self.disabled));
274 el.set_attr(flag("data-float", frame.floats && has_label && self.label_placement == LabelPlacement::Inside));
275 apply(&mut el, frame.root_attrs);
276 apply(&mut el, attrs);
277
278 let inside = self.label_placement == LabelPlacement::Inside;
279 if !inside {
280 el.children.extend(self.label_node(&id));
281 }
282 let mut wrap = Element::new("div").with(part_class("nr-field-wrap", &self.wrapper_class));
283 if let Some(start) = self.start_content.take() {
284 wrap.children.push(Element::new("span").with(attr("class", "nr-field-start")).with(start).into_node());
285 }
286 let mut inner = Element::new("div").with(attr("class", "nr-field-inner"));
287 if inside {
288 inner.children.extend(self.label_node(&id));
289 }
290 inner.children.push(control);
291 wrap.children.push(inner.into_node());
292 let mut end: Vec<Node> = self.end_content.take().into_iter().collect();
293 end.extend(frame.end);
294 if !end.is_empty() {
295 wrap.children.push(Element::new("span").with(attr("class", "nr-field-end")).with(end).into_node());
296 }
297 wrap.children.extend(frame.after_box);
299 let mut main = Element::new("div").with(attr("class", "nr-field-main"));
300 main.children.push(wrap.into_node());
301 if let Some(description) = &self.description {
302 main.children.push(
303 Element::new("p")
304 .with(part_class("nr-field-description", &self.description_class))
305 .with(attr("id", format!("{id}-description")))
306 .with(description.clone())
307 .into_node(),
308 );
309 }
310 if self.error_message.is_some() || self.name.is_some() {
311 let mut err = Element::new("p")
314 .with(part_class("nr-field-error", &self.error_class))
315 .with(attr("id", format!("{id}-error")))
316 .with(attr("aria-live", "polite"));
317 if let Some(name) = &self.name {
318 err = err.with(attr("data-nr-error", name.clone()));
319 }
320 main.children.push(err.with(self.error_message.clone()).into_node());
321 }
322 el.children.push(main.into_node());
323 styled(el)
324 }
325}
326
327#[derive(Default)]
336pub struct Input {
337 field: Field,
338 kind: Option<String>,
339 clearable: bool,
340}
341
342impl Input {
343 pub fn new() -> Self {
344 Self::default()
345 }
346 field_methods!();
347
348 pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
351 self.field.extra.push(part);
352 self
353 }
354 pub fn kind(mut self, v: impl Into<String>) -> Self {
356 self.kind = Some(v.into());
357 self
358 }
359 pub fn clearable(mut self, v: bool) -> Self {
361 self.clearable = v;
362 self
363 }
364
365 fn render(mut self, password: bool) -> Node {
366 let kind = if password { "password".to_owned() } else { self.kind.take().unwrap_or_else(|| "text".into()) };
367 let (class, attrs, _) = std::mem::take(&mut self.field.extra).split();
368 if let Some(class) = class {
369 self.field.extra.push(class);
370 }
371 let floats = self.field.placeholder.is_none();
372 let mut input = Element::new_void("input")
373 .with(part_class("nr-field-input", &self.field.input_class))
374 .with(attr("type", kind))
375 .with(attr("placeholder", self.field.placeholder.clone().unwrap_or_else(|| " ".into())));
376 apply(&mut input, self.field.control_attrs());
377 if let Some(value) = &self.field.value {
378 input.set_attr(attr("value", value.clone()));
379 }
380 input.set_attr(flag("readonly", self.field.readonly));
381 if password && !attrs.iter().any(|a| a.name == "autocomplete") {
382 input.set_attr(attr("autocomplete", "current-password"));
383 }
384 apply(&mut input, attrs);
385
386 let mut end = Vec::new();
387 let mut root_attrs = Vec::new();
388 if self.clearable {
389 root_attrs.push(attr("data-nr-ui", "field"));
390 end.push(icon_button("nr-field-clear", "Clear", "clear", icon(icons::close())));
391 }
392 if password {
393 root_attrs.push(attr("data-nr-ui", "field"));
394 end.push(
395 Element::new("button")
396 .with(attr("type", "button"))
397 .with(attr("class", "nr-field-action nr-password-toggle"))
398 .with(attr("data-nr-field-action", "toggle-password"))
399 .with(attr("aria-label", "Show password"))
400 .with(attr("aria-pressed", "false"))
401 .with(Element::new("span").with(attr("class", "nr-password-show")).with(icon(icons::eye())))
402 .with(Element::new("span").with(attr("class", "nr-password-hide")).with(icon(icons::eye_off())))
403 .into_node(),
404 );
405 }
406 let kind = if password { "nr-input nr-password" } else { "nr-input" };
407 self.field.render(input.into_node(), Frame { kind, floats, after_box: Vec::new(), root_attrs, end })
408 }
409}
410
411pub(crate) fn icon_button(class: &str, label: &str, action: &str, content: Node) -> Node {
413 Element::new("button")
414 .with(attr("type", "button"))
415 .with(attr("class", format!("nr-field-action {class}")))
416 .with(attr("data-nr-field-action", action.to_owned()))
417 .with(attr("aria-label", label.to_owned()))
418 .with(attr("tabindex", "-1"))
419 .with(content)
420 .into_node()
421}
422
423impl View for Input {
424 fn into_node(self) -> Node {
425 self.render(false)
426 }
427}
428
429#[derive(Default)]
431pub struct PasswordInput {
432 input: Input,
433}
434
435impl PasswordInput {
436 pub fn new() -> Self {
437 Self::default()
438 }
439
440 pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
442 self.input = self.input.with(part);
443 self
444 }
445}
446
447macro_rules! delegate_field {
449 ($($name:ident($ty:ty)),* $(,)?) => {
450 impl PasswordInput {$(
451 #[doc = concat!("See [`Input::", stringify!($name), "`].")]
452 pub fn $name(mut self, v: $ty) -> Self {
453 self.input = self.input.$name(v);
454 self
455 }
456 )*}
457 };
458}
459delegate_field!(
460 label(&str),
461 placeholder(&str),
462 name(&str),
463 id(&str),
464 required(bool),
465 disabled(bool),
466 readonly(bool),
467 color(Color),
468 size(Size),
469 variant(FieldVariant),
470 radius(Radius),
471 label_placement(LabelPlacement),
472 full_width(bool),
473 label_class(&str),
474 wrapper_class(&str),
475 input_class(&str),
476 description_class(&str),
477 error_class(&str),
478 class(&str),
479 unstyled(bool),
480);
481
482impl PasswordInput {
483 pub fn description(mut self, v: impl MaybeText) -> Self {
484 self.input = self.input.description(v);
485 self
486 }
487 pub fn error_message(mut self, v: impl MaybeText) -> Self {
488 self.input = self.input.error_message(v);
489 self
490 }
491 pub fn invalid(mut self, v: bool) -> Self {
492 self.input = self.input.invalid(v);
493 self
494 }
495 pub fn value(mut self, v: impl MaybeText) -> Self {
496 self.input = self.input.value(v);
497 self
498 }
499 pub fn start_content(mut self, v: impl View) -> Self {
500 self.input = self.input.start_content(v);
501 self
502 }
503 pub fn end_content(mut self, v: impl View) -> Self {
504 self.input = self.input.end_content(v);
505 self
506 }
507 pub fn new_password(self, v: bool) -> Self {
509 if v { self.with(attr("autocomplete", "new-password")) } else { self }
510 }
511}
512
513impl View for PasswordInput {
514 fn into_node(self) -> Node {
515 self.input.render(true)
516 }
517}
518
519#[derive(Default)]
521pub struct Textarea {
522 field: Field,
523 rows: Option<u32>,
524}
525
526impl Textarea {
527 pub fn new() -> Self {
528 Self::default()
529 }
530 field_methods!();
531
532 pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
534 self.field.extra.push(part);
535 self
536 }
537 pub fn rows(mut self, v: u32) -> Self {
539 self.rows = Some(v);
540 self
541 }
542}
543
544impl View for Textarea {
545 fn into_node(mut self) -> Node {
546 let (class, attrs, _) = std::mem::take(&mut self.field.extra).split();
547 if let Some(class) = class {
548 self.field.extra.push(class);
549 }
550 let floats = self.field.placeholder.is_none();
551 let mut area = Element::new("textarea")
552 .with(part_class("nr-field-input nr-textarea-input", &self.field.input_class))
553 .with(attr("rows", self.rows.unwrap_or(3).to_string()))
554 .with(attr("placeholder", self.field.placeholder.clone().unwrap_or_else(|| " ".into())));
555 apply(&mut area, self.field.control_attrs());
556 area.set_attr(flag("readonly", self.field.readonly));
557 apply(&mut area, attrs);
558 area.children.extend(self.field.value.clone().map(View::into_node));
559 self.field.render(
560 area.into_node(),
561 Frame { kind: "nr-textarea", floats, after_box: Vec::new(), root_attrs: Vec::new(), end: Vec::new() },
562 )
563 }
564}