browsy-core 0.1.1

Zero-render browser engine for AI agents — browsy.dev
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
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
//! Behavior detection — infers interactive patterns from HTML attributes.
//!
//! This module does NOT execute JavaScript. It detects common UI patterns
//! from HTML attributes (onclick, data-toggle, aria-controls, role="tab")
//! and reports what interactions are available. Combined with browsy's
//! hidden content exposure (where display:none elements are included with
//! `hidden: true`), this gives agents full visibility into page content
//! and available interactions without needing a JS runtime.

use crate::dom::{DomNode, NodeType};
use serde::Serialize;

/// A detected interactive behavior on the page.
#[derive(Debug, Clone, Serialize)]
pub struct JsBehavior {
    /// The element ID (from spatial DOM) that triggers this behavior.
    pub trigger_id: u32,
    /// What happens when the trigger is activated.
    pub action: JsAction,
}

/// An inferred JS action.
#[derive(Debug, Clone, Serialize)]
pub enum JsAction {
    /// Toggle visibility of a target element (show/hide).
    ToggleVisibility {
        /// CSS selector or ID of the target element.
        target: String,
    },
    /// Toggle a CSS class on a target element.
    ToggleClass {
        target: String,
        class: String,
    },
    /// Switch tabs: show one panel, hide siblings.
    TabSwitch {
        /// The panel to show.
        show_target: String,
        /// Sibling panels to hide.
        hide_targets: Vec<String>,
    },
    /// Submit a form (already handled by Session, but noted here).
    FormSubmit {
        form_selector: String,
    },
    /// Navigate to a URL (already handled by Session click).
    Navigate {
        url: String,
    },
}

/// Analyze the DOM for common JS patterns and return detected behaviors.
pub fn detect_behaviors(dom: &DomNode) -> Vec<JsBehavior> {
    let mut behaviors = Vec::new();
    let mut id_counter = 1u32;

    detect_behaviors_recursive(dom, &mut behaviors, &mut id_counter);

    behaviors
}

fn detect_behaviors_recursive(
    node: &DomNode,
    behaviors: &mut Vec<JsBehavior>,
    id_counter: &mut u32,
) {
    if node.node_type == NodeType::Element {
        // Check for onclick handlers
        if let Some(onclick) = node.get_attr("onclick") {
            if let Some(action) = parse_onclick(onclick) {
                behaviors.push(JsBehavior {
                    trigger_id: *id_counter,
                    action,
                });
            }
        }

        // Check for data-toggle patterns (Bootstrap-style)
        if let Some(toggle) = node.get_attr("data-toggle") {
            if let Some(target) = node.get_attr("data-target")
                .or_else(|| node.get_attr("href"))
            {
                let action = match toggle {
                    "collapse" | "dropdown" | "modal" => JsAction::ToggleVisibility {
                        target: target.to_string(),
                    },
                    "tab" | "pill" => {
                        if let Some(target_id) = target.strip_prefix('#') {
                            JsAction::TabSwitch {
                                show_target: target_id.to_string(),
                                hide_targets: Vec::new(),
                            }
                        } else {
                            JsAction::ToggleVisibility {
                                target: target.to_string(),
                            }
                        }
                    }
                    _ => JsAction::ToggleVisibility {
                        target: target.to_string(),
                    },
                };
                behaviors.push(JsBehavior {
                    trigger_id: *id_counter,
                    action,
                });
            }
        }

        // Check for aria-controls (accessibility pattern for toggles)
        if let Some(controls) = node.get_attr("aria-controls") {
            if node.get_attr("aria-expanded").is_some() {
                behaviors.push(JsBehavior {
                    trigger_id: *id_counter,
                    action: JsAction::ToggleVisibility {
                        target: format!("#{}", controls),
                    },
                });
            }
        }

        // Check for role="tab" with aria-controls
        if node.get_attr("role") == Some("tab") {
            if let Some(controls) = node.get_attr("aria-controls") {
                behaviors.push(JsBehavior {
                    trigger_id: *id_counter,
                    action: JsAction::TabSwitch {
                        show_target: controls.to_string(),
                        hide_targets: Vec::new(),
                    },
                });
            }
        }

        // Increment ID for elements that would be emitted in the spatial DOM
        if should_emit_node(node) {
            *id_counter += 1;
        }
    }

    for child in &node.children {
        detect_behaviors_recursive(child, behaviors, id_counter);
    }
}

