topcoat-view 0.7.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use std::sync::Arc;

#[cfg(feature = "http")]
use http::{HeaderMap, StatusCode};
use topcoat_core::context::Cx;

use crate::{
    Formatter,
    buffer::{InstructionPtr, Renderer, ViewBuffer, ViewBufferId, ViewBufferScope},
};

/// A self-contained piece of HTML content.
///
/// A view handle 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
/// ```
///
/// A handle is either self-contained or nested. A self-contained handle
/// carries everything it needs to render: it can be stored, sent across
/// tasks, spliced into another view, and rendered anywhere. The outermost
/// view of a build resolves to one. A nested handle is what a
/// [`View`](crate::View) inside that build resolves to: it points into the
/// build's buffer, so it splices into the content of the enclosing views
/// and renders only while the build is running.
#[derive(Debug, Default, Clone)]
pub struct ViewHandle {
    repr: ViewRepr,
}

/// The kinds of view: a static string independent of any buffer, a handle
/// into a buffer someone else holds, or an owned view carrying its own
/// buffer.
#[derive(Debug, Clone)]
pub(super) enum ViewRepr {
    /// Trusted static markup rendered verbatim, independent of any buffer.
    Static(&'static str),
    /// An instruction block in the buffer identified by `buffer`, starting
    /// at `entry`.
    Scoped {
        buffer: ViewBufferId,
        entry: InstructionPtr,
        /// An estimate of the number of bytes the block writes when
        /// rendered, accumulated while the view was built.
        size_hint: usize,
    },
    /// An instruction block starting at `entry` in a buffer the view holds
    /// on to itself.
    Owned {
        buffer: Arc<ViewBuffer>,
        entry: InstructionPtr,
        /// An estimate of the number of bytes the block writes when
        /// rendered, accumulated while the view was built.
        size_hint: usize,
    },
}

impl Default for ViewRepr {
    #[inline]
    fn default() -> Self {
        Self::Static("")
    }
}

impl ViewHandle {
    /// Creates the handle for an instruction block built in the buffer
    /// identified by `buffer`, estimated to write `size_hint` bytes.
    #[inline]
    pub(super) fn from_scope(
        buffer: ViewBufferId,
        entry: InstructionPtr,
        size_hint: usize,
    ) -> Self {
        Self {
            repr: ViewRepr::Scoped {
                buffer,
                entry,
                size_hint,
            },
        }
    }

    /// Unwraps the view into its representation.
    #[inline]
    pub(super) fn repr(self) -> ViewRepr {
        self.repr
    }

    /// Returns an estimate of the number of bytes the view writes when
    /// rendered.
    #[inline]
    #[must_use]
    pub fn size_hint(&self) -> usize {
        match &self.repr {
            ViewRepr::Static(body) => body.len(),
            ViewRepr::Scoped { size_hint, .. } | ViewRepr::Owned { size_hint, .. } => *size_hint,
        }
    }

    /// Makes a nested handle self-contained by taking ownership of the
    /// buffer its instructions were appended to.
    ///
    /// A handle that is self-contained already passes through, and the
    /// buffer is dropped.
    ///
    /// # Panics
    ///
    /// Panics if the handle's instructions live in a different buffer.
    #[must_use]
    pub(crate) fn seal(self, buffer: ViewBuffer) -> Self {
        match self.repr {
            ViewRepr::Static(_) | ViewRepr::Owned { .. } => self,
            ViewRepr::Scoped {
                buffer: id,
                entry,
                size_hint,
            } => {
                assert!(
                    id == buffer.id(),
                    "tried to seal a view into a buffer it was not built in",
                );
                Self {
                    repr: ViewRepr::Owned {
                        buffer: Arc::new(buffer),
                        entry,
                        size_hint,
                    },
                }
            }
        }
    }

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

    /// Returns `true` if the view is statically known to render no output.
    ///
    /// A view holding an instruction block reports `false` even when the
    /// block happens to write nothing.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        matches!(self.repr, ViewRepr::Static(""))
    }

