tablo-core 0.2.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
use super::*;

#[test]
fn brand_trims_name_and_ignores_blank_logo() {
    assert_eq!(Brand::new("  Acme  ").name, "Acme");
    assert_eq!(Brand::new("Acme").logo, None);
    assert_eq!(
        Brand::new("Acme").logo("  /logo.svg  ").logo.as_deref(),
        Some("/logo.svg")
    );
    // Blank logos fall back to the name-only render.
    assert_eq!(Brand::new("Acme").logo("   ").logo, None);
}

#[tokio::test]
async fn layout_shell_renders_a_complete_document() {
    use topcoat::{context::CxTestBuilder, view::view};

    use crate::navigation::{NavTarget, NavigationItem};

    let (parts, ()) = http::Request::builder()
        .uri("/admin/users")
        .body(())
        .unwrap()
        .into_parts();
    let cx = CxTestBuilder::new()
        .request_context(parts)
        .app_context(vec![NavigationItem {
            label: "Users".to_string(),
            target: NavTarget::Url("/admin/users".to_string()),
            order: 0,
            icon: None,
        }])
        .build();
    let cx_ref = &cx;
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::layout_shell(&cx, slot)
        .single()
        .await
        .unwrap()
        .render(&cx);

    assert!(
        html.starts_with("<!DOCTYPE html>"),
        "missing doctype in {html}"
    );
    assert!(
        html.contains("<html>") && html.contains("<head>"),
        "missing document head in {html}"
    );
    assert!(
        html.contains("<title>Tablo</title>"),
        "missing document title in {html}"
    );
    assert!(html.contains("hello"), "missing layout slot in {html}");
}

/// A page outside the panel takes the panel's document: the same head, around
/// the body content the page owns.
#[tokio::test]
async fn document_wraps_a_public_page() {
    use topcoat::{context::CxTestBuilder, view::view};

    let (parts, ()) = http::Request::builder()
        .uri("/blog")
        .body(())
        .unwrap()
        .into_parts();
    let cx = CxTestBuilder::new().request_context(parts).build();
    let cx_ref = &cx;
    let html = Panel::document(
        &cx,
        "Tablo Blog",
        view! { cx_ref => <div class="blog">"hello"</div> },
    )
    .await
    .unwrap()
    .single()
    .await
    .unwrap()
    .render(&cx);

    assert!(
        html.starts_with("<!DOCTYPE html>"),
        "missing doctype in {html}"
    );
    assert!(
        html.contains("<title>Tablo Blog</title>"),
        "missing document title in {html}"
    );
    // The panel renders the one `<body>`; the page's content sits inside it.
    assert_eq!(
        html.matches("<body").count(),
        1,
        "exactly one body element, got {html}"
    );
    assert_eq!(
        html.matches("<head>").count(),
        1,
        "exactly one head element, got {html}"
    );
    assert!(
        html.contains("<div class=\"blog\">"),
        "missing the page's own content in {html}"
    );
    assert!(html.contains("hello"), "missing page content in {html}");
    // No `ShellAssets` in app context: the head carries no asset URL, so a
    // router built without `.assets(..)` renders instead of panicking.
    assert!(
        !html.contains("rel=\"stylesheet\""),
        "no stylesheet without shell assets, got {html}"
    );

    // The head is the shell's own, byte for byte, for the same context and
    // title — `layout_shell` titles an admin page with the brand, which is
    // `Tablo` when none is registered.
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let shell = Panel::layout_shell(&cx, slot)
        .single()
        .await
        .unwrap()
        .render(&cx);
    let titled = Panel::document(&cx, "Tablo", view! { cx_ref => "hello" })
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx);
    assert_eq!(
        head_of(&titled),
        head_of(&shell),
        "the public document must take the shell's head"
    );
}

/// The `<head>` element of `html`, opening and closing tags included.
fn head_of(html: &str) -> &str {
    let start = html.find("<head>").expect("a rendered head");
    let len = html[start..].find("</head>").expect("a closed head") + "</head>".len();
    &html[start..start + len]
}