/// Parse an onclick attribute value into a JsAction.
fn parse_onclick(onclick: &str) -> Option<JsAction> {
    let onclick = onclick.trim();

    // Pattern: toggle/show/hide element by ID
    // e.g., document.getElementById('foo').style.display = 'none'
    // e.g., document.getElementById('menu').classList.toggle('hidden')
    // e.g., $('#dropdown').toggle()
    // e.g., toggle('panel')

    // getElementById with classList operations (check before generic toggle)
    if let Some(id) = extract_element_id(onclick) {
        if let Some(class) = extract_class_toggle(onclick) {
            return Some(JsAction::ToggleClass {
                target: format!("#{}", id),
                class,
            });
        }
        if onclick.contains("style.display") || onclick.contains(".toggle(") {
            return Some(JsAction::ToggleVisibility {
                target: format!("#{}", id),
            });
        }
        return Some(JsAction::ToggleVisibility {
            target: format!("#{}", id),
        });
    }

    // jQuery-style: $(...).toggle(), $(...).show(), $(...).hide()
    if let Some(selector) = extract_jquery_selector(onclick) {
        if onclick.contains(".toggle(") || onclick.contains(".show(")
            || onclick.contains(".hide(")
        {
            return Some(JsAction::ToggleVisibility {
                target: selector,
            });
        }
        if onclick.contains(".addClass(") || onclick.contains(".removeClass(")
            || onclick.contains(".toggleClass(")
        {
            if let Some(class) = extract_jquery_class(onclick) {
                return Some(JsAction::ToggleClass {
                    target: selector,
                    class,
                });
            }
        }
    }

    // Simple function call: toggle('id'), showPanel('id')
    if let Some(id) = extract_function_arg(onclick) {
        return Some(JsAction::ToggleVisibility {
            target: format!("#{}", id),
        });
    }

    // location.href = '...' or window.location = '...'
    if onclick.contains("location") {
        if let Some(url) = extract_url_assignment(onclick) {
            return Some(JsAction::Navigate { url });
        }
    }

    None
}

/// Extract element ID from getElementById('id') or similar patterns.
fn extract_element_id(s: &str) -> Option<String> {
    // getElementById('id') or getElementById("id")
    if let Some(start) = s.find("getElementById(") {
        let rest = &s[start + 15..];
        return extract_quoted_string(rest);
    }
    None
}

/// Extract class name from classList.toggle('class') pattern.
fn extract_class_toggle(s: &str) -> Option<String> {
    for method in &["classList.toggle(", "classList.add(", "classList.remove("] {
        if let Some(start) = s.find(method) {
            let rest = &s[start + method.len()..];
            return extract_quoted_string(rest);
        }
    }
    None
}

/// Extract jQuery selector from $('selector') or jQuery('selector').
fn extract_jquery_selector(s: &str) -> Option<String> {
    for prefix in &["$('", "$(\"", "jQuery('", "jQuery(\""] {
        if let Some(start) = s.find(prefix) {
            let rest = &s[start + prefix.len()..];
            let quote = if prefix.ends_with('\'') { '\'' } else { '"' };
            if let Some(end) = rest.find(quote) {
                return Some(rest[..end].to_string());
            }
        }
    }
    None
}

/// Extract class name from jQuery .addClass('class') etc.
fn extract_jquery_class(s: &str) -> Option<String> {
    for method in &[".addClass('", ".addClass(\"", ".removeClass('",
                    ".removeClass(\"", ".toggleClass('", ".toggleClass(\""] {
        if let Some(start) = s.find(method) {
            let rest = &s[start + method.len()..];
            let quote = if method.ends_with('\'') { '\'' } else { '"' };
            if let Some(end) = rest.find(quote) {
                return Some(rest[..end].to_string());
            }
        }
    }
    None
}

/// Extract a simple function argument: functionName('arg')
fn extract_function_arg(s: &str) -> Option<String> {
    // Match pattern: word('...')
    if let Some(paren) = s.find('(') {
        let before = &s[..paren];
        if before.chars().all(|c| c.is_alphanumeric() || c == '_') {
            let rest = &s[paren + 1..];
            return extract_quoted_string(rest);
        }
    }
    None
}

/// Extract URL from location.href = '...' or window.location = '...'
fn extract_url_assignment(s: &str) -> Option<String> {
    for pattern in &["location.href=", "location.href =", "location=", "location =",
                     "window.location.href=", "window.location.href =",
                     "window.location=", "window.location ="] {
        if let Some(start) = s.find(pattern) {
            let rest = &s[start + pattern.len()..].trim_start();
            if let Some(url) = extract_quoted_string(rest) {
                return Some(url);
            }
        }
    }
    None
}

/// Extract a quoted string (single or double quotes).
fn extract_quoted_string(s: &str) -> Option<String> {
    let s = s.trim();
    let quote = s.chars().next()?;
    if quote != '\'' && quote != '"' {
        return None;
    }
    let rest = &s[1..];
    if let Some(end) = rest.find(quote) {
        Some(rest[..end].to_string())
    } else {
        None
    }
}

