Skip to content

The design language that makes your AI harness better at design.

JavaScript

Visual contrast measures the copy of a repeated id it came from

Paul Bakausc8ca69168cd5
diff --git a/crates/browser/src/screenshot_contrast.rs b/crates/browser/src/screenshot_contrast.rs
index d09fc28a5..e0ddbb10d 100644
--- a/crates/browser/src/screenshot_contrast.rs
+++ b/crates/browser/src/screenshot_contrast.rs
@@ -273,13 +273,23 @@ pub fn capture_visual_contrast_candidate(
outcome
}
-const BRING_INTO_VIEW_JS: &str = r#"(async (selector) => {
- let el;
+/// `(selector, match) => element`: the element a candidate names. `match` is
+/// the candidate's `[n, count]` when its selector matched several elements
+/// (a repeated id), and then the `n`th match is the one, while the page still
+/// has `count` of them; `querySelector`'s first match would be a copy the
+/// candidate never came from. `null` for an invalid selector or no match.
+pub(crate) const PICK_CANDIDATE_JS: &str = r#"((selector, match) => {
+ let matches;
try {
- el = document.querySelector(selector);
+ matches = document.querySelectorAll(selector);
} catch (e) {
return null;
}
+ if (Array.isArray(match) && matches.length === match[1] && matches[match[0]]) return matches[match[0]];
+ return matches[0] || null;
+})"#;
+
+const BRING_INTO_VIEW_JS: &str = r#"(async (el) => {
if (!el) return null;
const saved = [];
for (let p = el.parentElement; p; p = p.parentElement) saved.push([p, p.scrollTop, p.scrollLeft]);
@@ -332,7 +342,11 @@ fn bring_into_view(
.and_then(Value::as_str)
.filter(|s| !s.is_empty())?;
let v = page
- .evaluate_value(&format!("({BRING_INTO_VIEW_JS})({})", json!(selector)))
+ .evaluate_value(&format!(
+ "({BRING_INTO_VIEW_JS})(({PICK_CANDIDATE_JS})({}, {}))",
+ json!(selector),
+ candidate.get("match").cloned().unwrap_or(Value::Null)
+ ))
.ok()?;
if v.get("moved").and_then(Value::as_bool) != Some(true) {
return None;
@@ -382,13 +396,8 @@ fn measure_candidate(
.and_then(Value::as_bool)
.unwrap_or(false);
let apply_expr = format!(
- r#"(({{ selector, token, backgroundClipText }}) => {{
- let el;
- try {{
- el = document.querySelector(selector);
- }} catch {{
- return false;
- }}
+ r#"(({{ selector, match, token, backgroundClipText }}) => {{
+ const el = ({PICK_CANDIDATE_JS})(selector, match);
if (!el) return false;
let style = document.getElementById('impeccable-visual-contrast-hide-style');
if (!style) {{
@@ -410,7 +419,7 @@ fn measure_candidate(
if (backgroundClipText) el.setAttribute('data-impeccable-bgclip-text', 'true');
return true;
}})({})"#,
- json!({ "selector": selector, "token": token, "backgroundClipText": bgclip })
+ json!({ "selector": selector, "match": candidate.get("match").cloned().unwrap_or(Value::Null), "token": token, "backgroundClipText": bgclip })
);
let applied = page.evaluate_value(&apply_expr)?;
if applied.as_bool() != Some(true) {
@@ -419,17 +428,14 @@ fn measure_candidate(
let after = page.screenshot_clip(clip.x, clip.y, clip.width, clip.height);
// finally: remove the marker attributes (errors swallowed).
let cleanup_expr = format!(
- r#"(({{ selector }}) => {{
- try {{
- const el = document.querySelector(selector);
- if (el) {{
- el.removeAttribute('data-impeccable-visual-contrast-target');
- el.removeAttribute('data-impeccable-bgclip-text');
- }}
- }} catch {{
+ r#"(({{ token }}) => {{
+ for (const el of document.querySelectorAll('[data-impeccable-visual-contrast-target]')) {{
+ if (el.getAttribute('data-impeccable-visual-contrast-target') !== token) continue;
+ el.removeAttribute('data-impeccable-visual-contrast-target');
+ el.removeAttribute('data-impeccable-bgclip-text');
}}
}})({})"#,
- json!({ "selector": selector })
+ json!({ "token": token })
);
let _ = page.evaluate(&cleanup_expr);
let after = after?;
diff --git a/crates/browser/src/snapshot_engine.rs b/crates/browser/src/snapshot_engine.rs
index f675eb910..4f0a238fc 100644
--- a/crates/browser/src/snapshot_engine.rs
+++ b/crates/browser/src/snapshot_engine.rs
@@ -290,13 +290,17 @@ fn scroll_to(page: &mut Page<'_>, x: f64, y: f64) -> CdpResult<()> {
Ok(())
}
-fn scroll_into_view(page: &mut Page<'_>, selector: &str) -> CdpResult<bool> {
+fn scroll_into_view(page: &mut Page<'_>, candidate: &Value) -> CdpResult<bool> {
+ let selector = candidate.get("selector").and_then(Value::as_str).unwrap_or("");
+ let identity = candidate.get("match").cloned().unwrap_or(Value::Null);
// Every ancestor's offset is kept before the scroll, so an element scroller
// it moves (a page that scrolls inside its body or an app shell's main) can
// be put back: `window.scrollTo` never reaches those.
let expr = format!(
- "(function(){{ let el; try {{ el = document.querySelector({}); }} catch {{ return false; }} if (!el || typeof el.scrollIntoView !== 'function') return false; const saved = window.__impeccableVisualScrollSaved || (window.__impeccableVisualScrollSaved = new Map()); for (let p = el.parentElement; p; p = p.parentElement) {{ if (!saved.has(p)) saved.set(p, [p.scrollTop, p.scrollLeft]); }} el.scrollIntoView({{ block: 'center', inline: 'nearest', behavior: 'instant' }}); return true; }})()",
- json!(selector)
+ "(function(){{ const el = ({})({}, {}); if (!el || typeof el.scrollIntoView !== 'function') return false; const saved = window.__impeccableVisualScrollSaved || (window.__impeccableVisualScrollSaved = new Map()); for (let p = el.parentElement; p; p = p.parentElement) {{ if (!saved.has(p)) saved.set(p, [p.scrollTop, p.scrollLeft]); }} el.scrollIntoView({{ block: 'center', inline: 'nearest', behavior: 'instant' }}); return true; }})()",
+ crate::screenshot_contrast::PICK_CANDIDATE_JS,
+ json!(selector),
+ identity
);
Ok(page.evaluate_value(&expr)?.as_bool() == Some(true))
}
@@ -597,8 +601,7 @@ pub fn analyze_visual_contrast(
}
let mut result = analyze_candidate(page, base, candidate)?;
if scroll_offscreen && visual::needs_scroll_retry(&result) {
- let selector = candidate.get("selector").and_then(Value::as_str).unwrap_or("");
- if scroll_into_view(page, selector)? {
+ if scroll_into_view(page, candidate)? {
retried = true;
wait_for_paint(page)?;
// Only geometry changed (the page scrolled); patch it onto the
diff --git a/crates/browser/tests/pixel_pass_identity.rs b/crates/browser/tests/pixel_pass_identity.rs
new file mode 100644
index 000000000..fc7798ced
--- /dev/null
+++ b/crates/browser/tests/pixel_pass_identity.rs
@@ -0,0 +1,72 @@
+//! The pixel pass measures the element its candidate came from when the page
+//! repeats the id the candidate's selector is anchored on. Rendered by an
+//! installed browser; skips cleanly when there is none.
+
+use std::collections::HashMap;
+use std::io::{Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::path::Path;
+
+use impeccable_browser::BrowserEngine;
+use impeccable_detect::engines::{ScanOptions, UrlEngine};
+
+fn serve(body: String) -> u16 {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
+ let port = listener.local_addr().unwrap().port();
+ std::thread::spawn(move || {
+ for stream in listener.incoming().flatten() {
+ let body = body.clone();
+ std::thread::spawn(move || handle(stream, &body));
+ }
+ });
+ port
+}
+
+fn handle(mut stream: TcpStream, body: &str) {
+ let mut buf = [0u8; 8192];
+ let _ = stream.read(&mut buf);
+ let head = format!(
+ "HTTP/1.0 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ let _ = stream.write_all(head.as_bytes());
+ let _ = stream.write_all(body.as_bytes());
+ let _ = stream.flush();
+}
+
+#[test]
+fn a_repeated_id_does_not_send_the_pixel_pass_to_a_collapsed_copy() {
+ let env: HashMap<String, String> = std::env::vars().collect();
+ if impeccable_browser::discovery::find_browser(&env).is_err() {
+ eprintln!("skip: no installed browser found");
+ return;
+ }
+ let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../tests/fixtures/antipatterns/fullpage-screenshot-scroller.html");
+ let html = std::fs::read_to_string(fixture).expect("fixture");
+ // A collapsed copy of the vector-copy paragraph, first in the document:
+ // `querySelector` answers with it, and it sits in the first viewport, so
+ // scrolling it into view moves nothing.
+ let html = html.replacen(
+ "<body>",
+ "<body>\n<div style=\"height:0;overflow:hidden\"><p id=\"flag-scroller-vector-copy\">Collapsed copy.</p></div>",
+ 1,
+ );
+ assert!(html.contains("Collapsed copy."));
+ let port = serve(html);
+ let engine = BrowserEngine::new(env);
+ let url = format!("http://127.0.0.1:{port}/");
+ let findings = engine.detect_url(&url, &ScanOptions::default()).expect("scan");
+ let pixel: Vec<&str> = findings
+ .iter()
+ .filter(|f| {
+ f.antipattern == "low-contrast"
+ && f.extras.get("selector").and_then(|v| v.as_str()) == Some("#flag-scroller-vector-copy")
+ })
+ .map(|f| f.snippet.as_str())
+ .collect();
+ assert!(
+ pixel.iter().any(|s| s.starts_with("pixel contrast ")),
+ "the vector copy past the body scroller's fold was not measured: {pixel:?}"
+ );
+}
diff --git a/crates/core/src/browser/visual.rs b/crates/core/src/browser/visual.rs
index 1635ff705..5130d7402 100644
--- a/crates/core/src/browser/visual.rs
+++ b/crates/core/src/browser/visual.rs
@@ -992,7 +992,9 @@ pub fn collect_visual_contrast_candidates(dom: &dyn Dom, options: &Value) -> Vec
});
let text = slice_utf16_prefix(&collapse_ws(js::trim(&direct)), 80);
let mut m = Map::new();
- m.insert("selector".into(), Value::String(super::driver::generate_selector(dom, el)));
+ let selector = super::driver::generate_selector(dom, el);
+ let identity = candidate_match(dom, &selector, el);
+ m.insert("selector".into(), Value::String(selector));
m.insert("tagName".into(), Value::String(tag));
m.insert("text".into(), Value::String(text));
m.insert("threshold".into(), json!(threshold));
@@ -1004,6 +1006,9 @@ pub fn collect_visual_contrast_candidates(dom: &dyn Dom, options: &Value) -> Vec
"backgroundClipText".into(),
Value::Bool(reasons.iter().any(|r| r == "background-clip text")),
);
+ if let Some(identity) = identity {
+ m.insert("match".into(), identity);
+ }
candidates.push(Value::Object(m));
}
candidates
@@ -1827,9 +1832,41 @@ fn unresolved(candidate: &Value, reason: &str) -> Value {
/// JS: index.mjs#analyzeVisualContrastCandidate — everything before the
/// sampling loop.
-pub fn prepare_analysis(dom: &dyn Dom, candidate: &Value) -> Prepared {
+/// `[n, count]` when `selector` matches `count` elements and `el` is the
+/// `n`th, in document order. A generated selector names one element unless
+/// the page repeats the id that anchors it (a search box rendered once per
+/// breakpoint), and then the first match can be a collapsed copy the
+/// candidate never came from. `None` for a selector that names one element.
+fn candidate_match(dom: &dyn Dom, selector: &str, el: ElId) -> Option<Value> {
+ if !selector.contains('#') {
+ return None;
+ }
+ let matches = dom.query_all(None, selector).ok()?;
+ if matches.len() < 2 {
+ return None;
+ }
+ let n = matches.iter().position(|m| *m == el)?;
+ Some(json!([n, matches.len()]))
+}
+
+/// The element a candidate names: the `n`th match its `match` field records
+/// while the page still has that many, the first match otherwise.
+pub fn candidate_element(dom: &dyn Dom, candidate: &Value) -> Result<Option<ElId>, ()> {
let selector = str_or_empty(candidate.get("selector"));
- let el = match dom.query_one(None, &selector) {
+ let identity = candidate.get("match").and_then(Value::as_array).and_then(|a| {
+ Some((a.first()?.as_u64()? as usize, a.get(1)?.as_u64()? as usize))
+ });
+ match identity {
+ Some((n, count)) => {
+ let matches = dom.query_all(None, &selector).map_err(|_| ())?;
+ Ok(if matches.len() == count { matches.get(n).copied() } else { matches.first().copied() })
+ }
+ None => dom.query_one(None, &selector).map_err(|_| ()),
+ }
+}
+
+pub fn prepare_analysis(dom: &dyn Dom, candidate: &Value) -> Prepared {
+ let el = match candidate_element(dom, candidate) {
Err(_) => return Prepared::Early { early: unresolved(candidate, "stale selector") },
Ok(None) => return Prepared::Early { early: unresolved(candidate, "missing element") },
Ok(Some(el)) => el,