#[tokio::test]
async fn shell_escapes_brand_name_and_logo() {
    use topcoat::{context::CxTestBuilder, view::view};

    use crate::navigation::{NavTarget, NavigationItem};

    // Attribute-injection safety rests on `view!` escaping:
    // lock it with a hostile brand on both render paths (header + sidebar).
    let (parts, ()) = http::Request::builder()
        .uri("/admin/users")
        .body(())
        .unwrap()
        .into_parts();
    let mut panel = crate::panel::test_support::panel_state("/admin", crate::Auth::disabled());
    panel.brand =
        Some(Brand::new("<script>alert(1)</script>").logo("\"><script>alert(2)</script>"));
    let cx = CxTestBuilder::new()
        .request_context(parts)
        .request_context(crate::panel::test_support::current_panel(panel))
        .build();
    let nav_items = vec![NavigationItem {
        label: "Users".to_string(),
        target: NavTarget::Url("/admin/users".to_string()),
        order: 0,
        icon: None,
    }];
    let cx_ref = &cx;
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::render_shell(&cx, &nav_items, "/admin/users", slot, None)
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx);
    assert!(
        !html.contains("\"><script>"),
        "brand must not break out of attributes, got {html}"
    );
    assert!(
        html.contains("&lt;script&gt;alert(1)&lt;/script&gt;"),
        "missing escaped brand text, got {html}"
    );
    assert!(
        html.contains("&quot;"),
        "attribute quotes must be escaped, got {html}"
    );
}

#[tokio::test]
async fn shell_dark_mode_sets_html_class_and_toggle() {
    fn cx_with(dark: Option<bool>) -> Cx {
        use topcoat::context::CxTestBuilder;
        let (parts, ()) = http::Request::builder()
            .uri("/admin/users")
            .body(())
            .unwrap()
            .into_parts();
        match dark {
            Some(v) => CxTestBuilder::new()
                .request_context(parts)
                .request_context(dark_panel(v)),
            None => CxTestBuilder::new().request_context(parts),
        }
        .build()
    }

    async fn document_html(cx: &Cx) -> String {
        let slot = view! { cx => "hello" }.boxed().into();
        Panel::layout_shell(cx, slot)
            .single()
            .await
            .unwrap()
            .render(cx)
    }

    let html = document_html(&cx_with(Some(true))).await;
    assert!(
        html.contains("<html class=\"dark\">"),
        "a dark panel must set the html class, got {html}"
    );
    assert!(
        html.contains("data-theme-toggle"),
        "theme toggle must render, got {html}"
    );
    // the build-time default is only that — the pre-paint script
    // can remove the class again when the visitor has stored `light`.
    assert!(
        html.contains("classList.add") && html.contains("classList.remove"),
        "the document must carry the reconciling theme script, got {html}"
    );

    let html = document_html(&cx_with(Some(false))).await;
    assert!(
        html.contains("<html>"),
        "a light panel must not set the dark class, got {html}"
    );

    let html = document_html(&cx_with(None)).await;
    assert!(
        html.contains("<html>"),
        "no panel must not set the dark class, got {html}"
    );
}

#[tokio::test]
async fn theme_cookie_overrides_the_dark_mode_default() {
    // Runtime navigation copies `<html>`'s attributes from the next page
    // and runs no script, so the server must render the stored choice.
    use topcoat::context::CxTestBuilder;

    async fn html_tag(default_dark: bool, cookie: &str) -> String {
        let (parts, ()) = http::Request::builder()
            .uri("/admin/users")
            .header(http::header::COOKIE, cookie)
            .body(())
            .unwrap()
            .into_parts();
        let cx = CxTestBuilder::new()
            .request_context(parts)
            .request_context(dark_panel(default_dark))
            .build();
        let cx_ref = &cx;
        let slot = view! { cx_ref => "hello" }.boxed().into();
        let html = Panel::layout_shell(&cx, slot)
            .single()
            .await
            .unwrap()
            .render(&cx);
        let start = html.find("<html").unwrap();
        html[start..=start + html[start..].find('>').unwrap()].to_string()
    }

    assert_eq!(html_tag(false, "theme=dark").await, "<html class=\"dark\">");
    assert_eq!(
        html_tag(true, "sidebar_state=collapsed; theme=light").await,
        "<html>"
    );
    assert_eq!(html_tag(true, "theme=sepia").await, "<html class=\"dark\">");
}

