autumn-web 0.7.0

An opinionated, convention-over-configuration web 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
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
//! Built-in widget stories: one story per gallery-visible widget in
//! [`crate::widgets`] (issue #1526).
//!
//! Every story is authored with the [`story!`](crate::stories::story) macro,
//! so the snippet shown in the gallery is byte-for-byte the code that
//! rendered. Blocks are self-contained (demo data is defined inside), because
//! they are coerced to zero-arg `fn() -> Markup` pointers — no environment
//! capture compiles.
//!
//! The CI coverage gate (`autumn/tests/integration/stories.rs`) enforces that
//! every public widget fn in `src/widgets.rs` is exercised by at least one
//! story's source. When you add a widget, add (or extend) a story here and
//! add the new top-level widget's slug to `EXPECTED_STORY_SLUGS` in that test.

use super::{Story, story};

/// The built-in story set, in gallery display order.
#[allow(clippy::too_many_lines)]
pub(super) fn builtin_stories() -> Vec<Story> {
    vec![
        story! {
            "Forms",
            "Active search",
            {
                use autumn_web::widgets::{
                    ActiveSearchConfig, active_search, active_search_empty_state,
                    active_search_input, active_search_results,
                };

                let config = ActiveSearchConfig::new("/search", "#post-search-results")
                    .placeholder("Search posts…");
                maud::html! {
                    (active_search("post-search", "Search posts", &config))
                    // What your handler returns when nothing matches:
                    (active_search_empty_state("No posts matched your search."))
                    // Compose the pieces yourself when you need custom layout
                    // between the input and the results container:
                    div {
                        (active_search_input("post-search-split", "Search posts", &config))
                        (active_search_results("post-search-split"))
                    }
                }
            }
        },
        story! {
            "Forms",
            "Autocomplete",
            {
                use autumn_web::widgets::{
                    AutocompleteConfig, autocomplete_empty_state, autocomplete_input,
                    autocomplete_option,
                };

                let config = AutocompleteConfig::new("/tags/search", "tag_id")
                    .placeholder("Start typing a tag…");
                maud::html! {
                    (autocomplete_input("tag-picker", "Tag", &config))
                    // One matching option, as your handler would render it:
                    (autocomplete_option("42", "rust"))
                    // And the empty state when nothing matches:
                    (autocomplete_empty_state("No matching tags."))
                }
            }
        },
        story! {
            "Display",
            "Property list",
            {
                use autumn_web::widgets::property_list;

                property_list(&[
                    ("Title", maud::html! { "Autumn in Practice" }),
                    ("Status", maud::html! { strong { "Published" } }),
                    ("Views", maud::html! { "1,024" }),
                ])
            }
        },
        story! {
            "Display",
            "Data table",
            {
                use autumn_web::widgets::{Column, DataTableConfig, data_table};

                struct Book {
                    title: &'static str,
                    author: &'static str,
                    year: u16,
                }
                let books = [
                    Book { title: "The Long Autumn", author: "R. Ellis", year: 2021 },
                    Book { title: "Falling Leaves", author: "M. Okafor", year: 2023 },
                ];
                let columns = [
                    Column::new("Title", |b: &Book| maud::html! { (b.title) })
                        .sortable("title"),
                    Column::new("Author", |b: &Book| maud::html! { (b.author) }),
                    Column::new("Year", |b: &Book| maud::html! { (b.year) }),
                ];
                let config = DataTableConfig::new("No books yet.")
                    .caption("Books")
                    .base_path("/books");
                data_table(&books, &columns, &config)
            }
        },
        story! {
            "Display",
            "Breadcrumb",
            {
                use autumn_web::widgets::{Crumb, breadcrumb};

                breadcrumb(&[
                    Crumb::link("Home", "/"),
                    Crumb::link("Posts", "/posts"),
                    Crumb::current("My Post"),
                ])
            }
        },
        story! {
            "Display",
            "Card",
            {
                use autumn_web::widgets::{CardConfig, card};

                let body = maud::html! { p { "Ship features, not boilerplate." } };
                let config = CardConfig::new()
                    .title("Release notes")
                    .footer(maud::html! { a href="/changelog" { "Read the changelog" } });
                card(&body, &config)
            }
        },
        story! {
            "Display",
            "Charts",
            {
                use autumn_web::widgets::{
                    ChartConfig, bar_chart, bar_chart_with, line_chart, line_chart_with,
                    sparkline, sparkline_with,
                };

                // A 30-point trend series, built with a loop (no env capture).
                let owned: Vec<(String, f64)> = (0..30)
                    .map(|day| {
                        let label = format!("Day {}", day + 1);
                        let swing = (f64::from(day) * 0.4).sin() * 10.0;
                        let value = 20.0 + swing;
                        (label, value)
                    })
                    .collect();
                let trend: Vec<(&str, f64)> =
                    owned.iter().map(|(l, v)| (l.as_str(), *v)).collect();

                let weekly = [
                    ("Mon", 3.0), ("Tue", 5.0), ("Wed", 4.0),
                    ("Thu", 7.0), ("Fri", 6.0),
                ];

                maud::html! {
                    // Compact inline trend — plain and configured variants:
                    (sparkline(&weekly))
                    (sparkline_with(&weekly, &ChartConfig::new().title("Weekly visits")))
                    // Bars, with a caller axis override + table fallback:
                    (bar_chart(&weekly))
                    (bar_chart_with(
                        &weekly,
                        &ChartConfig::new().min(0.0).max(10.0).with_table(),
                    ))
                    // A 30-point line chart, auto-scaled and configured:
                    (line_chart(&trend))
                    (line_chart_with(&trend, &ChartConfig::new().title("30-day trend")))
                }
            }
        },
        story! {
            "Display",
            "Stat card",
            {
                use autumn_web::widgets::stat_card;

                maud::html! {
                    (stat_card("Subscribers", "1,024", Some(("/subscribers", "View all"))))
                    (stat_card("Open rate", "62%", None))
                }
            }
        },
        story! {
            "Display",
            "Tabs",
            {
                use autumn_web::widgets::tabs;

                let panels = [
                    ("demo-profile", "Profile", maud::html! { p { "Profile settings" } }),
                    ("demo-security", "Security", maud::html! { p { "Security settings" } }),
                    ("demo-billing", "Billing", maud::html! { p { "Billing settings" } }),
                ];
                tabs("settings-tabs", None, &panels)
            }
        },
        story! {
            "Navigation",
            "Nav bar",
            {
                use autumn_web::widgets::{NavBarConfig, NavItem, NavMenu, nav_bar};

                let config = NavBarConfig::new()
                    .brand("Acme", "/")
                    .item(NavItem::link("/", "Home"))
                    .item(NavItem::link("/posts", "Posts"))
                    .item(NavItem::menu(
                        NavMenu::new("More")
                            .link("/about", "About")
                            .plain_link("https://docs.example.com", "Docs"),
                    ))
                    .trailing(NavItem::plain_link("/login", "Sign in"));
                // "/posts" is the current request path, so that link is active.
                nav_bar("/posts", &config)
            }
        },
        story! {
            "Navigation",
            "Nav link",
            {
                use autumn_web::widgets::{NavLinkMatch, nav_link, nav_link_matched};

                maud::html! {
                    nav {
                        // Exact match: active only on "/posts" itself.
                        (nav_link("/posts", "/posts", "Posts"))
                        // Prefix match: "/posts/3/edit" keeps "All posts" active.
                        (nav_link_matched("/posts/3/edit", "/posts", "All posts", NavLinkMatch::Prefix))
                        (nav_link("/posts", "/about", "About"))
                    }
                }
            }
        },
        story! {
            "Navigation",
            "Locale switcher",
            {
                use autumn_web::widgets::{locale_switcher, localized_path};

                maud::html! {
                    p { "Current page: " code { "/posts" } }
                    (locale_switcher(
                        "/posts",
                        "en",
                        &["en".to_owned(), "es".to_owned(), "fr".to_owned()],
                    ))
                    p class="text-xs text-stone-500" {
                        "Each link is built with " code { "localized_path" }
                        " — e.g. " code { (localized_path("/posts", "es")) }
                    }
                }
            }
        },
        story! {
            "Marketing",
            "Hero",
            {
                use autumn_web::widgets::{Cta, HeroConfig, hero};

                let config = HeroConfig::new("Welcome to the Blog")
                    .subtitle("Thoughts, tutorials, and stories.")
                    .cta(Cta::primary("New post", "/admin/new"))
                    .cta(Cta::secondary("About", "/about"));
                hero(&config)
            }
        },
        story! {
            "Overlays",
            "Modal",
            {
                use autumn_web::widgets::{
                    ModalConfig, modal, modal_close_button, modal_trigger,
                };

                let body = maud::html! { p { "This action cannot be undone." } };
                let config = ModalConfig::new()
                    .footer(maud::html! {
                        (modal_close_button("Cancel", "delete-confirm", None))
                    })
                    .light_dismiss(true);
                maud::html! {
                    (modal_trigger("Delete post", "delete-confirm", None))
                    (modal("delete-confirm", "Delete this post?", &body, &config))
                }
            }
        },
        story! {
            "Overlays",
            "Confirm action",
            {
                use autumn_web::widgets::{ConfirmActionConfig, confirm_action};

                let config = ConfirmActionConfig::new()
                    .title("Delete this post?")
                    .message(maud::html! { p { "This permanently removes the post." } })
                    .confirm_label("Delete post");
                // The rendered form is live, so this demo points it at a
                // synthetic target (nothing is mounted there — submitting on
                // a served gallery is a 404 no-op) with a fake CSRF token.
                confirm_action(
                    "delete-post",
                    "Delete…",
                    "/_stories/demo/delete-post",
                    http::Method::DELETE,
                    "demo-csrf-token",
                    &config,
                )
            }
        },
        story! {
            "Display",
            "Badge",
            {
                use autumn_web::widgets::{
                    BadgeConfig, BadgeVariant, badge, badge_with, status_tag,
                };

                maud::html! {
                    // Explicit variant, and a deterministic color from a label:
                    (badge("Published", BadgeVariant::Success))
                    (badge("Draft", BadgeVariant::for_label("draft")))
                    // With a tooltip / accessible name for an abbreviated label:
                    (badge_with(
                        "WIP",
                        BadgeVariant::Info,
                        &BadgeConfig::new().title("Work in progress"),
                    ))
                    // Neutral one-liner:
                    (status_tag("Archived"))
                }
            }
        },
        story! {
            "Display",
            "Avatar",
            {
                use autumn_web::widgets::{AvatarConfig, AvatarSize, avatar};

                maud::html! {
                    // With an image (the demo URL is synthetic — a served
                    // gallery has nothing mounted there):
                    (avatar("Ada Lovelace", &AvatarConfig::new()
                        .image("/_stories/demo/ada.png")
                        .size(AvatarSize::Large)))
                    // Deterministic colored-initials fallback, no image:
                    (avatar("Ada Lovelace", &AvatarConfig::new()))
                    (avatar("Grace Hopper", &AvatarConfig::new().size(AvatarSize::Small)))
                }
            }
        },
        story! {
            "Feedback",
            "Alert",
            {
                use autumn_web::form::Changeset;
                use autumn_web::widgets::{
                    AlertConfig, AlertVariant, alert, alert_with, error_summary,
                };

                // A form error summary from an invalid changeset.
                let mut errors = std::collections::HashMap::new();
                errors.insert("email".to_string(), vec!["is invalid".to_string()]);
                let changeset = Changeset::from_errors((), errors);

                maud::html! {
                    (alert(
                        AlertVariant::Info,
                        maud::html! { "No posts yet — create your first one." },
                    ))
                    (alert_with(
                        AlertVariant::Warning,
                        maud::html! { "Your trial ends in 3 days." },
                        &AlertConfig::new().title("Heads up").icon(true).dismissible(true),
                    ))
                    @if let Some(summary) = error_summary(&changeset) {
                        (summary)
                    }
                }
            }
        },
        story! {
            "Feedback",
            "Toast",
            {
                use autumn_web::widgets::{
                    AlertVariant, DEFAULT_TOAST_REGION_ID, toast, toast_in, toast_region,
                };

                maud::html! {
                    // Drop the region once in your base layout:
                    (toast_region(DEFAULT_TOAST_REGION_ID))
                    // Then return toasts from htmx handlers — appended OOB into
                    // the region. `Error` announces assertively, others politely.
                    (toast("Saved successfully", AlertVariant::Success))
                    (toast("Could not save — please retry", AlertVariant::Error))
                    // Target a differently-named region with `toast_in`:
                    (toast_in(DEFAULT_TOAST_REGION_ID, "Heads up: trial ends soon", AlertVariant::Warning))
                }
            }
        },
        story! {
            "Feedback",
            "Infinite feed",
            {
                use autumn_web::widgets::{FeedConfig, FeedMode, feed_page, infinite_feed};

                let items = maud::html! {
                    article class="post" { h3 { "First post" } }
                    article class="post" { h3 { "Second post" } }
                };
                let next = maud::html! {
                    article class="post" { h3 { "Third post" } }
                };
                let config = FeedConfig::new("/posts/feed").mode(FeedMode::Reveal);
                maud::html! {
                    // Initial view: the feed container + an auto-loading sentinel.
                    (infinite_feed(items, Some("eyJpZCI6Mn0"), &config))
                    // The fragment a handler returns for each append (here the
                    // last page, so no further sentinel is emitted):
                    (feed_page(next, None, &FeedConfig::new("/posts/feed").button()))
                }
            }
        },
        story! {
            "Forms",
            "Transition controls",
            {
                use autumn_web::widgets::transition_controls;

                // A `#[state_machine]` field emits a `(from, to, Option<guard>)`
                // transitions constant and a `can_transition_<field>_to`
                // predicate; pass those two straight through. Here they are
                // inlined so the story is self-contained.
                let transitions: &[(&str, &str, Option<&str>)] = &[
                    ("draft", "published", None),
                    ("published", "archived", None),
                ];
                // Only edges leaving `current` ("draft") render, so this shows
                // the single `draft -> published` action button.
                transition_controls(
                    "/orders/1/transitions/status",
                    "status",
                    "draft",
                    transitions,
                    |_to| true, // |to| order.can_transition_status_to(to)
                    None,
                    None,
                )
            }
        },
        story! {
            "Display",
            "Comment thread",
            {
                use autumn_web::widgets::{CommentThread, CommentView, comment_dom_id, comment_thread};

                // The view half of `#[commentable]`. The router hands back a
                // nested thread; this renders it with an inline reply form per
                // node. Plain POST forms, swapped in place by htmx when it is
                // present and a full page load when it is not.
                let thread = vec![
                    CommentView {
                        id: 7,
                        author: "ada".to_owned(),
                        body: "Does this nest?".to_owned(),
                        datetime: Some("2026-08-21T09:30:00Z".to_owned()),
                        timestamp: "2026-08-21 09:30".to_owned(),
                        replies: vec![CommentView {
                            id: 8,
                            author: "grace".to_owned(),
                            body: "It does — up to `max_depth`,\nafter which the reply form stops rendering.".to_owned(),
                            datetime: Some("2026-08-21T09:41:00Z".to_owned()),
                            timestamp: "2026-08-21 09:41".to_owned(),
                            replies: Vec::new(),
                        }],
                    },
                    CommentView {
                        id: 9,
                        author: "linus".to_owned(),
                        body: "A second top-level comment.".to_owned(),
                        datetime: None,
                        timestamp: String::new(),
                        replies: Vec::new(),
                    },
                ];

                let signed_in = CommentThread::new("comments-post-42", "/comments/Post/42")
                    .label("Post comments")
                    .csrf_token("story-token")
                    .return_to("/posts/42");

                // Anything linking to one comment — a notification, an email —
                // needs the id the widget actually renders, so the convention
                // has one definition rather than a copy per caller.
                let deep_link = comment_dom_id("comments-post-42", 8);

                maud::html! {
                    (comment_thread(&signed_in, &thread))

                    // Signed out: the thread still reads, the form is replaced
                    // by a prompt rather than a control that would 401.
                    (comment_thread(
                        &CommentThread::new("comments-post-43", "/comments/Post/43")
                            .label("Signed-out view")
                            .read_only()
                            .sign_in_prompt("Log in to comment."),
                        &thread,
                    ))

                    // Empty, and a rejected submission re-rendered inline —
                    // a bare 422 would be swallowed by htmx.
                    (comment_thread(
                        &CommentThread::new("comments-post-44", "/comments/Post/44")
                            .label("Empty and errored")
                            .empty_text("No comments yet. Start the conversation!")
                            .csrf_token("story-token")
                            .error("Comment cannot be empty."),
                        &[],
                    ))

                    p class="text-sm text-gray-500" {
                        "Deep link to the nested reply: #" (deep_link)
                    }
                }
            }
        },
        story! {
            "Display",
            "Reaction controls",
            {
                use autumn_web::widgets::{ReactionControls, reaction_controls};

                // The view half of `#[votable]`: `react()` returns the new
                // aggregate and the viewer's own reaction, which is all this
                // widget needs. Plain POST forms, upgraded in place by htmx.
                maud::html! {
                    // Sum mode -- signed up/down votes. The viewer has already
                    // upvoted, so the up arrow renders as a pressed toggle.
                    (reaction_controls(
                        &ReactionControls::votes(
                            "votes-42",
                            "/posts/42/upvote",
                            "/posts/42/downvote",
                        )
                        .aggregate(7)
                        .current(Some(1))
                        .label("Post score"),
                    ))
                    // Count mode -- one membership toggle, not yet pressed.
                    (reaction_controls(
                        &ReactionControls::likes("likes-42", "/posts/42/like")
                            .aggregate(3)
                            .label("Likes"),
                    ))
                }
            }
        },
        story! {
            "Display",
            "Bulk actions",
            {
                use autumn_web::widgets::{
                    BulkActionsConfig, Column, DataTableConfig, bulk_actions_form,
                    bulk_actions_toolbar, bulk_select_checkbox, data_table,
                };

                struct Post {
                    id: i64,
                    title: &'static str,
                }
                let rows = vec![
                    Post { id: 1, title: "First post" },
                    Post { id: 2, title: "Second post" },
                ];

                // `action` is the bulk endpoint -- `paths::bulk_delete()` in a
                // scaffolded app. The flow is entirely unscripted, so it works
                // with JavaScript disabled.
                let config = BulkActionsConfig::new("/posts/bulk_delete");

                // The checkbox goes in the row's first cell, so every row can be
                // selected. Each one submits as a repeated `ids=<id>` pair.
                let columns: Vec<Column<Post>> = vec![
                    Column::new("", |row: &Post| {
                        maud::html! { (bulk_select_checkbox(row.id, &config)) }
                    }),
                    Column::new("Title", |row: &Post| maud::html! { (row.title) }),
                ];

                // A second bulk action, driving a hand-rolled list instead of a
                // `data_table`. `bulk_actions_form` already appends a toolbar, so
                // `bulk_actions_toolbar` is called directly only here, where the
                // surrounding <form> is hand-built -- a bare toolbar outside any
                // form would render a submit button that does nothing.
                let archive = BulkActionsConfig::new("/posts/bulk_archive")
                    .submit_label("Archive selected");

                maud::html! {
                    // Page furniture stays OUTSIDE the form -- anything inside is
                    // submitted along with the selection.
                    a href="/posts/new" { "New Post" }
                    (bulk_actions_form(
                        &config,
                        Some("demo-csrf-token"),
                        None,
                        Some("demo-submit-token"),
                        None,
                        maud::html! {
                            (data_table(&rows, &columns, &DataTableConfig::new("No posts yet.")))
                        },
                    ))
                    form method="post" action="/posts/bulk_archive" class="autumn-bulk-form" {
                        // Hand-built forms carry the same hidden fields
                        // `bulk_actions_form` emits, and for the same reason: both
                        // lead the body, ahead of the checkboxes, because
                        // `SubmitTokenLayer` only scans its first chunk.
                        input type="hidden" name="_submit_token" value="demo-archive-token";
                        input type="hidden" name="_csrf" value="demo-csrf-token";
                        ul {
                            @for row in &rows {
                                li {
                                    (bulk_select_checkbox(row.id, &archive))
                                    " " (row.title)
                                }
                            }
                        }
                        (bulk_actions_toolbar(&archive))
                    }
                }
            }
        },
    ]
}