1
//! Every mutating htmx element drops a second request while one is in flight.
2

            
3
use std::path::{Path, PathBuf};
4

            
5
use axum::{Router, routing::get};
6
use web::model::User;
7

            
8
use crate::common::create_mock_user;
9
use crate::common::entity_edit::get_from;
10
use crate::common::tenant::provision_tenant;
11

            
12
const GUARD: [&str; 2] = [
13
    "hx-sync=\"this:drop\"",
14
    "hx-disabled-elt=\"find button[type=submit]\"",
15
];
16

            
17
21
fn templates(dir: &Path, found: &mut Vec<PathBuf>) {
18
21
    for entry in std::fs::read_dir(dir).expect("templates dir").flatten() {
19
102
        let path = entry.path();
20
102
        match path.is_dir() {
21
20
            true => templates(&path, found),
22
82
            false => found.push(path),
23
        }
24
    }
25
21
}
26

            
27
const MUTATING: [&str; 4] = ["hx-post", "hx-put", "hx-patch", "hx-delete"];
28

            
29
/// The text of a tag up to the first `>` outside a quoted attribute value.
30
722
fn tag_end(rest: &str) -> &str {
31
722
    let mut quote = None;
32
722
    for (at, c) in rest.char_indices() {
33
37987
        match (quote, c) {
34
722
            (None, '>') => return &rest[..at],
35
1022
            (None, '"' | '\'') => quote = Some(c),
36
17973
            (Some(open), _) if open == c => quote = None,
37
35221
            _ => {}
38
        }
39
    }
40
    rest
41
722
}
42

            
43
86
fn unguarded_elements(source: &str) -> usize {
44
86
    let mut count = 0;
45
86
    let mut rest = source;
46
1416
    while let Some(at) = rest.find('<') {
47
1330
        rest = &rest[at + 1..];
48
1330
        if !rest.starts_with(|c: char| c.is_ascii_alphabetic()) {
49
608
            continue;
50
722
        }
51
722
        let tag = tag_end(rest);
52
2847
        let mutating = MUTATING.iter().any(|verb| tag.contains(verb));
53
722
        let guarded = tag.contains("in_flight::guard") || tag.contains("hx-disabled-elt=\"this\"");
54
722
        count += usize::from(mutating && !guarded);
55
722
        rest = &rest[tag.len()..];
56
    }
57
86
    count
58
86
}
59

            
60
#[test]
61
1
fn every_mutating_htmx_element_is_guarded() {
62
1
    let mut files = Vec::new();
63
1
    templates(
64
1
        &Path::new(env!("CARGO_MANIFEST_DIR")).join("templates"),
65
1
        &mut files,
66
1
    );
67
1
    let bare: Vec<_> = files
68
1
        .iter()
69
82
        .filter(|file| unguarded_elements(&std::fs::read_to_string(file).expect("template")) > 0)
70
        .collect();
71
1
    assert!(bare.is_empty(), "unguarded htmx elements: {bare:?}");
72
1
}
73

            
74
2
fn page_router() -> Router<std::sync::Arc<web::AppState>> {
75
2
    Router::new()
76
2
        .route("/tag/create", get(web::pages::tag::create::tag_create_page))
77
2
        .route("/register", get(web::pages::register))
78
2
}
79

            
80
#[supp_macro::shared_runtime_test]
81
1
async fn the_tag_create_and_register_pages_render_the_guard() {
82
1
    let user: User = create_mock_user();
83
1
    provision_tenant(user.id).await;
84
1
    for path in ["/tag/create", "/register"] {
85
2
        let reply = get_from(page_router(), &user, path).await;
86
2
        for attr in GUARD {
87
4
            assert!(reply.body.contains(attr), "{path} lacks {attr}");
88
        }
89
    }
90
}
91

            
92
#[test]
93
1
fn a_greater_sign_inside_an_attribute_does_not_end_the_tag() {
94
1
    let form = "<form hx-on::after-request=\"a => b\" hx-put=\"/x\">";
95
1
    assert_eq!(unguarded_elements(form), 1);
96
1
    let guarded = "<form hx-on::after-request=\"a => b\" hx-delete=\"/x\" {% call in_flight::guard() %}{% endcall %}>";
97
1
    assert_eq!(unguarded_elements(guarded), 0);
98
1
}
99

            
100
#[test]
101
1
fn a_mutating_button_needs_the_guard_or_its_own_disabling() {
102
1
    assert_eq!(
103
1
        unguarded_elements("<button hx-post=\"/x\">a < b</button>"),
104
1
        1
105
    );
106
1
    assert_eq!(
107
1
        unguarded_elements("<button hx-post=\"/x\" hx-disabled-elt=\"this\">"),
108
1
        0
109
    );
110
1
}