cheers 0.1.0-alpha.1

Fullstack hypermedia framework for Rust.
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
use std::{borrow::Cow, fmt::Display, marker::PhantomData};

use serde::Deserialize;

use crate::{
    context::{AttributeValue, DatastarSource, ScriptSource},
    render::{
        Buffer, Render, push_datastar_source_to_html_attribute,
        push_js_single_quoted_string_to_html_attribute,
    },
    signal_path::{is_bare_signal_path_segment, parse_signal_path},
};

/// A DOM id generated for a component.
///
/// `ElementId` is not meant to be constructed manually.
///
/// - Ids are opt-in: use struct-level `#[id]`, field-level `#[id]`, or namespaced
///   `#[id("...")]` on the component.
/// - Inside the component that defines the ids, acquire `ElementId` values with the generated
///   `ids()` method.
/// - Outside that component, acquire them through the generated associated functions such as
///   `YourComponent::id(...)` and `YourComponent::id_name(...)`.
///
/// `ElementId` is used heavily when targeting patches at specific DOM nodes. It also renders as
/// an attribute value, so it can still be reused for attributes such as `id`, `for`, and
/// `aria-labelledby` when needed.
///
/// # Example
///
/// ```
/// use cheers::prelude::*;
///
/// #[derive(Cheers)]
/// struct Row {
///     #[id]
///     id: u32,
/// }
///
/// impl Render for Row {
///     fn render_to(&self, buffer: &mut Buffer<Element>) {
///         let RowIds { id } = self.ids();
///
///         html! {
///             tr id=id {}
///         }
///         .render_to(buffer);
///     }
/// }
///
/// assert_eq!(
///     Row { id: 4 }.render().into_inner(),
///     r#"<tr id="row-4"></tr>"#,
/// );
///
/// assert_eq!(Row::id(4).to_string(), "row-4");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct ElementId(pub(crate) String);

impl<'de> Deserialize<'de> for ElementId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(ElementId(s))
    }
}

impl Display for ElementId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.0, f)
    }
}

impl AsRef<ElementId> for ElementId {
    fn as_ref(&self) -> &ElementId {
        self
    }
}

impl ElementId {
    #[doc(hidden)]
    /// Used by the code generated by `#[derive(Cheers)]` for `#[id(...)]` fields.
    /// Not part of the stable public API.
    pub fn __dynamic(s: String) -> Self {
        Self(s)
    }
}

impl Render<AttributeValue> for ElementId {
    fn render_to(&self, buffer: &mut Buffer<AttributeValue>) {
        self.0.render_to(buffer);
    }
}

impl Render<DatastarSource> for ElementId {
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        self.0.render_to(buffer);
    }
}

impl Render<ScriptSource> for ElementId {
    fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
        self.0.render_to(buffer);
    }
}

#[inline]
fn push_signal_object_key(dst: &mut String, segment: &str) {
    if is_bare_signal_path_segment(segment) {
        push_datastar_source_to_html_attribute(dst, segment);
    } else {
        push_js_single_quoted_string_to_html_attribute(dst, segment);
    }
}

fn push_signal_object_prefix(path: &str, dst: &mut String) -> Option<usize> {
    let mut segments = parse_signal_path(path).into_iter();
    let first_segment = segments.next()?;

    // XSS SAFETY: signal paths are framework-generated Datastar paths. We
    // emit each object key as either a bare identifier or a quoted JS string
    // literal so arbitrary segments remain valid when embedded inside a
    // double-quoted HTML attribute value.
    push_signal_object_key(dst, &first_segment);

    let mut close_count = 0;
    for segment in segments {
        close_count += 1;
        dst.push_str(":{");
        push_signal_object_key(dst, &segment);
    }

    Some(close_count)
}

#[inline]
fn close_signal_object(dst: &mut String, count: usize) {
    for _ in 0..count {
        dst.push('}');
    }
}

/// A typed reference to a client-side signal.
///
/// `Signal<T>` is not meant to be constructed manually.
///
/// - Inside the component that defines the signal, acquire it with
///   the generated `signals()` method.
/// - Signals generated by `#[derive(Cheers)]` are Datastar-local by default: their root is
///   prefixed with `_`, so Datastar omits them from JSON request payloads. Use
///   `#[signal(global)]` for payload-sent signals.
/// - For ad-hoc client-only state defined inside a component method, acquire it with
///   [`scoped_signal!`](crate::scoped_signal).
/// - Outside the component that defines the signal, acquire it through the generated associated
///   functions such as `YourComponent::signal_name(...)`.
///
/// When rendered in [`DatastarSource`] context, a signal becomes a `$`-prefixed path
/// understood by the client-side runtime.
///
/// # Example
///
/// ```
/// use cheers::prelude::*;
///
/// #[derive(Cheers)]
/// struct Counter {
///     #[signal]
///     count: i32,
/// }
///
/// impl Render for Counter {
///     fn render_to(&self, buffer: &mut Buffer<Element>) {
///         let CounterSignals { signal_count } = self.signals();
///
///         html! {
///             span !text(signal_count) {}
///         }
///         .render_to(buffer);
///     }
/// }
///
/// assert_eq!(
///     Counter { count: 3 }.render().into_inner(),
///     r#"<span data-text="$_counter['count']"></span>"#,
/// );
///
/// let count: Signal<i32> = Counter::signal_count();
/// assert_eq!(
///     html! { span !text(count) {} }.render().into_inner(),
///     r#"<span data-text="$_counter['count']"></span>"#,
/// );
/// ```
#[derive(Debug)]
pub struct Signal<T> {
    path: Cow<'static, str>,
    ty: PhantomData<T>,
}