    /// 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 {
            repr: ViewRepr::Static(body),
        }
    }

    /// Renders the view into an HTML string.
    #[cfg_attr(
        feature = "http",
        doc = "",
        doc = "Status codes and headers declared in the view are discarded;",
        doc = "[`render_response`](Self::render_response) collects them."
    )]
    ///
    /// # Panics
    ///
    /// Panics if the view is a nested handle rendered outside the build it
    /// belongs to, or if a dynamic attribute key or element name in the
    /// view contains a character that could break out of the identifier.
    #[must_use]
    #[track_caller]
    pub fn render(self, cx: &Cx) -> String {
        let mut html = String::with_capacity(self.size_hint());
        self.render_into(cx, &mut Formatter::new(&mut html));
        html
    }

    /// Renders the view into HTML together with the status code and response
    /// headers declared in it.
    ///
    /// A view declares response metadata by placing an
    /// [`http::StatusCode`](StatusCode), an [`http::HeaderMap`](HeaderMap),
    /// or a single `(HeaderName, HeaderValue)` pair in the node position of
    /// the `view!` macro. Competing declarations resolve by render order:
    /// the first status code rendered wins, and the first part that mentions
    /// a header name provides all of that name's values.
    ///
    /// # Panics
    ///
    /// Panics if the view is a nested handle rendered outside the build it
    /// belongs to, or if a dynamic attribute key or element name in the
    /// view contains a character that could break out of the identifier.
    #[cfg(feature = "http")]
    #[must_use]
    #[track_caller]
    pub fn render_response(self, cx: &Cx) -> RenderedResponse {
        let mut html = String::with_capacity(self.size_hint());
        let mut f = Formatter::new(&mut html);
        self.render_into(cx, &mut f);
        let (status_code, headers) = f.into_recorded();
        RenderedResponse {
            html,
            status_code,
            headers,
        }
    }

    /// Writes the view's output through `f`.
    ///
    /// The formatter appends to its destination as it goes, so reserve the
    /// [`size_hint`](Self::size_hint) up front to avoid reallocations. A
    /// nested handle renders against the buffer of the build it belongs to,
    /// which must be the one running on the current task.
    ///
    /// # Panics
    ///
    /// Panics if the view is a nested handle and no build is running on the
    /// current task, or a different one is, or if a dynamic attribute key or
    /// element name in the view contains a character that could break out of
    /// the identifier.
    #[track_caller]
    pub fn render_into(self, cx: &Cx, f: &mut Formatter<'_>) {
        match self.repr {
            ViewRepr::Static(body) => f.write_str(body),
            ViewRepr::Scoped { buffer, entry, .. } => ViewBufferScope::with(|active| {
                assert!(
                    active.id() == buffer,
                    "tried to render a nested view handle outside the build it was built in",
                );
                Renderer::new(active, entry).execute(cx, f);
            }),
            ViewRepr::Owned { buffer, entry, .. } => {
                Renderer::new(&buffer, entry).execute(cx, f);
            }
        }
    }
}