#[tokio::test]
async fn shell_notification_carries_dismiss_hooks() {
    // The shell toast is the shadcn/Sonner surface, carrying
    // the auto-dismiss hooks notifications.js arms (mount + 4s + close).
    use crate::notification::Notification;

    let enc = serde_json::to_string(&Notification::success("Created")).unwrap();
    let html = shell_html_with_flash(&enc).await;
    assert!(
        html.contains("data-sonner-toast") && html.contains("data-type=\"success\""),
        "shell toast must be the Sonner surface, got {html}"
    );
    assert!(
        html.contains("data-close-button"),
        "shell toast must carry the Sonner close button, got {html}"
    );
    assert!(
        html.contains("data-title") && html.contains("Created"),
        "shell toast must carry the title, got {html}"
    );
    assert!(
        !html.contains("data-description"),
        "a title-only toast renders no description, got {html}"
    );

    // Error + description: the typed toast and the supporting line. The
    // icon's colour is paint; `data-type="error"` is what selects
    // the destructive icon, and the `<svg>` proves one rendered.
    let enc =
        serde_json::to_string(&Notification::error("Boom").description("What happened")).unwrap();
    let html = shell_html_with_flash(&enc).await;
    assert!(
        html.contains("data-type=\"error\"") && html.contains("<svg"),
        "an error toast must carry its type and destructive icon, got {html}"
    );
    assert!(
        html.contains("data-description") && html.contains("What happened"),
        "the description must render, got {html}"
    );
}

/// Slices the opening tag at `start` (topcoat#122).
fn opening_tag_at(html: &str, start: usize) -> &str {
    let mut quoted = false;
    for (offset, byte) in html.as_bytes()[start..].iter().enumerate() {
        match byte {
            b'"' => quoted = !quoted,
            b'>' if !quoted => return &html[start..start + offset],
            _ => {}
        }
    }
    panic!("unterminated tag at byte {start} in {html}");
}

/// Renders the shell once with a flash cookie carrying `enc`.
async fn shell_html_with_flash(enc: &str) -> String {
    use topcoat::{context::CxTestBuilder, cookie::CookieJarCell, view::view};

    use crate::navigation::{NavTarget, NavigationItem};

    let mut parts = http::Request::builder()
        .uri("/admin/users")
        .body(())
        .unwrap()
        .into_parts()
        .0;
    parts.headers.insert(
        http::header::COOKIE,
        format!("{}={enc}", crate::notification::COOKIE_NAME)
            .parse()
            .unwrap(),
    );
    let cx = CxTestBuilder::new()
        .request_context(parts)
        .request_context(CookieJarCell::new())
        .build();
    let nav_items = vec![NavigationItem {
        label: "Users".to_string(),
        target: NavTarget::Url("/admin/users".to_string()),
        order: 0,
        icon: None,
    }];
    let cx_ref = &cx;
    let slot = view! { cx_ref => "hello" }.boxed().into();
    Panel::render_shell(&cx, &nav_items, "/admin/users", slot, None)
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx)
}

#[tokio::test]
async fn sidebar_orders_custom_items_by_sort_key() {
    // `order: -1` interleaves a custom item above the
    // resources; ties keep declaration order.
    use topcoat::{context::CxTestBuilder, view::view};

    use crate::navigation::{NavTarget, NavigationItem};

    let (parts, ()) = http::Request::builder()
        .uri("/admin/users")
        .body(())
        .unwrap()
        .into_parts();
    let cx = CxTestBuilder::new().request_context(parts).build();
    let nav_items = vec![
        NavigationItem {
            label: "Users".to_string(),
            target: NavTarget::Url("/admin/users".to_string()),
            order: 0,
            icon: None,
        },
        NavigationItem {
            label: "Showcase".to_string(),
            target: NavTarget::Url("/admin/showcase".to_string()),
            order: -1,
            icon: None,
        },
    ];
    let cx_ref = &cx;
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::render_shell(&cx, &nav_items, "/admin/users", slot, None)
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx);
    let showcase_at = html.find("Showcase").expect("custom item renders");
    let users_at = html.find("Users").expect("resource item renders");
    assert!(
        showcase_at < users_at,
        "an order: -1 custom item must precede resources, got {html}"
    );
}

