tablo-core 0.6.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
use super::*;
use crate::{
    Ability, ResourceDef, lens,
    panel::test_support::{Dummy, dummy_table, mount, panel_for},
    test_support::memory_db,
};

/// Renders the list body with one seeded row.
async fn list_html<R: Resource>() -> String {
    list_html_with::<R>(&["Ada"]).await
}

/// Renders the list body with the named rows seeded in order.
async fn list_html_with<R: Resource>(names: &[&str]) -> String {
    list_html_via(names, panel_for::<R>).await
}

/// Renders the list body of the panel `panel` builds over a db seeded with `names`.
async fn list_html_via(names: &[&str], panel: fn() -> crate::Panel) -> String {
    use http_body_util::BodyExt;

    let mut db = memory_db(toasty::models!(Dummy)).await;
    for name in names {
        toasty::create!(Dummy {
            name: (*name).to_string(),
        })
        .exec(&mut db)
        .await
        .unwrap();
    }
    let router = mount(db, panel()).expect("panel builds");
    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/dummies")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert!(resp.status().is_success());
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    String::from_utf8_lossy(&body).to_string()
}

/// Asserts two lists declare distinct signal ids.
#[tokio::test]
async fn two_lists_declare_distinct_signal_ids() {
    use http_body_util::BodyExt;

    use crate::resource::Resource;

    macro_rules! list_resource {
        ($name:ident, $slug:literal) => {
            struct $name;
            impl Resource for $name {
                type Model = Dummy;
                type Form = crate::NoForm<Self::Model>;

                fn declare() -> ResourceDef<Self> {
                    ResourceDef::new()
                        .slug($slug)
                        .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| {
                            matches!(ability, Ability::ViewAny)
                        })
                        .table(dummy_table().paginate(25))
                }
            }
        };
    }
    list_resource!(FirstResource, "firsts");
    list_resource!(SecondResource, "seconds");

    let db = memory_db(toasty::models!(Dummy)).await;
    // The shell's sidebar signals match on every page; a bare layout leaves only the tables' own.
    fn bare<'a>(_cx: &'a Cx, slot: topcoat::router::Slot<'a>) -> topcoat::view::BoxView<'a> {
        topcoat::view::ViewExt::boxed(slot)
    }
    let router = mount(
        db,
        crate::Panel::new("admin")
            .resource::<FirstResource>()
            .resource::<SecondResource>()
            .auth(crate::Auth::disabled())
            .layout(bare),
    )
    .expect("panel builds");
    let mut ids = Vec::new();
    for uri in ["/admin/firsts", "/admin/seconds"] {
        let resp = router
            .handle(
                http::Request::builder()
                    .uri(uri)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await;
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let html = String::from_utf8_lossy(&body).to_string();
        let page: std::collections::HashSet<String> = html
            .split("&quot;id&quot;:&quot;")
            .skip(1)
            .filter_map(|rest| rest.split("&quot;").next().map(str::to_string))
            .collect();
        assert!(
            !page.is_empty(),
            "{uri} must declare its table signals, got {html}"
        );
        ids.push(page);
    }
    assert!(
        ids[0].is_disjoint(&ids[1]),
        "two lists share signal ids {:?}",
        ids[0].intersection(&ids[1]).collect::<Vec<_>>()
    );
}