impl<T> Signal<T> {
    #[doc(hidden)]
    /// Used by the code generated by `#[derive(Cheers)]` when generating signal
    /// accessors for components without an id field. Not part of the stable public API.
    pub const fn __static(path: &'static str) -> Self {
        Self {
            path: Cow::Borrowed(path),
            ty: PhantomData::<T>,
        }
    }

    #[doc(hidden)]
    /// Used by the `scoped_signal!` macro to scope component-local signals to the
    /// current component instance. Not part of the stable public API.
    pub fn __scoped_with_component(
        name: String,
        component_id: String,
        file: &'static str,
        line: u32,
        column: u32,
    ) -> Self {
        let hash = hash_component_location(&component_id, file, line, column).to_string();
        let mut path = String::with_capacity(name.len() + hash.len() + 1);
        path.push('_');
        path.push_str(&name);
        path.push_str(&hash);

        Self {
            path: Cow::Owned(path),
            ty: PhantomData::<T>,
        }
    }

    #[doc(hidden)]
    /// Used by the code generated by `#[derive(Cheers)]` when generating signal
    /// accessors for components with an id field. Not part of the stable public API.
    pub fn __string(path: String) -> Self {
        Signal {
            path: Cow::Owned(path),
            ty: PhantomData::<T>,
        }
    }

    #[doc(hidden)]
    /// Used internally by the macro support methods on [`Signal`]. Not part of the stable
    /// public API.
    pub fn __path(&self) -> &str {
        self.path.as_ref()
    }

    #[doc(hidden)]
    /// Used by the `html!` and `attribute!` macros when expanding computed signal
    /// attributes. Not part of the stable public API.
    pub fn __computed_open(&self, buffer: &mut Buffer<DatastarSource>) -> usize {
        let Some(close_count) =
            push_signal_object_prefix(self.__path(), buffer.dangerously_get_string())
        else {
            return 0;
        };

        // XSS SAFETY: statically assigning a JS function - the execution is intentional.
        buffer.dangerously_get_string().push_str(":()=>");

        close_count
    }
}

impl Signal<()> {
    #[doc(hidden)]
    /// Used by the `html!` and `attribute!` macros when expanding computed signal
    /// attributes. Not part of the stable public API.
    pub fn __computed_close(count: usize, buffer: &mut Buffer<DatastarSource>) {
        // XSS SAFETY: statically closing the JS object
        close_signal_object(buffer.dangerously_get_string(), count);
    }
}

impl<T: Render<DatastarSource>> Signal<T> {
    #[doc(hidden)]
    /// Used by the `html!` and `attribute!` macros when expanding `!signals(...)`.
    /// Not part of the stable public API.
    pub fn __assign(&self, buffer: &mut Buffer<DatastarSource>, v: T) {
        let Some(close_count) = ({
            let s = buffer.dangerously_get_string();
            push_signal_object_prefix(self.__path(), s)
        }) else {
            return;
        };

        buffer.dangerously_get_string().push(':');

        v.render_to(buffer);

        // XSS SAFETY: statically closing the JS object written above.
        close_signal_object(buffer.dangerously_get_string(), close_count);
    }
}

impl<T> Render<DatastarSource> for Signal<T> {
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        let s = buffer.dangerously_get_string();

        // XSS SAFETY: `$` is static syntax, while the signal path is
        // framework-generated and HTML-escaped for attribute embedding.
        s.push('$');
        push_datastar_source_to_html_attribute(s, self.__path());
    }
}