/// Apply a JS action to a DOM tree, returning the modified tree.
/// This simulates the effect of the JS action without running JS.
pub fn apply_action(dom: &DomNode, action: &JsAction) -> DomNode {
    match action {
        JsAction::ToggleVisibility { target } => {
            let id = target.strip_prefix('#').unwrap_or(target);
            toggle_element_visibility(dom, id)
        }
        JsAction::ToggleClass { target, class } => {
            let id = target.strip_prefix('#').unwrap_or(target);
            toggle_element_class(dom, id, class)
        }
        JsAction::TabSwitch { show_target, hide_targets } => {
            let mut result = dom.clone();
            // Show the target
            result = set_element_visibility(&result, show_target, true);
            // Hide siblings
            for hide in hide_targets {
                result = set_element_visibility(&result, hide, false);
            }
            result
        }
        JsAction::FormSubmit { .. } | JsAction::Navigate { .. } => {
            // Handled by Session, not DOM manipulation
            dom.clone()
        }
    }
}

/// Toggle the display of an element by ID.
fn toggle_element_visibility(node: &DomNode, target_id: &str) -> DomNode {
    let mut result = node.clone();

    if result.node_type == NodeType::Element {
        if result.get_attr("id") == Some(target_id) {
            // Toggle: if hidden, show; if visible, hide
            let is_hidden = result.get_attr("style")
                .map(|s| s.contains("display: none") || s.contains("display:none"))
                .unwrap_or(false)
                || result.attributes.contains_key("hidden");

            if is_hidden {
                // Show: remove hidden attribute and display:none from style
                result.attributes.remove("hidden");
                if let Some(style) = result.attributes.get_mut("style") {
                    *style = style
                        .replace("display: none", "")
                        .replace("display:none", "")
                        .trim_matches(';')
                        .trim()
                        .to_string();
                }
            } else {
                // Hide: add display:none
                let current = result.attributes.get("style")
                    .map(|s| s.to_string())
                    .unwrap_or_default();
                if current.is_empty() {
                    result.attributes.insert("style".to_string(), "display: none".to_string());
                } else {
                    result.attributes.insert("style".to_string(), format!("{}; display: none", current));
                }
            }
            return result;
        }
    }

    // Recurse
    result.children = result.children.iter()
        .map(|c| toggle_element_visibility(c, target_id))
        .collect();

    result
}

/// Set element visibility explicitly.
fn set_element_visibility(node: &DomNode, target_id: &str, visible: bool) -> DomNode {
    let mut result = node.clone();

    if result.node_type == NodeType::Element {
        if result.get_attr("id") == Some(target_id) {
            if visible {
                result.attributes.remove("hidden");
                if let Some(style) = result.attributes.get_mut("style") {
                    *style = style
                        .replace("display: none", "")
                        .replace("display:none", "")
                        .trim_matches(';')
                        .trim()
                        .to_string();
                }
            } else {
                let current = result.attributes.get("style")
                    .map(|s| s.to_string())
                    .unwrap_or_default();
                if current.is_empty() {
                    result.attributes.insert("style".to_string(), "display: none".to_string());
                } else if !current.contains("display: none") && !current.contains("display:none") {
                    result.attributes.insert("style".to_string(), format!("{}; display: none", current));
                }
            }
            return result;
        }
    }

    result.children = result.children.iter()
        .map(|c| set_element_visibility(c, target_id, visible))
        .collect();

    result
}

/// Toggle a class on an element by ID.
fn toggle_element_class(node: &DomNode, target_id: &str, class: &str) -> DomNode {
    let mut result = node.clone();

    if result.node_type == NodeType::Element {
        if result.get_attr("id") == Some(target_id) {
            let current_classes = result.attributes.get("class")
                .map(|s| s.to_string())
                .unwrap_or_default();
            let class_list: Vec<&str> = current_classes.split_whitespace().collect();

            if class_list.contains(&class) {
                // Remove class
                let new_classes: Vec<&str> = class_list.into_iter()
                    .filter(|c| *c != class)
                    .collect();
                result.attributes.insert("class".to_string(), new_classes.join(" "));
            } else {
                // Add class
                let new = if current_classes.is_empty() {
                    class.to_string()
                } else {
                    format!("{} {}", current_classes, class)
                };
                result.attributes.insert("class".to_string(), new);
            }
            return result;
        }
    }

    result.children = result.children.iter()
        .map(|c| toggle_element_class(c, target_id, class))
        .collect();

    result
}

fn is_interactive_tag(tag: &str) -> bool {
    matches!(tag, "a" | "button" | "input" | "select" | "textarea" | "details" | "summary")
}

fn is_text_tag(tag: &str) -> bool {
    matches!(tag,
        "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "p" | "label" | "span" |
        "li" | "td" | "th" | "dt" | "dd" | "figcaption" | "blockquote" |
        "pre" | "code" | "em" | "strong" | "b" | "i" | "mark" | "small"
    )
}

