next-rust-ui 0.1.10

Ready-made, themeable UI components for Next Rust: buttons, inputs, select, date picker, avatars, cards and layout.
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! Ready-made UI components for Next Rust.
//!
//! ```
//! use next_rust_ui::*;
//! use next_rust_view::*;
//!
//! let form = form![
//!     Input![label = "Email", name = "email", kind = "email", placeholder = "you@example.com"],
//!     PasswordInput![label = "Password", name = "password"],
//!     Button![color = Color::Primary, submit = true, class("w-full"), "Sign in"],
//! ];
//! let html = render_static(form);
//! assert!(html.contains(r#"class="nr-btn nr-btn-solid nr-c-primary nr-btn-md w-full""#));
//! ```
//!
//! Every component is a builder with a macro of the same name. Inside the
//! macro, `key = value` sets a property and anything else is added like in an
//! element macro: attributes (`class(..)`, `id(..)`, `aria(..)`, `data(..)`)
//! and children. Every property is optional.
//!
//! Styling:
//!
//! * Each component has default classes (`nr-btn`, `nr-input`, ...) whose
//!   rules live in the CSS `components` layer. Classes you add, Tailwind
//!   utilities or your own CSS, always win over them, without `!important`.
//! * `unstyled = true` drops the default classes of the outer element.
//! * Colors, radii and shadows are CSS variables (`--nr-primary`,
//!   `--nr-radius-md`, ...): set them on `:root` to theme every component.
//!   Dark mode follows the system, or `class="dark"` / `data-theme="dark"`
//!   on an ancestor.
//! * Pages receive only the CSS of the components they render.
//!
//! Interactive components (select, date picker, password toggle, `on_press`)
//! load a small script, `/_nr/ui.js`, on the pages that use them. Without it
//! they fall back to the native control, so forms keep working.

#![forbid(unsafe_code)]

use std::borrow::Cow;
use std::sync::atomic::{AtomicUsize, Ordering};

use next_rust_view::{Attr, Element, Node, Part, Stylesheet, View};

mod avatar;
mod button;
mod card;
mod date_picker;
mod feedback;
mod icons;
mod input;
mod layout;
mod press;
mod script;
mod select;
#[doc(hidden)]
pub mod style;
mod toggle;

pub use avatar::{Avatar, AvatarGroup};
pub use button::{Button, ButtonGroup};
pub use card::{Card, CardBody, CardFooter, CardHeader, Shadow};
pub use date_picker::DatePicker;
pub use feedback::{Chip, Divider, Spinner};
pub use input::{Input, LabelPlacement, PasswordInput, Textarea};
pub use layout::{Align, AppShell, Container, Grid, Justify, Navbar, NavbarItem, Sidebar, SidebarItem, Stack, Width};
pub use press::Press;
pub use select::{Select, SelectItem};
pub use toggle::{Checkbox, Radio, RadioGroup, Switch};

/// The component stylesheet. Components add it to the page themselves; only
/// the rules for the components a page renders are sent.
pub static UI_CSS: Stylesheet = Stylesheet {
    id: "nr-ui",
    // `style::UI_CSS_SOURCE`, minified by `build.rs`.
    css: include_str!(concat!(env!("OUT_DIR"), "/ui.min.css")),
    per_class: Some(&[]),
};

pub use script::{UI_JS, UI_JS_MIN, rename_classes as rename_script_classes};

/// Classes the components render that no stylesheet rule starts with (hooks
/// for the script and for your own CSS). Release builds shorten them with the
/// stylesheet's classes; `tests/components.rs` keeps the list complete.
#[doc(hidden)]
pub const EXTRA_CLASSES: &[&str] = &[
    "nr-checkbox-label",
    "nr-cols-1",
    "nr-datepicker-toggle",
    "nr-label-outside",
    "nr-password",
    "nr-radio-label",
    "nr-shell-with-sidebar",
    "nr-switch-label",
];

/// Color of a component.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Color {
    Default,
    #[default]
    Primary,
    Secondary,
    Success,
    Warning,
    Danger,
}

impl Color {
    pub(crate) fn class(self) -> &'static str {
        match self {
            Color::Default => "nr-c-default",
            Color::Primary => "nr-c-primary",
            Color::Secondary => "nr-c-secondary",
            Color::Success => "nr-c-success",
            Color::Warning => "nr-c-warning",
            Color::Danger => "nr-c-danger",
        }
    }
}

/// Size of a component.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Size {
    Sm,
    #[default]
    Md,
    Lg,
}

impl Size {
    pub(crate) fn suffix(self) -> &'static str {
        match self {
            Size::Sm => "sm",
            Size::Md => "md",
            Size::Lg => "lg",
        }
    }
}

/// Corner rounding. `None` in a builder keeps the component's own default.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Radius {
    None,
    Sm,
    Md,
    Lg,
    Full,
}

