leptodon 0.1.0

your Leptos UI toolkit for data science
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
// Leptodon
//
// Copyright (C) 2025-2026 Open Analytics NV
//
// ===========================================================================
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the Apache License as published by The Apache Software
// Foundation, either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the Apache License for more details.
//
// You should have received a copy of the Apache License along with this program.
// If not, see <http://www.apache.org/licenses/>
use crate::button::Button;
use crate::button::ButtonAppearance;
use crate::button_group::ButtonGroup;
use crate::button_group::First;
use crate::button_group::InGroupContext;
use crate::button_group::Last;
use crate::class_list;
use crate::form_input::FormInputContext;
use crate::form_input::Label;
use crate::form_input::MaybeLabelledFormInput;
use crate::icon::HideIcon;
use crate::icon::ShowIcon;
use crate::input_group::GroupItemClassContext;
use crate::util::callback::ArcOneCallback;
use crate::util::callback::BoxOneCallback;
use leptodon_proc_macros::generate_docs;
use leptos::either::Either;
use leptos::html;
use leptos::logging::debug_log;
use leptos::prelude::ClassAttribute;
use leptos::prelude::Effect;
use leptos::prelude::ElementChild;
use leptos::prelude::Get;
use leptos::prelude::GetUntracked;
use leptos::prelude::GlobalAttributes;
use leptos::prelude::IntoAny;
use leptos::prelude::MaybeProp;
use leptos::prelude::NodeRef;
use leptos::prelude::NodeRefAttribute;
use leptos::prelude::OnAttribute;
use leptos::prelude::RwSignal;
use leptos::prelude::Set;
use leptos::prelude::Signal;
use leptos::prelude::Update;
use leptos::prelude::use_context;
use leptos::{IntoView, component, view};
use leptos_use::math::use_or;
use std::fmt::Debug;
use web_sys::Event;
use web_sys::FocusEvent;
use web_sys::KeyboardEvent;
use zxcvbn::Score;
use zxcvbn::zxcvbn;

mod number;
pub use crate::input::number::*;
mod upload;
pub use crate::input::upload::*;

pub const OA_READONLY_INPUT_CLASSES: &str = "border-0 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500";
const OA_INPUT_CLASSES: &str = "shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500";
pub const PLACEHOLDER_TEXT_CLASS: &str = "text-gray-600 dark:text-gray-400";
#[generate_docs]
#[component]
#[allow(unused)] // Generated propsbuilder is used.
pub fn TextInputConfig(
    #[prop(optional, into)] max_len: MaybeProp<u32>,
    // A min-len of 1 should be provided via the "required" property instead.
    #[prop(optional, into)] min_len: MaybeProp<u32>,
    // Whether or not to trim surrounding whitespace "  My name " -> "My name"
    #[prop(default = true)] trim: bool,
) -> impl IntoView {
}

