1mod 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
58pub 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
72pub 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
80pub 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
90pub 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
96pub 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
116pub 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
127pub 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
137pub 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#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct LanguageChoice {
150 pub locale: String,
152 pub label: String,
154 pub current: bool,
156}
157
158pub 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
173pub 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
181pub 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
192pub async fn body_string(response: http::Response<Body>) -> String {
194 String::from_utf8_lossy(&body_bytes(response).await).into_owned()
195}
196
197pub 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
206pub 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
228pub fn input_value(html: &str, name: &str) -> Option<String> {
233 input_values(html, name).pop()
234}
235
236pub 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 let raw = &rest[..end];
267 posted.push(raw.replace(""", "\"").replace("'", "'"));
268 break;
269 }
270 }
271 }
272 }
273 posted
274}
275
276fn 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
305pub 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
318pub 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
329pub 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
337pub fn notification(response: &http::Response<Body>) -> Option<Notification> {
339 notification_in(&response_cookies(response))
340}
341
342pub(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
353pub 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
362pub 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
373pub 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
386pub 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
397pub 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}