#[tokio::test]
async fn panel_shell_renders_sidebar_with_active_and_tokens() {
    // structure/aria only — pixel Token/Tailwind classes live in
    // the showcase (`admin_resource_list_page_serve_seeded_users`), so a
    // restyle does not fail core without a behavior change.
    use topcoat::{context::CxTestBuilder, view::view};

    use crate::navigation::{NavTarget, NavigationItem};

    let cx = CxTestBuilder::new().build();
    let cx_ref = &cx;
    let nav_items = vec![
        NavigationItem {
            label: "Users".to_string(),
            target: NavTarget::Url("/admin/users".to_string()),
            order: 0,
            icon: None,
        },
        NavigationItem {
            label: "Showcase".to_string(),
            target: NavTarget::Url("/admin/showcase".to_string()),
            order: 0,
            icon: None,
        },
    ];
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::render_shell(&cx, &nav_items, "/admin/users", slot, None)
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx);
    assert!(
        html.contains("data-sidebar=\"sidebar\""),
        "missing sidebar data attr in {html}"
    );
    assert!(
        html.contains("data-sidebar=\"provider\""),
        "missing provider data attr in {html}"
    );
    assert!(
        html.contains("data-sidebar=\"inset\""),
        "missing inset data attr in {html}"
    );
    assert!(
        html.contains("data-sidebar=\"group\"") || html.contains("Navigation"),
        "missing sidebar group in {html}"
    );
    // Each entry navigates through the runtime; the menu button writes the
    // one `href`, so the runtime attributes add none.
    assert!(
        html.contains("href=\"/admin/showcase\"") && html.contains("data-topcoat-link="),
        "sidebar entries must carry runtime navigation in {html}"
    );
    assert!(!html.contains("href=\"\""), "no empty href in {html}");
    // Data-state for collapsible, seeded by the signal (cookie default:
    // expanded) and bound for the browser runtime.
    assert!(
        html.contains("data-state=\"expanded\"") && html.contains("data-topcoat-bind:data-state"),
        "missing bound data-state in {html}"
    );
    // No separator with no following group.
    assert!(
        !html.contains("Managed via Resource::query seam"),
        "dead placeholder must be gone, got {html}"
    );
    // The desktop/mobile trigger pair, wired to the runtime signals.
    assert_eq!(
        html.matches("data-sidebar=\"trigger\"").count(),
        2,
        "expected the desktop + mobile trigger pair in {html}"
    );
    assert!(
        html.contains("data-topcoat-on:click"),
        "missing runtime click bindings in {html}"
    );
    // Active highlight + real navigation links (the href prop, not attrs)
    assert!(
        html.contains("data-active=\"true\"") && html.contains("aria-current=\"page\""),
        "missing active highlight in {html}"
    );
    assert!(
        html.contains("<a") && html.contains("href=\"/admin/users\""),
        "navigation must render as links in {html}"
    );
    // Dark toggle
    assert!(
        html.contains("Toggle dark mode") || html.contains("data-theme-toggle"),
        "missing dark toggle in {html}"
    );
    // Ensure no ac-* remains in shell
    assert!(
        !html.contains("ac-sidebar") && !html.contains("ac-main") && !html.contains("ac-nav-item"),
        "ac-* should not remain in shell, got {html}"
    );
}

/// `sidebar_inset` renders the document's `<main>`; the slot wrapper must
/// be a plain element or the document carries two nested landmarks
/// (invalid HTML, and landmark navigation lists both).
#[tokio::test]
async fn shell_has_a_single_main_landmark() {
    use topcoat::{context::CxTestBuilder, view::view};

    let cx = CxTestBuilder::new().build();
    let cx_ref = &cx;
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::render_shell(&cx, &[], "/admin", slot, None)
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx);
    assert_eq!(
        html.matches("<main").count(),
        1,
        "the shell must expose exactly one main landmark, got {html}"
    );
    let main_tag = opening_tag_at(&html, html.find("<main").expect("main landmark"));
    assert!(
        main_tag.contains("data-sidebar=\"inset\""),
        "the inset stays the main landmark, got {main_tag}"
    );
}

