thaw/auto_complete/
types.rs

1use crate::{InputRef, InputSize};
2use leptos::prelude::*;
3use std::collections::HashMap;
4use thaw_utils::{ArcOneCallback, ComponentRef, Model};
5
6#[slot]
7pub struct AutoCompletePrefix {
8    children: Children,
9}
10
11#[slot]
12pub struct AutoCompleteSuffix {
13    children: Children,
14}
15
16#[derive(Clone)]
17pub(crate) struct AutoCompleteInjection {
18    pub(super) value: Model<String>,
19    pub(super) select_option: ArcOneCallback<String>,
20    pub(super) options: StoredValue<HashMap<String, String>>,
21}
22
23impl AutoCompleteInjection {
24    pub fn expect_context() -> Self {
25        expect_context()
26    }
27
28    pub fn is_selected(&self, key: &String) -> bool {
29        self.value.with(|value| value == key)
30    }
31
32    pub fn select_option(&self, value: String) {
33        (self.select_option)(value);
34    }
35
36    pub fn insert_option(&self, id: String, value: String) {
37        self.options.update_value(|options| {
38            options.insert(id, value);
39        });
40    }
41
42    pub fn remove_option(&self, id: &String) {
43        self.options.update_value(|options| {
44            options.remove(id);
45        });
46    }
47}
48
49#[derive(Clone)]
50pub struct AutoCompleteRef {
51    pub(super) input_ref: ComponentRef<InputRef>,
52}
53
54impl AutoCompleteRef {
55    /// Focus the input element.
56    pub fn focus(&self) {
57        if let Some(input_ref) = self.input_ref.get_untracked() {
58            input_ref.focus();
59        }
60    }
61
62    /// Blur the input element.
63    pub fn blur(&self) {
64        if let Some(input_ref) = self.input_ref.get_untracked() {
65            input_ref.blur();
66        }
67    }
68}
69
70#[derive(Debug, Default, PartialEq, Clone, Copy)]
71pub enum AutoCompleteSize {
72    Small,
73    #[default]
74    Medium,
75    Large,
76}
77
78impl AutoCompleteSize {
79    pub fn as_str(&self) -> &'static str {
80        match self {
81            Self::Small => "small",
82            Self::Medium => "medium",
83            Self::Large => "large",
84        }
85    }
86}
87
88impl From<AutoCompleteSize> for InputSize {
89    fn from(value: AutoCompleteSize) -> Self {
90        match value {
91            AutoCompleteSize::Small => Self::Small,
92            AutoCompleteSize::Medium => Self::Medium,
93            AutoCompleteSize::Large => Self::Large,
94        }
95    }
96}