tachys/html/
directive.rs

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
use super::attribute::{Attribute, NextAttribute};
use crate::{
    prelude::AddAnyAttr,
    view::{Position, ToTemplate},
};
use send_wrapper::SendWrapper;
use std::{marker::PhantomData, sync::Arc};

/// Adds a directive to the element, which runs some custom logic in the browser when the element
/// is created or hydrated.
pub trait DirectiveAttribute<T, P, D>
where
    D: IntoDirective<T, P>,
{
    /// The type of the element with the directive added.
    type Output;

    /// Adds a directive to the element, which runs some custom logic in the browser when the element
    /// is created or hydrated.
    fn directive(self, handler: D, param: P) -> Self::Output;
}

impl<V, T, P, D> DirectiveAttribute<T, P, D> for V
where
    V: AddAnyAttr,
    D: IntoDirective<T, P>,
    P: Clone + 'static,
    T: 'static,
{
    type Output = <Self as AddAnyAttr>::Output<Directive<T, D, P>>;

    fn directive(self, handler: D, param: P) -> Self::Output {
        self.add_any_attr(directive(handler, param))
    }
}

/// Adds a directive to the element, which runs some custom logic in the browser when the element
/// is created or hydrated.
#[inline(always)]
pub fn directive<T, P, D>(handler: D, param: P) -> Directive<T, D, P>
where
    D: IntoDirective<T, P>,
{
    Directive(Some(SendWrapper::new(DirectiveInner {
        handler,
        param,
        t: PhantomData,
    })))
}

/// Custom logic that runs in the browser when the element is created or hydrated.
#[derive(Debug)]
pub struct Directive<T, D, P>(Option<SendWrapper<DirectiveInner<T, D, P>>>);

