topcoat-view 0.1.0

A modular, batteries-included Rust web framework for server-rendered apps.
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
use core::fmt;
use std::borrow::Cow;

use smallvec::SmallVec;
use topcoat_core::context::Cx;

use crate::{Formatter, HtmlContext, HtmlWriter};

/// A self-contained piece of HTML content.
///
/// A view may contain multiple sibling nodes, but opened tags must be closed
/// so the fragment can be nested safely inside a larger document.
///
/// ```html
/// <!-- Valid: all tags are closed, safe to nest -->
/// <div>Hello</div>
/// <p>World</p>
///
/// <!-- Invalid: unclosed tag would corrupt the parent document -->
/// <div>Hello
/// ```
#[derive(Debug, Default, Clone)]
pub struct View {
    part: ViewPart,
}

impl View {
    /// Creates a view from accumulated view parts.
    ///
    /// This is called by generated `view!` code after collecting the nodes
    /// and attributes for a fragment.
    #[doc(hidden)]
    #[inline]
    #[must_use]
    pub fn new(parts: ViewParts) -> Self {
        Self { part: parts.into() }
    }

    /// Returns a `View` that renders to an empty string.
    #[inline]
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Creates a view from a `&'static str` without escaping it and without checking for syntax
    /// errors.
    #[inline]
    #[must_use]
    pub const fn unescaped_unchecked(body: &'static str) -> Self {
        Self {
            part: ViewPart::unescaped(body),
        }
    }

    /// Renders the view into an HTML string.
    pub fn render(&self, cx: &Cx) -> String {
        let mut buf = String::with_capacity(self.part.size_hint());
        let mut f = Formatter::new(&mut buf);
        self.part.render(cx, &mut f);
        buf
    }

    /// Unwraps the view into its root part.
    #[inline]
    pub(crate) fn into_part(self) -> ViewPart {
        self.part
    }
}

/// A renderable value stored in a [`View`].
///
/// View parts are created through a [`PartsWriter`] or the `view!` macro. A
/// part that holds text also records the [`HtmlContext`] it was written for,
/// so rendering escapes or validates it for exactly that position.
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub enum ViewPart {
    /// Renders no content.
    #[default]
    Empty,
    /// A boolean rendered as text.
    #[non_exhaustive]
    Bool(bool),
    /// An `i8` rendered as text.
    #[non_exhaustive]
    I8(i8),
    /// An `i16` rendered as text.
    #[non_exhaustive]
    I16(i16),
    /// An `i32` rendered as text.
    #[non_exhaustive]
    I32(i32),
    /// An `i64` rendered as text.
    #[non_exhaustive]
    I64(i64),
    /// An `i128` rendered as text.
    #[non_exhaustive]
    I128(i128),
    /// An `isize` rendered as text.
    #[non_exhaustive]
    Isize(isize),
    /// A `u8` rendered as text.
    #[non_exhaustive]
    U8(u8),
    /// A `u16` rendered as text.
    #[non_exhaustive]
    U16(u16),
    /// A `u32` rendered as text.
    #[non_exhaustive]
    U32(u32),
    /// A `u64` rendered as text.
    #[non_exhaustive]
    U64(u64),
    /// A `u128` rendered as text.
    #[non_exhaustive]
    U128(u128),
    /// A `usize` rendered as text.
    #[non_exhaustive]
    Usize(usize),
    /// An `f32` rendered as text.
    #[non_exhaustive]
    F32(f32),
    /// An `f64` rendered as text.
    #[non_exhaustive]
    F64(f64),
    /// A character rendered for the recorded context.
    #[non_exhaustive]
    Char { value: char, context: HtmlContext },
    /// A string rendered for the recorded context.
    #[non_exhaustive]
    Str {
        value: Cow<'static, str>,
        context: HtmlContext,
    },
    /// A custom view part that writes its output at render time.
    #[non_exhaustive]
    BoxDyn {
        inner: Box<dyn DynViewPart>,
        context: HtmlContext,
        size_hint: usize,
    },
    /// A sequence of view parts rendered in order.
    #[non_exhaustive]
    BoxSlice {
        inner: Box<[ViewPart]>,
        size_hint: usize,
    },
}

impl ViewPart {
    /// Returns an empty view part.
    #[inline]
    #[must_use]
    pub fn empty() -> Self {
        Self::Empty
    }