/// A list reads its state from its query signal: a rerun carrying another query renders that
/// query's rows, whatever the URL says.
#[tokio::test]
async fn a_rerun_renders_the_query_its_signal_carries() {
    use http_body_util::BodyExt;

    struct SearchResource;
    impl Resource for SearchResource {
        type Model = Dummy;
        type Form = crate::NoForm<Self::Model>;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dummies")
                .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| matches!(ability, Ability::ViewAny))
                .table(crate::table::Table::new(
                    crate::table::TextColumn::new(lens!(Dummy.name)).searchable(),
                ))
        }
    }

    let mut db = memory_db(toasty::models!(Dummy)).await;
    for name in ["Ada", "Bob"] {
        toasty::create!(Dummy {
            name: name.to_string(),
        })
        .exec(&mut db)
        .await
        .unwrap();
    }
    let router = mount(db, panel_for::<SearchResource>()).expect("panel builds");
    let read = |resp: http::Response<Body>| async move {
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        String::from_utf8_lossy(&body).to_string()
    };

    let html = read(
        router
            .handle(
                http::Request::builder()
                    .uri("/admin/dummies?q=Bob")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await,
    )
    .await;
    assert!(html.contains(">Bob<") && !html.contains(">Ada<"), "{html}");
    let declaration = html
        .split("::topcoat::signal(")
        .skip(1)
        .find(|declaration| declaration.contains("&quot;v&quot;:&quot;q=Bob&quot;"))
        .unwrap_or_else(|| panic!("the page must declare its query signal, got {html}"));
    let id = declaration
        .split("&quot;id&quot;:&quot;")
        .nth(1)
        .and_then(|rest| rest.split("&quot;").next())
        .expect("a signal id");

    let rerun = read(
        router
            .handle(
                http::Request::builder()
                    .method(http::Method::POST)
                    .uri("/admin/dummies?q=Bob")
                    .header("X-Topcoat-Runtime", "true")
                    .header(http::header::CONTENT_TYPE, "application/json")
                    .body(Body::from(format!(r#"{{"signals":{{"{id}":"q=Ada"}}}}"#)))
                    .unwrap(),
            )
            .await,
    )
    .await;
    assert!(
        rerun.contains(">Ada<") && !rerun.contains(">Bob<"),
        "{rerun}"
    );
}

#[tokio::test]
async fn read_only_resource_hides_delete_chrome() {
    use http_body_util::BodyExt;

    use crate::resource::Resource;

    struct ReadOnlyResource;
    impl Resource for ReadOnlyResource {
        type Model = Dummy;
        type Form = crate::NoForm<Self::Model>;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dummies")
                .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| matches!(ability, Ability::ViewAny))
                .table(dummy_table().paginate(25))
        }
    }

    let mut db = memory_db(toasty::models!(Dummy)).await;
    toasty::create!(Dummy {
        name: "Ada".to_string(),
    })
    .exec(&mut db)
    .await
    .unwrap();
    let router = mount(db, panel_for::<ReadOnlyResource>()).expect("panel builds");
    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/dummies")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert!(resp.status().is_success());
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let html = String::from_utf8_lossy(&body);
    assert!(
        html.contains("Ada"),
        "the grid must render the seeded row, or the negative assertions below are vacuous, got {html}"
    );
    assert!(
        !html.contains("Delete selected"),
        "read-only list must not render bulk chrome, got {html}"
    );
    assert!(
        !html.contains("/delete"),
        "read-only list must not render delete actions, got {html}"
    );
    // the read-only example must not emit an Edit link it cannot
    // honour — it has no record form and allows no delete.
    assert!(
        !html.contains("/edit") && !html.contains(">Edit<"),
        "read-only list must not render edit actions, got {html}"
    );
}

#[tokio::test]
async fn non_editable_resource_hides_edit_links() {
    // The per-row Edit link follows the record form: a `NoForm` resource
    // hides it, a resource with a form links each row to
    // `{list}/{id}/edit`.

    use crate::resource::Resource;

    struct WritableResource;
    impl Resource for WritableResource {
        type Model = Dummy;
        type Form = WritableForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dummies")
                // The row policy mirrors the edit route's own `View`
                // + `Update` check, so a form beside default-deny predicates
                // renders no link.
                .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| {
                    matches!(
                        ability,
                        Ability::ViewAny | Ability::View(_) | Ability::Create | Ability::Update(_)
                    )
                })
                .table(dummy_table().paginate(25))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Dummy)]
    struct WritableForm {
        name: String,
    }
    struct LockedResource;
    impl Resource for LockedResource {
        type Model = Dummy;
        type Form = crate::NoForm<Self::Model>;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dummies")
                .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| matches!(ability, Ability::ViewAny))
                .table(dummy_table().paginate(25))
        }
    }

    let html = list_html::<WritableResource>().await;
    assert!(
        html.contains("/edit") && html.contains("aria-label=\"Edit\""),
        "editable list must link rows to their edit pages, got {html}"
    );
    // The row and Create links navigate through the runtime, and the
    // panel's router turns prefetching off.
    assert!(
        html.contains("data-topcoat-link=\"never\"")
            && !html.contains("data-topcoat-link=\"intent\""),
        "panel links must use runtime navigation without prefetch, got {html}"
    );
    let html = list_html::<LockedResource>().await;
    assert!(
        !html.contains("/edit") && !html.contains(">Edit<"),
        "non-editable list must not render edit links, got {html}"
    );
}

