Skip to main content

tablo_test/
protocol.rs

1//! Reads values back out of rendered responses: bodies, cookies, form data, the page's language,
2//! and the semantic HTML queries over tables, action buttons, fields, filters, the ignored-filters
3//! banner, the impersonation banner, the import page, rich text values, the notification bell, the
4//! global search, sections, the sidebar, tabs, a list's tab bar, widgets, and wizard steps.
5
6mod bell;
7mod choice_create;
8mod controls;
9mod detail;
10pub mod dom;
11mod ignored;
12mod impersonation;
13mod import;
14mod list_tabs;
15mod page_filters;
16mod rich_text;
17mod search;
18mod sections;
19mod sidebar;
20mod summaries;
21mod tabs;
22mod widgets;
23mod wizard;
24
25pub use bell::{Bell, BellNotification, bell};
26pub use choice_create::{CreateOptionLink, Picked, create_option_links, picked, posts_picking};
27pub use controls::{
28    DisabledAction, action_badge, action_label, action_submits, action_tooltip, confirms_first,
29    disabled_actions, options_url, selects_matching,
30};
31pub use detail::{DetailEntry, RecordNavLink, detail_entries, record_navigation};
32pub use dom::{
33    CellEdit, EmptyReason, EmptyTable, ErrorKind, FilterOption, Group, PickerColumn, Row,
34    RowActions, column_picker, columns, empty_table, field_error, field_error_message,
35    filter_options, find_href_with, groups, row_actions, row_keys, rows, sortable_columns,
36};
37use http_body_util::BodyExt;
38pub use ignored::{IgnoredFilter, IgnoredReason, ignored_filters};
39pub use impersonation::{ImpersonationBanner, impersonate_buttons, impersonation_banner};
40pub use import::{ImportError, ImportRefusal, import_columns, import_errors, import_refusal};
41pub use list_tabs::{TabLink, tab_links};
42pub use page_filters::{PageFilterBar, page_filter_bar};
43pub use rich_text::rich_text_values;
44pub use search::{SearchGroup, SearchResult, search_box, search_results};
45pub use sections::{Section, sections};
46pub use sidebar::{
47    NavGroup, area_back_link, nav_badge, nav_groups, nav_links, tenant_page_link, trail,
48};
49pub use summaries::{SummaryFigure, summaries};
50use tablo_core::{Notification, auth::SESSION_COOKIE_PREFIX};
51pub use tabs::{Tab, tabs};
52use topcoat::router::Body;
53pub use widgets::{
54    ChartData, ChartSeries, RecordTableData, StatTile, charts, record_tables, stats, widgets,
55};
56pub use wizard::{WizardStep, wizard_steps};
57
58/// One `Cookie` header value from `(name, value)` pairs, or `None` when empty.
59pub fn cookie_header<'a>(cookies: impl IntoIterator<Item = (&'a str, &'a str)>) -> Option<String> {
60    let mut jar = String::new();
61    for (name, value) in cookies {
62        if !jar.is_empty() {
63            jar.push_str("; ");
64        }
65        jar.push_str(name);
66        jar.push('=');
67        jar.push_str(value);
68    }
69    (!jar.is_empty()).then_some(jar)
70}
71
72/// The language the page reads in, as its `<html lang>` names it.
73pub fn page_language(html: &str) -> Option<String> {
74    let (_, attrs, _) = dom::tags_where(html, |tag, _| tag == "html")
75        .into_iter()
76        .next()?;
77    dom::attr_value(&attrs, "lang")
78}
79
80/// The search engine instructions the page's robots tag names, `None` when it has no such tag.
81pub fn robots(html: &str) -> Option<String> {
82    let (_, attrs, _) = dom::tags_where(html, |tag, attrs| {
83        tag == "meta" && dom::attr_value(attrs, "name").as_deref() == Some("robots")
84    })
85    .into_iter()
86    .next()?;
87    dom::attr_value(&attrs, "content")
88}
89
90/// The text of the document's `<title>`; `None` when it has none.
91pub fn document_title(html: &str) -> Option<String> {
92    let (_, _, inner) = dom::elements(html, "title").into_iter().next()?;
93    Some(dom::strip_text(&inner))
94}
95
96/// The `id` the page's skip link moves focus to, when an element the keyboard can focus carries
97/// it; `None` when the page has no skip link or its target is missing or unfocusable.
98pub fn skip_link_target(html: &str) -> Option<String> {
99    let (_, attrs, _) = dom::tags_where(html, |tag, attrs| {
100        tag == "a" && dom::attr_value(attrs, "data-skip-link").is_some()
101    })
102    .into_iter()
103    .next()?;
104    let target = dom::attr_value(&attrs, "href")?
105        .strip_prefix('#')?
106        .to_owned();
107    dom::open_tags(html)
108        .into_iter()
109        .any(|(_, attrs, _)| {
110            dom::attr_value(&attrs, "id").as_deref() == Some(target.as_str())
111                && dom::attr_value(&attrs, "tabindex").is_some()
112        })
113        .then_some(target)
114}
115
116/// The text of each `th` that names neither its column nor its row through `scope`, in
117/// document order.
118pub fn unscoped_headers(html: &str) -> Vec<String> {
119    dom::tags_where(html, |tag, attrs| {
120        tag == "th" && dom::attr_value(attrs, "scope").is_none()
121    })
122    .into_iter()
123    .map(|(_, _, inner)| dom::strip_text(&inner))
124    .collect()
125}
126
127/// The text of each script the page carries inline, in document order.
128pub fn inline_scripts(html: &str) -> Vec<String> {
129    dom::tags_where(html, |tag, attrs| {
130        tag == "script" && dom::attr_value(attrs, "src").is_none()
131    })
132    .into_iter()
133    .map(|(_, _, inner)| inner)
134    .collect()
135}
136
137/// The page's heading, as its `[data-page-title]` holds it; `None` when it has none.
138pub fn page_title(html: &str) -> Option<String> {
139    let (_, _, inner) = dom::tags_where(html, |_, attrs| {
140        dom::attr_value(attrs, "data-page-title").is_some()
141    })
142    .into_iter()
143    .next()?;
144    Some(dom::strip_text(&inner))
145}
146
147/// One locale the shell's language menu offers.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct LanguageChoice {
150    /// The locale the choice posts, as its tag spells it.
151    pub locale: String,
152    /// What the choice renders, in the locale the page reads.
153    pub label: String,
154    /// Whether the page reads in this locale.
155    pub current: bool,
156}
157
158/// The locales the shell's language menu offers, in the order the panel lists them; empty when
159/// the page shows no menu.
160pub fn language_choices(html: &str) -> Vec<LanguageChoice> {
161    dom::tags_where(html, |_, attrs| {
162        dom::attr_value(attrs, "data-locale").is_some()
163    })
164    .into_iter()
165    .map(|(_, attrs, inner)| LanguageChoice {
166        locale: dom::attr_value(&attrs, "data-locale").unwrap_or_default(),
167        label: dom::strip_text(&inner),
168        current: dom::attr_value(&attrs, "aria-current").as_deref() == Some("true"),
169    })
170    .collect()
171}
172
173/// The direction the page's text runs in, `ltr` or `rtl`, as its `<html dir>` names it.
174pub fn page_direction(html: &str) -> Option<String> {
175    let (_, attrs, _) = dom::tags_where(html, |tag, _| tag == "html")
176        .into_iter()
177        .next()?;
178    dom::attr_value(&attrs, "dir")
179}
180
181/// Collect a response body as bytes.
182pub async fn body_bytes(response: http::Response<Body>) -> Vec<u8> {
183    response
184        .into_body()
185        .collect()
186        .await
187        .expect("collect body")
188        .to_bytes()
189        .to_vec()
190}
191
192/// Collect a response body as a lossy UTF-8 string.
193pub async fn body_string(response: http::Response<Body>) -> String {
194    String::from_utf8_lossy(&body_bytes(response).await).into_owned()
195}
196
197/// URL-encode `(key, value)` pairs into an urlencoded form body.
198pub fn form_body(pairs: &[(&str, &str)]) -> String {
199    let mut serializer = form_urlencoded::Serializer::new(String::new());
200    for (key, value) in pairs {
201        serializer.append_pair(key, value);
202    }
203    serializer.finish()
204}
205
206/// Builds a multipart body, one part per entry: `None` is a text part,
207/// `Some("")` the browser's "no file chosen" part, `Some(name)` a chosen file.
208///
209/// No part carries a `Content-Type`: the panel tells file parts from text parts by the
210/// `filename` parameter alone. A test asserting on an upload's content type builds its own body.
211pub fn multipart_body(boundary: &str, parts: &[(&str, Option<&str>, &str)]) -> String {
212    let mut body = String::new();
213    for (name, filename, content) in parts {
214        body.push_str(&format!(
215            "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\""
216        ));
217        if let Some(filename) = filename {
218            body.push_str(&format!("; filename=\"{filename}\""));
219        }
220        body.push_str("\r\n\r\n");
221        body.push_str(content);
222        body.push_str("\r\n");
223    }
224    body.push_str(&format!("--{boundary}--\r\n"));
225    body
226}
227
228/// Reads the value the named `<input>`s post when the form submits untouched, in either attribute
229/// order or quote style: the last one's `value`, skipping a radio or checkbox left unchecked. A
230/// toggle reads `true` or its hidden `false`, and a radio choice its checked option, or the hidden
231/// blank before them when none is checked.
232pub fn input_value(html: &str, name: &str) -> Option<String> {
233    input_values(html, name).pop()
234}
235
236/// Reads every value the named `<input>`s post when the form submits untouched, in document
237/// order, skipping a radio or checkbox left unchecked: each row a file list keeps posts one.
238pub fn input_values(html: &str, name: &str) -> Vec<String> {
239    let double = format!("name=\"{name}\"");
240    let single = format!("name='{name}'");
241    let mut posted = Vec::new();
242    for tag in html.split('<').skip(1) {
243        if !tag.starts_with("input") || (!tag.contains(&double) && !tag.contains(&single)) {
244            continue;
245        }
246        let Some(end) = tag.find('>') else {
247            continue;
248        };
249        let attrs = &tag[..end];
250        let checkable = [
251            "type=\"radio\"",
252            "type=\"checkbox\"",
253            "type='radio'",
254            "type='checkbox'",
255        ]
256        .iter()
257        .any(|kind| attrs.contains(kind));
258        if checkable && !has_attribute(attrs, "checked") {
259            continue;
260        }
261        for (prefix, term) in [("value=\"", '"'), ("value='", '\'')] {
262            if let Some(start) = attrs.find(prefix) {
263                let rest = &attrs[start + prefix.len()..];
264                if let Some(end) = rest.find(term) {
265                    // Unescape the matching quote entity the encoder may emit.
266                    let raw = &rest[..end];
267                    posted.push(raw.replace("&quot;", "\"").replace("&#x27;", "'"));
268                    break;
269                }
270            }
271        }
272    }
273    posted
274}
275
276/// Whether the opening tag `attrs` carries the attribute `name`, valued or bare, skipping quoted
277/// values so a class naming `checked:` does not count.
278fn has_attribute(attrs: &str, name: &str) -> bool {
279    let mut rest = attrs;
280    while let Some(at) = rest.find(|c: char| !c.is_whitespace()) {
281        rest = &rest[at..];
282        let end = rest
283            .find(|c: char| c.is_whitespace() || c == '=' || c == '/')
284            .unwrap_or(rest.len());
285        if &rest[..end] == name {
286            return true;
287        }
288        rest = &rest[end..];
289        if let Some(value) = rest.strip_prefix('=') {
290            rest = match value.chars().next() {
291                Some(quote @ ('"' | '\'')) => value[1..]
292                    .find(quote)
293                    .map_or("", |close| &value[close + 2..]),
294                _ => value
295                    .find(char::is_whitespace)
296                    .map_or("", |space| &value[space..]),
297            };
298        } else if let Some(after) = rest.strip_prefix('/') {
299            rest = after;
300        }
301    }
302    false
303}
304
305/// The `(name, value)` pairs a response's `Set-Cookie` headers carry.
306pub fn response_cookies(response: &http::Response<Body>) -> Vec<(String, String)> {
307    response
308        .headers()
309        .get_all(http::header::SET_COOKIE)
310        .iter()
311        .filter_map(|value| value.to_str().ok())
312        .filter_map(|value| value.split(';').next())
313        .filter_map(|pair| pair.split_once('='))
314        .map(|(name, value)| (name.trim().to_string(), value.trim().to_string()))
315        .collect()
316}
317
318/// The full `Set-Cookie` header for `name`, so tests can assert attributes.
319pub fn set_cookie_header(response: &http::Response<Body>, name: &str) -> Option<String> {
320    response
321        .headers()
322        .get_all(http::header::SET_COOKIE)
323        .iter()
324        .filter_map(|value| value.to_str().ok())
325        .find(|value| value.starts_with(&format!("{name}=")))
326        .map(str::to_string)
327}
328
329/// The value of the session cookie a response set, on whichever panel, if any.
330pub fn session_cookie_value(response: &http::Response<Body>) -> Option<String> {
331    response_cookies(response)
332        .into_iter()
333        .find(|(name, _)| name.starts_with(SESSION_COOKIE_PREFIX))
334        .map(|(_, value)| value)
335}
336
337/// The flash notification a response set for the next page, decoded.
338pub fn notification(response: &http::Response<Body>) -> Option<Notification> {
339    notification_in(&response_cookies(response))
340}
341
342/// The flash notification among a response's `(name, value)` cookie pairs, decoded.
343pub(crate) fn notification_in(cookies: &[(String, String)]) -> Option<Notification> {
344    let (_, value) = cookies
345        .iter()
346        .find(|(name, _)| name.ends_with("tablo_notification"))?;
347    let json = percent_encoding::percent_decode_str(value)
348        .decode_utf8()
349        .ok()?;
350    serde_json::from_str(&json).ok()
351}
352
353/// Whether the edit form refuses the save because another save changed the record since the form
354/// opened: it renders an element carrying `data-stale`.
355pub fn stale_form(html: &str) -> bool {
356    !dom::tags_where(html, |_, attrs| {
357        attrs.iter().any(|(attr, _)| attr == "data-stale")
358    })
359    .is_empty()
360}
361
362/// The message a record fn declined the save with, which the form renders above its fields in
363/// an element carrying `data-declined`.
364pub fn declined_message(html: &str) -> Option<String> {
365    let (_, _, inner) = dom::tags_where(html, |_, attrs| {
366        attrs.iter().any(|(attr, _)| attr == "data-declined")
367    })
368    .into_iter()
369    .next()?;
370    Some(dom::strip_text(&inner))
371}
372
373/// Where a panel behind external auth sends a user out to: the page it refuses them on, and the
374/// page its Sign out answers with, link the app's sign-out from a `data-external-sign-out` element.
375pub fn external_sign_out(html: &str) -> Option<String> {
376    let (_, attrs, _) = dom::tags_where(html, |_, attrs| {
377        attrs
378            .iter()
379            .any(|(attr, _)| attr == "data-external-sign-out")
380    })
381    .into_iter()
382    .next()?;
383    attrs.into_iter().find(|(attr, _)| attr == "href")?.1
384}
385
386/// The URL a `<meta http-equiv="refresh">` moves the page on to.
387pub fn refreshes_to(html: &str) -> Option<String> {
388    let (_, attrs, _) = dom::tags_where(html, |name, attrs| {
389        name == "meta" && attrs.iter().any(|(attr, _)| attr == "http-equiv")
390    })
391    .into_iter()
392    .next()?;
393    let content = attrs.into_iter().find(|(attr, _)| attr == "content")?.1?;
394    content.split_once("url=").map(|(_, url)| url.to_string())
395}
396
397/// Whether a form renders dirty, so leaving the page asks first: a refused save keeps what the
398/// user typed, and the server marks its form with `data-form-dirty`.
399pub fn dirty_form(html: &str) -> bool {
400    !dom::tags_where(html, |name, attrs| {
401        name == "form" && attrs.iter().any(|(attr, _)| attr == "data-form-dirty")
402    })
403    .is_empty()
404}