#[generate_docs]
#[component]
pub fn TextInput(
    /// Id for the input.
    #[prop(optional, into)]
    id: MaybeProp<String>,
    /// Extra classes added to augment the default style.
    #[prop(optional, into)]
    class: MaybeProp<String>,
    /// Will be initialised with a DOM reference to the backing <input> element.
    #[prop(optional)]
    input_ref: NodeRef<html::Input>,
    /// Text above the input that informs the user what to type.
    #[prop(optional, into)]
    label: MaybeProp<String>,
    /// This name is submitted along with the control's value when the form data is submitted.
    #[prop(optional, into)]
    name: MaybeProp<String>,
    /// An input can have different text-based types based on the type of value the user will enter.
    #[prop(optional, into)]
    input_type: Signal<InputType>,
    /// An input can have different modes, useful for mobile devices to bring up the correct virtual keyboard. More fine-grained than type.
    #[prop(optional, into)]
    input_mode: Signal<InputMode>,
    #[prop(default = TextInputConfigProps::builder().build())] text_config: TextInputConfigProps,
    /// Binds to the value of the input, has to be a string.
    #[prop(optional)]
    value: RwSignal<String>,
    /// Whether the input is readonly.
    #[prop(optional, into)]
    readonly: Signal<bool>,
    /// Whether the input is required.
    #[prop(optional, into)]
    required: Signal<bool>,
    /// Placeholder text for the input.
    #[prop(optional, into)]
    placeholder: MaybeProp<String>,
) -> impl IntoView {
    let parser = move |input: String| {
        // Trim first if configured, so we do not count whitespace characters.
        let input = if text_config.trim {
            input.trim()
        } else {
            input.as_str()
        };

        // != input.len()
        // emojis and other special characters are counted as only 1 extra length using the String::chars(&self) iterator.
        let input_len = input.chars().count() as u32;

        if let Some(max_len) = text_config.max_len.get()
            && let Some(min_len) = text_config.min_len.get()
        {
            if input_len > max_len || input_len < min_len {
                return Err(format!("Input Length must be >{min_len} and <{max_len}"));
            }
        } else if let Some(max_len) = text_config.max_len.get() {
            if input_len > max_len {
                return Err(format!("Input Length must be <{max_len}"));
            }
        } else if let Some(min_len) = text_config.min_len.get()
            && input_len < min_len
        {
            return Err(format!("Input Length must be >{min_len}"));
        }

        Ok(String::from(input))
    };

    let format = move |input: String| input;

    view! {
        <GenericInput<String, String>
            id
            class
            input_ref
            label
            name
            input_type
            input_mode
            value
            readonly
            required
            placeholder
            parser
            format
        />
    }
}

#[generate_docs]
/// Integrates with dropbox's zxcvbn to create non annoying and actually strong passwords.
#[component]
pub fn PasswordInput(
    /// Id for the input.
    #[prop(optional, into)]
    id: MaybeProp<String>,
    /// Extra classes added to augment the default style.
    #[prop(optional, into)]
    class: MaybeProp<String>,
    /// Will be initialised with a DOM reference to the backing <input> element.
    #[prop(optional)]
    input_ref: NodeRef<html::Input>,
    /// Text above the input that informs the user what to type.
    #[prop(optional, into)]
    label: MaybeProp<String>,
    /// This name is submitted along with the control's value when the form data is submitted.
    #[prop(optional, into)]
    name: MaybeProp<String>,
    /// List of information to disallow in the password, should be all available info on the user.
    /// Attackers frequently try combinations of public/leaked information they have on people.
    #[prop(into)]
    hazards: Vec<String>,
    // TODO: Show strength bar
    // #[prop(default = false)]
    // show_strength: bool,
    /// Shows an eye-icon-button next to the password input.
    /// Clicking the button toggles the input between plaintext and password mode.
    #[prop(default = false)]
    show_eye: bool,
    /// Binds to the value of the input.
    /// Passwords support all characters.
    #[prop(optional, into)]
    value: RwSignal<String>,
    /// Whether the input is readonly.
    #[prop(optional, into)]
    readonly: Signal<bool>,
    /// Whether the input is required.
    #[prop(optional, into)]
    required: Signal<bool>,
    /// Placeholder text for the input.
    #[prop(optional, into)]
    placeholder: MaybeProp<String>,
) -> impl IntoView {
    let parser = ArcOneCallback::new(move |input: String| {
        let hazard_strs: Vec<&str> = hazards.iter().map(|s| s.as_ref()).collect();
        let entropy = zxcvbn(input.as_str(), hazard_strs.as_slice());

        if let Some(feedback) = entropy.feedback() {
            return Err(format!("{feedback}"));
        }

        if entropy.score() < Score::Four {
            return Err("Almost strong enough, add another word or a couple symbols.".to_string());
        }

        Ok(input)
    });

    let password_vis = RwSignal::new(false);

    if show_eye {
        // Form context
        let form_context = use_context::<FormInputContext<String>>();
        let form_required = Signal::from(
            form_context
                .clone()
                .map(|ctx| ctx.required)
                .unwrap_or_default(),
        );
        let required = use_or(required, form_required);
        let label = if let Some(form_context) = form_context {
            if form_context.label.get().is_some() || label.get().is_none() {
                // Either the form context already provides the label, or we don't have one
                // -> Then don't place a label
                MaybeProp::default()
            } else {
                label
            }
        } else {
            label
        };
        view! {
            <MaybeLabelledFormInput<String> label required=required.get()>
                <ButtonGroup>
                    <First slot:first>
                        <GenericInput<String, String>
                            id
                            class
                            input_ref
                            label
                            name
                            value
                            readonly
                            required
                            placeholder
                            input_type=Signal::derive(move || { if password_vis.get() { InputType::Text } else { InputType::Password } })
                            parser=parser.clone()
                        />
                    </First>
                    <Last slot:last>
                        <Button
                            on_click=move |_| {
                                password_vis.update(|mut_vis| *mut_vis = !*mut_vis)
                            }
                            appearance=ButtonAppearance::Secondary
                            icon=Signal::derive(move || {
                                if password_vis.get() { HideIcon() } else { ShowIcon() }
                            })
                        ></Button>
                    </Last>
                </ButtonGroup>
            </MaybeLabelledFormInput<String>>
        }.into_any()
    } else {
        view! {
            <GenericInput<String, String>
                id
                class
                input_ref
                label
                name
                value
                readonly
                required
                placeholder
                input_type=move || { if password_vis.get() { InputType::Text } else { InputType::Password } }
                parser=parser.clone()
            />
        }.into_any()
    }
}