/// The sheet header carries a mobile-only close control (upstream
/// `examples/ui`, `sidebar`'s "Include a close button in the mobile
/// header"): below `md` the open sheet veils the inset header, so the
/// mobile trigger there is unreachable and the sheet needs its own.
#[tokio::test]
async fn sidebar_sheet_header_carries_a_mobile_close_button() {
    use topcoat::{context::CxTestBuilder, view::view};

    let cx = CxTestBuilder::new().build();
    let cx_ref = &cx;
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::render_shell(&cx, &[], "/admin", slot, None)
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx);
    let label = html
        .find("aria-label=\"Close sidebar\"")
        .unwrap_or_else(|| panic!("missing Close sidebar control in {html}"));
    // Find the tag by its label, then assert on the whole opening tag:
    // `Attributes` renders in no guaranteed order (topcoat#122).
    let tag_start = html[..label].rfind('<').expect("close control tag start");
    let tag = opening_tag_at(&html, tag_start);
    // `md:hidden` is the responsive class that makes this control
    // mobile-only, and it is paint; what a regression would break is that
    // the close control is a real button wired to the sheet's close hook.
    assert!(
        tag.contains("<button") && tag.contains("data-topcoat-on:click"),
        "close control must be a button wired to close the sheet, got {tag}"
    );
}

#[tokio::test]
async fn toaster_renders_no_stray_span_when_empty() {
    // the toaster renders an `<ol>`, which permits only
    // `li`/`script`/`template` children — with no flash notification and
    // no live toast, neither slot may strand a `<span>` in the list.
    use topcoat::{context::CxTestBuilder, view::view};

    use crate::navigation::NavigationItem;

    let cx = CxTestBuilder::new().build();
    let cx_ref = &cx;
    let nav_items: Vec<NavigationItem> = vec![];
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::render_shell(&cx, &nav_items, "/admin/users", slot, None)
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx);
    let ol = &html[html.find("<ol").expect("toaster list")..];
    let ol = &ol[..ol.find("</ol>").expect("toaster close") + "</ol>".len()];
    assert!(
        ol.contains("data-sonner-toaster"),
        "sliced the toaster list, got {ol}"
    );
    assert!(
        !ol.contains("<span"),
        "empty toaster must not strand a span in the list, got {ol}"
    );
}

#[tokio::test]
async fn render_shell_extra_class_reaches_the_provider() {
    // `extra_class` is the custom-document extension point — a
    // passed class must reach the provider markup.
    use topcoat::context::CxTestBuilder;

    let cx = CxTestBuilder::new().build();
    let cx_ref = &cx;
    let nav_items: Vec<NavigationItem> = vec![];
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::render_shell(
        &cx,
        &nav_items,
        "/admin/users",
        slot,
        Some("my-shell".to_string()),
    )
    .await
    .unwrap()
    .single()
    .await
    .unwrap()
    .render(&cx);
    assert!(
        html.contains("my-shell"),
        "extra_class must reach the shell markup, got {html}"
    );
}

#[tokio::test]
async fn collapsed_sidebar_cookie_seeds_the_signal() {
    // The persisted `sidebar_state` cookie seeds the runtime signal's
    // initial value, so the first paint matches the last choice; from
    // hydration on, the browser owns the state (assets/sidebar.js mirrors
    // it back).
    use topcoat::{context::CxTestBuilder, view::view};

    use crate::navigation::{NavTarget, NavigationItem};

    let (parts, ()) = http::Request::builder()
        .uri("/admin/users")
        .header(http::header::COOKIE, "theme=dark; sidebar_state=collapsed")
        .body(())
        .unwrap()
        .into_parts();
    let cx = CxTestBuilder::new().request_context(parts).build();
    let cx_ref = &cx;
    let nav_items = vec![NavigationItem {
        label: "Users".to_string(),
        target: NavTarget::Url("/admin/users".to_string()),
        order: 0,
        icon: None,
    }];
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::render_shell(&cx, &nav_items, "/admin/users", slot, None)
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx);
    assert!(
        html.contains("data-state=\"collapsed\"")
            && html.contains("data-collapsible=\"offcanvas\""),
        "collapsed cookie must seed the collapsed state in {html}"
    );
}