    /// Returns `true` if the view part is [`Empty`].
    ///
    /// [`Empty`]: ViewPart::Empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        matches!(self, Self::Empty)
    }

    /// Returns a part that renders `value` verbatim.
    #[inline]
    pub(crate) const fn unescaped(value: &'static str) -> Self {
        Self::Str {
            value: Cow::Borrowed(value),
            context: HtmlContext::Unescaped,
        }
    }

    /// Writes the part into `f`, escaped or validated for the context each
    /// piece of text was written in.
    pub(crate) fn render(&self, cx: &Cx, f: &mut Formatter<'_>) {
        let mut int_buffer = itoa::Buffer::new();
        let mut float_buffer = zmij::Buffer::new();

        match self {
            Self::Empty => {}
            Self::Bool(inner) => f.write_str(if *inner { "true" } else { "false" }),
            // The `Display` output of the numeric types consists of digits,
            // signs, and plain letters, none of which are significant in any
            // HTML context, so they write verbatim.
            Self::I8(inner) => f.write_str(int_buffer.format(*inner)),
            Self::I16(inner) => f.write_str(int_buffer.format(*inner)),
            Self::I32(inner) => f.write_str(int_buffer.format(*inner)),
            Self::I64(inner) => f.write_str(int_buffer.format(*inner)),
            Self::I128(inner) => f.write_str(int_buffer.format(*inner)),
            Self::Isize(inner) => f.write_str(int_buffer.format(*inner)),
            Self::U8(inner) => f.write_str(int_buffer.format(*inner)),
            Self::U16(inner) => f.write_str(int_buffer.format(*inner)),
            Self::U32(inner) => f.write_str(int_buffer.format(*inner)),
            Self::U64(inner) => f.write_str(int_buffer.format(*inner)),
            Self::U128(inner) => f.write_str(int_buffer.format(*inner)),
            Self::Usize(inner) => f.write_str(int_buffer.format(*inner)),
            Self::F32(inner) => f.write_str(float_buffer.format(*inner)),
            Self::F64(inner) => f.write_str(float_buffer.format(*inner)),
            Self::Char { value, context } => context.writer(f).write_char(*value),
            Self::Str { value, context } => context.writer(f).write_str(value),
            Self::BoxDyn { inner, context, .. } => inner.render(cx, &mut context.writer(f)),
            Self::BoxSlice { inner, .. } => {
                for part in inner {
                    part.render(cx, f);
                }
            }
        }
    }

    /// Returns an estimate of the number of bytes this part will write.
    ///
    /// Used to pre-allocate the output buffer. A slight over-estimate is
    /// preferable to an under-estimate: falling short forces the buffer to
    /// grow and copy, whereas a modest over-estimate only leaves a little
    /// capacity unused.
    pub(crate) fn size_hint(&self) -> usize {
        // Each numeric hint is the midpoint, rounded up, between the shortest
        // and widest output the type can `Display`, including the leading `-`
        // for signed types (`isize`/`usize` assume a 64-bit target). A
        // float's `Display` width is unbounded for extreme magnitudes, so the
        // upper end is the shortest round-trip form of a typical value.
        #[allow(clippy::match_same_arms)]
        match self {
            Self::Empty => 0,
            Self::Bool(_) => 5,
            Self::I8(_) => 3,
            Self::I16(_) => 4,
            Self::I32(_) => 6,
            Self::I64(_) => 11,
            Self::I128(_) => 21,
            Self::Isize(_) => 11,
            Self::U8(_) => 2,
            Self::U16(_) => 3,
            Self::U32(_) => 6,
            Self::U64(_) => 11,
            Self::U128(_) => 20,
            Self::Usize(_) => 11,
            Self::F32(_) => 9,
            Self::F64(_) => 13,
            // One to four UTF-8 bytes, or an escape sequence.
            Self::Char { .. } => 3,
            Self::Str { value, context } => match context {
                HtmlContext::Unescaped => value.len(),
                // Assume some characters escape into multi-byte sequences.
                _ => value.len() + value.len() / 8,
            },
            Self::BoxDyn { size_hint, .. } | Self::BoxSlice { size_hint, .. } => *size_hint,
        }
    }
}

/// A boxed view part that writes its output at render time.
///
/// Implement this for values whose output is only known when the view
/// renders, such as resolved asset URLs. The writer passed to
/// [`render`](Self::render) already carries the [`HtmlContext`] of the
/// position the part was pushed into, so everything written through it is
/// escaped or validated for that position.
pub trait DynViewPart: 'static + fmt::Debug + Send {
    /// Writes this part's output into `w`.
    fn render(&self, cx: &Cx, w: &mut HtmlWriter<'_, '_>);

    /// Returns an estimate of the number of bytes this part will write.
    ///
    /// Used to pre-allocate the output buffer, so aim for a close estimate. A
    /// slight over-estimate is usually preferable to an under-estimate.
    #[inline]
    fn size_hint(&self) -> usize {
        0
    }

    /// Clones this view part into a fresh boxed value.
    fn clone_box(&self) -> Box<dyn DynViewPart>;
}