#[generate_docs]
/// If the input is empty but you supplied **value** then check if you supplied a **format** handler
///
/// The normal layout is as follows:
/// ---------
/// | <Required *><Label>
/// | <Input required>
/// | <ParserFeedback<E>>
/// ---------
///
/// The layout can be changed by providing FormInputContext, generally done via `<FormInput label=... required=true><GenericInput<T,E> ... /></FormInput>`
/// The result is as follows:
/// ----GenericInput<T,E>----
/// | <Input required>
/// ---------
/// The label and parser feedback are then to be rendered by the FormInputContext-providing parent (e.g. [FormInput]).
/// Most useful when you need a ButtonGroup around the input. An example can be seen in the overview under forms, specifically the password input.
#[component]
pub fn GenericInput<T, E>(
    /// Id for the input.
    #[prop(optional, into)]
    id: MaybeProp<String>,
    /// Extra classes added to augment the default style.
    #[prop(optional, into)]
    class: MaybeProp<String>,
    /// Will be initialised with a DOM reference to the backing <input> element.
    #[prop(optional)]
    input_ref: NodeRef<html::Input>,
    /// Text above the input that informs the user what to type.
    #[prop(optional, into)]
    label: MaybeProp<String>,
    /// A string specifying a name for the input control.
    /// This name is submitted along with the control's value when the form data is submitted.
    #[prop(optional, into)]
    name: MaybeProp<String>,
    /// An input can have different text-based types based on the type of value the user will enter.
    #[prop(optional, into)]
    input_type: Signal<InputType>,
    /// An inputform_context.required can have different modes, useful for mobile devices to bring up the correct virtual keyboard. More fine-grained than type.
    #[prop(optional, into)]
    input_mode: Signal<InputMode>,
    /// Binds to the value of the input.
    #[prop(optional, into)]
    value: RwSignal<T>,
    /// Maps the user input to [T], not ran on empty inputs unless [required] is true
    #[prop(optional, into)]
    parser: Option<ArcOneCallback<String, Result<T, E>>>,
    /// Formats the value to be shown to the user, only happens when the user indicates they are done inputting.
    /// E.g. via Enter, Escape or leaving the input
    #[prop(optional, into)]
    format: Option<BoxOneCallback<T, String>>,
    /// Whether the input is required.
    #[prop(optional, into)]
    required: Signal<bool>,
    /// On focus event listener, sometimes the input is wrapped inside a label etc so listeners can't be added from outside.
    /// In such cases use this property.
    #[prop(optional, into)]
    on_focus: MaybeProp<ArcOneCallback<FocusEvent>>,
    /// Whether the input is readonly.
    #[prop(optional, into)]
    readonly: Signal<bool>,
    /// Placeholder text for the input.
    #[prop(optional, into)]
    placeholder: MaybeProp<String>,
    /// Stepsize for number and date-inputs.
    #[prop(optional, into)]
    step: MaybeProp<String>,
    /// Minimum for comparable inputs.
    #[prop(optional, into)]
    min: MaybeProp<String>,
    /// Maximum for comparable inputs.
    #[prop(optional, into)]
    max: MaybeProp<String>,
) -> impl IntoView
where
    T: Clone + PartialEq + Debug + Default + Sync + Send + 'static,
    E: Clone + Send + Sync + Debug + std::fmt::Display + 'static,
{
    // let input_ref = NodeRef::<html::Input>::new();
    // comp_ref.load(InputRef { input_ref });
    let group_context = use_context::<GroupItemClassContext>();
    let group_classes = group_context.map(|item| item.class);
    let in_group = use_context::<InGroupContext>().unwrap_or(InGroupContext { in_group: false });
    let last_set_value = RwSignal::new(value.get_untracked());

    // Form context
    let form_context = use_context::<FormInputContext<E>>();
    let form_required = Signal::from(
        form_context
            .clone()
            .map(|ctx| ctx.required)
            .unwrap_or_default(),
    );
    let required = use_or(required, form_required);
    let in_form = form_context.is_some();

    // String value bound to <input>
    // let internal_value_signal = RwSignal::new("".to_string());
    let invalid_reason = RwSignal::new(None);

    let try_parse = {
        let parser = parser.clone();
        move |should_format: bool| {
            let Some(input) = input_ref.get_untracked() else {
                return;
            };
            // let internal_value = internal_value_signal.get();
            let internal_value = input.value();
            debug_log!("Attempting to parse: {internal_value}, format({should_format})",);
            if let Some(parser) = parser.as_ref()
                && (!internal_value.is_empty() || required.get())
            {
                let parsed_value = parser(internal_value);
                debug_log!("Parse result: {parsed_value:?}");

                match parsed_value {
                    Ok(parsed_success) => {
                        // Set both signals, used to differentiate outside changes (where we always want to format) vs inside changes (where we sometimes want to format).
                        // Changing the parsed value causes a format
                        // the blur handler will want to format while input handling does not.
                        if !should_format {
                            debug_log!("Preventing internal format");
                            last_set_value.set(parsed_success.clone());
                        }
                        debug_log!("Updating value");
                        value.set(parsed_success);

                        invalid_reason.set(None);
                    }
                    Err(err) => {
                        invalid_reason.set(Some(err));
                    }
                }
            } else if internal_value.is_empty() && !required.get() {
                // Parse empty data such that cases where going from "some_input" to "" still update the value when the parser accepts this.
                // E.g. a description field probably allows empty strings.
                if let Some(parser) = parser.as_ref()
                    && let Ok(parsed_value) = parser(internal_value)
                {
                    if !should_format {
                        debug_log!("Preventing internal format");
                        last_set_value.set(parsed_value.clone());
                    }
                    debug_log!("Updating value");
                    value.set(parsed_value);
                }

                // debug_log!("Non-required empty field, clearing invalid status.");
                invalid_reason.set(None);
            }
        }
    };

    // Notify form feedback of this input's invalid reason.
    if let Some(form_context) = form_context {
        Effect::new(move || {
            form_context.feedback.set(invalid_reason.get());
        });
    }

    // When the Input loses focus, try parsing the new value
    let on_blur = {
        let try_parse = try_parse.clone();
        move |_| {
            try_parse(true);
        }
    };

    // If there is an error, try parsing on each key to transition in real time to a good state.
    let on_input = {
        let try_parse = try_parse.clone();
        move |_: Event| {
            // if invalid_reason.get().is_some() {
            // Formatting should only be done when the user indicates they are done, e.g. by leaving the field (on_blur).
            // Otherwise a format can disrupt the input
            try_parse(false);
            // }
        }
    };

    // On a successfull parsing or change of value this function formats the input field.
    Effect::watch(
        move || value.get(),
        move |value, _, _| {
            if let Some(format) = format.as_ref() {
                if &(last_set_value.get_untracked()) != value {
                    let Some(input) = input_ref.get_untracked() else {
                        return;
                    };
                    input.set_value(format(value.clone()).as_str());
                } else {
                    debug_log!("Prevented internal format");
                }
            } else {
                debug_log!("No formatter to format {:?}", value)
            }
        },
        true,
    );

    let standalone_input = view! {
        <input id=id.get()
            type=move || input_type.get().as_str()
            inputmode=move || input_mode.get().as_str()
            name={name.get()}
            // bind:value=internal_value_signal
            class=class_list![
                ("border-oa-red", move || invalid_reason.get().is_some()),
                group_classes.unwrap_or_default(),
                if in_group.in_group { "rounded-none border-r-0 !mr-0" } else { "" },
                (OA_READONLY_INPUT_CLASSES, move || readonly.get()),
                (OA_INPUT_CLASSES, move || !readonly.get()),
                class
            ]
            disabled={readonly.get()}
            readonly={readonly.get()}
            node_ref=input_ref
            placeholder={placeholder.get()}
            required={required.get()}
            on:blur=on_blur
            on:input=on_input
            on:focus=move |e| {if let Some(on_focus) = on_focus.get() { on_focus(e) }}
            on:keydown={
                let try_parse = try_parse.clone();
                move |key: KeyboardEvent| {
                    if key.code() == "Enter" {
                        try_parse(true);
                    }
                }
            }
            step=step.get()
            min=min.get()
            max=max.get()
        />
        {
            move || {
                if let Some(invalid_reason) = invalid_reason.get() && !in_form {
                    Either::Left(view!{
                        <div
                            id=id.get().map(|id| format!("{id}-invalid-reason"))
                            class="text-oa-red"
                        >{
                            invalid_reason.to_string()
                        }</div>
                    })
                } else { Either::Right(()) }
            }
        }
    };

    if let Some(label) = label.get()
        && !in_form
    {
        Either::Left(view! {
            <div>
                <Label required=required.get() label>
                    {standalone_input}
                </Label>
            </div>
        })
    } else {
        Either::Right(standalone_input)
    }
}