/// A home entry at the bare prefix matches every path under it: only the
/// most specific matching entry is active, and only the first of two entries
/// that share a URL.
#[tokio::test]
async fn sidebar_marks_only_the_longest_matching_entry_active() {
    use topcoat::{context::CxTestBuilder, view::view};

    use crate::navigation::NavigationItem;

    let nav_items = vec![
        NavigationItem::at("Dashboard", "/admin"),
        NavigationItem::at("Users", "/admin/users"),
        NavigationItem::at("Overview", "/admin"),
    ];
    for (path, active_label) in [
        ("/admin", "Dashboard"),
        ("/admin/users/create", "Users"),
        ("/admin/media", "Dashboard"),
    ] {
        let (parts, ()) = http::Request::builder()
            .uri(path)
            .body(())
            .unwrap()
            .into_parts();
        let cx = CxTestBuilder::new().request_context(parts).build();
        let cx_ref = &cx;
        let slot = view! { cx_ref => "hello" }.boxed().into();
        let html = Panel::render_shell(&cx, &nav_items, path, slot, None)
            .await
            .unwrap()
            .single()
            .await
            .unwrap()
            .render(&cx);
        let active: Vec<&str> = html
            .match_indices("data-active=\"true\"")
            .map(|(at, _)| {
                let start = html[..at].rfind('<').unwrap();
                // The whole link: an attribute value can hold a `>`.
                let end = at + html[at..].find("</a>").unwrap();
                &html[start..end]
            })
            .collect();
        assert_eq!(active.len(), 1, "one active entry on {path}: {active:?}");
        assert!(
            active[0].contains(&format!("title=\"{active_label}\"")),
            "{active_label} is active on {path}: {active:?}"
        );
    }
}

/// A navigation entry's icon renders inside its menu button, before the
/// label; an entry without one renders the label alone.
#[tokio::test]
async fn nav_item_icon_renders_before_its_label() {
    use topcoat::{context::CxTestBuilder, view::view};

    use crate::navigation::NavigationItem;

    let (parts, ()) = http::Request::builder()
        .uri("/admin/users")
        .body(())
        .unwrap()
        .into_parts();
    let cx = CxTestBuilder::new().request_context(parts).build();
    let cx_ref = &cx;
    let nav_items = vec![
        NavigationItem::at("Users", "/admin/users").icon(tablo_ui::icons::USERS),
        NavigationItem::at("Posts", "/admin/posts"),
    ];
    let slot = view! { cx_ref => "hello" }.boxed().into();
    let html = Panel::render_shell(&cx, &nav_items, "/admin/users", slot, None)
        .await
        .unwrap()
        .single()
        .await
        .unwrap()
        .render(&cx);
    let button = |href: &str| {
        let start = html
            .find(&format!("href=\"{href}\""))
            .unwrap_or_else(|| panic!("no link to {href} in {html}"));
        let open = html[..start].rfind("<a").expect("the link's tag");
        let close = open + html[open..].find("</a>").expect("the link's end");
        html[open..close].to_string()
    };
    let users = button("/admin/users");
    let svg = users
        .find("<svg")
        .expect("the Users entry renders its icon");
    let label = users.find("<span>Users</span>").expect("the Users label");
    assert!(svg < label, "the icon precedes the label in {users}");
    assert!(
        !button("/admin/posts").contains("<svg"),
        "an entry without an icon renders none"
    );
}

/// A panel at `/admin` whose shell starts dark when `dark` is set.
fn dark_panel(dark: bool) -> crate::panel::state::CurrentPanel {
    let mut panel = crate::panel::test_support::panel_state("/admin", crate::Auth::disabled());
    panel.dark_mode = dark;
    crate::panel::test_support::current_panel(panel)
}