/// Asserts denied rows render no edit chrome.
#[tokio::test]
async fn denied_rows_render_no_edit_chrome() {
    use http_body_util::BodyExt;

    use crate::resource::Resource;

    /// The minimum a resource can declare: `ViewAny` so the list
    /// renders, a grid and a form so there is something to link to, and
    /// every other `can_*` left at its default.
    struct DeniedResource;
    impl Resource for DeniedResource {
        type Model = Dummy;
        type Form = DeniedForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dummies")
                .policy(|_cx: &Cx, ability: Ability<'_, Dummy>| matches!(ability, Ability::ViewAny))
                .table(dummy_table().paginate(25))
        }
    }
    #[derive(crate::RecordForm)]
    #[form(model = Dummy)]
    struct DeniedForm {
        name: String,
    }
    let mut db = memory_db(toasty::models!(Dummy)).await;
    let row = toasty::create!(Dummy {
        name: "Ada".to_string(),
    })
    .exec(&mut db)
    .await
    .unwrap();
    let router = mount(db, panel_for::<DeniedResource>()).expect("panel builds");

    let resp = router
        .handle(
            http::Request::builder()
                .uri("/admin/dummies")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert!(resp.status().is_success());
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let html = String::from_utf8_lossy(&body);
    assert!(
        html.contains("Ada"),
        "the grid must render the seeded row, or the negative assertions below are vacuous, got {html}"
    );
    assert!(
        !html.contains("/edit") && !html.contains(">Edit<"),
        "a row the policy denies must render no Edit link, got {html}"
    );
    assert!(
        !html.contains("Delete selected")
            && !html.contains("data-bulk-form")
            && !html.contains("/delete"),
        "a resource that allows no delete must render no delete affordance, got {html}"
    );

    // The route's own answer for the row the list no longer links.
    let resp = router
        .handle(
            http::Request::builder()
                .uri(format!("/admin/dummies/{}/edit", row.id))
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert_eq!(
        resp.status(),
        http::StatusCode::FORBIDDEN,
        "the edit route must deny the row the list no longer links"
    );
}

#[test]
fn retry_url_for_error_drops_only_bad_cursors() {
    // a malformed cursor can never decode, so its retry link drops
    // pagination; any other failure keeps the full evidence.
    let state = TableState {
        search: Some("Ada".to_string()),
        cursor: Some(crate::table::Cursor::After("cur".to_string())),
        ..TableState::default()
    };
    let bad_cursor =
        crate::toasty_compat::cursor::decode("zz").expect_err("malformed cursor must fail");
    let retry = retry_url_for_error(&state, &bad_cursor, "/admin/users");
    assert!(
        !retry.contains("after="),
        "bad-cursor retry must drop pagination, got {retry}"
    );
    assert!(
        retry.contains("q=Ada"),
        "bad-cursor retry keeps the other state, got {retry}"
    );

    let db_error = crate::error::unavailable("connection reset");
    let retry = retry_url_for_error(&state, &db_error, "/admin/users");
    assert!(
        retry.contains("after=cur"),
        "transient failures retry the same evidence, got {retry}"
    );
}