#[derive(Clone)]
pub struct InputRef {
    pub input_ref: NodeRef<html::Input>,
}

#[derive(Default, Clone)]
pub enum InputType {
    #[default]
    Text,
    Password,
    Search,
    Tel,
    Url,
    Email,
    Time,
    Date,
    DatetimeLocal,
    Month,
    Week,
    Number,
}

impl InputType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::Password => "password",
            Self::Search => "search",
            Self::Tel => "tel",
            Self::Url => "url",
            Self::Email => "email",
            Self::Time => "time",
            Self::Date => "date",
            Self::DatetimeLocal => "datetime-local",
            Self::Month => "month",
            Self::Week => "week",
            Self::Number => "number",
        }
    }
}

#[derive(Default, Clone)]
pub enum InputMode {
    #[default]
    Text,
    /// Decimal numbers
    Decimal,
    /// Only digits
    Numeric,
    /// Telephone number keypad
    Tel,
    /// Submit button may become "search" button
    Search,
    /// Standard text with an @ key
    Email,
    /// Standard keyboard with perhaps a / key
    Url,
}

impl InputMode {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::Decimal => "decimal",
            Self::Numeric => "numeric",
            Self::Search => "search",
            Self::Tel => "tel",
            Self::Url => "url",
            Self::Email => "email",
        }
    }
}