fn is_landmark_tag(tag: &str) -> bool {
    matches!(tag, "nav" | "main" | "header" | "footer" | "aside" | "section" | "form")
}

const LANDMARK_ROLES: &[&str] = &[
    "navigation", "main", "banner", "contentinfo", "complementary", "region", "form",
];

fn is_landmark_role_attr(node: &DomNode) -> bool {
    node.get_attr("role")
        .map(|r| LANDMARK_ROLES.contains(&r))
        .unwrap_or(false)
}

fn should_emit_node(node: &DomNode) -> bool {
    let tag = node.tag.as_str();
    let is_interactive = is_interactive_tag(tag)
        || node.attributes.contains_key("onclick")
        || node.attributes.contains_key("role")
        || node.attributes.get("tabindex").is_some();
    let is_text = is_text_tag(tag);
    let has_role = node.attributes.contains_key("role");
    let is_landmark = is_landmark_tag(tag) || is_landmark_role_attr(node);
    let is_img_with_alt = tag == "img" && node.attributes.contains_key("alt");
    let should_emit = is_interactive || is_text || has_role || is_img_with_alt || is_landmark;

    if !should_emit {
        return false;
    }

    if is_landmark {
        return true;
    }

    if is_text && !is_interactive && !has_role {
        let text_content = node.text_content();
        if is_trivial_text(&text_content) {
            return false;
        }
    }

    let has_interactive = has_interactive_descendants(node);
    let is_wrapper = matches!(tag, "li" | "td" | "th" | "span" | "p" | "dt" | "dd");

    if is_wrapper && !is_interactive && has_interactive {
        let own_text = collect_own_text(node);
        if own_text.is_empty() || is_trivial_text(&own_text) {
            return false;
        }
    } else if is_text && !is_interactive && has_interactive {
        let own_text = collect_own_text(node);
        if own_text.is_empty() || is_trivial_text(&own_text) {
            return false;
        }
    }

    true
}

fn has_interactive_descendants(node: &DomNode) -> bool {
    for child in &node.children {
        let tag = child.tag.as_str();
        if is_interactive_tag(tag)
            || child.attributes.contains_key("onclick")
            || child.attributes.contains_key("role")
            || child.attributes.get("tabindex").is_some()
        {
            return true;
        }
        if has_interactive_descendants(child) {
            return true;
        }
    }
    false
}

fn collect_own_text(node: &DomNode) -> String {
    let mut result = String::new();
    for child in &node.children {
        collect_own_text_recursive(child, &mut result);
    }
    result.trim().to_string()
}

fn collect_own_text_recursive(node: &DomNode, out: &mut String) {
    if node.node_type == NodeType::Text {
        let t = node.text.trim();
        if !t.is_empty() {
            if !out.is_empty() && !out.ends_with(' ') {
                out.push(' ');
            }
            out.push_str(t);
        }
        return;
    }
    let tag = node.tag.as_str();
    if is_interactive_tag(tag)
        || is_text_tag(tag)
        || node.attributes.contains_key("onclick")
        || node.attributes.contains_key("role")
        || node.attributes.get("tabindex").is_some()
    {
        return;
    }
    for child in &node.children {
        collect_own_text_recursive(child, out);
    }
}

fn is_trivial_text(text: &str) -> bool {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return true;
    }
    trimmed.chars().all(|c| matches!(
        c,
        '|' | '·' | '' | '-' | '' | '' | '/' | '\\' | ',' | '.' | ':' | ';'
            | '(' | ')' | '[' | ']' | '{' | '}' | ' ' | '\t' | '\n'
    ))
}

/// Detect tab groups from the DOM (role="tablist" patterns).
pub fn detect_tab_groups(dom: &DomNode) -> Vec<TabGroup> {
    let mut groups = Vec::new();
    find_tab_groups(dom, &mut groups);
    groups
}

/// A group of tabs with their associated panels.
#[derive(Debug, Clone)]
pub struct TabGroup {
    pub tabs: Vec<TabInfo>,
}

#[derive(Debug, Clone)]
pub struct TabInfo {
    pub id: String,
    pub label: String,
    pub panel_id: String,
    pub selected: bool,
}

fn find_tab_groups(node: &DomNode, groups: &mut Vec<TabGroup>) {
    if node.get_attr("role") == Some("tablist") {
        let mut tabs = Vec::new();
        for child in &node.children {
            if child.get_attr("role") == Some("tab") {
                let id = child.get_attr("id").unwrap_or("").to_string();
                let label = child.text_content();
                let panel_id = child.get_attr("aria-controls").unwrap_or("").to_string();
                let selected = child.get_attr("aria-selected") == Some("true");
                tabs.push(TabInfo { id, label, panel_id, selected });
            }
        }
        if !tabs.is_empty() {
            groups.push(TabGroup { tabs });
        }
    }

    for child in &node.children {
        find_tab_groups(child, groups);
    }
}