Skip to main content

blitz_control_protocol/
document.rs

1//! Inspecting, capturing and driving a document, with no window involved.
2//!
3//! This is the core the two transports sit on. It answers a request against a
4//! `blitz-dom` document and returns a response, and it knows nothing about
5//! sockets, listeners, event loops or windows: [`crate::in_process`] calls it
6//! directly and [`crate::server`] calls it across a socket, and neither is
7//! visible from here.
8//!
9//! It used to live in `izumo`, beside the Tauri runtime, which
10//! meant that depending on it meant compiling Tauri. On Linux that means GTK:
11//! system libraries pulled in to build a binary that never creates a window,
12//! and a crate that would not compile there at all. The dependency edge was
13//! wrong, not the platform. A runtime bridges Tauri to Blitz and owns a native
14//! window; it is not where an inspection service lives.
15
16use std::collections::{BTreeMap, HashMap};
17
18use crate::{
19    AgentSnapshot, DebugError, DebugResponse, KeyPhase, Modifiers as ControlModifiers, SemanticNode,
20};
21#[cfg(feature = "capture")]
22use crate::{
23    DebugSnapshot, FrameMetrics, FrameWindowMetrics, LayoutBounds, LayoutDiagnosticRow,
24    LayoutEdges, LayoutOffset, LayoutSize, RendererMetrics, RevisionSet, SnapshotCost,
25    SnapshotRequest, TimingStats,
26};
27use blitz_traits::events::{
28    BlitzKeyEvent, BlitzPointerEvent, BlitzPointerId, KeyState, MouseEventButton,
29    MouseEventButtons, Point, PointerCoords, PointerDetails, UiEvent,
30};
31#[cfg(feature = "capture")]
32use blitz_traits::node_id::NodeId;
33use keyboard_types::{Code, Key, Location, Modifiers as KeyboardModifiers};
34
35/// The live inspector's reusable offscreen surface.
36///
37/// A capture used to construct this whole renderer for every frame. Besides
38/// reallocating the viewport-sized RGBA buffer, that threw away the CPU text
39/// renderer's glyph resources, so a stability assertion shaped and rasterised
40/// every label four times. The surface belongs to one runtime and is resized
41/// only when the window or requested scale changes.
42#[cfg(feature = "capture")]
43pub(crate) struct CaptureSurface {
44    pub(crate) width: u32,
45    pub(crate) height: u32,
46    pub(crate) renderer: anyrender_vello_cpu::VelloCpuImageRenderer,
47    pub(crate) rgba: Vec<u8>,
48}
49
50/// Reusable offscreen renderer for captures of one document.
51///
52/// A headless inspection host asks for several adjacent frames when it checks
53/// visual stability. Reusing this object preserves the CPU renderer's glyph
54/// resources and pixel allocation between those requests instead of rebuilding
55/// an entire renderer for every sample.
56#[cfg(feature = "capture")]
57pub struct DocumentCapture {
58    surface: Option<CaptureSurface>,
59}
60
61#[cfg(feature = "capture")]
62impl DocumentCapture {
63    pub fn new() -> Self {
64        Self { surface: None }
65    }
66
67    pub fn capture(
68        &mut self,
69        document: &mut (impl crate::ControlScriptBackend + ?Sized),
70        request: crate::CaptureRequest,
71    ) -> Result<crate::CapturedImage, DebugError> {
72        capture_document_with_surface(document, request, &mut self.surface)
73    }
74}
75
76#[cfg(feature = "capture")]
77impl Default for DocumentCapture {
78    fn default() -> Self {
79        Self::new()
80    }
81}
82
83#[cfg(feature = "capture")]
84impl CaptureSurface {
85    pub(crate) fn new(width: u32, height: u32) -> Self {
86        use anyrender::ImageRenderer as _;
87
88        Self {
89            width,
90            height,
91            renderer: anyrender_vello_cpu::VelloCpuImageRenderer::new(width, height),
92            rgba: Vec::with_capacity((width as usize) * (height as usize) * 4),
93        }
94    }
95
96    pub(crate) fn size_to(&mut self, width: u32, height: u32) {
97        use anyrender::ImageRenderer as _;
98
99        if self.width == width && self.height == height {
100            return;
101        }
102        self.renderer.resize(width, height);
103        self.width = width;
104        self.height = height;
105    }
106}
107
108/// Draw a standalone control document through the same CPU paint path used by
109/// runtime diagnostics.
110///
111/// Headless QA hosts intentionally have no `RuntimeApplication`, but they must
112/// not substitute a second renderer for native visual checks. Keeping the
113/// capture implementation here makes a host capture and a live-app capture
114/// byte-for-byte comparable.
115#[cfg(feature = "capture")]
116pub fn capture_document(
117    script_document: &mut (impl crate::ControlScriptBackend + ?Sized),
118    request: crate::CaptureRequest,
119) -> Result<crate::CapturedImage, DebugError> {
120    DocumentCapture::new().capture(script_document, request)
121}
122
123#[cfg(feature = "capture")]
124pub(crate) fn capture_document_with_surface(
125    script_document: &mut (impl crate::ControlScriptBackend + ?Sized),
126    request: crate::CaptureRequest,
127    surface: &mut Option<CaptureSurface>,
128) -> Result<crate::CapturedImage, DebugError> {
129    use anyrender::ImageRenderer;
130    use base64::Engine as _;
131
132    // Clamped rather than trusted. A scale of zero produces a zero-sized
133    // buffer and a negative one panics inside the rasteriser, and neither
134    // should be reachable from a debug socket.
135    let scale = if request.scale.is_finite() && request.scale > 0.0 {
136        request.scale.clamp(0.1, 8.0)
137    } else {
138        1.0
139    };
140
141    let node_id = request.node_id;
142
143    // Style and layout first, so the capture reflects pending mutations
144    // rather than the frame before them. Same call `collect_diagnostics`
145    // makes, for the same reason.
146    script_document.inner_mut().resolve(0.0);
147
148    // Copied out rather than held: the guard is a `Ref` and the borrow has
149    // to end before the mutable one the paint below needs.
150    let (full_width, full_height) = {
151        let inner = script_document.inner();
152        let viewport = inner.viewport();
153        (viewport.window_size.0, viewport.window_size.1)
154    };
155    if full_width == 0 || full_height == 0 {
156        return Err(debug_error(
157            "captureUnavailable",
158            "the document has no viewport to draw",
159        ));
160    }
161
162    // The region to keep, in unscaled document pixels.
163    let (crop_x, crop_y, crop_width, crop_height) = match node_id {
164        None => (
165            0.0_f64,
166            0.0_f64,
167            f64::from(full_width),
168            f64::from(full_height),
169        ),
170        Some(id) => {
171            let inner = script_document.inner();
172            let rect = inner
173                .get_client_bounding_rect(NodeId::from_u64(id))
174                .ok_or_else(|| debug_error("unknownNode", &format!("no node {id}")))?;
175            if rect.width <= 0.0 || rect.height <= 0.0 {
176                return Err(debug_error(
177                    "captureEmpty",
178                    &format!("node {id} has a zero-sized box, so there is nothing to capture"),
179                ));
180            }
181            (rect.x, rect.y, rect.width, rect.height)
182        }
183    };
184
185    let full_pixel_width = ((f64::from(full_width) * f64::from(scale)).round() as u32).max(1);
186    let full_pixel_height = ((f64::from(full_height) * f64::from(scale)).round() as u32).max(1);
187    // Clamp before painting: a node partly offscreen yields the visible part,
188    // and the regional renderer never allocates pixels that will be discarded.
189    let left = ((crop_x * f64::from(scale)).round().max(0.0) as u32).min(full_pixel_width);
190    let top = ((crop_y * f64::from(scale)).round().max(0.0) as u32).min(full_pixel_height);
191    let width = ((crop_width * f64::from(scale)).round() as u32)
192        .min(full_pixel_width.saturating_sub(left))
193        .max(1);
194    let height = ((crop_height * f64::from(scale)).round() as u32)
195        .min(full_pixel_height.saturating_sub(top))
196        .max(1);
197    // Leave room for the JSON-RPC and MCP envelopes inside the transport's
198    // fixed frame ceiling. The old 64-million-pixel limit allowed a 256 MiB
199    // raster and a 341 MiB base64 string, only for protocol encoding to reject
200    // the result against its 16 MiB frame limit after all that work was done.
201    const FRAME_ENVELOPE_RESERVE: usize = 64 * 1024;
202    const MAX_BASE64_BYTES: usize = crate::MAX_DEBUG_FRAME_BYTES - FRAME_ENVELOPE_RESERVE;
203    const MAX_RAW_BYTES: usize = (MAX_BASE64_BYTES / 4) * 3;
204    const MAX_PIXELS: u64 = (MAX_RAW_BYTES / 4) as u64;
205    if u64::from(width) * u64::from(height) > MAX_PIXELS {
206        return Err(debug_error(
207            "captureTooLarge",
208            &format!(
209                "{width}x{height} cannot fit in one diagnostic frame; capture a node or lower the scale"
210            ),
211        ));
212    }
213
214    let surface = surface.get_or_insert_with(|| CaptureSurface::new(width, height));
215    surface.size_to(width, height);
216    // `ImageRenderer` retains its scene between calls. A capture is a complete
217    // frame, not an incremental paint, so carrying the previous command list
218    // forward duplicates every shape and makes each sample slower than the
219    // last. Keep reusable renderer resources, but always begin with an empty
220    // scene.
221    surface.renderer.reset();
222    let mut document = script_document.inner_mut();
223    surface.renderer.render_to_vec(
224        |scene| {
225            if node_id.is_some() {
226                blitz_paint::paint_scene_region(
227                    scene,
228                    &mut document,
229                    blitz_paint::PaintRegion::crop(
230                        f64::from(scale),
231                        f64::from(left) / f64::from(scale),
232                        f64::from(top) / f64::from(scale),
233                        width,
234                        height,
235                    ),
236                );
237            } else {
238                blitz_paint::paint_scene(
239                    scene,
240                    &mut document,
241                    f64::from(scale),
242                    width,
243                    height,
244                    0,
245                    0,
246                );
247            }
248        },
249        &mut surface.rgba,
250    );
251
252    Ok(crate::CapturedImage {
253        width,
254        height,
255        rgba_base64: base64::engine::general_purpose::STANDARD.encode(&surface.rgba),
256        node_id,
257    })
258}
259
260/// Drain script work that is already queued before an observer reads the page.
261///
262/// An inspection or snapshot is an observer, not a frame driver: it runs
263/// pending microtasks and scripts but fires no timers, and it stops after a
264/// small budget. Polling with timers made every inspect run up to a hundred
265/// `setTimeout(0)` slices of a page that yields that way, so a page doing
266/// time-sliced work answered each request seconds late. Returns how many
267/// passes made progress and how many ran.
268fn drain_for_observer(document: &mut (impl crate::ControlScriptBackend + ?Sized)) -> (u64, u64) {
269    const BUDGET: std::time::Duration = std::time::Duration::from_millis(16);
270    let started = std::time::Instant::now();
271    let (mut progressed, mut passes) = (0u64, 0u64);
272    while passes < 100 && started.elapsed() < BUDGET {
273        passes += 1;
274        if !document.poll_for_settle(None, false) {
275            break;
276        }
277        progressed += 1;
278    }
279    (progressed, passes)
280}
281
282/// Collect the same typed diagnostic snapshot from a standalone Blitz document
283/// that the windowed runtime exposes over its control socket.
284///
285/// Headless component hosts can provide a document backend without a Tauri event
286/// loop. Keeping snapshot collection here gives those hosts the renderer's real
287/// DOM, layout and computed paint data instead of a partial or reimplemented view.
288#[cfg(feature = "capture")]
289pub fn snapshot_document(
290    document: &mut (impl crate::ControlScriptBackend + ?Sized),
291    request: SnapshotRequest,
292    revision: u64,
293) -> Result<DebugSnapshot, DebugError> {
294    let started = std::time::Instant::now();
295    let poll_started = std::time::Instant::now();
296    let polls = drain_for_observer(document).1;
297    let poll_ms = poll_started.elapsed().as_secs_f64() * 1_000.0;
298    // This forces a style and layout pass so the snapshot reports current
299    // geometry. It is work the observer caused, so it is reported as snapshot
300    // cost, never as the cost of a frame the application drew.
301    let resolve_started = std::time::Instant::now();
302    document.inner_mut().resolve(0.0);
303    let snapshot_resolve_ms = resolve_started.elapsed().as_secs_f64() * 1_000.0;
304    let inner = document.inner();
305    let layout_node_limit = inner.tree().iter().count();
306    let active_element = inner.get_focussed_node_id().map(|id| id.as_u64());
307    // Once for the whole snapshot: the question a control asks is "which label
308    // points at me", and answering it from the control costs a document scan
309    // each time.
310    let labels = LabelIndex::build(&inner);
311    let nodes: Vec<SemanticNode> = inner
312        .tree()
313        .iter()
314        .filter_map(|(id, node)| {
315            if !request.node_ids.is_empty() && !request.node_ids.contains(&id.as_u64()) {
316                return None;
317            }
318            let element = node.element_data()?;
319            if !dom_chain_is_attached(&inner, id, layout_node_limit)
320                || !layout_chain_is_valid(&inner, id, layout_node_limit)
321            {
322                return None;
323            }
324            let rect = inner.get_client_bounding_rect(id);
325            let visible = node_is_visible(&inner, id)
326                && rect
327                    .as_ref()
328                    .is_some_and(|rect| rect.width > 0.0 && rect.height > 0.0);
329            let role = semantic_role(element);
330            let value = if role == "generic" {
331                Some(
332                    element
333                        .attrs()
334                        .iter()
335                        .map(|attribute| format!("{}={}", attribute.name.local, attribute.value))
336                        .collect::<Vec<_>>()
337                        .join(" "),
338                )
339            } else {
340                semantic_value(element, &inner, id)
341            };
342            Some(SemanticNode {
343                dom_id: element_attr(element, "id").map(str::to_owned),
344                id: id.as_u64(),
345                parent: semantic_parent(&inner, id, None).map(|id| id.as_u64()),
346                name: semantic_name(element, node, &role, &inner, id, &labels),
347                role,
348                value,
349                enabled: element_attr(element, "disabled").is_none()
350                    && element_attr(element, "aria-disabled") != Some("true"),
351                focusable: focuses_on_click(element),
352                viewport_fixed: viewport_fixed_descendant(&inner, id, layout_node_limit),
353                visible,
354                selected: semantic_selected(element, &inner, id),
355                bounds: rect.and_then(|rect| {
356                    let bounds = [rect.x, rect.y, rect.width, rect.height];
357                    bounds
358                        .iter()
359                        .all(|value| value.is_finite())
360                        .then_some(bounds)
361                }),
362                slot: element_attr(element, "data-slot").map(str::to_owned),
363                attributes: semantic_target_attributes(element),
364            })
365        })
366        .collect();
367    let total_ms = started.elapsed().as_secs_f64() * 1_000.0;
368    // The runtime keeps one counter and stamps it onto all four revision
369    // fields. Style, layout and paint are not versioned independently
370    // anywhere in blitz, so four copies of one number would claim a
371    // resolution that does not exist. Report the counter once, as the
372    // document revision, and leave the rest at zero.
373    let revisions = RevisionSet {
374        document: revision,
375        style: 0,
376        layout: 0,
377        paint: 0,
378    };
379    // Real per-frame timings, published by blitz-shell from `View::redraw`.
380    // These describe frames the application actually presented. Everything
381    // measured inside this function describes the snapshot collection instead,
382    // and is reported under `snapshot` so the two never get mixed up again.
383    let frame_stats = blitz_shell::latest_frame_stats();
384    let metrics = RendererMetrics {
385        revisions: revisions.clone(),
386        queue_depth: None,
387        invalidations_coalesced: polls.saturating_sub(1),
388        frame: frame_stats.as_ref().map(|stats| FrameMetrics {
389            input_to_present_ms: None,
390            style_ms: None,
391            layout_ms: None,
392            resolve_ms: stats.latest.resolve_ms,
393            scene_ms: stats.latest.paint_ms,
394            submit_ms: None,
395            present_ms: None,
396            renderer_ms: stats.latest.renderer_ms,
397            total_ms: stats.latest.total_ms,
398            age_ms: stats.latest.age_ms,
399        }),
400        frame_window: frame_stats.as_ref().map(|stats| FrameWindowMetrics {
401            frames_total: stats.frames_total,
402            window_frames: stats.window_frames,
403            resolve: timing_stats(stats.resolve),
404            scene: timing_stats(stats.paint),
405            renderer: timing_stats(stats.renderer),
406            total: timing_stats(stats.frame_total),
407            interval: timing_stats(stats.interval),
408            active_fps: stats.active_fps,
409            missed_refreshes: stats.missed_refreshes,
410            display_refresh_hz: stats.display_refresh_hz,
411        }),
412        snapshot: Some(SnapshotCost {
413            poll_ms,
414            resolve_ms: snapshot_resolve_ms,
415            total_ms,
416        }),
417        // Script metrics are supplied by the active document backend.
418        script: document.script_metrics(),
419        resident_bytes: resident_bytes(),
420    };
421    let dom = request
422        .include_dom
423        .then(|| serde_json::to_value(&nodes).unwrap_or(serde_json::Value::Null));
424    let layout = request.include_layout.then(|| {
425        nodes
426            .iter()
427            .filter_map(|node| diagnostic_layout_row(&inner, node))
428            .collect()
429    });
430    /*
431     * Resolved colours, folded into the layout rows.
432     *
433     * This used to answer `computedStyleUnavailable`, which left one class
434     * of bug unanswerable from outside: an element whose *declared* colour
435     * is correct and whose *painted* colour is not. Reading the stylesheet
436     * cannot settle that - the cascade, the custom-property chain and the
437     * `@supports` gating all sit between the two - and neither can a DOM
438     * test environment, which has no cascade at all.
439     *
440     * Only the four that decide legibility, rather than a full style dump:
441     * a snapshot of every longhand for 4,500 nodes is megabytes of JSON
442     * nobody reads, and these are what a "why is this text invisible"
443     * question actually needs.
444     */
445    let computed_style = request.include_computed_style.then(|| {
446        serde_json::Value::Array(
447            nodes
448                .iter()
449                .filter_map(|node| diagnostic_style_row(&inner, node))
450                .collect(),
451        )
452    });
453    Ok(DebugSnapshot {
454        revisions,
455        active_window: Some("blitz-main".into()),
456        active_element,
457        dom,
458        layout,
459        computed_style,
460        metrics,
461    })
462}
463
464pub(crate) fn element_attr<'a>(element: &'a blitz_dom::ElementData, name: &str) -> Option<&'a str> {
465    element
466        .attrs()
467        .iter()
468        .find(|attribute| attribute.name.local.as_ref() == name)
469        // `as_ref`, not `as_str`. Attribute values are an interned atom as of
470        // ps-blitz-dom 0.3.0-beta.11, and `str::as_str` is still unstable, so
471        // `as_str` here resolved to the nightly-only inherent method and
472        // failed to build on stable. `as_ref` borrows the atom as a `&str`,
473        // which is what this signature returns.
474        .map(|attribute| attribute.value.as_ref())
475}
476
477fn semantic_target_attributes(element: &blitz_dom::ElementData) -> BTreeMap<String, String> {
478    element
479        .attrs()
480        .iter()
481        .filter_map(|attribute| {
482            let name = attribute.name.local.as_ref();
483            (name.starts_with("aria-") || name.starts_with("data-")).then(|| {
484                let value: &str = attribute.value.as_ref();
485                (name.to_owned(), value.to_owned())
486            })
487        })
488        .collect()
489}
490
491pub(crate) fn semantic_role(element: &blitz_dom::ElementData) -> String {
492    semantic_role_ref(element).to_owned()
493}
494
495/// The same answer without owning it.
496///
497/// A text node asks every element above it whether that element is already
498/// named by the words in question, and the owned form allocated a `String` per
499/// ancestor per text node to be compared against a fixed list and dropped. The
500/// role is either a `&'static str` or the `role` attribute's own text, so
501/// nothing here needs a copy.
502pub(crate) fn semantic_role_ref(element: &blitz_dom::ElementData) -> &str {
503    // An author's explicit role wins, and travels verbatim. ARIA is a
504    // vocabulary the page may extend with roles no HTML element implies, and a
505    // harness addressing `role="switch"` needs the word the page used.
506    if let Some(role) = element_attr(element, "role") {
507        return role;
508    }
509    wire_role(blitz_dom::accessibility::implicit_role(element))
510}
511
512/// What this surface calls one of blitz-dom's roles.
513///
514/// # Why there is a projection at all
515///
516/// The rules are blitz-dom's, in `accessibility::implicit_role`, and there is
517/// one copy of them. What is here is only the naming: blitz-dom answers in
518/// AccessKit's vocabulary, which is what a platform screen-reader adapter
519/// consumes, and this wire answers in ARIA role names, which is what a check
520/// is written against.
521///
522/// The mapping is deliberately lossy, and the loss is the compatibility
523/// guarantee. Eleven fleet sites and roughly 1,700 checks are written against
524/// the role strings this surface has always reported, so every arm below
525/// reproduces one of them. `_ => "generic"` is not a fallback for roles nobody
526/// thought about: it is the answer this surface has always given for
527/// `<article>`, `<p>`, `<footer>`, `<code>`, `<summary>` and the rest, which
528/// carry a distinct AccessKit role and have never carried a distinct one here.
529///
530/// A role that ought to be reported more precisely is a decision about the
531/// wire, made once, with the checks that read it. Making it silently, as a
532/// side effect of sharing the table, is how the two trees came to disagree in
533/// the first place.
534fn wire_role(role: blitz_dom::accesskit::Role) -> &'static str {
535    use blitz_dom::accesskit::Role;
536
537    match role {
538        Role::Link => "link",
539        Role::Button => "button",
540        Role::CheckBox => "checkbox",
541        Role::RadioButton => "radio",
542        Role::Slider => "slider",
543        Role::ComboBox => "combobox",
544        // A `<select multiple>`. blitz-dom calls it a list box, correctly, and
545        // this surface has always called every `<select>` a combobox. Reporting
546        // the more precise role is a wire change, so it stays a decision rather
547        // than a consequence.
548        Role::ListBox => "combobox",
549        Role::ListBoxOption => "option",
550        // Every kind of `<input>` that edits text: a date, a colour, an email
551        // address and a password all arrive as `textbox`, which is what a
552        // harness has to type into them anyway.
553        Role::TextInput
554        | Role::MultilineTextInput
555        | Role::SearchInput
556        | Role::DateInput
557        | Role::DateTimeInput
558        | Role::WeekInput
559        | Role::MonthInput
560        | Role::TimeInput
561        | Role::EmailInput
562        | Role::NumberInput
563        | Role::PasswordInput
564        | Role::PhoneNumberInput
565        | Role::UrlInput
566        | Role::ColorWell => "textbox",
567        Role::Image => "img",
568        Role::Navigation => "navigation",
569        Role::Main => "main",
570        Role::Region => "region",
571        Role::Form => "form",
572        Role::List => "list",
573        Role::ListItem => "listitem",
574        Role::Table => "table",
575        Role::Row => "row",
576        Role::Cell => "cell",
577        Role::ColumnHeader => "columnheader",
578        Role::RowHeader => "rowheader",
579        Role::Heading => "heading",
580        _ => "generic",
581    }
582}
583
584/// Where the labels are, so a control can be asked what names it.
585///
586/// # Why this exists
587///
588/// A name was computed from `aria-label`, `alt` and `title` and from nothing
589/// else, so the ordinary way to label a form control -- a `<label for>` beside
590/// it, or a `<label>` wrapped around it -- produced no name at all. Every text
591/// field on every page in the fleet arrived in the semantic tree anonymous.
592///
593/// That is not only a reporting defect. A harness addresses a control by name,
594/// so an anonymous field cannot be typed into, and a check that means "enter a
595/// URL and save" cannot be written. Measured on support.cafe's connection
596/// settings: three `Input.Field`s, each with a correct `<Label for>` beside it,
597/// all three reported as `textbox ""`.
598///
599/// Built once per snapshot rather than searched per node, because the lookup is
600/// "which label points at me" and answering that from the control costs a scan
601/// of the document each time.
602///
603/// `aria-labelledby` is resolved from here too, for the same reason and against
604/// the same single pass: it points at other elements by `id`, and finding them
605/// from the referring node is a document scan per reference.
606pub(crate) struct LabelIndex {
607    /// The `for` attribute's value, to that label's text.
608    by_control_id: std::collections::HashMap<String, String>,
609    /// Labels by node id, so an ancestor walk can recognise one it is inside.
610    labels: std::collections::HashMap<blitz_dom::NodeId, String>,
611    /// Every `id` in the document, to the node carrying it.
612    ///
613    /// The node rather than its text, because the text a reference resolves to
614    /// is only ever read for the few elements that carry an `aria-labelledby`.
615    /// Naming every element in the document up front to answer a question almost
616    /// none of them ask would walk each subtree twice per snapshot.
617    by_dom_id: std::collections::HashMap<String, blitz_dom::NodeId>,
618}
619
620impl LabelIndex {
621    pub(crate) fn build(document: &blitz_dom::BaseDocument) -> Self {
622        let mut by_control_id = std::collections::HashMap::new();
623        let mut labels = std::collections::HashMap::new();
624        let mut by_dom_id = std::collections::HashMap::new();
625        for (id, node) in document.tree().iter() {
626            let Some(element) = node.element_data() else {
627                continue;
628            };
629            // The first one wins, which is what `getElementById` answers when a
630            // document repeats an `id`. Duplicate ids are invalid markup and a
631            // reference to one is ambiguous by construction, so the rule here is
632            // only about answering the same way twice.
633            if let Some(dom_id) = element_attr(element, "id") {
634                by_dom_id.entry(dom_id.to_owned()).or_insert(id);
635            }
636            if element.name.local.as_ref() != "label" {
637                continue;
638            }
639            // Read the same way a name is, not with `textContent`. A label is a
640            // name once it reaches a control, so a stylesheet inside it, or the
641            // half of a responsive label that is not rendered at this width,
642            // has to be left out here too.
643            let text = name_text(node, document);
644            if let Some(control) = element_attr(element, "for") {
645                by_control_id.insert(control.to_owned(), text.clone());
646            }
647            labels.insert(id, text);
648        }
649        Self {
650            by_control_id,
651            labels,
652            by_dom_id,
653        }
654    }
655
656    /// The name an element gives itself by pointing at other elements.
657    ///
658    /// # Why this exists
659    ///
660    /// `aria-labelledby` was not followed at all, so an element named that way
661    /// arrived anonymous. Two reports, independently: a QA agent giving a
662    /// dashboard card an identity on ui-starter-app found the region came back
663    /// unnamed and had to fall back to `aria-label`, and the `<section>` rule
664    /// beside this one reads `aria-labelledby` to decide the element is a
665    /// `region`, so such a section got the landmark role and an empty name,
666    /// which is worse than the wrapper it used to be reported as.
667    ///
668    /// # What it computes
669    ///
670    /// The attribute is a space-separated list of ids. Each referenced element's
671    /// rendered text is read in the order the ids are written, and the results
672    /// are joined by a single space.
673    ///
674    /// # Hidden referenced elements
675    ///
676    /// A referenced element contributes its text **even when it is not
677    /// rendered**, which is the opposite of the rule `name_text` applies inside
678    /// a subtree. Both are accname: a node that is hidden and *not* referenced
679    /// returns the empty string, while one directly referenced by
680    /// `aria-labelledby` is exempt from that check. The exemption is the whole
681    /// point of the pattern -- `<span hidden id="units">bytes per second</span>`
682    /// exists to name something without appearing itself -- and a resolver that
683    /// skipped it would name nothing on exactly the markup written to use it.
684    ///
685    /// The exemption is for the element named by the id, not for its subtree:
686    /// `name_text` goes on skipping hidden elements inside it, so the half of a
687    /// responsive label that is not shown stays out of the name. An element
688    /// nested inside a `display: none` referenced element is not hidden by that
689    /// rule, because its own computed display is not `none`, which is the answer
690    /// a browser gives for the same markup.
691    ///
692    /// # Termination
693    ///
694    /// A reference resolves through `name_text`, which reads text, and never
695    /// through `semantic_name`, which would consult `aria-labelledby` again. So
696    /// `<h2 id="h" aria-labelledby="h">Fleet</h2>` is named "Fleet" rather than
697    /// recursing, and no cycle between elements can exist to be guarded against.
698    /// ARIA reaches the same answer by forbidding the second traversal.
699    fn labelled_by(
700        &self,
701        document: &blitz_dom::BaseDocument,
702        element: &blitz_dom::ElementData,
703    ) -> Option<String> {
704        let reference = element_attr(element, "aria-labelledby")?;
705        let mut name = String::new();
706        for token in reference.split_ascii_whitespace() {
707            // An id that matches nothing contributes nothing, rather than
708            // abandoning the whole name. A list of ids is written by hand and
709            // one of them going stale is the common way it breaks; the names
710            // that do still resolve are worth more than an empty string.
711            let Some(node) = self
712                .by_dom_id
713                .get(token)
714                .and_then(|id| document.get_node(*id))
715            else {
716                continue;
717            };
718            if !name.is_empty() {
719                name.push(' ');
720            }
721            name.push_str(&name_text(node, document));
722        }
723        // Nothing resolved, or everything that did was blank. That is the
724        // absence of a name rather than a name, and returning it would make
725        // every rule below this one unreachable for the element.
726        (!name.trim().is_empty()).then_some(name)
727    }
728
729    /// The label text for a control, by association or by containment.
730    ///
731    /// `for` first, matching the order a browser resolves them in: an explicit
732    /// association wins over the label the control happens to sit inside.
733    fn name_for(
734        &self,
735        document: &blitz_dom::BaseDocument,
736        id: blitz_dom::NodeId,
737        element: &blitz_dom::ElementData,
738    ) -> Option<String> {
739        if let Some(dom_id) = element_attr(element, "id")
740            && let Some(text) = self.by_control_id.get(dom_id)
741            && !text.trim().is_empty()
742        {
743            return Some(text.clone());
744        }
745        // A wrapping label, walked outward. Bounded rather than open, because
746        // a malformed tree must not cost a traversal per node.
747        //
748        // An empty label does not stop the walk. Labels nested inside labels
749        // are invalid markup, but they happen: a checkbox component that draws
750        // its own `<label>` around a styled box, wrapped again by the page to
751        // add the text beside it. The inner label has no text, and returning
752        // its emptiness here made the control anonymous while a name sat one
753        // level further out. Skipping it costs nothing when the markup is
754        // well formed, because a real label has text.
755        let mut current = document.get_node(id)?.parent;
756        for _ in 0..16 {
757            let ancestor = current?;
758            if let Some(text) = self.labels.get(&ancestor)
759                && !text.trim().is_empty()
760            {
761                return Some(text.clone());
762            }
763            current = document.get_node(ancestor)?.parent;
764        }
765        None
766    }
767}
768
769/// The text a name is made of, which is not the same as `textContent`.
770///
771/// `textContent` is the DOM property and includes every text node under the
772/// element, `<style>` and `<script>` among them. An accessible name does not:
773/// those elements are not rendered, and a name computation that walks into
774/// them reads out a stylesheet.
775///
776/// Measured on honey.id, whose header logo is an anchor wrapping an inline SVG
777/// with a `<style>` in it. The site's home link arrived named
778/// ".animated-logo path { fill-opacity: 0; stroke: currentColor; ... }",
779/// which is unusable to a person and unaddressable to a check.
780///
781/// Measured on crates.vip, whose failure alert stacks two block-level lines.
782/// It arrived named "This page could not loadWebSocket connection failed",
783/// because every text node was concatenated with nothing between it and the
784/// next. A browser puts a space there: accname appends each descendant's
785/// contribution separated by a space unless the descendant is inline, which
786/// is why "<span>a</span><span>b</span>" is still "ab".
787fn name_text(node: &blitz_dom::Node, document: &blitz_dom::BaseDocument) -> String {
788    /// Whether this node's contribution runs into its siblings' or stands
789    /// apart from them. Text and inline-level elements run together; anything
790    /// laid out as a block, a flex item's container, a table cell and so on
791    /// is a separate run. An element with no resolved style is treated as
792    /// inline, which keeps a name from gaining spaces that are not there.
793    fn is_inline(node: &blitz_dom::Node) -> bool {
794        use style::values::specified::box_::{DisplayInside, DisplayOutside};
795        if node.element_data().is_none() {
796            return true;
797        }
798        node.primary_styles().is_none_or(|styles| {
799            let display = styles.clone_display();
800            // Inline flow only. `inline-block` and `inline-flex` are atomic
801            // inlines: they establish their own box and a browser separates
802            // them from their siblings, which is the same rule
803            // `dom-accessibility-api` applies by comparing the computed
804            // display against the string "inline".
805            display.outside() == DisplayOutside::Inline && display.inside() == DisplayInside::Flow
806        })
807    }
808
809    fn write(node: &blitz_dom::Node, document: &blitz_dom::BaseDocument, out: &mut String) {
810        if let Some(element) = node.element_data()
811            && matches!(
812                element.name.local.as_ref(),
813                "style" | "script" | "template" | "noscript"
814            )
815        {
816            return;
817        }
818        if let blitz_dom::node::NodeData::Text(text) = &node.data {
819            out.push_str(&text.content);
820        }
821        for child in &node.children {
822            let Some(child) = document.get_node(*child) else {
823                continue;
824            };
825            // What is not rendered is not part of the name.
826            //
827            // A responsive control writes both labels and shows one:
828            // `sm:hidden` on the short one, `hidden sm:inline` on the long one.
829            // Folding both together produced "Book Book a diagnostic", a name
830            // no viewer at any width can see and no check can be written
831            // against. `visibility: hidden` and `aria-hidden` are excluded for
832            // the same reason, which is the rule accname states directly.
833            //
834            // Elements only. A text node carries no display of its own, so it
835            // is present exactly when the element holding it is.
836            if child.element_data().is_some() && !node_is_individually_visible(child) {
837                continue;
838            }
839            // A boundary either side, so a block between two others is
840            // separated from both. `normalize_name` collapses the runs.
841            let separate = !is_inline(child);
842            if separate {
843                out.push(' ');
844            }
845            write(child, document, out);
846            if separate {
847                out.push(' ');
848            }
849        }
850    }
851    let mut out = String::new();
852    write(node, document, &mut out);
853    out
854}
855
856/// Whether a role takes its accessible name from its own subtree when the
857/// author wrote no explicit one.
858///
859/// ARIA's *nameFrom: author, contents*, and nothing else. The list is closed on
860/// purpose: a role that is not on it is named only by what the author declared,
861/// because a container's text content is its whole subtree and naming those
862/// would give every wrapper on a page a name made of the page.
863///
864/// `alert` and `status` are here because they are the roles an application uses
865/// to say something happened -- a refusal, a saved confirmation -- and what they
866/// say is their content. Without them a live region arrives anonymous, so "the
867/// reason is shown" is not a question a suite can ask, and every validation
868/// outcome has to be approximated by something else that moved.
869///
870/// `menuitem`, `tab` and `treeitem` are the menu, tab and tree equivalents of
871/// `option`. Leaving them out made every dropdown item in the fleet anonymous:
872/// a `<button role="menuitem">Platform Admin</button>` came back with an empty
873/// name, so nothing was announced and no check could name the option it meant
874/// to press.
875///
876/// The table roles are here because ARIA gives all five of them
877/// *nameFrom: contents*, and their absence is why whole tables of crate names,
878/// versions and column types were unreadable: the cells were in the tree and
879/// every one of them was anonymous, which reads from outside as a table that is
880/// not in the tree at all. A row's name being the run of its cells is not an
881/// accident of that rule, it is the rule: it is what a screen reader announces
882/// when the caret enters the row.
883///
884/// `semantic_role` returns a `role` attribute verbatim, so an author who writes
885/// one of these opts into the naming this list provides.
886pub(crate) fn names_from_contents(role: &str) -> bool {
887    matches!(
888        role,
889        "button"
890            | "link"
891            | "heading"
892            | "option"
893            | "alert"
894            | "status"
895            // The same class as `alert` and `status`: a tooltip exists to say
896            // one thing, and what it says is its content. Anonymous, it is a
897            // node reporting that some explanation is on screen without
898            // reporting the explanation.
899            | "tooltip"
900            | "menuitem"
901            | "menuitemcheckbox"
902            | "menuitemradio"
903            | "tab"
904            | "treeitem"
905            | "cell"
906            | "gridcell"
907            | "columnheader"
908            | "rowheader"
909            | "row"
910    )
911}
912
913pub(crate) fn semantic_name(
914    element: &blitz_dom::ElementData,
915    node: &blitz_dom::Node,
916    role: &str,
917    document: &blitz_dom::BaseDocument,
918    id: blitz_dom::NodeId,
919    labels: &LabelIndex,
920) -> String {
921    // The elements an author pointed at, which outrank everything below.
922    //
923    // ARIA's order: `aria-labelledby` first, then `aria-label`, then the host
924    // language's own labelling, then contents. It is first because it is the
925    // most deliberate thing an author can write. Naming one element by the
926    // visible text of another says the two belong together, and it is the only
927    // rule here that can name something from outside itself.
928    let name = labels
929        .labelled_by(document, element)
930        .map(std::borrow::Cow::Owned)
931        .or_else(|| element_attr(element, "aria-label").map(std::borrow::Cow::Borrowed))
932        // The label a form control was given. After `aria-label`, which is the
933        // author overriding the visible text on purpose, and before `title`,
934        // which is a tooltip rather than a name.
935        .or_else(|| {
936            labels
937                .name_for(document, id, element)
938                .map(std::borrow::Cow::Owned)
939        })
940        .or_else(|| element_attr(element, "alt").map(std::borrow::Cow::Borrowed))
941        .or_else(|| element_attr(element, "title").map(std::borrow::Cow::Borrowed))
942        // An option's `label`, which HTML gives precedence over the option's
943        // own text: `<option label="Sixty four bits">u64</option>` announces the
944        // label.
945        .or_else(|| {
946            (role == "option")
947                .then(|| element_attr(element, "label"))
948                .flatten()
949                .map(std::borrow::Cow::Borrowed)
950        })
951        // Named by their own content.
952        //
953        // Empty contents are not a name, and stopping here on an empty string
954        // is how the fallbacks below became unreachable for the roles on this
955        // list.
956        .or_else(|| {
957            names_from_contents(role)
958                .then(|| name_text(node, document))
959                .filter(|text| !text.trim().is_empty())
960                .map(std::borrow::Cow::Owned)
961        })
962        // What is left of an option that carries no text at all: a
963        // `<datalist>` entry is written `<option value="u64">`, and its value is
964        // what a browser announces and what a person sees in the list.
965        .or_else(|| {
966            (role == "option")
967                .then(|| element_attr(element, "value"))
968                .flatten()
969                .map(std::borrow::Cow::Borrowed)
970        })
971        // A placeholder is the last resort a browser falls back to, and it is
972        // the only thing naming a great many search and filter fields. Last, so
973        // it never displaces a real label.
974        .or_else(|| {
975            matches!(role, "textbox" | "combobox")
976                .then(|| element_attr(element, "placeholder").map(std::borrow::Cow::Borrowed))
977                .flatten()
978        })
979        .unwrap_or_default();
980    normalize_text(&name)
981}
982
983/// One space between words, and 512 characters at most.
984///
985/// A name crosses a socket and is matched against by a check, so the runs of
986/// newlines and indentation that markup puts between two words are noise in
987/// both places. The cap is on the value that leaves here rather than on the
988/// text that arrives, so a name made of a long subtree still starts with the
989/// words a person would read first.
990pub(crate) fn normalize_text(text: &str) -> String {
991    let mut normalized = String::with_capacity(text.len().min(512));
992    let mut characters = 0;
993    for word in text.split_whitespace() {
994        if !normalized.is_empty() && characters < 512 {
995            normalized.push(' ');
996            characters += 1;
997        }
998        for character in word.chars() {
999            if characters == 512 {
1000                return normalized;
1001            }
1002            normalized.push(character);
1003            characters += 1;
1004        }
1005    }
1006    normalized
1007}
1008
1009/// The text a node contributes to the tree in its own right, if any.
1010///
1011/// # Why text is in this tree at all
1012///
1013/// Everything that is not an element was dropped, so text that is not some
1014/// element's accessible name could not be read at all: a paragraph, a `<pre>`,
1015/// a code block, the prose of a documentation page. A check could assert that a
1016/// button exists and not that the page says what the button does.
1017///
1018/// It is not only a check limitation. A browser exposes those text runs, and so
1019/// does blitz-dom, whose own accessibility tree gives every text node
1020/// `Role::TextRun` with its content. This tree disagreed with both.
1021///
1022/// # Why not every text node
1023///
1024/// Text under a role that is named by its contents is already in the tree, as
1025/// that node's name, and that node is the one a harness can act on. Reporting
1026/// it twice would make "the page says this once" false and hand a check a node
1027/// it cannot click for text it can already read. It is the rule the ARIA
1028/// snapshot formats apply as well: a button carries its label, and no separate
1029/// text line appears under it.
1030///
1031/// `<style>`, `<script>` and friends are excluded for the reason `name_text`
1032/// excludes them: their content is not rendered, and reading it out returns a
1033/// stylesheet.
1034pub(crate) fn exposed_text(
1035    document: &blitz_dom::BaseDocument,
1036    id: blitz_dom::NodeId,
1037    node: &blitz_dom::Node,
1038) -> Option<String> {
1039    let blitz_dom::node::NodeData::Text(text) = &node.data else {
1040        return None;
1041    };
1042    let normalized = normalize_text(&text.content);
1043    if normalized.is_empty() {
1044        return None;
1045    }
1046    // Every element above it, not only the nearest one: the text of
1047    // `<button><span>Save</span></button>` is the button's name however many
1048    // wrappers sit between the two, and the span it is written in does not make
1049    // it a second appearance of the same words.
1050    let mut current = document.get_node(id)?.parent;
1051    for _ in 0..64 {
1052        let Some(ancestor) = current else {
1053            break;
1054        };
1055        let ancestor_node = document.get_node(ancestor)?;
1056        if let Some(element) = ancestor_node.element_data() {
1057            if matches!(
1058                element.name.local.as_ref(),
1059                "style" | "script" | "template" | "noscript" | "title"
1060            ) {
1061                return None;
1062            }
1063            if names_from_contents(semantic_role_ref(element)) {
1064                return None;
1065            }
1066        }
1067        current = ancestor_node.parent;
1068    }
1069    Some(normalized)
1070}
1071
1072fn semantic_value(
1073    element: &blitz_dom::ElementData,
1074    document: &blitz_dom::BaseDocument,
1075    id: blitz_dom::NodeId,
1076) -> Option<String> {
1077    if element.name.local.as_ref() == "select" {
1078        return Some(document.select_value(id));
1079    }
1080    element
1081        .text_input_data()
1082        .map(|input| input.editor.text().to_string())
1083        .or_else(|| {
1084            element
1085                .checkbox_input_checked()
1086                .map(|checked| checked.to_string())
1087        })
1088        .or_else(|| element_attr(element, "aria-valuetext").map(str::to_string))
1089        .or_else(|| element_attr(element, "aria-valuenow").map(str::to_string))
1090        .or_else(|| element_attr(element, "value").map(str::to_string))
1091}
1092
1093pub(crate) fn semantic_selected(
1094    element: &blitz_dom::ElementData,
1095    document: &blitz_dom::BaseDocument,
1096    id: blitz_dom::NodeId,
1097) -> bool {
1098    if element.name.local.as_ref() == "option" {
1099        return document.option_is_selected(id);
1100    }
1101    /*
1102     * A real checkbox answers from its live state, not from its markup.
1103     *
1104     * `checkbox_input_checked` is the value the DOM updates when the control is
1105     * toggled; the attributes below are the document as it was parsed and never
1106     * move again. Asking the attributes about an input that has one is how a
1107     * toggle reports the same state for ever.
1108     */
1109    if let Some(checked) = element.checkbox_input_checked() {
1110        return checked;
1111    }
1112
1113    /*
1114     * Presence is not truth for these two.
1115     *
1116     * `checked` and `selected` are HTML boolean attributes, so bare `checked`
1117     * means on. But a framework that renders a controlled value writes the
1118     * value out: Solid emits `checked="false"`, and `.is_some()` called that
1119     * selected. Every Switch, Radio and Checkbox in the QA harness reported
1120     * `selected: true` before anything was pressed and could never change,
1121     * which read as three components that ignore a click.
1122     *
1123     * Explicitly `"false"` is off; anything else present is on.
1124     */
1125    let attribute_on = |name| match element_attr(element, name) {
1126        Some("false") => false,
1127        Some(_) => true,
1128        None => false,
1129    };
1130
1131    element_attr(element, "aria-selected") == Some("true")
1132        || element_attr(element, "aria-pressed") == Some("true")
1133        || element_attr(element, "aria-checked") == Some("true")
1134        || element_attr(element, "aria-current").is_some_and(|value| value != "false")
1135        || attribute_on("checked")
1136        || attribute_on("selected")
1137}
1138
1139fn semantic_parent(
1140    document: &blitz_dom::BaseDocument,
1141    node_id: blitz_dom::NodeId,
1142    root: Option<blitz_dom::NodeId>,
1143) -> Option<blitz_dom::NodeId> {
1144    if Some(node_id) == root {
1145        return None;
1146    }
1147    let mut current = document.get_node(node_id)?.parent;
1148    while let Some(id) = current {
1149        let node = document.get_node(id)?;
1150        if node.element_data().is_some() {
1151            return Some(id);
1152        }
1153        current = node.parent;
1154    }
1155    None
1156}
1157
1158pub(crate) fn node_is_visible(
1159    document: &blitz_dom::BaseDocument,
1160    node_id: blitz_dom::NodeId,
1161) -> bool {
1162    let mut current = Some(node_id);
1163    while let Some(id) = current {
1164        let Some(node) = document.get_node(id) else {
1165            return false;
1166        };
1167        if !node_is_individually_visible(node) {
1168            return false;
1169        }
1170        current = node.parent;
1171    }
1172    true
1173}
1174
1175pub(crate) fn dom_chain_is_attached(
1176    document: &blitz_dom::BaseDocument,
1177    node_id: blitz_dom::NodeId,
1178    node_limit: usize,
1179) -> bool {
1180    let root = document.root_node().id;
1181    let mut current = Some(node_id);
1182    // Removed DOM nodes intentionally remain allocated while JavaScript may
1183    // still hold wrappers for them. They are not part of the document unless
1184    // their parent chain reaches the one document root.
1185    for _ in 0..=node_limit {
1186        let Some(id) = current else {
1187            return false;
1188        };
1189        if id == root {
1190            return true;
1191        }
1192        let Some(node) = document.get_node(id) else {
1193            return false;
1194        };
1195        current = node.parent;
1196    }
1197    false
1198}
1199
1200pub(crate) fn layout_chain_is_valid(
1201    document: &blitz_dom::BaseDocument,
1202    node_id: blitz_dom::NodeId,
1203    node_limit: usize,
1204) -> bool {
1205    let mut current = Some(node_id);
1206    // A valid layout chain reaches its root in no more steps than there are
1207    // nodes. The bound also rejects corrupt cycles instead of hanging control.
1208    for _ in 0..=node_limit {
1209        let Some(id) = current else {
1210            return true;
1211        };
1212        let Some(node) = document.get_node(id) else {
1213            return false;
1214        };
1215        current = node.layout_parent.get();
1216    }
1217    false
1218}
1219
1220/// Whether layout places this node inside a fixed box anchored to the window.
1221///
1222/// Fixed boxes retain their DOM ancestry, but Blitz reparents their layout box
1223/// to the root element. Following layout parents therefore covers every child
1224/// in the fixed surface and still excludes CSS fixed boxes whose transformed
1225/// ancestor makes them locally positioned.
1226pub(crate) fn viewport_fixed_descendant(
1227    document: &blitz_dom::BaseDocument,
1228    node_id: blitz_dom::NodeId,
1229    node_limit: usize,
1230) -> bool {
1231    use style::properties::generated::longhands::position::computed_value::T as Position;
1232
1233    let root_element = document.root_element().id;
1234    let mut current = Some(node_id);
1235    for _ in 0..=node_limit {
1236        let Some(id) = current else { return false };
1237        let Some(node) = document.get_node(id) else {
1238            return false;
1239        };
1240        if node
1241            .primary_styles()
1242            .is_some_and(|styles| styles.clone_position() == Position::Fixed)
1243            && node.layout_parent.get() == Some(root_element)
1244        {
1245            return true;
1246        }
1247        current = node.layout_parent.get();
1248    }
1249    false
1250}
1251
1252/// Activate the node the caller selected, without asking hit-testing to select
1253/// it a second time from a screen coordinate.
1254///
1255/// The coordinates carried by DOM events are still the node's own geometry,
1256/// because handlers use offsets and text fields use them for caret placement.
1257/// They never choose the target. An overflowed or clipped node therefore gets
1258/// the same pointer, mouse and click sequence as an on-screen one.
1259/// Click a semantic node, by id, the way the runtime does.
1260///
1261/// Dispatches pointer, mouse and click events in browser order against the
1262/// document directly, so a headless host can drive a control without a window,
1263/// a pointer or a compositor. This is what makes the interaction checks
1264/// runnable at all: a still picture of the tree cannot answer what a control
1265/// does when it is pressed.
1266/// Send one key to a document, down then up.
1267///
1268/// Only keys, deliberately. The pointer and wheel arms of the runtime's input
1269/// handler carry pointer position and button state on the runtime itself, and a
1270/// headless host has no window for those to mean anything against. A key needs
1271/// nothing but the document.
1272///
1273/// Escape closing a menu is a real assertion in a check suite, and it is the one
1274/// that says a control does not trap the person using it. Without this a host
1275/// answers those checks with `unsupported`, which is honest but leaves the
1276/// suite unable to run them at all.
1277/// Move the pointer onto a semantic node, by id.
1278///
1279/// The position comes from the node's own box, so this needs no pointer
1280/// bookkeeping and works in a host that has no window to own a cursor. A
1281/// control revealed on hover cannot be reached any other way, and a defect that
1282/// only appears on the second entry cannot be reached at all without it.
1283pub fn hover_agent_node(
1284    document: &mut (impl crate::ControlScriptBackend + ?Sized),
1285    node_id: u64,
1286) -> Result<(f32, f32), DebugError> {
1287    let (node_id, position) = resolve_agent_node(document, node_id)?;
1288    document.handle_pointer_move_to_node(
1289        pointer_event_for_document(
1290            document,
1291            position,
1292            MouseEventButton::Main,
1293            MouseEventButtons::default(),
1294            KeyboardModifiers::empty(),
1295        ),
1296        node_id,
1297    );
1298    Ok(position)
1299}
1300
1301pub fn press_agent_key(
1302    document: &mut (impl crate::ControlScriptBackend + ?Sized),
1303    key: &str,
1304    code: &str,
1305) -> Result<(), DebugError> {
1306    let parsed_key = key
1307        .parse::<Key>()
1308        .unwrap_or_else(|_| Key::Character(key.to_owned()));
1309    let parsed_code = code.parse::<Code>().unwrap_or(Code::Unidentified);
1310    for phase in [KeyPhase::Down, KeyPhase::Up] {
1311        let event = key_event(
1312            phase,
1313            parsed_key.clone(),
1314            parsed_code,
1315            keyboard_modifiers(Default::default()),
1316        );
1317        document.handle_ui_event(match phase {
1318            KeyPhase::Down => UiEvent::KeyDown(event),
1319            KeyPhase::Up => UiEvent::KeyUp(event),
1320        });
1321    }
1322    Ok(())
1323}
1324
1325pub fn click_agent_node(
1326    document: &mut (impl crate::ControlScriptBackend + ?Sized),
1327    node_id: u64,
1328    count: u8,
1329) -> Result<(f32, f32), DebugError> {
1330    activate_agent_node(document, node_id, count)
1331}
1332
1333pub fn focus_agent_node(
1334    document: &mut (impl crate::ControlScriptBackend + ?Sized),
1335    node_id: blitz_dom::NodeId,
1336) -> Result<(), DebugError> {
1337    let focusable = document
1338        .inner()
1339        .get_node(node_id)
1340        .and_then(|node| node.element_data())
1341        .is_some_and(focuses_on_click);
1342    if !focusable {
1343        return Err(debug_error(
1344            "notFocusable",
1345            "node does not accept keyboard focus",
1346        ));
1347    }
1348    document.inner_mut().set_focus_to(node_id);
1349    Ok(())
1350}
1351
1352/// Read a document's semantic tree.
1353///
1354/// Split out of the runtime's `Inspect` handler so a host that is not this
1355/// runtime can answer the same request from the same code. Nothing in it is
1356/// window-dependent: it polls the document, resolves layout and reads the tree.
1357///
1358/// Sharing the implementation is the point. A second copy of "what is a node's
1359/// name" drifts from this one immediately. A QA harness that reimplemented
1360/// naming against `build_accessibility_tree` got a different answer than the
1361/// inspector for every element on the page, because that builder names only
1362/// text nodes and carries no geometry at all.
1363pub fn inspect_document(
1364    document: &mut (impl crate::ControlScriptBackend + ?Sized),
1365    root: Option<u64>,
1366    max_depth: u32,
1367    revision: u64,
1368) -> DebugResponse {
1369    /*
1370     * Drain immediately runnable script work, but do not force a full style and
1371     * layout pass for an already committed document. Agent actions resolve
1372     * before their Ack and the window loop resolves asynchronous frames; an
1373     * idle inspection is an observer, not another frame driver. Re-resolving
1374     * every 25ms made scoped outcome latency proportional to the entire retained
1375     * application even though the response contained one pane.
1376     */
1377    let ran_script = drain_for_observer(document).0 > 0;
1378    if ran_script {
1379        document.inner_mut().resolve(0.0);
1380    }
1381    let inner = document.inner();
1382    let root = root.map(blitz_dom::NodeId::from_u64);
1383    if root.is_some_and(|id| inner.get_node(id).is_none()) {
1384        return control_error("unknownNode", "the requested root node does not exist");
1385    }
1386    let focused_node = inner.get_focussed_node_id().map(|id| id.as_u64());
1387    let viewport = inner.viewport();
1388    let viewport_scale = viewport.scale_f64();
1389    let viewport_bounds = Some([
1390        0.0,
1391        0.0,
1392        viewport.window_size.0 as f64 / viewport_scale,
1393        viewport.window_size.1 as f64 / viewport_scale,
1394    ]);
1395    // Built over the whole document even when a subtree was asked for: a label
1396    // is frequently a sibling of the control rather than a descendant of the
1397    // node the caller rooted at.
1398    let labels = LabelIndex::build(&inner);
1399    let node_limit = inner.tree().iter().count();
1400    let candidates = if let Some(root) = root {
1401        semantic_subtree_ids(&inner, root, max_depth)
1402            .into_iter()
1403            .filter_map(|id| {
1404                inner.get_node(id)?;
1405                dom_chain_is_attached(&inner, id, node_limit).then(|| SemanticCandidate {
1406                    id,
1407                    parent: semantic_parent(&inner, id, Some(root)),
1408                    visible: node_is_visible(&inner, id),
1409                })
1410            })
1411            .collect()
1412    } else {
1413        attached_semantic_candidates(&inner, max_depth)
1414    };
1415    let layout_validity = layout_chain_validities(&inner, &candidates, node_limit);
1416    let nodes = candidates
1417        .into_iter()
1418        .filter_map(|candidate| {
1419            let id = candidate.id;
1420            let node = inner.get_node(id)?;
1421            if layout_validity.get(&id) != Some(&true) {
1422                return None;
1423            }
1424            let rect = inner.get_client_bounding_rect(id);
1425            let bounds = rect.and_then(|rect| {
1426                let bounds = [rect.x, rect.y, rect.width, rect.height];
1427                bounds
1428                    .iter()
1429                    .all(|value| value.is_finite())
1430                    .then_some(bounds)
1431            });
1432            let Some(element) = node.element_data() else {
1433                // Text the page shows in its own right. A text run has no
1434                // attributes, no state and nothing to press, so every field
1435                // below the name describes the box it is drawn in.
1436                let text = exposed_text(&inner, id, node)?;
1437                return Some(SemanticNode {
1438                    dom_id: None,
1439                    id: id.as_u64(),
1440                    parent: candidate.parent.map(|id| id.as_u64()),
1441                    role: "text".to_owned(),
1442                    name: text,
1443                    value: None,
1444                    enabled: true,
1445                    focusable: false,
1446                    viewport_fixed: false,
1447                    visible: candidate.visible,
1448                    selected: false,
1449                    bounds,
1450                    slot: None,
1451                    attributes: BTreeMap::new(),
1452                });
1453            };
1454            let visible = candidate.visible
1455                && rect
1456                    .as_ref()
1457                    .is_some_and(|rect| rect.width > 0.0 && rect.height > 0.0);
1458            let role = semantic_role(element);
1459            let name = semantic_name(element, node, &role, &inner, id, &labels);
1460            // An unnamed SVG shape is drawing, not a node anyone addresses:
1461            // browsers leave it out of the accessibility tree, and it has no
1462            // box of its own here because its <svg> root paints it. Listing a
1463            // wireframe's thousands of paths made every check report the page
1464            // as retaining dead subtrees. Shapes are leaves, so no kept node
1465            // loses its parent.
1466            if role == "generic"
1467                && name.is_empty()
1468                && element_attr(element, "id").is_none()
1469                && element.name.ns.as_ref() == "http://www.w3.org/2000/svg"
1470                && matches!(
1471                    element.name.local.as_ref(),
1472                    "path"
1473                        | "line"
1474                        | "polyline"
1475                        | "polygon"
1476                        | "rect"
1477                        | "circle"
1478                        | "ellipse"
1479                        | "use"
1480                )
1481            {
1482                return None;
1483            }
1484            let value = semantic_value(element, &inner, id);
1485            Some(SemanticNode {
1486                dom_id: element_attr(element, "id").map(str::to_owned),
1487                id: id.as_u64(),
1488                parent: candidate.parent.map(|id| id.as_u64()),
1489                role,
1490                name,
1491                value,
1492                enabled: element_attr(element, "disabled").is_none()
1493                    && element_attr(element, "aria-disabled") != Some("true"),
1494                focusable: focuses_on_click(element),
1495                viewport_fixed: viewport_fixed_descendant(&inner, id, node_limit),
1496                visible,
1497                selected: semantic_selected(element, &inner, id),
1498                bounds,
1499                slot: element_attr(element, "data-slot").map(str::to_owned),
1500                attributes: semantic_target_attributes(element),
1501            })
1502        })
1503        .collect();
1504    DebugResponse::AgentSnapshot(AgentSnapshot {
1505        revision,
1506        active_window: Some("blitz-main".into()),
1507        focused_node,
1508        viewport: viewport_bounds,
1509        nodes,
1510    })
1511}
1512
1513/// Carry blitz-shell's timing summary onto the wire type.
1514///
1515/// The two structs are deliberately separate: the protocol is versioned by this
1516/// crate, while the shell type is free to grow fields that have no wire meaning.
1517#[cfg(feature = "capture")]
1518pub(crate) fn timing_stats(stats: blitz_shell::TimingStats) -> TimingStats {
1519    TimingStats {
1520        mean_ms: stats.mean_ms,
1521        p95_ms: stats.p95_ms,
1522        max_ms: stats.max_ms,
1523    }
1524}
1525
1526pub(crate) fn debug_error(code: &str, message: &str) -> DebugError {
1527    DebugError {
1528        code: code.into(),
1529        message: message.into(),
1530    }
1531}
1532
1533pub(crate) fn focuses_on_click(element: &blitz_dom::ElementData) -> bool {
1534    let tag = element.name.local.as_ref();
1535    matches!(tag, "button" | "input" | "select" | "textarea")
1536        || tag == "a" && element_attr(element, "href").is_some()
1537        || element_attr(element, "tabindex")
1538            .and_then(|value| value.parse::<i32>().ok())
1539            .is_some_and(|value| value >= 0)
1540        || element_attr(element, "contenteditable").is_some_and(|value| value != "false")
1541}
1542
1543#[cfg(feature = "capture")]
1544pub(crate) fn resident_bytes() -> Option<u64> {
1545    let output = std::process::Command::new("ps")
1546        .args(["-o", "rss=", "-p", &std::process::id().to_string()])
1547        .output()
1548        .ok()?;
1549    if !output.status.success() {
1550        return None;
1551    }
1552    std::str::from_utf8(&output.stdout)
1553        .ok()?
1554        .trim()
1555        .parse::<u64>()
1556        .ok()
1557        .and_then(|kilobytes| kilobytes.checked_mul(1_024))
1558}
1559
1560pub(crate) fn node_is_individually_visible(node: &blitz_dom::Node) -> bool {
1561    if !node.flags.is_in_document() || node.is_display_none() {
1562        return false;
1563    }
1564    /*
1565     * `visibility: hidden` counts too, not just `display: none`.
1566     *
1567     * The two are different in layout and identical to a viewer: a hidden
1568     * node keeps its box and paints nothing. Reporting it as visible made
1569     * an audit of the running application call it a fault, because the box
1570     * was there and the pixels were not. Tailwind's `invisible` is exactly
1571     * this, and it is how a control that is deliberately dormant - a Stop
1572     * button with no run to stop - is expressed.
1573     *
1574     * `Collapse` is included: on anything that is not a table row it means
1575     * the same as `Hidden`, and on a row it removes the row entirely, so
1576     * treating it as not-visible is right in both cases.
1577     */
1578    if node.primary_styles().is_some_and(|style| {
1579        use style::computed_values::visibility::T as Visibility;
1580        matches!(
1581            style.clone_visibility(),
1582            Visibility::Hidden | Visibility::Collapse
1583        )
1584    }) {
1585        return false;
1586    }
1587    !node.element_data().is_some_and(|element| {
1588        element_attr(element, "hidden").is_some()
1589            || element_attr(element, "aria-hidden") == Some("true")
1590    })
1591}
1592
1593pub(crate) fn resolve_agent_node(
1594    document: &mut (impl crate::ControlScriptBackend + ?Sized),
1595    raw_node_id: u64,
1596) -> Result<(blitz_dom::NodeId, (f32, f32)), DebugError> {
1597    resolve_agent_node_inner(document, raw_node_id, Area::Required)
1598}
1599
1600/// Whether the caller needs the node to have a box a pointer could land in.
1601#[derive(Clone, Copy, PartialEq, Eq)]
1602pub(crate) enum Area {
1603    /// A real pointer is going to travel to this box, so it has to have one.
1604    Required,
1605    /// The event is delivered to the node itself, and the coordinate only
1606    /// fills in `clientX`/`clientY` for a handler that reads them.
1607    Optional,
1608}
1609
1610/// Resolve a node to press, and the point to say the press happened at.
1611///
1612/// The area requirement is a parameter because the two callers want different
1613/// things from it. `Hover` and the pointer moves genuinely travel to a
1614/// coordinate, and a box with no area has no honest one. `Click` does not:
1615/// [`activate_agent_node`] dispatches every phase with
1616/// `DomEvent::new(node_id, ..)`, so the node is the target and the position is
1617/// only the number the event carries.
1618///
1619/// Requiring area of both was one predicate standing for two facts, and it
1620/// made a whole class of control unpressable for a reason that has nothing to
1621/// do with whether pressing it works. A control sized entirely by its label --
1622/// a bare `<a>`, a trigger with no padding -- lays out at zero height on a host
1623/// with no font catalogue, which is what a Linux CI runner is. It is attached,
1624/// styled visible, enabled, and its handler runs perfectly well; only the
1625/// coordinate it would never use was missing.
1626///
1627/// What still refuses is everything about the node itself: it must exist, be
1628/// attached with a valid layout ancestry, not be `display: none`,
1629/// `visibility: hidden`, `hidden` or `aria-hidden`, and not be disabled. Those
1630/// are the reasons a press should not land, and none of them is a box size.
1631pub(crate) fn resolve_agent_node_inner(
1632    document: &mut (impl crate::ControlScriptBackend + ?Sized),
1633    raw_node_id: u64,
1634    area: Area,
1635) -> Result<(blitz_dom::NodeId, (f32, f32)), DebugError> {
1636    let node_id = blitz_dom::NodeId::from_u64(raw_node_id);
1637    document.inner_mut().resolve(0.0);
1638    let inner = document.inner();
1639    let node = inner
1640        .get_node(node_id)
1641        .ok_or_else(|| debug_error("unknownNode", "node does not exist"))?;
1642    if !node_is_visible(&inner, node_id) {
1643        return Err(debug_error("notInteractable", "node is not visible"));
1644    }
1645    let node_limit = inner.tree().iter().count();
1646    if !dom_chain_is_attached(&inner, node_id, node_limit)
1647        || !layout_chain_is_valid(&inner, node_id, node_limit)
1648    {
1649        return Err(debug_error(
1650            "notInteractable",
1651            "node has a detached layout ancestor",
1652        ));
1653    }
1654    if node
1655        .element_data()
1656        .is_some_and(|element| element_attr(element, "disabled").is_some())
1657    {
1658        return Err(debug_error("notInteractable", "node is disabled"));
1659    }
1660    let rect = inner
1661        .get_client_bounding_rect(node_id)
1662        .filter(|rect| area == Area::Optional || (rect.width > 0.0 && rect.height > 0.0))
1663        .ok_or_else(|| {
1664            debug_error(
1665                "notInteractable",
1666                match area {
1667                    // The node was never laid out at all, which is a different
1668                    // thing from being laid out flat and is worth saying so.
1669                    Area::Optional => "node has no layout box",
1670                    Area::Required => "node has no layout box a pointer can reach",
1671                },
1672            )
1673        })?;
1674    Ok((
1675        node_id,
1676        (
1677            (rect.x + rect.width / 2.0) as f32,
1678            (rect.y + rect.height / 2.0) as f32,
1679        ),
1680    ))
1681}
1682
1683pub(crate) fn pointer_event(
1684    position: (f32, f32),
1685    button: MouseEventButton,
1686    buttons: MouseEventButtons,
1687    modifiers: KeyboardModifiers,
1688) -> BlitzPointerEvent {
1689    BlitzPointerEvent {
1690        id: BlitzPointerId::Mouse,
1691        is_primary: true,
1692        coords: pointer_coords(position),
1693        button,
1694        buttons,
1695        mods: modifiers,
1696        details: PointerDetails::default(),
1697        element: Point::default(),
1698        active_pointers: Default::default(),
1699    }
1700}
1701
1702/// Build a pointer event from viewport coordinates without losing document
1703/// coordinates after scrolling.
1704///
1705/// Agent input is expressed in the same client-space coordinates as semantic
1706/// bounds. DOM `clientX/Y` keep those values, while `pageX/Y` include the
1707/// document's current viewport scroll. Treating both as the client position
1708/// makes hit testing and component pointer math miss after `ScrollIntoView`.
1709pub(crate) fn pointer_event_for_document(
1710    document: &(impl crate::ControlScriptBackend + ?Sized),
1711    position: (f32, f32),
1712    button: MouseEventButton,
1713    buttons: MouseEventButtons,
1714    modifiers: KeyboardModifiers,
1715) -> BlitzPointerEvent {
1716    let mut event = pointer_event(position, button, buttons, modifiers);
1717    let scroll = document.inner().viewport_scroll();
1718    event.coords.page_x += scroll.x as f32;
1719    event.coords.page_y += scroll.y as f32;
1720    event
1721}
1722
1723pub(crate) fn pointer_coords_for_document(
1724    document: &(impl crate::ControlScriptBackend + ?Sized),
1725    position: (f32, f32),
1726) -> PointerCoords {
1727    let mut coords = pointer_coords(position);
1728    let scroll = document.inner().viewport_scroll();
1729    coords.page_x += scroll.x as f32;
1730    coords.page_y += scroll.y as f32;
1731    coords
1732}
1733
1734pub(crate) struct SemanticCandidate {
1735    pub(crate) id: blitz_dom::NodeId,
1736    pub(crate) parent: Option<blitz_dom::NodeId>,
1737    pub(crate) visible: bool,
1738}
1739
1740#[derive(Clone, Copy)]
1741enum LayoutChainState {
1742    Visiting,
1743    Valid,
1744    Invalid,
1745}
1746
1747/// Resolve layout ancestry once for every inspected node.
1748///
1749/// DOM ancestry and layout ancestry are not interchangeable, but they share
1750/// the same performance trap: walking every node back to a root makes a full
1751/// inspection proportional to `nodes * depth`. Memoize each layout ancestor so
1752/// later candidates stop at the first result the traversal already proved.
1753pub(crate) fn layout_chain_validities(
1754    document: &blitz_dom::BaseDocument,
1755    candidates: &[SemanticCandidate],
1756    node_limit: usize,
1757) -> HashMap<blitz_dom::NodeId, bool> {
1758    let mut states = HashMap::with_capacity(candidates.len());
1759
1760    for candidate in candidates {
1761        if matches!(
1762            states.get(&candidate.id),
1763            Some(LayoutChainState::Valid | LayoutChainState::Invalid)
1764        ) {
1765            continue;
1766        }
1767
1768        let mut chain = Vec::new();
1769        let mut current = Some(candidate.id);
1770        let valid = loop {
1771            let Some(id) = current else {
1772                break true;
1773            };
1774            match states.get(&id) {
1775                Some(LayoutChainState::Valid) => break true,
1776                Some(LayoutChainState::Invalid | LayoutChainState::Visiting) => break false,
1777                None => {}
1778            }
1779            if chain.len() > node_limit {
1780                break false;
1781            }
1782            let Some(node) = document.get_node(id) else {
1783                break false;
1784            };
1785            states.insert(id, LayoutChainState::Visiting);
1786            chain.push(id);
1787            current = node.layout_parent.get();
1788        };
1789
1790        let resolved = if valid {
1791            LayoutChainState::Valid
1792        } else {
1793            LayoutChainState::Invalid
1794        };
1795        for id in chain {
1796            states.insert(id, resolved);
1797        }
1798    }
1799
1800    states
1801        .into_iter()
1802        .filter_map(|(id, state)| match state {
1803            LayoutChainState::Valid => Some((id, true)),
1804            LayoutChainState::Invalid => Some((id, false)),
1805            LayoutChainState::Visiting => None,
1806        })
1807        .collect()
1808}
1809
1810/// Collect one rooted DOM subtree in document order without visiting retained
1811/// panes outside it.
1812pub(crate) fn semantic_subtree_ids(
1813    document: &blitz_dom::BaseDocument,
1814    root: blitz_dom::NodeId,
1815    max_depth: u32,
1816) -> Vec<blitz_dom::NodeId> {
1817    let mut out = Vec::new();
1818    let mut stack = vec![(root, 0_u32)];
1819    while let Some((node_id, depth)) = stack.pop() {
1820        let Some(node) = document.get_node(node_id) else {
1821            continue;
1822        };
1823        if node.element_data().is_some() || node.is_text_node() {
1824            out.push(node_id);
1825        }
1826        for &child_id in node.children.iter().rev() {
1827            let child_depth = depth.saturating_add(
1828                document
1829                    .get_node(child_id)
1830                    .is_some_and(|child| child.element_data().is_some()) as u32,
1831            );
1832            if max_depth == 0 || child_depth <= max_depth {
1833                stack.push((child_id, child_depth));
1834            }
1835        }
1836    }
1837    out
1838}
1839
1840pub(crate) fn pointer_coords((x, y): (f32, f32)) -> PointerCoords {
1841    PointerCoords {
1842        page_x: x,
1843        page_y: y,
1844        screen_x: x,
1845        screen_y: y,
1846        client_x: x,
1847        client_y: y,
1848    }
1849}
1850
1851/// The colours a node actually resolved to, as `#rrggbbaa`.
1852///
1853/// The point of reporting these rather than the stylesheet is that they are the
1854/// end of the chain: the cascade, every custom-property indirection and the
1855/// `@supports` gating have already been applied, so a disagreement between what
1856/// a rule declares and what an element paints shows up here and nowhere else.
1857/// That disagreement is exactly the shape of "this text is invisible and the CSS
1858/// says it should not be", which cannot be settled by reading files.
1859///
1860/// Four properties rather than a full longhand dump: a complete style for every
1861/// node in a real application is megabytes of JSON that nobody reads, and these
1862/// are the ones legibility depends on.
1863#[cfg(feature = "capture")]
1864pub(crate) fn diagnostic_style_row(
1865    document: &blitz_dom::BaseDocument,
1866    node: &SemanticNode,
1867) -> Option<serde_json::Value> {
1868    let dom_node = document.get_node(NodeId::from_u64(node.id))?;
1869    let styles = dom_node.primary_styles()?;
1870
1871    let current = styles.clone_color();
1872    // The same conversion `blitz-paint` does before handing a colour to the
1873    // rasteriser, inlined so this crate does not need that extension trait.
1874    let hex = |absolute: style::color::AbsoluteColor| {
1875        let [r, g, b, a] = *absolute
1876            .to_color_space(style::color::ColorSpace::Srgb)
1877            .raw_components();
1878        let channel = |value: f32| (value.clamp(0.0, 1.0) * 255.0).round() as u8;
1879        format!(
1880            "#{:02x}{:02x}{:02x}{:02x}",
1881            channel(r),
1882            channel(g),
1883            channel(b),
1884            channel(a),
1885        )
1886    };
1887
1888    /*
1889     * Reported as a plain number of pixels rather than stylo's debug shape,
1890     * which nothing reading this over the wire can parse - and being able to
1891     * read it is the entire reason the field exists.
1892     */
1893    let radius = format!("{:?}", styles.get_border().border_top_left_radius.0.width);
1894    let border = styles.get_border();
1895    let border_width = border.border_top_width.0.to_f64_px();
1896    let font_size = styles.clone_font_size().computed_size().px();
1897    let has_text_content = !dom_node.text_content().trim().is_empty();
1898
1899    Some(serde_json::json!({
1900        "nodeId": node.id,
1901        "color": hex(current),
1902        "backgroundColor": hex(
1903            styles.clone_background_color().resolve_to_absolute(&current),
1904        ),
1905        "borderColor": hex(border.border_top_color.resolve_to_absolute(&current)),
1906        "borderWidth": format!("{border_width}px"),
1907        "fontSize": format!("{font_size}px"),
1908        "hasTextContent": has_text_content,
1909        "opacity": styles.clone_opacity(),
1910        /*
1911         * The corner, as the renderer resolved it.
1912         *
1913         * Radius is set from three unrelated places in a themed application -
1914         * the library's own component CSS, the theme's tokens, and utility
1915         * classes at the call site - and which one wins is a cascade question
1916         * that reading any single file cannot answer. Reported repeatedly as
1917         * "radius is wrong" with no way to tell *which* of the three was
1918         * responsible; this is what settles it per element.
1919         */
1920        "borderTopLeftRadius": radius,
1921        "visibility": format!("{:?}", styles.clone_visibility()),
1922    }))
1923}
1924
1925pub(crate) fn keyboard_modifiers(modifiers: ControlModifiers) -> KeyboardModifiers {
1926    let mut output = KeyboardModifiers::empty();
1927    output.set(KeyboardModifiers::SHIFT, modifiers.shift);
1928    output.set(KeyboardModifiers::CONTROL, modifiers.control);
1929    output.set(KeyboardModifiers::ALT, modifiers.alt);
1930    output.set(KeyboardModifiers::META, modifiers.meta);
1931    output.set(KeyboardModifiers::SUPER, modifiers.meta);
1932    output
1933}
1934
1935pub(crate) fn key_event(
1936    phase: KeyPhase,
1937    key: Key,
1938    code: Code,
1939    modifiers: KeyboardModifiers,
1940) -> BlitzKeyEvent {
1941    let text = match (&key, phase) {
1942        (Key::Character(value), KeyPhase::Down)
1943            if !modifiers.intersects(
1944                KeyboardModifiers::CONTROL | KeyboardModifiers::ALT | KeyboardModifiers::META,
1945            ) =>
1946        {
1947            Some(value.clone().into())
1948        }
1949        _ => None,
1950    };
1951    BlitzKeyEvent {
1952        key,
1953        code,
1954        modifiers,
1955        location: Location::Standard,
1956        is_auto_repeating: false,
1957        is_composing: false,
1958        state: match phase {
1959            KeyPhase::Down => KeyState::Pressed,
1960            KeyPhase::Up => KeyState::Released,
1961        },
1962        text,
1963    }
1964}
1965
1966/// Collect the attached document in one traversal.
1967///
1968/// The previous full inspection asked every node to rediscover its depth,
1969/// semantic parent, attachment and inherited visibility by walking back to the
1970/// root independently. A retained application therefore paid roughly
1971/// `nodes * depth` before it serialized one byte. Carry those inherited facts
1972/// down the tree once instead.
1973pub(crate) fn attached_semantic_candidates(
1974    document: &blitz_dom::BaseDocument,
1975    max_depth: u32,
1976) -> Vec<SemanticCandidate> {
1977    let root = document.root_node().id;
1978    let mut candidates = Vec::new();
1979    let mut stack = vec![(root, 0_u32, None, true)];
1980
1981    while let Some((id, depth, semantic_parent, ancestors_visible)) = stack.pop() {
1982        let Some(node) = document.get_node(id) else {
1983            continue;
1984        };
1985        let visible = ancestors_visible && node_is_individually_visible(node);
1986        let is_element = node.element_data().is_some();
1987        if is_element && max_depth != 0 && depth > max_depth {
1988            continue;
1989        }
1990        // Elements, and the text a page shows in its own right. `exposed_text`
1991        // decides which text nodes survive; offering them all here keeps that
1992        // one rule in one place, and the walk already visits them.
1993        if is_element || node.is_text_node() {
1994            candidates.push(SemanticCandidate {
1995                id,
1996                parent: semantic_parent,
1997                visible,
1998            });
1999        }
2000
2001        let child_depth = depth.saturating_add(is_element as u32);
2002        let child_parent = if is_element {
2003            Some(id)
2004        } else {
2005            semantic_parent
2006        };
2007        for &child in node.children.iter().rev() {
2008            stack.push((child, child_depth, child_parent, visible));
2009        }
2010    }
2011
2012    candidates
2013}
2014
2015pub(crate) fn control_error(code: &str, message: &str) -> DebugResponse {
2016    DebugResponse::Error(debug_error(code, message))
2017}
2018
2019#[cfg(feature = "capture")]
2020pub(crate) fn diagnostic_layout_row(
2021    document: &blitz_dom::BaseDocument,
2022    node: &SemanticNode,
2023) -> Option<LayoutDiagnosticRow> {
2024    let bounds = node.bounds?;
2025    let dom_node = document.get_node(NodeId::from_u64(node.id))?;
2026    let layout = dom_node.final_layout();
2027    let unzoom = |value: f32| match dom_node.primary_styles() {
2028        Some(styles) => styles.effective_zoom.unzoom(value),
2029        None => value,
2030    };
2031    // Every field here is unzoomed, including the two that used to be raw.
2032    //
2033    // `scrollOffset` and `scrollRange` came straight off the layout while
2034    // `clientSize` and `scrollSize` went through `unzoom`, so a single row
2035    // carried two unit systems and any arithmetic across them was wrong by the
2036    // zoom factor. Under zoom that makes every scroller read as overscrolled,
2037    // and it is not only a reading error: a consumer testing
2038    // `scrollOffset < scrollSize - clientSize` for "is there more to scroll"
2039    // gets a false negative at the true end, leaving an overflow control
2040    // disabled while content remains off screen.
2041    //
2042    // Unzoomed is the right side to land on because it is what the DOM already
2043    // reports: `blitz-script`'s `scrollLeft`/`scrollTop` unzoom before
2044    // answering, so a raw diagnostic also disagreed with the same measurement
2045    // taken from script.
2046    //
2047    // Not covered by a unit test, deliberately rather than by omission. The
2048    // existing row test runs at zoom 1, where `unzoom` is the identity and a
2049    // mixed row is indistinguishable from a consistent one. Reproducing it
2050    // needs a scroller that is itself zoomed, and in this engine `zoom` on an
2051    // `overflow-y:auto` element leaves `scroll_height()` at 0 while `zoom` on
2052    // its child does not reach the scroller's own styles — so a test asserting
2053    // the relation either holds vacuously (0 == 0) or fails its own setup.
2054    // Verified against a zoomed live scroller where the raw offset exceeded
2055    // the unzoomed range by exactly the zoom factor.
2056    let scroll_offset = dom_node.scroll_offset();
2057    Some(LayoutDiagnosticRow {
2058        node_id: node.id,
2059        bounds: LayoutBounds::from(bounds),
2060        scroll_offset: LayoutOffset {
2061            x: f64::from(unzoom(scroll_offset.x as f32)),
2062            y: f64::from(unzoom(scroll_offset.y as f32)),
2063        },
2064        client_size: LayoutSize {
2065            width: f64::from(unzoom(layout.size.width)),
2066            height: f64::from(unzoom(layout.size.height)),
2067        },
2068        scroll_size: LayoutSize {
2069            width: f64::from(unzoom(layout.size.width + layout.scroll_width())),
2070            height: f64::from(unzoom(layout.size.height + layout.scroll_height())),
2071        },
2072        scroll_range: LayoutSize {
2073            width: f64::from(unzoom(layout.scroll_width())),
2074            height: f64::from(unzoom(layout.scroll_height())),
2075        },
2076        // Border and padding, so a box that renders taller than it was asked
2077        // for can be attributed instead of guessed at.
2078        //
2079        // Without these the only readable numbers are the outer bounds and
2080        // `clientSize`, and both are the border box: a pill declared `24px`
2081        // that measures 27.8 offers no way to tell a 1px border from padding
2082        // from a wrong height, and the difference decides which file to edit.
2083        // Four consecutive wrong diagnoses of one composer pill came from
2084        // inferring these from CSS files rather than reading what the engine
2085        // computed, which is exactly the guessing this replaces.
2086        //
2087        // Edge order matches CSS shorthand: top, right, bottom, left.
2088        border: LayoutEdges {
2089            top: f64::from(unzoom(layout.border.top)),
2090            right: f64::from(unzoom(layout.border.right)),
2091            bottom: f64::from(unzoom(layout.border.bottom)),
2092            left: f64::from(unzoom(layout.border.left)),
2093        },
2094        padding: LayoutEdges {
2095            top: f64::from(unzoom(layout.padding.top)),
2096            right: f64::from(unzoom(layout.padding.right)),
2097            bottom: f64::from(unzoom(layout.padding.bottom)),
2098            left: f64::from(unzoom(layout.padding.left)),
2099        },
2100        // The content box, which is what an author's `height` sets under the
2101        // default `content-box` sizing. `clientSize` above is the border box.
2102        content_size: LayoutSize {
2103            width: f64::from(unzoom(
2104                layout.size.width
2105                    - layout.border.left
2106                    - layout.border.right
2107                    - layout.padding.left
2108                    - layout.padding.right,
2109            )),
2110            height: f64::from(unzoom(
2111                layout.size.height
2112                    - layout.border.top
2113                    - layout.border.bottom
2114                    - layout.padding.top
2115                    - layout.padding.bottom,
2116            )),
2117        },
2118    })
2119}
2120
2121pub(crate) fn activate_agent_node(
2122    document: &mut (impl crate::ControlScriptBackend + ?Sized),
2123    raw_node_id: u64,
2124    count: u8,
2125) -> Result<(f32, f32), DebugError> {
2126    // `Area::Optional`: every phase below is dispatched with
2127    // `DomEvent::new(node_id, ..)`, so the node is the target and `position`
2128    // only fills in the coordinate the event carries. A control sized entirely
2129    // by its label has no area on a host with no fonts and is still perfectly
2130    // pressable.
2131    let (node_id, position) = resolve_agent_node_inner(document, raw_node_id, Area::Optional)?;
2132    let focusable = document
2133        .inner()
2134        .get_node(node_id)
2135        .and_then(|node| node.element_data())
2136        .is_some_and(focuses_on_click);
2137
2138    for _ in 0..count {
2139        let movement = pointer_event_for_document(
2140            document,
2141            position,
2142            MouseEventButton::Main,
2143            MouseEventButtons::default(),
2144            KeyboardModifiers::empty(),
2145        );
2146        let down = pointer_event_for_document(
2147            document,
2148            position,
2149            MouseEventButton::Main,
2150            MouseEventButtons::Primary,
2151            KeyboardModifiers::empty(),
2152        );
2153        let up = pointer_event_for_document(
2154            document,
2155            position,
2156            MouseEventButton::Main,
2157            MouseEventButtons::default(),
2158            KeyboardModifiers::empty(),
2159        );
2160        for event in [
2161            UiEvent::PointerMove(movement),
2162            UiEvent::PointerDown(down),
2163            UiEvent::PointerUp(up),
2164        ] {
2165            // A pointer handler can deliberately replace its own control. The
2166            // action already happened; later phases have no surviving target
2167            // and must not be retargeted to whatever took its place.
2168            if document.inner().get_node(node_id).is_none() {
2169                break;
2170            }
2171            document.handle_ui_event_to_node(event, node_id);
2172        }
2173        if focusable && document.inner().get_node(node_id).is_some() {
2174            document.inner_mut().set_focus_to(node_id);
2175        }
2176    }
2177    Ok(position)
2178}
2179
2180#[cfg(test)]
2181mod tests {
2182    use super::*;
2183    use crate::test_document::TestDocument;
2184    use blitz_dom::{Document, DocumentConfig};
2185
2186    #[test]
2187    fn meta_also_sets_the_super_modifier() {
2188        let modifiers = keyboard_modifiers(ControlModifiers {
2189            meta: true,
2190            ..ControlModifiers::default()
2191        });
2192        assert!(modifiers.contains(KeyboardModifiers::META));
2193        assert!(modifiers.contains(KeyboardModifiers::SUPER));
2194    }
2195
2196    /// A control whose whole size is its label, next to one with padding.
2197    ///
2198    /// `font-size: 0` stands in for the host this exists for: a Linux CI
2199    /// runner with no font catalogue, where every glyph shapes to nothing and
2200    /// a trigger with no padding lays out flat. Written as a style rather than
2201    /// reproduced by removing fonts, so the test says what it is testing and
2202    /// does not depend on which faces the machine running it happens to have.
2203    fn document() -> TestDocument {
2204        let mut document = TestDocument::from_html(
2205            r#"<style>
2206                 button { border: 0; padding: 0; margin: 0; font-size: 0; }
2207                 #padded { padding: 8px 12px; }
2208               </style>
2209               <button id="flat">Open dialog</button>
2210               <button id="padded">Open dialog</button>"#,
2211            DocumentConfig::default(),
2212        );
2213        document.inner_mut().resolve(0.0);
2214        document
2215    }
2216
2217    fn node_id(document: &TestDocument, selector: &str) -> u64 {
2218        document
2219            .inner()
2220            .query_selector(selector)
2221            .unwrap()
2222            .expect("the fixture should contain the selector")
2223            .as_u64()
2224    }
2225
2226    #[test]
2227    fn a_control_with_no_area_is_still_pressable() {
2228        let mut document = document();
2229        let flat = node_id(&document, "#flat");
2230        // The premise: this really is the degenerate case, not an accident of
2231        // the fixture. Without it a passing test proves nothing.
2232        let rect = document
2233            .inner()
2234            .get_client_bounding_rect(blitz_dom::NodeId::from_u64(flat));
2235        assert!(
2236            rect.is_some_and(|rect| rect.width == 0.0 || rect.height == 0.0),
2237            "the flat button should lay out with no area"
2238        );
2239
2240        activate_agent_node(&mut document, flat, 1)
2241            .expect("a click is dispatched at the node, so it needs no area");
2242    }
2243
2244    #[test]
2245    fn a_control_with_no_area_still_refuses_a_pointer() {
2246        let mut document = document();
2247        let flat = node_id(&document, "#flat");
2248        // The other half of the split: `Hover` moves a real pointer to a
2249        // coordinate, and a flat box has no honest one. Keeping this failing
2250        // is the point -- it is why the area requirement became a parameter
2251        // rather than being deleted.
2252        let error = hover_agent_node(&mut document, flat)
2253            .expect_err("hover needs a box a pointer can land in");
2254        assert!(
2255            error.message.contains("no layout box"),
2256            "unexpected error: {error:?}"
2257        );
2258    }
2259
2260    #[test]
2261    fn a_hidden_control_is_still_refused() {
2262        // The area gate was doing double duty. Deleting it for clicks must not
2263        // have opened the door to a control the author hid, which is what the
2264        // visibility gate above it is for.
2265        let mut document = TestDocument::from_html(
2266            r#"<button id="gone" style="display: none">Open dialog</button>"#,
2267            DocumentConfig::default(),
2268        );
2269        document.inner_mut().resolve(0.0);
2270        let gone = node_id(&document, "#gone");
2271        let error = activate_agent_node(&mut document, gone, 1)
2272            .expect_err("a display:none control must stay unpressable");
2273        assert!(
2274            error.message.contains("not visible"),
2275            "unexpected error: {error:?}"
2276        );
2277    }
2278
2279    #[test]
2280    fn pointer_coordinates_keep_client_and_page_space_distinct_after_scroll() {
2281        let mut document = document();
2282        document
2283            .inner_mut()
2284            .set_viewport_scroll(blitz_dom::Point { x: 17.0, y: 600.0 });
2285
2286        let coords = pointer_coords_for_document(&document, (24.0, 32.0));
2287
2288        assert_eq!((coords.client_x, coords.client_y), (24.0, 32.0));
2289        assert_eq!((coords.page_x, coords.page_y), (41.0, 632.0));
2290    }
2291}
2292
2293/// What the semantic tree says about one small document.
2294///
2295/// Every test here reads the tree through `inspect_document`, which is the
2296/// entry point a headless QA host calls, rather than through the naming
2297/// helpers directly. A role or a name that is right inside the crate and wrong
2298/// by the time it reaches the socket is the defect these were written for.
2299#[cfg(test)]
2300mod semantic_tests {
2301    use super::*;
2302    use crate::test_document::TestDocument;
2303    use blitz_dom::{Document, DocumentConfig};
2304
2305    /// One document, reproducing every naming and role defect this module
2306    /// covers. Kept whole rather than split per test so a fix that repairs one
2307    /// case by breaking another is caught by the next assertion down.
2308    const REPRO: &str = r#"<table aria-label="named table">
2309  <thead><tr><th scope="col">Crate</th></tr></thead>
2310  <tbody><tr><td>worktable</td></tr></tbody>
2311</table>
2312<section aria-label="a named section"><p>text</p></section>
2313<datalist id="t"><option value="u64"></option></datalist>
2314<pre>plain text in a pre</pre>
2315<div role="tooltip">tooltip text</div>"#;
2316
2317    fn tree(html: &str) -> Vec<SemanticNode> {
2318        let mut document = TestDocument::from_html(html, DocumentConfig::default());
2319        document.inner_mut().resolve(0.0);
2320        match inspect_document(&mut document, None, 0, 1) {
2321            DebugResponse::AgentSnapshot(snapshot) => snapshot.nodes,
2322            other => panic!("inspection did not answer with a tree: {other:?}"),
2323        }
2324    }
2325
2326    fn roles<'a>(nodes: &'a [SemanticNode], role: &str) -> Vec<&'a SemanticNode> {
2327        nodes.iter().filter(|node| node.role == role).collect()
2328    }
2329
2330    fn names(nodes: &[SemanticNode], role: &str) -> Vec<String> {
2331        roles(nodes, role)
2332            .into_iter()
2333            .map(|node| node.name.clone())
2334            .collect()
2335    }
2336
2337    #[test]
2338    fn a_header_cell_is_a_header() {
2339        let nodes = tree(REPRO);
2340        assert_eq!(
2341            roles(&nodes, "columnheader").len(),
2342            1,
2343            "a `<th scope=\"col\">` is a column header, not an ordinary cell"
2344        );
2345        assert_eq!(roles(&nodes, "cell").len(), 1, "only the `<td>` is a cell");
2346    }
2347
2348    #[test]
2349    fn a_cell_is_named_by_what_it_holds() {
2350        let nodes = tree(REPRO);
2351        assert_eq!(
2352            names(&nodes, "cell"),
2353            vec!["worktable".to_string()],
2354            "a data cell's text is its accessible name, so a table of values is readable"
2355        );
2356        assert_eq!(
2357            names(&nodes, "columnheader"),
2358            vec!["Crate".to_string()],
2359            "a header cell is named by its content too"
2360        );
2361    }
2362
2363    #[test]
2364    fn a_row_is_named_by_its_cells() {
2365        let nodes = tree(REPRO);
2366        assert_eq!(
2367            names(&nodes, "row"),
2368            vec!["Crate".to_string(), "worktable".to_string()],
2369            "a row is named from its contents, which is what makes a table row addressable"
2370        );
2371    }
2372
2373    #[test]
2374    fn a_row_scoped_header_is_a_row_header() {
2375        let nodes = tree(r#"<table><tr><th scope="row">Crate</th><td>worktable</td></tr></table>"#);
2376        assert_eq!(
2377            roles(&nodes, "rowheader").len(),
2378            1,
2379            "`scope=\"row\"` makes a header describe its row, which is what blitz-dom reports"
2380        );
2381    }
2382
2383    #[test]
2384    fn a_named_section_is_a_region() {
2385        let nodes = tree(REPRO);
2386        assert_eq!(
2387            names(&nodes, "region"),
2388            vec!["a named section".to_string()],
2389            "a `<section>` with an accessible name is a landmark, not a wrapper"
2390        );
2391    }
2392
2393    #[test]
2394    fn text_the_page_shows_is_in_the_tree() {
2395        let nodes = tree(REPRO);
2396        assert!(
2397            names(&nodes, "text").contains(&"plain text in a pre".to_string()),
2398            "a `<pre>`'s text is not any element's name, so without a text node it is unreadable: \
2399             {:?}",
2400            names(&nodes, "text")
2401        );
2402    }
2403
2404    #[test]
2405    fn fixed_boxes_are_identified_as_viewport_anchored() {
2406        let nodes = tree(
2407            "<main style='height:1600px'><button id='flow'>Flow</button>\
2408             <section style='position:fixed;top:16px;left:16px'>\
2409               <button id='fixed'>Fixed</button>\
2410             </section></main>",
2411        );
2412        let flow = nodes
2413            .iter()
2414            .find(|node| node.dom_id.as_deref() == Some("flow"))
2415            .expect("flow button is inspected");
2416        let fixed = nodes
2417            .iter()
2418            .find(|node| node.dom_id.as_deref() == Some("fixed"))
2419            .expect("fixed button is inspected");
2420
2421        assert!(!flow.viewport_fixed);
2422        assert!(fixed.viewport_fixed);
2423    }
2424
2425    #[test]
2426    fn a_text_run_refuses_a_click_rather_than_panicking() {
2427        // Text runs are new ids in a tree a harness drives by id, so the
2428        // failure mode when one is pressed has to be a typed refusal and not a
2429        // crash inside the control server.
2430        let mut document =
2431            TestDocument::from_html("<pre>plain text in a pre</pre>", DocumentConfig::default());
2432        document.inner_mut().resolve(0.0);
2433        let DebugResponse::AgentSnapshot(snapshot) = inspect_document(&mut document, None, 0, 1)
2434        else {
2435            panic!("inspection did not answer with a tree");
2436        };
2437        let text = snapshot
2438            .nodes
2439            .iter()
2440            .find(|node| node.role == "text")
2441            .expect("the pre's text is in the tree");
2442        let error = activate_agent_node(&mut document, text.id, 1)
2443            .expect_err("a text run has no box to press");
2444        assert_eq!(error.code, "notInteractable", "unexpected error: {error:?}");
2445    }
2446
2447    #[test]
2448    fn text_that_already_names_a_node_is_not_repeated() {
2449        let nodes = tree(REPRO);
2450        let text = names(&nodes, "text");
2451        assert!(
2452            !text.contains(&"worktable".to_string()),
2453            "the cell carries this text as its name, and the cell is the node a harness can act \
2454             on: {text:?}"
2455        );
2456        let nodes = tree(r#"<button><span>Save</span></button>"#);
2457        assert!(
2458            names(&nodes, "text").is_empty(),
2459            "a wrapper between a control and its text does not make the text a second node"
2460        );
2461    }
2462
2463    #[test]
2464    fn a_stylesheet_is_not_text() {
2465        let nodes = tree("<style>.a { color: red }</style><p>shown</p>");
2466        assert_eq!(
2467            names(&nodes, "text"),
2468            vec!["shown".to_string()],
2469            "a `<style>` is not rendered, and reading it out returns a stylesheet"
2470        );
2471    }
2472
2473    /// Both halves of a responsive label, the way Tailwind writes one.
2474    ///
2475    /// `sm:hidden` on the short one and `hidden sm:inline` on the long one is a
2476    /// single control that says "Book" on a phone and "Book a diagnostic" on a
2477    /// laptop. Exactly one of them is rendered at any width, and folding both
2478    /// into the name produced "Book Book a diagnostic", which matches nothing a
2479    /// person can see and nothing a check can be written against.
2480    const RESPONSIVE_LABEL: &str = r#"<button>
2481         <span>Book</span>
2482         <span style="display: none">Book a diagnostic</span>
2483       </button>"#;
2484
2485    #[test]
2486    fn a_name_skips_a_subtree_that_is_not_rendered() {
2487        let nodes = tree(RESPONSIVE_LABEL);
2488        assert_eq!(
2489            names(&nodes, "button"),
2490            vec!["Book".to_string()],
2491            "a display:none subtree contributes nothing to a name"
2492        );
2493    }
2494
2495    #[test]
2496    fn a_name_skips_a_subtree_that_is_hidden_or_aria_hidden() {
2497        let nodes = tree(
2498            r#"<button>Save<span style="visibility: hidden">draft</span><span aria-hidden="true">now</span></button>"#,
2499        );
2500        assert_eq!(
2501            names(&nodes, "button"),
2502            vec!["Save".to_string()],
2503            "an invisible box and an aria-hidden one are both outside the name"
2504        );
2505    }
2506
2507    #[test]
2508    fn a_label_skips_what_it_does_not_show() {
2509        let nodes = tree(
2510            r#"<label for="url">Endpoint<span style="display: none"> (advanced)</span></label>
2511               <input id="url" type="text">"#,
2512        );
2513        assert_eq!(
2514            names(&nodes, "textbox"),
2515            vec!["Endpoint".to_string()],
2516            "the label a control is named by is read the same way a name is"
2517        );
2518    }
2519
2520    #[test]
2521    fn a_value_only_option_is_named_by_its_value() {
2522        let nodes = tree(REPRO);
2523        assert_eq!(
2524            names(&nodes, "option"),
2525            vec!["u64".to_string()],
2526            "a `<datalist>` option carries its text in `value`, which is what a browser announces"
2527        );
2528    }
2529
2530    #[test]
2531    fn an_options_label_attribute_wins_over_its_text() {
2532        let nodes = tree(r#"<select><option label="Sixty four bits">u64</option></select>"#);
2533        assert_eq!(
2534            names(&nodes, "option"),
2535            vec!["Sixty four bits".to_string()],
2536            "HTML gives `label` precedence over an option's own text"
2537        );
2538    }
2539
2540    #[test]
2541    fn a_tooltip_says_what_it_says() {
2542        let nodes = tree(REPRO);
2543        assert_eq!(
2544            names(&nodes, "tooltip"),
2545            vec!["tooltip text".to_string()],
2546            "a tooltip is named by its contents, and its contents are the whole point of it"
2547        );
2548    }
2549
2550    #[test]
2551    fn an_unnamed_section_is_not_a_region() {
2552        let nodes = tree("<section><p>text</p></section>");
2553        assert!(
2554            roles(&nodes, "region").is_empty(),
2555            "HTML-AAM gives an unnamed section no landmark role, so a page of \
2556             plain sections does not grow a landmark per wrapper"
2557        );
2558    }
2559
2560    /// The shape both reports arrived as: a heading names the region under it.
2561    ///
2562    /// A card with a title above its body is how a dashboard is written, and
2563    /// `aria-labelledby` pointing at that title is the markup for saying so
2564    /// without repeating the words in an attribute.
2565    #[test]
2566    fn a_region_is_named_by_the_heading_it_points_at() {
2567        let nodes = tree(
2568            r#"<h2 id="title">Fleet health</h2>
2569               <section aria-labelledby="title"><p>text</p></section>"#,
2570        );
2571        assert_eq!(
2572            names(&nodes, "region"),
2573            vec!["Fleet health".to_string()],
2574            "a section named by reference is a named landmark, not an anonymous one"
2575        );
2576    }
2577
2578    #[test]
2579    fn a_list_of_references_is_joined_in_the_order_it_is_written() {
2580        let nodes = tree(
2581            r#"<span id="unit">per second</span><span id="what">Requests</span>
2582               <button aria-labelledby="what unit">?</button>"#,
2583        );
2584        assert_eq!(
2585            names(&nodes, "button"),
2586            vec!["Requests per second".to_string()],
2587            "the ids are read in the order the author listed them, not in document order, \
2588             and their text is joined by a single space"
2589        );
2590    }
2591
2592    #[test]
2593    fn a_reference_outranks_an_aria_label_and_the_contents() {
2594        let nodes = tree(
2595            r#"<span id="title">Fleet health</span>
2596               <button aria-labelledby="title" aria-label="overridden">Save</button>"#,
2597        );
2598        assert_eq!(
2599            names(&nodes, "button"),
2600            vec!["Fleet health".to_string()],
2601            "ARIA ranks `aria-labelledby` above `aria-label`, which is above name from contents"
2602        );
2603    }
2604
2605    /// ARIA exempts a directly referenced element from the hidden check, which
2606    /// is the opposite of the rule applied inside a name's own subtree. It has
2607    /// to be, or the pattern the exemption exists for names nothing: an element
2608    /// written only to be pointed at is routinely not shown.
2609    #[test]
2610    fn a_referenced_element_names_even_when_it_is_not_rendered() {
2611        let nodes = tree(
2612            r#"<span id="title" style="display: none">Fleet <b>health</b></span>
2613               <section aria-labelledby="title"><p>text</p></section>"#,
2614        );
2615        assert_eq!(
2616            names(&nodes, "region"),
2617            vec!["Fleet health".to_string()],
2618            "a referenced element contributes its whole text even when it is hidden"
2619        );
2620    }
2621
2622    /// The other half of that rule, so the exemption stays as narrow as ARIA
2623    /// makes it: the element named by the id is exempt, its subtree is not.
2624    #[test]
2625    fn a_reference_still_skips_what_is_hidden_inside_it() {
2626        let nodes = tree(
2627            r#"<span id="title">Book<span style="display: none"> a diagnostic</span></span>
2628               <button aria-labelledby="title">?</button>"#,
2629        );
2630        assert_eq!(
2631            names(&nodes, "button"),
2632            vec!["Book".to_string()],
2633            "the hidden half of a responsive label stays out of a name reached by reference too"
2634        );
2635    }
2636
2637    #[test]
2638    fn a_reference_to_nothing_falls_through_to_the_next_rule() {
2639        let nodes = tree(r#"<button aria-labelledby="deleted" aria-label="Save">?</button>"#);
2640        assert_eq!(
2641            names(&nodes, "button"),
2642            vec!["Save".to_string()],
2643            "an id that matches no element is not a name, so the rules below it stay reachable"
2644        );
2645        let nodes = tree(r#"<button aria-labelledby="deleted">Save</button>"#);
2646        assert_eq!(
2647            names(&nodes, "button"),
2648            vec!["Save".to_string()],
2649            "with nothing else declared the control is still named by its own contents"
2650        );
2651    }
2652
2653    #[test]
2654    fn a_reference_that_resolves_to_no_text_falls_through_too() {
2655        let nodes = tree(
2656            r#"<span id="title"></span>
2657               <button aria-labelledby="title">Save</button>"#,
2658        );
2659        assert_eq!(
2660            names(&nodes, "button"),
2661            vec!["Save".to_string()],
2662            "an element that exists and says nothing gives no name, which is not the same as \
2663             giving an empty one"
2664        );
2665    }
2666
2667    /// A self-reference resolves to the element's own text and terminates.
2668    ///
2669    /// The `aria-label` is what makes this an assertion rather than a tautology.
2670    /// A resolver that followed a reference by computing the referenced
2671    /// element's *name* would either not terminate here or, with a cycle guard,
2672    /// abandon the reference and answer "overridden". Reading the reference as
2673    /// text is what gives the heading's own words, and it is why no cycle guard
2674    /// is needed anywhere in this path.
2675    #[test]
2676    fn an_element_that_references_itself_is_named_by_its_own_contents() {
2677        let nodes = tree(
2678            r#"<h2 id="self" aria-labelledby="self" aria-label="overridden">Fleet health</h2>"#,
2679        );
2680        assert_eq!(
2681            names(&nodes, "heading"),
2682            vec!["Fleet health".to_string()],
2683            "a reference is read as text and never as another name computation"
2684        );
2685    }
2686}
2687
2688/// What this surface calls each element, and what it deliberately does not.
2689///
2690/// # Why this exists
2691///
2692/// The role rules moved into `blitz-dom`, which owns them for its AccessKit
2693/// tree as well, and this surface now narrows that richer vocabulary down to
2694/// the role strings it has always reported. The narrowing is where a wire
2695/// change could hide: adding a tag to blitz-dom's table would otherwise change
2696/// what this reports, silently, for eleven fleet sites and roughly 1,700
2697/// checks.
2698///
2699/// So every row below is the answer this surface gave before the tables were
2700/// merged. A row that changes is a decision someone made; a row that changes by
2701/// accident fails here.
2702#[cfg(test)]
2703mod role_projection_tests {
2704    use super::*;
2705    use crate::test_document::TestDocument;
2706    use blitz_dom::{Document, DocumentConfig};
2707
2708    fn role(html: &str) -> String {
2709        let mut document = TestDocument::from_html(html, DocumentConfig::default());
2710        document.inner_mut().resolve(0.0);
2711        let id = document
2712            .inner()
2713            .query_selector("#it")
2714            .unwrap()
2715            .expect("the fixture should carry #it");
2716        let inner = document.inner();
2717        let element = inner
2718            .get_node(id)
2719            .and_then(|node| node.element_data())
2720            .expect("#it should be an element");
2721        semantic_role(element)
2722    }
2723
2724    /// The roles this surface reports, and the elements that produce them.
2725    #[test]
2726    fn the_reported_roles_are_the_ones_this_surface_has_always_reported() {
2727        for (html, expected) in [
2728            (r#"<a id="it" href="/x">x</a>"#, "link"),
2729            (r#"<button id="it">x</button>"#, "button"),
2730            (r#"<textarea id="it"></textarea>"#, "textbox"),
2731            (r#"<input id="it">"#, "textbox"),
2732            (r#"<select id="it"><option>a</option></select>"#, "combobox"),
2733            (
2734                r#"<select id="it" multiple><option>a</option></select>"#,
2735                "combobox",
2736            ),
2737            (r#"<option id="it">a</option>"#, "option"),
2738            (r#"<img id="it" alt="x">"#, "img"),
2739            (r#"<nav id="it">x</nav>"#, "navigation"),
2740            (r#"<main id="it">x</main>"#, "main"),
2741            (
2742                r#"<section id="it" aria-label="named">x</section>"#,
2743                "region",
2744            ),
2745            (r#"<form id="it">x</form>"#, "form"),
2746            (r#"<ul id="it"><li>a</li></ul>"#, "list"),
2747            (r#"<ol id="it"><li>a</li></ol>"#, "list"),
2748            (r#"<ul><li id="it">a</li></ul>"#, "listitem"),
2749            (r#"<table id="it"><tr><td>a</td></tr></table>"#, "table"),
2750            (r#"<table><tr id="it"><td>a</td></tr></table>"#, "row"),
2751            (r#"<table><tr><td id="it">a</td></tr></table>"#, "cell"),
2752            (
2753                r#"<table><tr><th id="it">a</th></tr></table>"#,
2754                "columnheader",
2755            ),
2756            (
2757                r#"<table><tr><th id="it" scope="row">a</th></tr></table>"#,
2758                "rowheader",
2759            ),
2760            (r#"<h2 id="it">x</h2>"#, "heading"),
2761            (r#"<input id="it" type="checkbox">"#, "checkbox"),
2762            (r#"<input id="it" type="radio">"#, "radio"),
2763            (r#"<input id="it" type="submit">"#, "button"),
2764            (r#"<input id="it" type="range">"#, "slider"),
2765            (r#"<div id="it">x</div>"#, "generic"),
2766        ] {
2767            assert_eq!(role(html), expected, "for {html}");
2768        }
2769    }
2770
2771    /// The narrowing, stated as the wire change it would be to undo it.
2772    ///
2773    /// Every element here carries a distinct AccessKit role in `blitz-dom` and
2774    /// has always arrived at this surface as `generic`. Reporting any of them
2775    /// more precisely is a decision to make with the checks that read it, not a
2776    /// consequence of the two tables becoming one.
2777    #[test]
2778    fn elements_with_a_richer_accesskit_role_still_arrive_generic() {
2779        for html in [
2780            r#"<p id="it">x</p>"#,
2781            r#"<article id="it">x</article>"#,
2782            r#"<aside id="it">x</aside>"#,
2783            r#"<header id="it">x</header>"#,
2784            r#"<footer id="it">x</footer>"#,
2785            r#"<section id="it">x</section>"#,
2786            r#"<blockquote id="it">x</blockquote>"#,
2787            r#"<figure id="it">x</figure>"#,
2788            r#"<hr id="it">"#,
2789            r#"<dl id="it"><dt>a</dt><dd>b</dd></dl>"#,
2790            r#"<dialog id="it">x</dialog>"#,
2791            r#"<fieldset id="it">x</fieldset>"#,
2792            r#"<label id="it">x</label>"#,
2793            r#"<table><thead id="it"><tr><td>a</td></tr></thead></table>"#,
2794            r#"<code id="it">x</code>"#,
2795            r#"<em id="it">x</em>"#,
2796            r#"<strong id="it">x</strong>"#,
2797            r#"<time id="it">x</time>"#,
2798            r#"<iframe id="it"></iframe>"#,
2799            r#"<progress id="it"></progress>"#,
2800            r#"<meter id="it"></meter>"#,
2801            r#"<output id="it"></output>"#,
2802            r#"<details><summary id="it">x</summary>y</details>"#,
2803            r#"<a id="it">no href</a>"#,
2804            r#"<input id="it" type="password">"#,
2805            r#"<input id="it" type="email">"#,
2806            r#"<input id="it" type="color">"#,
2807            r#"<input id="it" type="date">"#,
2808            r#"<input id="it" type="search">"#,
2809        ] {
2810            let reported = role(html);
2811            let expected = if html.contains("type=\"password\"")
2812                || html.contains("type=\"email\"")
2813                || html.contains("type=\"color\"")
2814                || html.contains("type=\"date\"")
2815                || html.contains("type=\"search\"")
2816            {
2817                // Every kind of text-editing input is a `textbox` here: what a
2818                // harness does with one is type into it.
2819                "textbox"
2820            } else {
2821                "generic"
2822            };
2823            assert_eq!(reported, expected, "for {html}");
2824        }
2825    }
2826
2827    /// An author's `role` wins, and travels verbatim.
2828    ///
2829    /// ARIA is a vocabulary a page may extend with roles no HTML element
2830    /// implies. A harness addressing `role="switch"` needs the word the page
2831    /// used, not the closest thing the implicit table knows about.
2832    #[test]
2833    fn an_explicit_role_is_reported_as_written() {
2834        assert_eq!(role(r#"<div id="it" role="switch">x</div>"#), "switch");
2835        assert_eq!(role(r#"<div id="it" role="tooltip">x</div>"#), "tooltip");
2836        assert_eq!(
2837            role(r#"<button id="it" role="menuitem">x</button>"#),
2838            "menuitem",
2839            "an author's role overrides the element's own"
2840        );
2841    }
2842}
2843
2844/// What the runtime's own tests asserted about this code.
2845///
2846/// They lived in `izumo`'s `runtime.rs`, beside a window, and
2847/// every one of them is about a document instead: what a node is named, what
2848/// it is called, whether it is visible, what an activation reaches, what a
2849/// capture draws, and what a diagnostic row reports. They move with the code
2850/// they cover.
2851#[cfg(test)]
2852mod runtime_tests {
2853    use super::*;
2854    fn set_result(document: &mut blitz_dom::BaseDocument, value: &str) {
2855        let result = document.query_selector("#result").unwrap().unwrap();
2856        let mut mutator = document.mutate();
2857        mutator.remove_and_drop_all_children(result);
2858        let text = mutator.create_text_node(value);
2859        mutator.append_children(result, &[text]);
2860    }
2861
2862    fn append_result(document: &mut blitz_dom::BaseDocument, value: &str) {
2863        let result = document.query_selector("#result").unwrap().unwrap();
2864        let mut text = document.get_node(result).unwrap().text_content();
2865        text.push_str(value);
2866        set_result(document, &text);
2867    }
2868
2869    use crate::SemanticNode;
2870    use crate::document::{
2871        SemanticCandidate, diagnostic_layout_row, diagnostic_style_row, dom_chain_is_attached,
2872        element_attr, layout_chain_is_valid, layout_chain_validities, node_is_visible,
2873        semantic_name, semantic_role, semantic_selected,
2874    };
2875    use crate::test_document::TestDocument;
2876    use blitz_dom::{Document, DocumentConfig};
2877
2878    #[test]
2879    fn semantic_visibility_includes_display_none_ancestors() {
2880        let mut document = TestDocument::from_html(
2881            "<main><button id='shown'>Run</button><div style='display:none'><button id='hidden'>Hidden</button></div></main>",
2882            DocumentConfig::default(),
2883        );
2884        document.inner_mut().resolve(0.0);
2885        let inner = document.inner();
2886        let node_id = |value: &str| {
2887            inner
2888                .tree()
2889                .iter()
2890                .find_map(|(id, node)| {
2891                    node.element_data()
2892                        .is_some_and(|element| element_attr(element, "id") == Some(value))
2893                        .then_some(id)
2894                })
2895                .unwrap()
2896        };
2897        let shown = node_id("shown");
2898        let hidden = node_id("hidden");
2899        assert!(node_is_visible(&inner, shown));
2900        assert!(!node_is_visible(&inner, hidden));
2901        let shown_node = inner.get_node(shown).unwrap();
2902        let shown_element = shown_node.element_data().unwrap();
2903        assert_eq!(semantic_role(shown_element), "button");
2904        let labels = crate::document::LabelIndex::build(&inner);
2905        assert_eq!(
2906            semantic_name(shown_element, shown_node, "button", &inner, shown, &labels),
2907            "Run"
2908        );
2909    }
2910
2911    /// A name is made of rendered text, so a `<style>` inside a link is not
2912    /// part of it.
2913    ///
2914    /// `textContent` is the DOM property and includes every text node in the
2915    /// subtree, stylesheets and scripts among them. An accessible name does
2916    /// not, because those elements are not rendered.
2917    ///
2918    /// Measured on honey.id, whose header logo is an anchor wrapping an inline
2919    /// SVG with a `<style>` in it. The home link arrived named
2920    /// ".animated-logo path { fill-opacity: 0; ... }", which is unusable to a
2921    /// person and unaddressable to a check.
2922
2923    #[test]
2924    fn a_style_element_is_not_part_of_a_name() {
2925        let mut document = TestDocument::from_html(
2926            "<main>\
2927               <a id='logo' href='/'>\
2928                 <svg><style>.logo path { fill: red; }</style></svg>\
2929                 Honey\
2930               </a>\
2931               <a id='scripted' href='/x'><script>var noise = 1;</script>Docs</a>\
2932             </main>",
2933            DocumentConfig::default(),
2934        );
2935        // HTML parsing includes the text after inert script elements.
2936        document.inner_mut().resolve(0.0);
2937        let inner = document.inner();
2938        let labels = crate::document::LabelIndex::build(&inner);
2939        let named = |value: &str| {
2940            let id = inner
2941                .tree()
2942                .iter()
2943                .find_map(|(id, node)| {
2944                    node.element_data()
2945                        .is_some_and(|element| element_attr(element, "id") == Some(value))
2946                        .then_some(id)
2947                })
2948                .unwrap();
2949            let node = inner.get_node(id).unwrap();
2950            let element = node.element_data().unwrap();
2951            let role = semantic_role(element);
2952            semantic_name(element, node, &role, &inner, id, &labels)
2953        };
2954
2955        assert_eq!(named("logo"), "Honey", "a stylesheet is not part of a name");
2956        assert_eq!(named("scripted"), "Docs", "and neither is a script");
2957    }
2958
2959    /// Two stacked lines make two words, not one run-on word.
2960    ///
2961    /// crates.vip's failure alert is a column of two block-level lines, and it
2962    /// arrived named "This page could not loadWebSocket connection failed":
2963    /// every text node was concatenated with nothing between it and the next.
2964    /// A name a person cannot read is a name a check cannot address.
2965    ///
2966    /// The inline case is the other half of the assertion, and it is what
2967    /// stops the fix being "put a space everywhere": a name built from two
2968    ///
2969    /// `inline-block` is the third case, and it is why the test is not
2970    /// "outside is inline": an atomic inline establishes its own box, so a
2971    /// browser separates it the way it separates a block.
2972    /// spans is still one word, because that is what the page draws.
2973    #[test]
2974    fn stacked_lines_are_separated_and_inline_ones_are_not() {
2975        let mut document = TestDocument::from_html(
2976            "<main>\
2977               <div id='stacked' role='alert'>\
2978                 <div>This page could not load</div>\
2979                 <div>WebSocket connection failed</div>\
2980               </div>\
2981               <div id='inline' role='alert'><span>Work</span><span>Tables</span></div>\
2982               <div id='atomic' role='alert'>\
2983                 <span style='display: inline-block'>Registry</span>\
2984                 <span style='display: inline-block'>unavailable</span>\
2985               </div>\
2986             </main>",
2987            DocumentConfig::default(),
2988        );
2989        document.inner_mut().resolve(0.0);
2990        let inner = document.inner();
2991        let labels = crate::document::LabelIndex::build(&inner);
2992        let named = |value: &str| {
2993            let id = inner
2994                .tree()
2995                .iter()
2996                .find_map(|(id, node)| {
2997                    node.element_data()
2998                        .is_some_and(|element| element_attr(element, "id") == Some(value))
2999                        .then_some(id)
3000                })
3001                .unwrap();
3002            let node = inner.get_node(id).unwrap();
3003            let element = node.element_data().unwrap();
3004            let role = semantic_role(element);
3005            semantic_name(element, node, &role, &inner, id, &labels)
3006        };
3007
3008        assert_eq!(
3009            named("stacked"),
3010            "This page could not load WebSocket connection failed",
3011            "block-level lines are separate words"
3012        );
3013        assert_eq!(
3014            named("inline"),
3015            "WorkTables",
3016            "inline spans are one word, as the page draws them"
3017        );
3018        assert_eq!(
3019            named("atomic"),
3020            "Registry unavailable",
3021            "an inline-block is an atomic inline, and a browser separates it"
3022        );
3023    }
3024
3025    /// A form control is named by the label pointing at it.
3026    ///
3027    /// The name came from `aria-label`, `alt` and `title` and from nothing
3028    /// else, so the ordinary way to label a field produced no name at all and
3029    /// every text input on every page arrived anonymous. That is not only a
3030    /// reporting defect: a harness addresses a control by name, so an
3031    /// anonymous field cannot be typed into and a check that means "enter a URL
3032    /// and save" cannot be written.
3033    ///
3034    /// Measured on support.cafe's connection settings, whose three fields each
3035    /// carry a correct `<Label for>` and all reported as `textbox ""`.
3036
3037    #[test]
3038    fn a_field_is_named_by_its_label() {
3039        let mut document = TestDocument::from_html(
3040            "<main>\
3041               <label for='endpoint'>Endpoint URL</label><input id='endpoint'>\
3042               <label>Wrapped<input id='wrapped'></label>\
3043               <label for='overridden'>Ignored</label>\
3044               <input id='overridden' aria-label='Author own name'>\
3045               <input id='placeheld' placeholder='Search everything'>\
3046               <input id='nameless'>\
3047             </main>",
3048            DocumentConfig::default(),
3049        );
3050        document.inner_mut().resolve(0.0);
3051        let inner = document.inner();
3052        let labels = crate::document::LabelIndex::build(&inner);
3053        let named = |value: &str| {
3054            let id = inner
3055                .tree()
3056                .iter()
3057                .find_map(|(id, node)| {
3058                    node.element_data()
3059                        .is_some_and(|element| element_attr(element, "id") == Some(value))
3060                        .then_some(id)
3061                })
3062                .unwrap();
3063            let node = inner.get_node(id).unwrap();
3064            let element = node.element_data().unwrap();
3065            let role = semantic_role(element);
3066            semantic_name(element, node, &role, &inner, id, &labels)
3067        };
3068
3069        assert_eq!(named("endpoint"), "Endpoint URL", "a `for` association");
3070        assert_eq!(named("wrapped"), "Wrapped", "a label wrapped around it");
3071        assert_eq!(
3072            named("overridden"),
3073            "Author own name",
3074            "`aria-label` is the author overriding the visible text, and wins"
3075        );
3076        assert_eq!(
3077            named("placeheld"),
3078            "Search everything",
3079            "a placeholder is the last resort, and names most search fields"
3080        );
3081        assert_eq!(named("nameless"), "", "nothing names it, so it has no name");
3082    }
3083
3084    /// A live region is named by what it says.
3085    ///
3086    /// `alert` and `status` are the roles an application uses to report that
3087    /// something happened -- a refusal, a saved confirmation -- and what they
3088    /// report is their content. Anonymous, "the reason is shown" is not a
3089    /// question a check can ask, so every validation outcome has to be
3090    /// approximated by something else that moved.
3091    ///
3092    /// The negative half is the point of the test. A wrapper's text content is
3093    /// its whole subtree, so naming generic containers would give every one of
3094    /// them a name made of the entire page, and any name-matching selector
3095    /// would then match everything.
3096
3097    #[test]
3098    fn a_live_region_is_named_by_what_it_says() {
3099        let mut document = TestDocument::from_html(
3100            "<main>\
3101               <p id='refusal' role='alert'>that is not an address</p>\
3102               <p id='saved' role='status'>Settings saved</p>\
3103               <div id='wrapper'><span>inner text</span></div>\
3104             </main>",
3105            DocumentConfig::default(),
3106        );
3107        document.inner_mut().resolve(0.0);
3108        let inner = document.inner();
3109        let labels = crate::document::LabelIndex::build(&inner);
3110        let named = |value: &str| {
3111            let id = inner
3112                .tree()
3113                .iter()
3114                .find_map(|(id, node)| {
3115                    node.element_data()
3116                        .is_some_and(|element| element_attr(element, "id") == Some(value))
3117                        .then_some(id)
3118                })
3119                .unwrap();
3120            let node = inner.get_node(id).unwrap();
3121            let element = node.element_data().unwrap();
3122            let role = semantic_role(element);
3123            semantic_name(element, node, &role, &inner, id, &labels)
3124        };
3125
3126        assert_eq!(named("refusal"), "that is not an address");
3127        assert_eq!(named("saved"), "Settings saved");
3128        assert_eq!(
3129            named("wrapper"),
3130            "",
3131            "a container named by its subtree would make every selector match everything"
3132        );
3133    }
3134
3135    #[test]
3136    fn rooted_inspection_returns_only_the_requested_dom_subtree() {
3137        let mut document = TestDocument::from_html(
3138            "<main><section id='left'><button>Left action</button></section><section id='right'><button>Right action</button></section></main>",
3139            DocumentConfig::default(),
3140        );
3141        document.inner_mut().resolve(0.0);
3142        let root = document
3143            .inner()
3144            .query_selector("#left")
3145            .unwrap()
3146            .unwrap()
3147            .as_u64();
3148
3149        let DebugResponse::AgentSnapshot(snapshot) =
3150            inspect_document(&mut document, Some(root), 40, 7)
3151        else {
3152            panic!("rooted inspection did not return a semantic snapshot");
3153        };
3154        let names: Vec<_> = snapshot
3155            .nodes
3156            .iter()
3157            .map(|node| node.name.as_str())
3158            .collect();
3159        assert!(names.contains(&"Left action"));
3160        assert!(!names.contains(&"Right action"));
3161        assert_eq!(snapshot.revision, 7);
3162    }
3163
3164    #[test]
3165    fn semantic_geometry_rejects_a_detached_layout_ancestor() {
3166        let mut document = TestDocument::from_html(
3167            "<main><button id='target'>Run</button></main>",
3168            DocumentConfig::default(),
3169        );
3170        document.inner_mut().resolve(0.0);
3171        let inner = document.inner();
3172        let target = inner.query_selector("#target").unwrap().unwrap();
3173        let node_limit = inner.tree().iter().count();
3174        assert!(layout_chain_is_valid(&inner, target, node_limit));
3175        let candidate = || SemanticCandidate {
3176            id: target,
3177            parent: None,
3178            visible: true,
3179        };
3180        assert_eq!(
3181            layout_chain_validities(&inner, &[candidate()], node_limit).get(&target),
3182            Some(&true)
3183        );
3184
3185        let missing_parent = (1..=1024)
3186            .map(blitz_dom::NodeId::from_u64)
3187            .find(|id| inner.get_node(*id).is_none())
3188            .expect("the fixture must leave at least one node id unused");
3189        inner
3190            .get_node(target)
3191            .unwrap()
3192            .layout_parent
3193            .set(Some(missing_parent));
3194
3195        assert!(!layout_chain_is_valid(&inner, target, node_limit));
3196        assert_eq!(
3197            layout_chain_validities(&inner, &[candidate()], node_limit).get(&target),
3198            Some(&false)
3199        );
3200    }
3201
3202    #[test]
3203    fn semantic_geometry_rejects_a_retained_dom_subtree() {
3204        let mut document = TestDocument::from_html(
3205            "<main><section id='removed'><button id='target'>Run</button></section></main>",
3206            DocumentConfig::default(),
3207        );
3208        let (removed, target) = {
3209            let inner = document.inner();
3210            (
3211                inner.query_selector("#removed").unwrap().unwrap(),
3212                inner.query_selector("#target").unwrap().unwrap(),
3213            )
3214        };
3215        let node_limit = document.inner().tree().iter().count();
3216        assert!(dom_chain_is_attached(&document.inner(), target, node_limit));
3217
3218        blitz_dom::DocumentMutator::new(&mut document.inner_mut()).remove_node(removed);
3219
3220        let inner = document.inner();
3221        assert!(
3222            inner.get_node(target).is_some(),
3223            "the DOM keeps detached nodes alive for JavaScript wrappers"
3224        );
3225        assert!(!dom_chain_is_attached(&inner, target, node_limit));
3226    }
3227
3228    #[test]
3229    fn semantic_selection_includes_native_and_aria_states() {
3230        let document = TestDocument::from_html(
3231            r#"
3232            <button id="pressed" aria-pressed="true">Pressed</button>
3233            <div id="checked" role="radio" aria-checked="true">Checked</div>
3234            <div id="selected" role="option" aria-selected="true">Selected</div>
3235            <button id="current-page" aria-current="page">Current page</button>
3236            <input id="native" type="checkbox" checked>
3237            <button id="plain">Plain</button>
3238            <!--
3239              A framework rendering a controlled value writes the value out
3240              rather than omitting the attribute. Solid emits `checked="false"`
3241              for `checked={false}`, and reading presence alone called that
3242              selected: every Switch, Radio and Checkbox in the QA harness
3243              reported `selected: true` before anything was pressed, and could
3244              never change, which read as three components ignoring a click.
3245            -->
3246            <input id="native-unchecked" type="checkbox" checked="false">
3247            <div id="aria-false" role="option" aria-selected="false">Not selected</div>
3248            <button id="current-false" aria-current="false">Not current</button>
3249            <div id="selected-false" role="option" selected="false">Not selected</div>
3250            "#,
3251            DocumentConfig::default(),
3252        );
3253        let inner = document.inner();
3254        let selected = |selector: &str| {
3255            let id = inner.query_selector(selector).unwrap().unwrap();
3256            semantic_selected(
3257                inner.get_node(id).unwrap().element_data().unwrap(),
3258                &inner,
3259                id,
3260            )
3261        };
3262
3263        assert!(selected("#pressed"));
3264        assert!(selected("#checked"));
3265        assert!(selected("#selected"));
3266        assert!(selected("#current-page"));
3267        assert!(selected("#native"));
3268        assert!(!selected("#plain"));
3269        assert!(!selected("#native-unchecked"));
3270        assert!(!selected("#aria-false"));
3271        assert!(!selected("#current-false"));
3272        assert!(!selected("#selected-false"));
3273    }
3274
3275    #[test]
3276    fn node_activation_reaches_an_offscreen_mousedown_handler() {
3277        let mut document = TestDocument::from_html(
3278            r#"
3279            <button id="target" style="position:absolute;left:-900px;width:80px;height:30px">Run</button>
3280            <output id="result"></output>
3281            "#,
3282            DocumentConfig::default(),
3283        );
3284        document.on("#target", "mousedown", |doc, _, _| {
3285            append_result(doc, "down ");
3286        });
3287        document.on("#target", "click", |doc, _, _| {
3288            append_result(doc, "click");
3289        });
3290        document.inner_mut().resolve(0.0);
3291        let (target, result) = {
3292            let inner = document.inner();
3293            (
3294                inner.query_selector("#target").unwrap().unwrap(),
3295                inner.query_selector("#result").unwrap().unwrap(),
3296            )
3297        };
3298        assert!(
3299            document
3300                .inner()
3301                .get_client_bounding_rect(target)
3302                .is_some_and(|rect| rect.x < 0.0),
3303            "the fixture must be outside the viewport"
3304        );
3305
3306        activate_agent_node(&mut document, target.as_u64(), 1).unwrap();
3307
3308        assert_eq!(
3309            document.inner().get_node(result).unwrap().text_content(),
3310            "down click"
3311        );
3312    }
3313
3314    #[test]
3315    fn node_activation_bubbles_to_delegated_handlers() {
3316        let mut document = TestDocument::from_html(
3317            r#"
3318            <main id="root">
3319              <button id="target" style="width:80px;height:30px">Run</button>
3320              <output id="result"></output>
3321            </main>
3322            "#,
3323            DocumentConfig::default(),
3324        );
3325        document.on("#root", "mousedown", |doc, event, _| {
3326            if doc.query_selector("#target").unwrap() == Some(event.target) {
3327                append_result(doc, "down ");
3328            }
3329        });
3330        document.on("#root", "click", |doc, event, _| {
3331            if doc.query_selector("#target").unwrap() == Some(event.target) {
3332                append_result(doc, "click");
3333            }
3334        });
3335        document.inner_mut().resolve(0.0);
3336        let (target, result) = {
3337            let inner = document.inner();
3338            (
3339                inner.query_selector("#target").unwrap().unwrap(),
3340                inner.query_selector("#result").unwrap().unwrap(),
3341            )
3342        };
3343
3344        activate_agent_node(&mut document, target.as_u64(), 1).unwrap();
3345
3346        assert_eq!(
3347            document.inner().get_node(result).unwrap().text_content(),
3348            "down click"
3349        );
3350    }
3351
3352    #[test]
3353    fn node_activation_reaches_solid_style_document_delegation() {
3354        let mut document = TestDocument::from_html(
3355            r#"
3356            <main id="root">
3357              <button id="target" style="width:80px;height:30px">Run</button>
3358              <output id="result"></output>
3359            </main>
3360            "#,
3361            DocumentConfig::default(),
3362        );
3363        let target = document.inner().query_selector("#target").unwrap().unwrap();
3364        document.on("html", "click", move |doc, event, _| {
3365            let mut node = Some(event.target);
3366            while let Some(id) = node {
3367                if id == target {
3368                    set_result(doc, "delegated");
3369                }
3370                node = doc.get_node(id).and_then(|node| node.parent);
3371            }
3372        });
3373        document.inner_mut().resolve(0.0);
3374        let (target, result) = {
3375            let inner = document.inner();
3376            (
3377                inner.query_selector("#target").unwrap().unwrap(),
3378                inner.query_selector("#result").unwrap().unwrap(),
3379            )
3380        };
3381
3382        activate_agent_node(&mut document, target.as_u64(), 1).unwrap();
3383
3384        assert_eq!(
3385            document.inner().get_node(result).unwrap().text_content(),
3386            "delegated"
3387        );
3388    }
3389
3390    #[test]
3391    fn node_activation_applies_the_native_focus_default() {
3392        let mut document = TestDocument::from_html(
3393            r#"<main><div id="slider" role="slider" tabindex="0" style="width:80px;height:30px">Value</div></main>"#,
3394            DocumentConfig::default(),
3395        );
3396        document.inner_mut().resolve(0.0);
3397        let slider = document.inner().query_selector("#slider").unwrap().unwrap();
3398
3399        activate_agent_node(&mut document, slider.as_u64(), 1).unwrap();
3400
3401        assert_eq!(document.inner().get_focussed_node_id(), Some(slider));
3402    }
3403
3404    #[test]
3405    fn semantic_focus_does_not_activate_the_target() {
3406        let mut document = TestDocument::from_html(
3407            r#"
3408            <main>
3409              <button id="target" style="width:80px;height:30px">Start fork</button>
3410              <output id="result"></output>
3411            </main>
3412            "#,
3413            DocumentConfig::default(),
3414        );
3415        document.on("#target", "click", |doc, _, _| {
3416            set_result(doc, "activated");
3417        });
3418        document.inner_mut().resolve(0.0);
3419        let (target, result) = {
3420            let inner = document.inner();
3421            (
3422                inner.query_selector("#target").unwrap().unwrap(),
3423                inner.query_selector("#result").unwrap().unwrap(),
3424            )
3425        };
3426
3427        focus_agent_node(&mut document, target).unwrap();
3428
3429        assert_eq!(document.inner().get_focussed_node_id(), Some(target));
3430        assert_eq!(
3431            document.inner().get_node(result).unwrap().text_content(),
3432            ""
3433        );
3434    }
3435
3436    /// It used to need a font, and it no longer does.
3437    ///
3438    /// Replacing a field.s contents came down to select-all selecting
3439    /// something, and selection is over shaped text: with no face registered
3440    /// parley measures nothing, the select-all covers nothing, and the
3441    /// replacement lands after the old value. So this ran on macOS only, where
3442    /// Core Text supplies a face for free, and compiled out everywhere else.
3443    ///
3444    /// `set_node_value` counts bytes now, which is what the headless browser
3445    /// always did and why its copy was the one that survived the merge. There
3446    /// is no layout in the path, so the test runs everywhere, which is where
3447    /// the property was always meant to hold.
3448    #[test]
3449    fn setting_a_node_value_replaces_text_and_dispatches_input() {
3450        let mut document = TestDocument::from_html(
3451            r#"
3452            <main>
3453              <input id="field" value="old" style="width:80px;height:30px">
3454              <output id="result"></output>
3455            </main>
3456            "#,
3457            DocumentConfig::default(),
3458        );
3459        document.on("#field", "input", |doc, event, _| {
3460            if let blitz_traits::events::DomEventData::Input(input) = &event.data {
3461                set_result(doc, &input.value);
3462            }
3463        });
3464        document.inner_mut().resolve(0.0);
3465        let (field, result) = {
3466            let inner = document.inner();
3467            (
3468                inner.query_selector("#field").unwrap().unwrap(),
3469                inner.query_selector("#result").unwrap().unwrap(),
3470            )
3471        };
3472
3473        let replacement = "https://example.test/org/repository/issues/40?view=full#comment-2";
3474        crate::in_process::set_node_value(&mut document, field, replacement.into()).unwrap();
3475
3476        let inner = document.inner();
3477        let text = inner
3478            .get_node(field)
3479            .unwrap()
3480            .element_data()
3481            .unwrap()
3482            .text_input_data()
3483            .unwrap()
3484            .editor
3485            .raw_text();
3486        assert_eq!(text, replacement);
3487        assert_eq!(inner.get_node(result).unwrap().text_content(), replacement);
3488    }
3489
3490    #[test]
3491    fn node_double_click_is_one_runtime_action() {
3492        let mut document = TestDocument::from_html(
3493            r#"
3494            <button id="target" style="width:80px;height:30px">Open row</button>
3495            <output id="result"></output>
3496            "#,
3497            DocumentConfig::default(),
3498        );
3499        document.on("#target", "dblclick", |doc, _, _| {
3500            set_result(doc, "double");
3501        });
3502        let (target, result) = {
3503            let inner = document.inner();
3504            (
3505                inner.query_selector("#target").unwrap().unwrap(),
3506                inner.query_selector("#result").unwrap().unwrap(),
3507            )
3508        };
3509
3510        activate_agent_node(&mut document, target.as_u64(), 2).unwrap();
3511
3512        assert_eq!(
3513            document.inner().get_node(result).unwrap().text_content(),
3514            "double"
3515        );
3516    }
3517
3518    #[cfg(feature = "capture")]
3519    #[test]
3520    fn repeated_live_captures_reuse_one_surface_and_keep_identical_pixels() {
3521        use blitz_traits::shell::{ColorScheme, Viewport};
3522
3523        let mut document = TestDocument::from_html(
3524            "<body style='margin:0;background:transparent'><main style='width:320px;height:200px;background:rgba(24,32,42,.55);color:#f4f5f7'>\
3525               <h1>Capture cache</h1><button>Ready</button>\
3526             </main></body>",
3527            DocumentConfig::default(),
3528        );
3529        document
3530            .inner_mut()
3531            .set_viewport(Viewport::new(320, 200, 1.0, ColorScheme::Dark));
3532        document.inner_mut().resolve(0.0);
3533
3534        let mut surface = None;
3535        let request = crate::CaptureRequest::default();
3536        let first = capture_document_with_surface(&mut document, request, &mut surface).unwrap();
3537        let first_renderer = surface
3538            .as_ref()
3539            .map(|cached| std::ptr::from_ref(&cached.renderer))
3540            .unwrap();
3541        let second = capture_document_with_surface(&mut document, request, &mut surface).unwrap();
3542        let second_renderer = surface
3543            .as_ref()
3544            .map(|cached| std::ptr::from_ref(&cached.renderer))
3545            .unwrap();
3546
3547        assert_eq!(first_renderer, second_renderer);
3548        assert_eq!(first.width, 320);
3549        assert_eq!(first.height, 200);
3550        assert_eq!(first.rgba_base64, second.rgba_base64);
3551    }
3552
3553    #[cfg(feature = "capture")]
3554    #[test]
3555    fn node_region_matches_the_same_pixels_cut_from_a_full_document_capture() {
3556        use base64::Engine as _;
3557        use blitz_traits::shell::{ColorScheme, Viewport};
3558
3559        let mut document = TestDocument::from_html(
3560            "<main style='width:320px;height:200px;background:#18202a;padding:24px'>\
3561               <button id='target' style='width:96px;height:40px;background:#d24db8;color:#111'>Ready</button>\
3562             </main>",
3563            DocumentConfig::default(),
3564        );
3565        document
3566            .inner_mut()
3567            .set_viewport(Viewport::new(320, 200, 1.0, ColorScheme::Dark));
3568        document.inner_mut().resolve(0.0);
3569        let (target, left, top) = {
3570            let inner = document.inner();
3571            let target = inner.query_selector("#target").unwrap().unwrap();
3572            let position = inner.get_node(target).unwrap().absolute_position(0.0, 0.0);
3573            (
3574                target,
3575                position.x.round() as usize,
3576                position.y.round() as usize,
3577            )
3578        };
3579
3580        let mut surface = None;
3581        let full = capture_document_with_surface(
3582            &mut document,
3583            crate::CaptureRequest::default(),
3584            &mut surface,
3585        )
3586        .unwrap();
3587        let node = capture_document_with_surface(
3588            &mut document,
3589            crate::CaptureRequest {
3590                node_id: Some(target.as_u64()),
3591                scale: 1.0,
3592            },
3593            &mut surface,
3594        )
3595        .unwrap();
3596
3597        let full_rgba = base64::engine::general_purpose::STANDARD
3598            .decode(full.rgba_base64)
3599            .unwrap();
3600        let node_rgba = base64::engine::general_purpose::STANDARD
3601            .decode(node.rgba_base64)
3602            .unwrap();
3603        let mut expected = Vec::with_capacity(node_rgba.len());
3604        for row in 0..node.height as usize {
3605            let start = ((top + row) * full.width as usize + left) * 4;
3606            expected.extend_from_slice(&full_rgba[start..start + node.width as usize * 4]);
3607        }
3608
3609        assert!(node.width > 0);
3610        assert!(node.height > 0);
3611        assert_eq!(node_rgba, expected);
3612    }
3613
3614    #[cfg(feature = "capture")]
3615    #[test]
3616    fn fixed_node_capture_uses_viewport_coordinates_after_document_scroll() {
3617        use blitz_traits::shell::{ColorScheme, Viewport};
3618
3619        let mut document = TestDocument::from_html(
3620            "<body style='margin:0;height:1600px'>\
3621               <textarea id='target' style='position:fixed;left:24px;top:32px;width:240px;height:96px;background:#18202a'>theme css</textarea>\
3622             </body>",
3623            DocumentConfig::default(),
3624        );
3625        document
3626            .inner_mut()
3627            .set_viewport(Viewport::new(320, 200, 1.0, ColorScheme::Dark));
3628        document.inner_mut().resolve(0.0);
3629        document
3630            .inner_mut()
3631            .set_viewport_scroll(blitz_dom::Point { x: 0.0, y: 600.0 });
3632        let target = document.inner().query_selector("#target").unwrap().unwrap();
3633        let expected = document
3634            .inner()
3635            .get_client_bounding_rect(target)
3636            .expect("the fixed textarea is laid out");
3637
3638        let image = capture_document(
3639            &mut document,
3640            crate::CaptureRequest {
3641                node_id: Some(target.as_u64()),
3642                scale: 1.0,
3643            },
3644        )
3645        .unwrap();
3646
3647        assert!(expected.width > 0.0 && expected.height > 1.0);
3648        assert_eq!(image.width, expected.width.round() as u32);
3649        assert_eq!(image.height, expected.height.round() as u32);
3650    }
3651
3652    #[cfg(feature = "capture")]
3653    #[test]
3654    fn diagnostic_layout_reports_scroll_state_without_script_evaluation() {
3655        let mut document = TestDocument::from_html(
3656            "<section id='scroller' style='height:100px;overflow-y:auto'><div style='height:400px'>tail</div></section>",
3657            DocumentConfig::default(),
3658        );
3659        document.inner_mut().resolve(0.0);
3660        let scroller = document
3661            .inner()
3662            .tree()
3663            .iter()
3664            .find_map(|(id, node)| {
3665                node.element_data()
3666                    .is_some_and(|element| element_attr(element, "id") == Some("scroller"))
3667                    .then_some(id)
3668            })
3669            .unwrap();
3670        document
3671            .inner_mut()
3672            .get_node_mut(scroller)
3673            .unwrap()
3674            .scroll_offset_mut()
3675            .y = 60.0;
3676
3677        let inner = document.inner();
3678        let row = diagnostic_layout_row(
3679            &inner,
3680            &SemanticNode {
3681                dom_id: Some("scroller".into()),
3682                id: scroller.as_u64(),
3683                parent: None,
3684                role: "generic".into(),
3685                name: "Scrollable region".into(),
3686                value: None,
3687                enabled: true,
3688                focusable: false,
3689                viewport_fixed: false,
3690                visible: true,
3691                selected: false,
3692                bounds: Some([0.0, 0.0, 100.0, 100.0]),
3693                slot: None,
3694                attributes: BTreeMap::new(),
3695            },
3696        )
3697        .unwrap();
3698
3699        assert_eq!(row.scroll_offset.y, 60.0);
3700        assert_eq!(row.client_size.height, 100.0);
3701        assert!(row.scroll_size.height >= 100.0);
3702        assert!(row.scroll_range.height >= 0.0);
3703    }
3704
3705    #[cfg(feature = "capture")]
3706    #[test]
3707    fn diagnostic_style_reports_resolved_font_and_border() {
3708        let mut document = TestDocument::from_html(
3709            "<main id='target' style='font-size:1.4375rem;border:2px solid #123456'>Readable</main>",
3710            DocumentConfig::default(),
3711        );
3712        document.inner_mut().resolve(0.0);
3713        let target = document.inner().query_selector("#target").unwrap().unwrap();
3714        let inner = document.inner();
3715        let row = diagnostic_style_row(
3716            &inner,
3717            &SemanticNode {
3718                dom_id: Some("target".into()),
3719                id: target.as_u64(),
3720                parent: None,
3721                role: "main".into(),
3722                name: "Readable".into(),
3723                value: None,
3724                enabled: true,
3725                focusable: false,
3726                viewport_fixed: false,
3727                visible: true,
3728                selected: false,
3729                bounds: Some([0.0, 0.0, 100.0, 24.0]),
3730                slot: None,
3731                attributes: BTreeMap::new(),
3732            },
3733        )
3734        .unwrap();
3735
3736        assert_eq!(row["fontSize"], "23px");
3737        assert_eq!(row["borderColor"], "#123456ff");
3738        assert_eq!(row["borderWidth"], "2px");
3739        assert_eq!(row["hasTextContent"], true);
3740    }
3741
3742    #[test]
3743    fn native_key_event_preserves_physical_code_and_modifiers() {
3744        let event = key_event(
3745            KeyPhase::Down,
3746            Key::Character("2".into()),
3747            Code::Digit2,
3748            KeyboardModifiers::META,
3749        );
3750        assert_eq!(event.code, Code::Digit2);
3751        assert!(event.modifiers.meta());
3752        assert!(event.text.is_none());
3753    }
3754
3755    #[test]
3756    fn agent_action_settlement_drains_until_the_document_is_idle() {
3757        let mut document = TestDocument::from_html("<main>Ready</main>", DocumentConfig::default());
3758        let polls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
3759        let observed = std::sync::Arc::clone(&polls);
3760        document.set_poll_hook(move |_, _| {
3761            observed.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 3
3762        });
3763
3764        crate::in_process::settle(&mut document).unwrap();
3765
3766        assert_eq!(polls.load(std::sync::atomic::Ordering::Relaxed), 4);
3767    }
3768
3769    #[test]
3770    fn agent_action_settlement_never_acks_a_still_runnable_document() {
3771        let mut document = TestDocument::from_html("<main>Busy</main>", DocumentConfig::default());
3772        let polls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
3773        let observed = std::sync::Arc::clone(&polls);
3774        document.set_poll_hook(move |_, _| {
3775            observed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3776            true
3777        });
3778
3779        let error = crate::in_process::settle(&mut document).unwrap_err();
3780
3781        assert_eq!(error.code, "actionDidNotSettle");
3782        assert_eq!(
3783            polls.load(std::sync::atomic::Ordering::Relaxed),
3784            crate::in_process::MAX_SETTLE_POLLS
3785        );
3786    }
3787}