/// The output of rendering a [`ViewHandle`] for an HTTP response.
///
/// Returned by [`ViewHandle::render_response`]: the rendered HTML alongside the
/// status code and headers the view declared.
#[cfg(feature = "http")]
#[derive(Debug)]
#[non_exhaustive]
pub struct RenderedResponse {
    /// The rendered HTML.
    pub html: String,
    /// The first status code the render encountered, if any.
    pub status_code: Option<StatusCode>,
    /// The collected response headers.
    ///
    /// Each name carries the values of the first render part that mentioned
    /// it.
    pub headers: HeaderMap,
}

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

    /// Appends a nested view to `buffer` in one synchronous burst from the
    /// parts `f` pushes.
    fn nested(buffer: &mut ViewBuffer, f: impl FnOnce(&mut PartsWriter<'_>)) -> ViewHandle {
        buffer.block(f)
    }

    /// Builds a self-contained view in one synchronous burst from the parts
    /// `f` pushes.
    fn owned(f: impl FnOnce(&mut PartsWriter<'_>)) -> ViewHandle {
        ViewBuffer::build(f)
    }

    /// Runs `f` with a build active on the current thread and returns its
    /// output alongside the build's buffer.
    fn in_scope<R>(f: impl FnOnce() -> R) -> (R, ViewBuffer) {
        let mut slot = Some(Box::new(ViewBuffer::new()));
        let output = {
            let _buffer = ViewBufferScope::new(&mut slot);
            f()
        };
        (output, *slot.expect("the buffer was swapped back on exit"))
    }

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

    #[test]
    fn push_view_splices_nested_views() {
        let mut buffer = ViewBuffer::new();
        let inner = nested(&mut buffer, |parts| {
            parts.push_str("a < b");
        });
        let outer = nested(&mut buffer, |parts| {
            parts.push_str_unescaped("<p>");
            parts.push_view_handle(inner);
            parts.push_str_unescaped("</p>");
        });
        assert_eq!(outer.seal(buffer).render(&Cx::default()), "<p>a &lt; b</p>");
    }

    #[test]
    fn document_order_follows_splice_order_not_buffer_order() {
        let mut buffer = ViewBuffer::new();
        // Built in reverse: `second` occupies earlier buffer addresses.
        let second = nested(&mut buffer, |parts| {
            parts.push_str("B");
        });
        let first = nested(&mut buffer, |parts| {
            parts.push_str("A");
        });
        let outer = nested(&mut buffer, |parts| {
            parts.push_view_handle(first);
            parts.push_view_handle(second);
        });
        assert_eq!(outer.seal(buffer).render(&Cx::default()), "AB");
    }

    #[test]
    fn sealed_views_own_their_buffer() {
        let view = owned(|parts| {
            parts.push_str("a < b");
        });
        assert!(matches!(view.repr, ViewRepr::Owned { .. }));
        assert_eq!(view.render(&Cx::default()), "a &lt; b");
    }

    #[test]
    fn owned_views_splice_across_buffers() {
        let inner = owned(|parts| {
            parts.push_str("a < b");
        });
        let outer = owned(|parts| {
            parts.push_str_unescaped("<p>");
            parts.push_view_handle(inner);
            parts.push_str_unescaped("</p>");
        });
        assert_eq!(outer.render(&Cx::default()), "<p>a &lt; b</p>");
    }

    #[test]
    fn owned_views_are_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>(_value: &T) {}

        let view = owned(|parts| {
            parts.push_str("x");
        });
        assert_send_sync(&view);
    }

    #[test]
    fn static_views_are_spliced_verbatim() {
        let outer = owned(|parts| {
            parts.push_view_handle(ViewHandle::unescaped_unchecked("<hr>"));
            parts.push_view_handle(ViewHandle::empty());
        });
        assert_eq!(outer.render(&Cx::default()), "<hr>");
    }

    #[test]
    fn size_hint_accumulates_across_splices() {
        let mut buffer = ViewBuffer::new();
        let inner = nested(&mut buffer, |parts| {
            parts.push_str_unescaped("12345678");
        });
        let outer = nested(&mut buffer, |parts| {
            parts.push_view_handle(inner.clone());
            parts.push_view_handle(inner);
            parts.push_view_handle(ViewHandle::unescaped_unchecked("<hr>"));
        });
        let ViewRepr::Scoped { size_hint, .. } = outer.repr() else {
            panic!("expected a nested view");
        };
        assert_eq!(size_hint, 8 + 8 + 4);
    }

    #[test]
    fn a_nested_view_renders_inside_its_build() {
        let (rendered, _buffer) = in_scope(|| {
            let view = ViewBufferScope::with(|buffer| {
                buffer.block(|parts| {
                    parts.push_str("a < b");
                })
            });
            view.render(&Cx::default())
        });
        assert_eq!(rendered, "a &lt; b");
    }

    #[test]
    #[should_panic(expected = "outside of a `ViewBufferScope`")]
    fn rendering_a_nested_view_outside_any_build_panics() {
        let mut buffer = ViewBuffer::new();
        let view = nested(&mut buffer, |_parts| {});
        let _ = view.render(&Cx::default());
    }

    #[test]
    #[should_panic(expected = "outside the build it was built in")]
    fn rendering_a_nested_view_inside_a_different_build_panics() {
        let mut buffer = ViewBuffer::new();
        let view = nested(&mut buffer, |_parts| {});
        in_scope(|| view.render(&Cx::default()));
    }

    #[test]
    #[should_panic(expected = "outside the `view!` invocation it was built in")]
    fn splicing_a_nested_view_from_a_different_buffer_panics() {
        let mut built_in = ViewBuffer::new();
        let view = nested(&mut built_in, |_parts| {});
        let mut other = ViewBuffer::new();
        nested(&mut other, |parts| {
            parts.push_view_handle(view);
        });
    }

    #[test]
    #[should_panic(expected = "tried to seal a view into a buffer it was not built in")]
    fn sealing_a_view_into_a_different_buffer_panics() {
        let mut built_in = ViewBuffer::new();
        let view = nested(&mut built_in, |_parts| {});
        let _ = view.seal(ViewBuffer::new());
    }

    #[cfg(feature = "http")]
    mod response {
        use http::{
            HeaderMap, HeaderName, HeaderValue, StatusCode,
            header::{CACHE_CONTROL, SET_COOKIE},
        };

        use super::*;
        use crate::NodeViewParts;

        fn push_node(cx: &Cx, parts: &mut PartsWriter<'_>, value: impl NodeViewParts) {
            value.into_view_parts(cx, parts);
        }

        #[test]
        fn status_code_is_recorded_and_renders_nothing() {
            let cx = &Cx::default();
            let view = owned(|parts| {
                push_node(cx, parts, "a");
                push_node(cx, parts, StatusCode::NOT_FOUND);
                push_node(cx, parts, "b");
            });

            let rendered = view.render_response(cx);
            assert_eq!(rendered.html, "ab");
            assert_eq!(rendered.status_code, Some(StatusCode::NOT_FOUND));
            assert!(rendered.headers.is_empty());
        }

        #[test]
        fn render_response_without_declarations_is_empty() {
            let cx = &Cx::default();
            let view = owned(|parts| {
                push_node(cx, parts, "a");
            });

            let rendered = view.render_response(cx);
            assert_eq!(rendered.html, "a");
            assert_eq!(rendered.status_code, None);
            assert!(rendered.headers.is_empty());
        }

        #[test]
        fn render_discards_declarations() {
            let cx = &Cx::default();
            let view = owned(|parts| {
                push_node(cx, parts, StatusCode::NOT_FOUND);
                push_node(
                    cx,
                    parts,
                    (CACHE_CONTROL, HeaderValue::from_static("no-store")),
                );
                push_node(cx, parts, "a");
            });

            assert_eq!(view.render(cx), "a");
        }

        #[test]
        fn first_status_code_wins() {
            let cx = &Cx::default();
            let view = owned(|parts| {
                push_node(cx, parts, StatusCode::NOT_FOUND);
                push_node(cx, parts, StatusCode::OK);
            });

            let rendered = view.render_response(cx);
            assert_eq!(rendered.status_code, Some(StatusCode::NOT_FOUND));
        }

        #[test]
        fn first_mention_of_a_header_name_wins() {
            let cx = &Cx::default();
            let view = owned(|parts| {
                push_node(
                    cx,
                    parts,
                    (CACHE_CONTROL, HeaderValue::from_static("no-store")),
                );
                let mut later = HeaderMap::new();
                later.insert(CACHE_CONTROL, HeaderValue::from_static("max-age=60"));
                later.insert(
                    HeaderName::from_static("x-extra"),
                    HeaderValue::from_static("1"),
                );
                push_node(cx, parts, later);
            });

            let rendered = view.render_response(cx);
            assert_eq!(rendered.headers[CACHE_CONTROL], "no-store");
            assert_eq!(rendered.headers["x-extra"], "1");
        }

        #[test]
        fn one_map_keeps_all_values_for_a_name() {
            let cx = &Cx::default();
            let mut first = HeaderMap::new();
            first.append(SET_COOKIE, HeaderValue::from_static("a=1"));
            first.append(SET_COOKIE, HeaderValue::from_static("b=2"));
            let mut later = HeaderMap::new();
            later.insert(SET_COOKIE, HeaderValue::from_static("c=3"));

            let view = owned(|parts| {
                push_node(cx, parts, first);
                push_node(cx, parts, later);
            });

            let rendered = view.render_response(cx);
            let cookies: Vec<_> = rendered.headers.get_all(SET_COOKIE).iter().collect();
            assert_eq!(cookies, ["a=1", "b=2"]);
        }

        #[test]
        fn placement_decides_precedence_across_nested_views() {
            let cx = &Cx::default();
            let inner = owned(|parts| {
                push_node(cx, parts, StatusCode::NOT_FOUND);
                push_node(cx, parts, "inner");
            });

            // A status code before the nested view overrides it.
            let outer = owned(|parts| {
                push_node(cx, parts, StatusCode::FORBIDDEN);
                parts.push_view_handle(inner.clone());
            });
            let rendered = outer.render_response(cx);
            assert_eq!(rendered.status_code, Some(StatusCode::FORBIDDEN));

            // A status code after the nested view is only a fallback.
            let outer = owned(|parts| {
                parts.push_view_handle(inner);
                push_node(cx, parts, StatusCode::FORBIDDEN);
            });
            let rendered = outer.render_response(cx);
            assert_eq!(rendered.status_code, Some(StatusCode::NOT_FOUND));
        }
    }
}