impl Clone for Box<dyn DynViewPart> {
    #[inline]
    fn clone(&self) -> Self {
        (**self).clone_box()
    }
}

/// A buffer collecting renderable values before they become a [`View`].
///
/// This is plumbing for generated `view!` code, which fills the buffer
/// through [`PartsWriter`] lenses and the position helpers and finally passes
/// it to `View::new`.
#[doc(hidden)]
#[derive(Debug, Default, Clone)]
pub struct ViewParts {
    items: SmallVec<[ViewPart; 8]>,
}

impl ViewParts {
    /// Creates an empty view-parts buffer.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a nested view, such as a rendered component.
    #[inline]
    pub fn push_view(&mut self, view: View) -> &mut Self {
        self.items.push(view.into_part());
        self
    }

    /// Appends an already-sealed view part.
    ///
    /// A part records the [`HtmlContext`] its text was written for. Pushing
    /// it into a position with different escaping requirements bypasses that
    /// protection, so this is reserved for framework plumbing that re-emits
    /// parts in the position family they were built for.
    #[doc(hidden)]
    #[inline]
    pub fn push_part(&mut self, part: ViewPart) -> &mut Self {
        self.items.push(part);
        self
    }
}

impl From<ViewParts> for ViewPart {
    #[inline]
    fn from(mut value: ViewParts) -> Self {
        match value.items.len() {
            0 => ViewPart::Empty,
            1 => value.items.pop().unwrap(),
            _ => {
                let size_hint = value.items.iter().map(ViewPart::size_hint).sum();
                ViewPart::BoxSlice {
                    inner: value.items.into_boxed_slice(),
                    size_hint,
                }
            }
        }
    }
}

macro_rules! impl_push_primitive {
    ($method:ident, $ty:ty, $variant:ident) => {
        #[doc = concat!("Appends a `", stringify!($ty), "` rendered as text.")]
        ///
        /// Its rendered form contains no character that is significant in any
        /// HTML context, so no escaping applies.
        #[inline]
        pub fn $method(&mut self, value: $ty) -> &mut Self {
            self.parts.items.push(ViewPart::$variant(value));
            self
        }
    };
}

/// A context-carrying writer over a view-parts buffer, created per position.
///
/// The `view!` macro creates a `PartsWriter` for each dynamic position it
/// fills and hands it to the matching position trait:
/// [`NodeViewParts`](crate::NodeViewParts),
/// [`AttributeValueViewParts`](crate::AttributeValueViewParts),
/// [`AttributeKeyViewParts`](crate::AttributeKeyViewParts),
/// [`ElementNameViewParts`](crate::ElementNameViewParts), or
/// [`AttributeViewParts`](crate::AttributeViewParts).
///
/// Implementations of those traits make a value renderable by pushing it
/// through the `push_*` methods, which seal the pushed text with the
/// [`HtmlContext`] of the position so rendering escapes or validates it
/// correctly, or by delegating to another implementation of the same
/// position trait. [`push_str_unescaped`](Self::push_str_unescaped) is the
/// only way to opt out of that protection.
pub struct PartsWriter<'a> {
    parts: &'a mut ViewParts,
    context: HtmlContext,
}

impl<'a> PartsWriter<'a> {
    /// Creates a writer that seals everything pushed into it with `context`.
    #[inline]
    pub fn new(parts: &'a mut ViewParts, context: HtmlContext) -> Self {
        Self { parts, context }
    }