impl<T, D, P> Clone for Directive<T, D, P>
where
    P: Clone + 'static,
    D: Clone,
{
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

#[derive(Debug)]
struct DirectiveInner<T, D, P> {
    handler: D,
    param: P,
    t: PhantomData<T>,
}

impl<T, D, P> Clone for DirectiveInner<T, D, P>
where
    P: Clone + 'static,
    D: Clone,
{
    fn clone(&self) -> Self {
        Self {
            handler: self.handler.clone(),
            param: self.param.clone(),
            t: PhantomData,
        }
    }
}

impl<T, P, D> Attribute for Directive<T, D, P>
where
    D: IntoDirective<T, P>,
    P: Clone + 'static, // TODO this is just here to make them cloneable
    T: 'static,
{
    const MIN_LENGTH: usize = 0;

    type AsyncOutput = Self;
    type State = crate::renderer::types::Element;
    type Cloneable = Directive<T, D::Cloneable, P>;
    type CloneableOwned = Directive<T, D::Cloneable, P>;

    fn html_len(&self) -> usize {
        0
    }

    fn to_html(
        self,
        _buf: &mut String,
        _class: &mut String,
        _style: &mut String,
        _inner_html: &mut String,
    ) {
    }

    fn hydrate<const FROM_SERVER: bool>(
        self,
        el: &crate::renderer::types::Element,
    ) -> Self::State {
        let inner = self.0.expect("directive removed early").take();
        inner.handler.run(el.clone(), inner.param);
        el.clone()
    }

    fn build(self, el: &crate::renderer::types::Element) -> Self::State {
        let inner = self.0.expect("directive removed early").take();
        inner.handler.run(el.clone(), inner.param);
        el.clone()
    }

    fn rebuild(self, state: &mut Self::State) {
        let inner = self.0.expect("directive removed early").take();
        inner.handler.run(state.clone(), inner.param);
    }

    fn into_cloneable(self) -> Self::Cloneable {
        self.into_cloneable_owned()
    }

    fn into_cloneable_owned(self) -> Self::CloneableOwned {
        let inner = self.0.map(|inner| {
            let DirectiveInner { handler, param, t } = inner.take();
            SendWrapper::new(DirectiveInner {
                handler: handler.into_cloneable(),
                param,
                t,
            })
        });
        Directive(inner)
    }

    fn dry_resolve(&mut self) {
        // dry_resolve() only runs during SSR, and we should use it to
        // synchronously remove and drop the SendWrapper value
        // we don't need this value during SSR and leaving it here could drop it
        // from a different thread
        self.0.take();
    }

    async fn resolve(self) -> Self::AsyncOutput {
        self
    }
}

impl<T, D, P> NextAttribute for Directive<T, D, P>
where
    D: IntoDirective<T, P>,
    P: Clone + 'static,
    T: 'static,
{
    type Output<NewAttr: Attribute> = (Self, NewAttr);

    fn add_any_attr<NewAttr: Attribute>(
        self,
        new_attr: NewAttr,
    ) -> Self::Output<NewAttr> {
        (self, new_attr)
    }
}

impl<T, D, P> ToTemplate for Directive<T, D, P> {
    const CLASS: &'static str = "";

    fn to_template(
        _buf: &mut String,
        _class: &mut String,
        _style: &mut String,
        _inner_html: &mut String,
        _position: &mut Position,
    ) {
    }
}

/// Trait for a directive handler function.
/// This is used so it's possible to use functions with one or two
/// parameters as directive handlers.
///
/// You can use directives like the following.
///
/// ```ignore
/// # use leptos::{*, html::AnyElement};
///
/// // This doesn't take an attribute value
/// fn my_directive(el: crate::renderer::types::Element) {
///     // do sth
/// }
///
/// // This requires an attribute value
/// fn another_directive(el: crate::renderer::types::Element, params: i32) {
///     // do sth
/// }
///
/// #[component]
/// pub fn MyComponent() -> impl IntoView {
///     view! {
///         // no attribute value
///         <div use:my_directive></div>
///
///         // with an attribute value
///         <div use:another_directive=8></div>
///     }
/// }
/// ```
///
/// A directive is just syntactic sugar for
///
/// ```ignore
/// let node_ref = create_node_ref();
///
/// create_effect(move |_| {
///     if let Some(el) = node_ref.get() {
///         directive_func(el, possibly_some_param);
///     }
/// });
/// ```
///
/// A directive can be a function with one or two parameters.
/// The first is the element the directive is added to and the optional
/// second is the parameter that is provided in the attribute.
pub trait IntoDirective<T: ?Sized, P> {
    /// An equivalent to this directive that is cloneable and owned.
    type Cloneable: IntoDirective<T, P> + Clone + 'static;

    /// Calls the handler function
    fn run(&self, el: crate::renderer::types::Element, param: P);

    /// Converts this into a cloneable type.
    fn into_cloneable(self) -> Self::Cloneable;
}

impl<F> IntoDirective<(crate::renderer::types::Element,), ()> for F
where
    F: Fn(crate::renderer::types::Element) + 'static,
{
    type Cloneable = Arc<dyn Fn(crate::renderer::types::Element)>;

    fn run(&self, el: crate::renderer::types::Element, _: ()) {
        self(el)
    }

    fn into_cloneable(self) -> Self::Cloneable {
        Arc::new(self)
    }
}

impl IntoDirective<(crate::renderer::types::Element,), ()>
    for Arc<dyn Fn(crate::renderer::types::Element)>
{
    type Cloneable = Arc<dyn Fn(crate::renderer::types::Element)>;

    fn run(&self, el: crate::renderer::types::Element, _: ()) {
        self(el)
    }

    fn into_cloneable(self) -> Self::Cloneable {
        self
    }
}

impl<F, P> IntoDirective<(crate::renderer::types::Element, P), P> for F
where
    F: Fn(crate::renderer::types::Element, P) + 'static,
    P: 'static,
{
    type Cloneable = Arc<dyn Fn(crate::renderer::types::Element, P)>;

    fn run(&self, el: crate::renderer::types::Element, param: P) {
        self(el, param);
    }

    fn into_cloneable(self) -> Self::Cloneable {
        Arc::new(self)
    }
}

impl<P> IntoDirective<(crate::renderer::types::Element, P), P>
    for Arc<dyn Fn(crate::renderer::types::Element, P)>
where
    P: 'static,
{
    type Cloneable = Arc<dyn Fn(crate::renderer::types::Element, P)>;

    fn run(&self, el: crate::renderer::types::Element, param: P) {
        self(el, param)
    }

    fn into_cloneable(self) -> Self::Cloneable {
        self
    }
}