impl Radius {
    pub(crate) fn class(self) -> &'static str {
        match self {
            Radius::None => "nr-r-none",
            Radius::Sm => "nr-r-sm",
            Radius::Md => "nr-r-md",
            Radius::Lg => "nr-r-lg",
            Radius::Full => "nr-r-full",
        }
    }
}

/// Visual style of buttons and chips.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Variant {
    /// Filled with the color.
    #[default]
    Solid,
    /// Outlined with the color.
    Bordered,
    /// Transparent until hovered.
    Light,
    /// A soft tint of the color.
    Flat,
    /// Neutral fill and border, colored text.
    Faded,
    /// Solid with a colored glow.
    Shadow,
    /// Outlined, filled on hover.
    Ghost,
}

impl Variant {
    pub(crate) fn suffix(self) -> &'static str {
        match self {
            Variant::Solid => "solid",
            Variant::Bordered => "bordered",
            Variant::Light => "light",
            Variant::Flat => "flat",
            Variant::Faded => "faded",
            Variant::Shadow => "shadow",
            Variant::Ghost => "ghost",
        }
    }
}

/// Visual style of text fields, selects and date pickers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FieldVariant {
    /// A soft filled box.
    #[default]
    Flat,
    /// An outlined box.
    Bordered,
    /// Filled and outlined.
    Faded,
    /// Only a bottom line.
    Underlined,
}

impl FieldVariant {
    pub(crate) fn class(self) -> &'static str {
        match self {
            FieldVariant::Flat => "nr-field-flat",
            FieldVariant::Bordered => "nr-field-bordered",
            FieldVariant::Faded => "nr-field-faded",
            FieldVariant::Underlined => "nr-field-underlined",
        }
    }
}

/// Text that may be absent: `&str`, `String` or an `Option` of either, so
/// `error_message = form.error("email")` works as is.
pub trait MaybeText {
    fn into_text(self) -> Option<String>;
}

impl MaybeText for &str {
    fn into_text(self) -> Option<String> {
        Some(self.to_owned())
    }
}
impl MaybeText for String {
    fn into_text(self) -> Option<String> {
        Some(self)
    }
}
impl MaybeText for &String {
    fn into_text(self) -> Option<String> {
        Some(self.clone())
    }
}
impl<T: MaybeText> MaybeText for Option<T> {
    fn into_text(self) -> Option<String> {
        self.and_then(MaybeText::into_text).filter(|s| !s.is_empty())
    }
}

/// Attributes and children given to a component inside its macro.
#[derive(Default)]
pub(crate) struct Extra {
    el: Option<Element>,
}

impl Extra {
    pub(crate) fn push(&mut self, part: impl Part) {
        part.apply(self.el.get_or_insert_with(|| Element::new("div")));
    }

    /// `(class attribute of the outer element, other attributes, children)`.
    pub(crate) fn split(self) -> (Option<Attr>, Vec<Attr>, Vec<Node>) {
        let Some(el) = self.el else { return (None, Vec::new(), Vec::new()) };
        let mut class = None;
        let mut attrs = Vec::new();
        for a in el.attrs {
            if a.name == "class" {
                class = Some(a);
            } else {
                attrs.push(a);
            }
        }
        (class, attrs, el.children)
    }
}

/// Unique element id for labels and descriptions.
pub(crate) fn next_id(prefix: &str) -> String {
    static NEXT: AtomicUsize = AtomicUsize::new(0);
    format!("{prefix}-{}", NEXT.fetch_add(1, Ordering::Relaxed))
}

/// An element with the component classes (unless unstyled), the extra class
/// and the component stylesheet.
pub(crate) fn root(tag: &'static str, classes: &[&str], unstyled: bool, extra: Option<Attr>) -> Element {
    let mut el = Element::new(tag);
    if !unstyled {
        el.set_attr(Attr::new(
            "class",
            classes.iter().filter(|c| !c.is_empty()).copied().collect::<Vec<_>>().join(" "),
        ));
    }
    if let Some(class) = extra {
        el.set_attr(class);
    }
    el
}

/// `class="…"` for an inner part: its default class plus the one given for it.
pub(crate) fn part_class(default: &str, extra: &Option<String>) -> Attr {
    match extra {
        Some(e) => Attr::new("class", format!("{default} {e}")),
        None => Attr::new("class", default.to_owned()),
    }
}

pub(crate) fn attr(name: &'static str, value: impl Into<Cow<'static, str>>) -> Attr {
    Attr::new(name, value)
}

pub(crate) fn flag(name: &'static str, on: bool) -> Attr {
    Attr::boolean(name, on)
}

/// Apply attributes to an element (`class` merges, others replace).
pub(crate) fn apply(el: &mut Element, attrs: Vec<Attr>) {
    for a in attrs {
        el.set_attr(a);
    }
}