    /// Returns a writer over the same buffer for a different context.
    ///
    /// This is how in-crate compositions such as
    /// [`Attribute`](crate::Attribute) transition between the
    /// positions they span.
    #[inline]
    pub(crate) fn with_context(&mut self, context: HtmlContext) -> PartsWriter<'_> {
        PartsWriter {
            parts: self.parts,
            context,
        }
    }

    /// Appends a string, sealed with this writer's context.
    #[inline]
    pub fn push_str(&mut self, value: impl Into<Cow<'static, str>>) -> &mut Self {
        self.parts.items.push(ViewPart::Str {
            value: value.into(),
            context: self.context,
        });
        self
    }

    /// Appends a string that renders verbatim, bypassing this writer's
    /// context.
    ///
    /// Use this only for trusted markup. Passing untrusted input defeats the
    /// runtime's escaping and can lead to XSS vulnerabilities.
    #[inline]
    pub fn push_str_unescaped(&mut self, value: impl Into<Cow<'static, str>>) -> &mut Self {
        self.parts.items.push(ViewPart::Str {
            value: value.into(),
            context: HtmlContext::Unescaped,
        });
        self
    }

    /// Appends a character, sealed with this writer's context.
    #[inline]
    pub fn push_char(&mut self, value: char) -> &mut Self {
        self.parts.items.push(ViewPart::Char {
            value,
            context: self.context,
        });
        self
    }

    impl_push_primitive!(push_bool, bool, Bool);
    impl_push_primitive!(push_i8, i8, I8);
    impl_push_primitive!(push_i16, i16, I16);
    impl_push_primitive!(push_i32, i32, I32);
    impl_push_primitive!(push_i64, i64, I64);
    impl_push_primitive!(push_i128, i128, I128);
    impl_push_primitive!(push_isize, isize, Isize);
    impl_push_primitive!(push_u8, u8, U8);
    impl_push_primitive!(push_u16, u16, U16);
    impl_push_primitive!(push_u32, u32, U32);
    impl_push_primitive!(push_u64, u64, U64);
    impl_push_primitive!(push_u128, u128, U128);
    impl_push_primitive!(push_usize, usize, Usize);
    impl_push_primitive!(push_f32, f32, F32);
    impl_push_primitive!(push_f64, f64, F64);

    /// Appends a part that writes its output at render time, sealed with
    /// this writer's context.
    #[inline]
    pub fn push_dyn(&mut self, part: Box<dyn DynViewPart>) -> &mut Self {
        self.parts.items.push(ViewPart::BoxDyn {
            size_hint: part.size_hint(),
            inner: part,
            context: self.context,
        });
        self
    }

    /// Appends an already-sealed view part.
    ///
    /// A part records the [`HtmlContext`] its text was written for; this
    /// writer's context does not apply. See [`ViewParts::push_part`].
    #[doc(hidden)]
    #[inline]
    pub fn push_part(&mut self, part: ViewPart) -> &mut Self {
        self.parts.items.push(part);
        self
    }
}

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

    fn render(build: impl FnOnce(&mut ViewParts)) -> String {
        let mut parts = ViewParts::new();
        build(&mut parts);
        View::new(parts).render(&Cx::default())
    }

    #[test]
    fn empty_view_renders_empty() {
        assert_eq!(View::empty().render(&Cx::default()), "");
    }

    #[test]
    fn unescaped_unchecked_renders_verbatim() {
        let view = View::unescaped_unchecked("<b>raw</b>");
        assert_eq!(view.render(&Cx::default()), "<b>raw</b>");
    }

    #[test]
    fn push_str_seals_the_writer_context() {
        let out = render(|parts| {
            PartsWriter::new(parts, HtmlContext::Text).push_str("<b> & \"q\"");
        });
        assert_eq!(out, "&lt;b&gt; &amp; \"q\"");

        let out = render(|parts| {
            PartsWriter::new(parts, HtmlContext::AttributeValue).push_str("<b> & \"q\"");
        });
        assert_eq!(out, "<b> &amp; &quot;q&quot;");
    }

    #[test]
    fn push_str_unescaped_bypasses_the_context() {
        let out = render(|parts| {
            PartsWriter::new(parts, HtmlContext::Text).push_str_unescaped("<b>raw</b>");
        });
        assert_eq!(out, "<b>raw</b>");
    }

    #[test]
    fn push_char_seals_the_writer_context() {
        let out = render(|parts| {
            PartsWriter::new(parts, HtmlContext::Text).push_char('<');
        });
        assert_eq!(out, "&lt;");
    }

    #[test]
    #[should_panic(expected = "invalid attribute key")]
    fn ident_context_panics_on_forbidden_characters_at_render() {
        render(|parts| {
            PartsWriter::new(parts, HtmlContext::AttributeKey).push_str("on click");
        });
    }

    #[test]
    fn push_primitives_render_as_text() {
        let out = render(|parts| {
            let mut writer = PartsWriter::new(parts, HtmlContext::Text);
            writer.push_i32(-42).push_str_unescaped(" ");
            writer.push_bool(true).push_str_unescaped(" ");
            writer.push_f64(1.5);
        });
        assert_eq!(out, "-42 true 1.5");
    }

    #[test]
    fn push_view_splices_nested_views() {
        let mut inner_parts = ViewParts::new();
        PartsWriter::new(&mut inner_parts, HtmlContext::Text).push_str("a < b");
        let inner = View::new(inner_parts);

        let out = render(|parts| {
            PartsWriter::new(parts, HtmlContext::Unescaped).push_str("<p>");
            parts.push_view(inner);
            PartsWriter::new(parts, HtmlContext::Unescaped).push_str("</p>");
        });
        assert_eq!(out, "<p>a &lt; b</p>");
    }

    #[test]
    fn size_hint_is_exact_for_unescaped_strings() {
        let view = View::unescaped_unchecked("<b>raw</b>");
        assert_eq!(view.part.size_hint(), 10);
    }
}