/// A form field name generated for a component.
///
/// `FormName` is only meant to be acquired with the generated `form_names()` method inside the
/// component that defines the form fields.
///
/// Form names are component-local and are not meant to be referenced from outside the component.
/// They render as attribute values and are used for `name=` on form controls.
///
/// # Example
///
/// ```
/// use cheers::prelude::*;
///
/// #[derive(Cheers)]
/// struct LoginForm {
///     #[form]
///     email: String,
/// }
///
/// impl Render for LoginForm {
///     fn render_to(&self, buffer: &mut Buffer<Element>) {
///         let LoginFormFormNames { form_email } = self.form_names();
///
///         html! {
///             input name=(form_email);
///         }
///         .render_to(buffer);
///     }
/// }
///
/// assert_eq!(
///     LoginForm {
///         email: String::from("hello@example.com"),
///     }
///     .render()
///     .into_inner(),
///     r#"<input name="email">"#,
/// );
/// ```
#[derive(Debug, Clone, Copy)]
pub struct FormName(&'static str);

impl FormName {
    #[doc(hidden)]
    /// Used by the code generated by `#[derive(Cheers)]` and exposed through the generated
    /// `form_names()` method. Not part of the stable public API.
    pub const fn __static(s: &'static str) -> Self {
        Self(s)
    }
}

impl Render<AttributeValue> for FormName {
    fn render_to(&self, buffer: &mut Buffer<AttributeValue>) {
        self.0.render_to(buffer);
    }
}

impl Render<DatastarSource> for FormName {
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        self.0.render_to(buffer);
    }
}

impl Render<ScriptSource> for FormName {
    fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
        self.0.render_to(buffer);
    }
}

#[doc(hidden)]
/// Internal bridge used by `#[derive(Cheers)]` to compose generated form types.
pub trait FormComponent {
    type Form;
    type FormNames;

    const __FORM_NAMES: Self::FormNames;
}

/// Computes 32-bit FNV1a hash for component's location
const fn hash_component_location(
    component_id: &str,
    file: &'static str,
    line: u32,
    column: u32,
) -> u32 {
    const FNV_OFFSET_BASIS_32: u32 = 0x811c9dc5;
    const FNV_PRIME_32: u32 = 0x01000193;

    const fn hash_bytes(mut hash: u32, bytes: &[u8]) -> u32 {
        let mut i = 0;

        while i < bytes.len() {
            hash ^= bytes[i] as u32;
            hash = hash.wrapping_mul(FNV_PRIME_32);
            i += 1;
        }

        hash
    }

    const fn hash_u32(hash: u32, value: u32) -> u32 {
        hash_bytes(hash, &value.to_ne_bytes())
    }

    const fn hash_location(file: &'static str, line: u32, column: u32) -> u32 {
        let hash = hash_bytes(FNV_OFFSET_BASIS_32, file.as_bytes());
        let hash = hash_u32(hash, line);
        hash_u32(hash, column)
    }

    hash_bytes(hash_location(file, line, column), component_id.as_bytes())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn element_id_renders_as_js_string() {
        let id = ElementId::__dynamic("row-4<&\"'".to_string());
        let mut buffer = Buffer::<DatastarSource>::new();
        id.render_to(&mut buffer);
        assert_eq!(
            buffer.rendered().into_inner(),
            r#"'row-4&lt;&amp;&quot;\''"#
        );
    }

    #[test]
    fn form_name_renders_as_js_string() {
        let name = FormName::__static("email");
        let mut buffer = Buffer::<DatastarSource>::new();
        name.render_to(&mut buffer);
        assert_eq!(buffer.rendered().into_inner(), "'email'");
    }

    #[test]
    fn signal_object_string_value() {
        let signal = Signal::<&str>::__string("user['name']".to_string());
        let mut buffer = Buffer::<DatastarSource>::new();
        signal.__assign(&mut buffer, "Nick");
        assert_eq!(buffer.rendered().into_inner(), r#"user:{name:'Nick'}"#);
    }

    #[test]
    fn signal_object_number_value() {
        let signal = Signal::<f64>::__string("user['age']".to_string());
        let mut buffer = Buffer::<DatastarSource>::new();
        signal.__assign(&mut buffer, -42.0);
        assert_eq!(buffer.rendered().into_inner(), r#"user:{age:-42.0}"#);
    }

    #[test]
    fn signal_object_unsafe_segment() {
        let signal = Signal::<&str>::__string("project['user.123']['name']".to_string());
        let mut buffer = Buffer::<DatastarSource>::new();
        signal.__assign(&mut buffer, "Nick");
        assert_eq!(
            buffer.rendered().into_inner(),
            r#"project:{'user.123':{name:'Nick'}}"#
        );
    }

    #[test]
    fn hash_different_locations() {
        const HASH1: u32 = hash_component_location("diff", "src/main.rs", 10, 5);
        const HASH2: u32 = hash_component_location("diff", "src/main.rs", 10, 6);

        assert_ne!(HASH1, HASH2);
    }

    #[test]
    fn hash_same_locations() {
        const HASH1: u32 = hash_component_location("same", "src/main.rs", 42, 13);
        const HASH2: u32 = hash_component_location("same", "src/main.rs", 42, 13);

        assert_eq!(HASH1, HASH2);
    }
}