/// The element plus the stylesheet, as a node.
pub(crate) fn styled(el: Element) -> Node {
    Node::Fragment(vec![Node::Style(&UI_CSS), el.into_node()])
}

/// Set properties and add parts: `ui!(Button::new(), color = Color::Primary, class("x"), "Save")`.
///
/// The component macros (`Button!`, `Input!`, ...) are built on this.
#[doc(hidden)]
#[macro_export]
macro_rules! __ui_munch {
    ([$($acc:tt)*]) => { $($acc)* };
    ([$($acc:tt)*] $key:ident = $val:expr $(, $($rest:tt)*)?) => {
        $crate::__ui_munch!([$($acc)*.$key($val)] $($($rest)*)?)
    };
    ([$($acc:tt)*] $part:expr $(, $($rest:tt)*)?) => {
        $crate::__ui_munch!([$($acc)*.with($part)] $($($rest)*)?)
    };
}

/// Build a [`AppShell`](struct@crate::AppShell): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! AppShell {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::AppShell::new()] $($body)*) };
}

/// Build a [`Avatar`](struct@crate::Avatar): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Avatar {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Avatar::new()] $($body)*) };
}

/// Build a [`AvatarGroup`](struct@crate::AvatarGroup): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! AvatarGroup {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::AvatarGroup::new()] $($body)*) };
}

/// Build a [`Button`](struct@crate::Button): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Button {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Button::new()] $($body)*) };
}

/// Build a [`ButtonGroup`](struct@crate::ButtonGroup): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! ButtonGroup {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::ButtonGroup::new()] $($body)*) };
}

/// Build a [`Card`](struct@crate::Card): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Card {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Card::new()] $($body)*) };
}

/// Build a [`CardBody`](struct@crate::CardBody): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! CardBody {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::CardBody::new()] $($body)*) };
}

/// Build a [`CardFooter`](struct@crate::CardFooter): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! CardFooter {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::CardFooter::new()] $($body)*) };
}

/// Build a [`CardHeader`](struct@crate::CardHeader): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! CardHeader {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::CardHeader::new()] $($body)*) };
}

/// Build a [`Checkbox`](struct@crate::Checkbox): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Checkbox {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Checkbox::new()] $($body)*) };
}

/// Build a [`Chip`](struct@crate::Chip): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Chip {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Chip::new()] $($body)*) };
}

/// Build a [`Container`](struct@crate::Container): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Container {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Container::new()] $($body)*) };
}

/// Build a [`DatePicker`](struct@crate::DatePicker): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! DatePicker {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::DatePicker::new()] $($body)*) };
}

/// Build a [`Divider`](struct@crate::Divider): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Divider {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Divider::new()] $($body)*) };
}

/// Build a [`Grid`](struct@crate::Grid): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Grid {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Grid::new()] $($body)*) };
}

/// Build a [`Input`](struct@crate::Input): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Input {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Input::new()] $($body)*) };
}

/// Build a [`Navbar`](struct@crate::Navbar): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Navbar {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Navbar::new()] $($body)*) };
}

/// Build a [`NavbarItem`](struct@crate::NavbarItem): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! NavbarItem {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::NavbarItem::new()] $($body)*) };
}

/// Build a [`PasswordInput`](struct@crate::PasswordInput): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! PasswordInput {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::PasswordInput::new()] $($body)*) };
}

/// Build a [`Radio`](struct@crate::Radio): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Radio {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Radio::new()] $($body)*) };
}

/// Build a [`RadioGroup`](struct@crate::RadioGroup): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! RadioGroup {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::RadioGroup::new()] $($body)*) };
}

/// Build a [`Select`](struct@crate::Select): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Select {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Select::new()] $($body)*) };
}

/// Build a [`SelectItem`](struct@crate::SelectItem): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! SelectItem {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::SelectItem::new()] $($body)*) };
}

/// Build a [`Sidebar`](struct@crate::Sidebar): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Sidebar {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Sidebar::new()] $($body)*) };
}

/// Build a [`SidebarItem`](struct@crate::SidebarItem): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! SidebarItem {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::SidebarItem::new()] $($body)*) };
}

/// Build a [`Spinner`](struct@crate::Spinner): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Spinner {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Spinner::new()] $($body)*) };
}

/// Build a [`Stack`](struct@crate::Stack): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Stack {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Stack::new()] $($body)*) };
}

/// Build a [`Switch`](struct@crate::Switch): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Switch {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Switch::new()] $($body)*) };
}

/// Build a [`Textarea`](struct@crate::Textarea): `key = value` sets a property, anything else is
/// added as an attribute or child.
#[macro_export]
macro_rules! Textarea {
    ($($body:tt)*) => { $crate::__ui_munch!([$crate::Textarea::new()] $($body)*) };
}