Skip to content

armgit / iris

Public Imported from GitHub
0

Screenshots of live websites. Minimal interface, powerful engine.

Add precise element capture and JSON reporting

Bridger Towerdc1d744b0ca0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3185492..f1808bb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -16,4 +16,5 @@ jobs:
- uses: Swatinem/rust-cache@v2
- run: cargo fmt --check
- run: cargo clippy -- -D warnings
+ - run: cargo test
- run: cargo build
diff --git a/Cargo.lock b/Cargo.lock
index 21b9ec9..4e45fe9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -657,12 +657,13 @@ checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78"
[[package]]
name = "iris"
-version = "0.2.0"
+version = "0.3.0"
dependencies = [
"anyhow",
"chromiumoxide",
"clap",
"futures",
+ "serde",
"serde_json",
"tokio",
"url",
diff --git a/Cargo.toml b/Cargo.toml
index 41a9e46..fa86e8c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "iris"
-version = "0.2.0"
+version = "0.3.0"
edition = "2024"
rust-version = "1.85"
description = "Minimal, powerful screenshots of live websites"
@@ -15,6 +15,7 @@ anyhow = "1"
clap = { version = "4", features = ["derive", "env"] }
chromiumoxide = { version = "0.7", default-features = false, features = ["tokio-runtime"] }
futures = "0.3"
+serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "fs"] }
url = "2"
diff --git a/README.md b/README.md
index d96e40c..2c32568 100644
--- a/README.md
+++ b/README.md
@@ -6,9 +6,11 @@ Screenshots of live websites. Minimal interface, powerful engine.
iris example.com # 1440×900 @2x → example.com.png
iris --full --dark tailwindcss.com # full page, dark color scheme
iris --size iphone stripe.com # 390×844 @3x with a mobile UA
+iris --selector '#hero' --padding 24 app.dev # first matching element, tightly framed
iris -o shots/ a.com b.com c.com # batch, captured concurrently
cat urls.txt | iris - -o shots/ # batch from stdin (# comments ok)
iris -o hero.jpg --wait-for 'h1' app.dev
+iris --selector 'h1' --json app.dev # machine-readable JSON Lines
```
`iris --full bridger.to` →
@@ -33,10 +35,18 @@ The only runtime dependency is an installed Chrome-family browser (Chrome, Chrom
- Renders with your real installed Chrome, driven over the DevTools Protocol
- Waits for fonts, image loads, entrance animations, and — on `--full` — scroll-triggers lazy-loaded content before capturing
+- Captures the first matching element with `--selector`, automatically scrolling it into view and settling newly visible content before framing it
- Retina `@2x` output by default; full pages taller than Chrome's ~16k px render limit fall back to `@1x` automatically (the report tells you which you got)
- Image format from the `-o` extension or `--format`: `png` (default), `jpg`, `webp` (JPEG/WebP encode at quality 90)
- One browser process, concurrent tabs; a failed URL prints `✗` and never kills the batch (exit code 1 if anything failed)
- Batch filenames derive from the URL (`example.com-pricing.png`); collisions get `-2`, `-3` suffixes
+- `--json` writes one JSON object per completed capture to stdout, in concurrent completion order; capture failures are JSON too and still produce exit code 1
+
+Element capture is intentionally CSS-selector based: Iris captures the first match in document order. `--selector` conflicts with `--full`; `--padding` requires it. Cross-origin iframe contents and capturing every match are not supported.
+
+```json
+{"status":"ok","url":"https://example.com/","output":"/absolute/example.com.png","mode":"element","selector":"h1","padding":24,"css_width":180,"css_height":72,"scale":2.0,"format":"png","bytes":14231}
+```
## Flags
@@ -44,6 +54,8 @@ The only runtime dependency is an installed Chrome-family browser (Chrome, Chrom
-o, --out <PATH> output file (single URL) or directory (batch)
-s, --size <SIZE> WxH, or desktop (1440x900@2x) | iphone (390x844@3x) | ipad (1024x1366@2x)
--full capture the full page height
+ --selector <CSS> capture the first element matching a CSS selector
+ --padding <PX> nonnegative CSS-pixel padding around a selected element
--dark emulate prefers-color-scheme: dark
--format <FMT> png | jpg | webp (a recognized --out extension wins)
--wait <MS> extra settle delay after smart waiting
@@ -52,6 +64,7 @@ The only runtime dependency is an installed Chrome-family browser (Chrome, Chrom
--jobs <N> concurrent captures (default: min(4, URLs))
--timeout <SECS> per-page budget (default: 30)
--chrome <PATH> browser binary (auto-detected; also via $CHROME)
+ --json emit one JSON object per completed capture
```
## License
diff --git a/src/capture.rs b/src/capture.rs
index a2d179b..6931c82 100644
--- a/src/capture.rs
+++ b/src/capture.rs
@@ -7,11 +7,14 @@ use chromiumoxide::cdp::browser_protocol::emulation::{
MediaFeature, SetDeviceMetricsOverrideParams, SetEmulatedMediaParams,
SetUserAgentOverrideParams,
};
-use chromiumoxide::cdp::browser_protocol::page::CaptureScreenshotFormat;
+use chromiumoxide::cdp::browser_protocol::page::{
+ CaptureScreenshotFormat, Viewport as ScreenshotViewport,
+};
use chromiumoxide::cdp::js_protocol::runtime::EvaluateParams;
use chromiumoxide::error::CdpError;
use chromiumoxide::page::{Page, ScreenshotParams};
use futures::StreamExt;
+use serde::Deserialize;
use tokio::task::JoinHandle;
const IPHONE_UA: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) \
@@ -59,9 +62,40 @@ impl Format {
}
}
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum CaptureMode {
+ Viewport,
+ FullPage,
+ Element { selector: String, padding: u32 },
+}
+
+impl CaptureMode {
+ pub fn name(&self) -> &'static str {
+ match self {
+ Self::Viewport => "viewport",
+ Self::FullPage => "full_page",
+ Self::Element { .. } => "element",
+ }
+ }
+
+ pub fn selector(&self) -> Option<&str> {
+ match self {
+ Self::Element { selector, .. } => Some(selector),
+ _ => None,
+ }
+ }
+
+ pub fn padding(&self) -> Option<u32> {
+ match self {
+ Self::Element { padding, .. } => Some(*padding),
+ _ => None,
+ }
+ }
+}
+
pub struct Opts {
pub viewport: Viewport,
- pub full: bool,
+ pub mode: CaptureMode,
pub dark: bool,
pub wait_ms: u64,
pub wait_for: Option<String>,
@@ -69,8 +103,10 @@ pub struct Opts {
pub format: Format,
}
+#[derive(Debug)]
pub struct Shot {
- /// Captured page height in CSS pixels (viewport height, or document height when full).
+ /// Captured width and height in CSS pixels.
+ pub width: u32,
pub height: u32,
/// Device scale factor actually used (full-page shots too tall for Chrome's
/// ~16k texture limit fall back to 1x).
@@ -78,6 +114,24 @@ pub struct Shot {
pub bytes: u64,
}
+#[derive(Debug, Deserialize)]
+struct ElementBounds {
+ x: f64,
+ y: f64,
+ width: f64,
+ height: f64,
+ doc_width: f64,
+ doc_height: f64,
+}
+
+#[derive(Debug, PartialEq)]
+struct ClipRect {
+ x: f64,
+ y: f64,
+ width: f64,
+ height: f64,
+}
+
pub struct Session {
browser: Browser,
handler: JoinHandle<()>,
@@ -185,49 +239,109 @@ impl Session {
self.eval(page, wait_for_js(selector, budget.as_millis() as u64))
.await?;
}
- if opts.full {
- self.eval(page, SCROLL_JS.into()).await?;
+ match &opts.mode {
+ CaptureMode::Viewport => {}
+ CaptureMode::FullPage => {
+ self.eval(page, SCROLL_JS.into()).await?;
+ }
+ CaptureMode::Element { selector, .. } => {
+ let budget = opts
+ .timeout
+ .saturating_sub(started.elapsed())
+ .saturating_sub(Duration::from_millis(500));
+ self.eval(
+ page,
+ wait_and_scroll_js(selector, budget.as_millis() as u64),
+ )
+ .await?;
+ // Scrolling can start image loads, IntersectionObservers, and
+ // entrance transitions that the initial settle could not see.
+ self.eval(page, SETTLE_JS.into()).await?;
+ }
}
if opts.wait_ms > 0 {
tokio::time::sleep(Duration::from_millis(opts.wait_ms)).await;
self.eval(page, SETTLE_JS.into()).await?;
}
- let mut params = ScreenshotParams::builder().format(opts.format.cdp());
- if opts.format != Format::Png {
- params = params.quality(90);
- }
+ let screenshot_params = || {
+ let mut params = ScreenshotParams::builder().format(opts.format.cdp());
+ if opts.format != Format::Png {
+ params = params.quality(90);
+ }
+ params
+ };
- let (height, scale, data) = if opts.full {
- let doc_h = self
- .eval_u32(page, DOC_HEIGHT_JS)
- .await
- .unwrap_or(v.height)
- .max(v.height);
- if doc_h as f64 * v.scale <= 16_000.0 {
- // Retina full page: grow the viewport to the whole document so the
- // scale factor still applies (CDP's captureBeyondViewport renders at 1x).
- page.execute(
- SetDeviceMetricsOverrideParams::builder()
- .width(v.width as i64)
- .height(doc_h as i64)
- .device_scale_factor(v.scale)
- .mobile(v.mobile)
- .build()
- .map_err(|e| anyhow!(e))?,
- )
- .await?;
- self.eval(page, SETTLE_JS.into()).await?;
- (doc_h, v.scale, page.screenshot(params.build()).await?)
- } else {
+ let (width, height, scale, data) = match &opts.mode {
+ CaptureMode::Viewport => (
+ v.width,
+ v.height,
+ v.scale,
+ page.screenshot(screenshot_params().build()).await?,
+ ),
+ CaptureMode::FullPage => {
+ let doc_h = self
+ .eval_u32(page, DOC_HEIGHT_JS)
+ .await
+ .unwrap_or(v.height)
+ .max(v.height);
+ if doc_h as f64 * v.scale <= 16_000.0 {
+ // Retina full page: grow the viewport to the whole document so the
+ // scale factor still applies (CDP's captureBeyondViewport renders at 1x).
+ page.execute(
+ SetDeviceMetricsOverrideParams::builder()
+ .width(v.width as i64)
+ .height(doc_h as i64)
+ .device_scale_factor(v.scale)
+ .mobile(v.mobile)
+ .build()
+ .map_err(|e| anyhow!(e))?,
+ )
+ .await?;
+ self.eval(page, SETTLE_JS.into()).await?;
+ (
+ v.width,
+ doc_h,
+ v.scale,
+ page.screenshot(screenshot_params().build()).await?,
+ )
+ } else {
+ (
+ v.width,
+ doc_h,
+ 1.0,
+ page.screenshot(screenshot_params().full_page(true).build())
+ .await?,
+ )
+ }
+ }
+ CaptureMode::Element { selector, padding } => {
+ let value = self.eval(page, element_bounds_js(selector)).await?;
+ let bounds: ElementBounds = serde_json::from_value(value)
+ .context("failed to read selected element bounds")?;
+ let clip = round_clip(&bounds, *padding)
+ .with_context(|| format!("cannot capture selected element: {selector}"))?;
+ let cdp_clip = ScreenshotViewport::builder()
+ .x(clip.x)
+ .y(clip.y)
+ .width(clip.width)
+ .height(clip.height)
+ .scale(1.0)
+ .build()
+ .map_err(|e| anyhow!(e))?;
(
- doc_h,
- 1.0,
- page.screenshot(params.full_page(true).build()).await?,
+ clip.width as u32,
+ clip.height as u32,
+ v.scale,
+ page.screenshot(
+ screenshot_params()
+ .clip(cdp_clip)
+ .capture_beyond_viewport(true)
+ .build(),
+ )
+ .await?,
)
}
- } else {
- (v.height, v.scale, page.screenshot(params.build()).await?)
};
let bytes = data.len() as u64;
@@ -235,6 +349,7 @@ impl Session {
.await
.with_context(|| format!("failed to write {}", out.display()))?;
Ok(Shot {
+ width,
height,
scale,
bytes,
@@ -367,13 +482,312 @@ const DOC_HEIGHT_JS: &str = r#"Math.max(
)"#;
fn wait_for_js(selector: &str, budget_ms: u64) -> String {
+ let selector = serde_json::to_string(selector).expect("selector is serializable");
+ format!(
+ r#"(async () => {{
+ const deadline = Date.now() + {budget_ms};
+ const selector = {selector};
+ const find = () => {{
+ try {{ return document.querySelector(selector); }}
+ catch {{ throw new Error("invalid selector: " + selector); }}
+ }};
+ while (!find()) {{
+ if (Date.now() >= deadline) throw new Error("selector never appeared: " + selector);
+ await new Promise(r => setTimeout(r, 100));
+ }}
+}})()"#
+ )
+}
+
+fn wait_and_scroll_js(selector: &str, budget_ms: u64) -> String {
+ let selector = serde_json::to_string(selector).expect("selector is serializable");
format!(
r#"(async () => {{
const deadline = Date.now() + {budget_ms};
- while (!document.querySelector({selector:?})) {{
- if (Date.now() > deadline) throw new Error("selector never appeared: " + {selector:?});
+ const selector = {selector};
+ const find = () => {{
+ try {{ return document.querySelector(selector); }}
+ catch {{ throw new Error("invalid selector: " + selector); }}
+ }};
+ let element;
+ while (!(element = find())) {{
+ if (Date.now() >= deadline) throw new Error("selector never appeared: " + selector);
await new Promise(r => setTimeout(r, 100));
}}
+ element.scrollIntoView({{ block: "center", inline: "center" }});
+ await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
+}})()"#
+ )
+}
+
+fn element_bounds_js(selector: &str) -> String {
+ let selector = serde_json::to_string(selector).expect("selector is serializable");
+ format!(
+ r#"(() => {{
+ const selector = {selector};
+ let element;
+ try {{ element = document.querySelector(selector); }}
+ catch {{ throw new Error("invalid selector: " + selector); }}
+ if (!element) throw new Error("selector disappeared: " + selector);
+ const rect = element.getBoundingClientRect();
+ if (![rect.x, rect.y, rect.width, rect.height].every(Number.isFinite) ||
+ rect.width <= 0 || rect.height <= 0) {{
+ throw new Error("element has no rendered size: " + selector);
+ }}
+ return {{
+ x: rect.left + window.scrollX,
+ y: rect.top + window.scrollY,
+ width: rect.width,
+ height: rect.height,
+ doc_width: Math.max(
+ document.body?.scrollWidth ?? 0,
+ document.documentElement.scrollWidth,
+ document.documentElement.clientWidth
+ ),
+ doc_height: Math.max(
+ document.body?.scrollHeight ?? 0,
+ document.documentElement.scrollHeight,
+ document.documentElement.clientHeight
+ )
+ }};
}})()"#
)
}
+
+fn round_clip(bounds: &ElementBounds, padding: u32) -> Result<ClipRect> {
+ let padding = padding as f64;
+ let left = (bounds.x - padding).floor().clamp(0.0, bounds.doc_width);
+ let top = (bounds.y - padding).floor().clamp(0.0, bounds.doc_height);
+ let right = (bounds.x + bounds.width + padding)
+ .ceil()
+ .clamp(0.0, bounds.doc_width);
+ let bottom = (bounds.y + bounds.height + padding)
+ .ceil()
+ .clamp(0.0, bounds.doc_height);
+
+ if ![left, top, right, bottom].iter().all(|n| n.is_finite()) {
+ bail!("selected element returned invalid bounds");
+ }
+ if right <= left || bottom <= top {
+ bail!("selected element is outside the document bounds");
+ }
+
+ Ok(ClipRect {
+ x: left,
+ y: top,
+ width: right - left,
+ height: bottom - top,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn clip_rounds_outward_and_applies_padding() {
+ let clip = round_clip(
+ &ElementBounds {
+ x: 10.25,
+ y: 20.75,
+ width: 100.5,
+ height: 50.5,
+ doc_width: 200.0,
+ doc_height: 200.0,
+ },
+ 5,
+ )
+ .unwrap();
+ assert_eq!(
+ clip,
+ ClipRect {
+ x: 5.0,
+ y: 15.0,
+ width: 111.0,
+ height: 62.0,
+ }
+ );
+ }
+
+ #[test]
+ fn clip_clamps_to_each_document_edge() {
+ let top_left = round_clip(
+ &ElementBounds {
+ x: 1.2,
+ y: 1.2,
+ width: 20.2,
+ height: 30.2,
+ doc_width: 200.0,
+ doc_height: 200.0,
+ },
+ 10,
+ )
+ .unwrap();
+ assert_eq!(
+ top_left,
+ ClipRect {
+ x: 0.0,
+ y: 0.0,
+ width: 32.0,
+ height: 42.0,
+ }
+ );
+
+ let bottom_right = round_clip(
+ &ElementBounds {
+ x: 190.4,
+ y: 180.4,
+ width: 20.0,
+ height: 30.0,
+ doc_width: 200.0,
+ doc_height: 200.0,
+ },
+ 5,
+ )
+ .unwrap();
+ assert_eq!(
+ bottom_right,
+ ClipRect {
+ x: 185.0,
+ y: 175.0,
+ width: 15.0,
+ height: 25.0,
+ }
+ );
+ }
+
+ #[tokio::test]
+ async fn browser_element_capture_contract() -> Result<()> {
+ let temp = std::env::temp_dir().join(format!("iris-browser-{}", std::process::id()));
+ tokio::fs::create_dir_all(&temp).await?;
+ let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures/precise-capture.html")
+ .canonicalize()?;
+ let url = url::Url::from_file_path(&fixture)
+ .map_err(|_| anyhow!("fixture path is not a file URL"))?;
+ let viewport = Viewport {
+ width: 320,
+ height: 240,
+ scale: 1.0,
+ mobile: false,
+ };
+ let session = Session::launch(None, viewport).await?;
+
+ let one_x_path = temp.join("target-1x.png");
+ let one_x = session
+ .capture(
+ url.as_str(),
+ &one_x_path,
+ &element_opts(viewport, ".capture-target", 10, Format::Png),
+ )
+ .await?;
+ // The first duplicate starts at 80.5px and transitions to 120.5px only
+ // after scrolling into view. The final 141x81 frame proves first-match,
+ // automatic scroll/settle, outward rounding, and padding together.
+ assert_eq!((one_x.width, one_x.height), (141, 81));
+ assert_eq!(
+ png_dimensions(&tokio::fs::read(&one_x_path).await?),
+ (141, 81)
+ );
+
+ let two_x_viewport = Viewport {
+ scale: 2.0,
+ ..viewport
+ };
+ let two_x_path = temp.join("target-2x.png");
+ let two_x = session
+ .capture(
+ url.as_str(),
+ &two_x_path,
+ &element_opts(two_x_viewport, ".capture-target", 10, Format::Png),
+ )
+ .await?;
+ assert_eq!((two_x.width, two_x.height), (141, 81));
+ assert_eq!(
+ png_dimensions(&tokio::fs::read(&two_x_path).await?),
+ (282, 162)
+ );
+
+ let jpeg_path = temp.join("target.jpg");
+ session
+ .capture(
+ url.as_str(),
+ &jpeg_path,
+ &element_opts(viewport, ".capture-target", 0, Format::Jpeg),
+ )
+ .await?;
+ let jpeg = tokio::fs::read(&jpeg_path).await?;
+ assert!(jpeg.starts_with(&[0xff, 0xd8, 0xff]));
+
+ let webp_path = temp.join("target.webp");
+ session
+ .capture(
+ url.as_str(),
+ &webp_path,
+ &element_opts(viewport, ".capture-target", 0, Format::Webp),
+ )
+ .await?;
+ let webp = tokio::fs::read(&webp_path).await?;
+ assert_eq!(&webp[..4], b"RIFF");
+ assert_eq!(&webp[8..12], b"WEBP");
+
+ let invalid = session
+ .capture(
+ url.as_str(),
+ &temp.join("invalid.png"),
+ &element_opts(viewport, "[", 0, Format::Png),
+ )
+ .await
+ .unwrap_err();
+ assert!(format!("{invalid:#}").contains("invalid selector: ["));
+
+ let mut missing_url = url.clone();
+ missing_url.set_query(Some("missing=1"));
+ let missing = session
+ .capture(
+ missing_url.as_str(),
+ &temp.join("missing.png"),
+ &element_opts(viewport, ".capture-target", 0, Format::Png),
+ )
+ .await
+ .unwrap_err();
+ assert!(format!("{missing:#}").contains("selector never appeared: .capture-target"));
+
+ let zero = session
+ .capture(
+ url.as_str(),
+ &temp.join("zero.png"),
+ &element_opts(viewport, "#zero-size", 0, Format::Png),
+ )
+ .await
+ .unwrap_err();
+ assert!(format!("{zero:#}").contains("element has no rendered size: #zero-size"));
+
+ session.close().await;
+ tokio::fs::remove_dir_all(temp).await?;
+ Ok(())
+ }
+
+ fn element_opts(viewport: Viewport, selector: &str, padding: u32, format: Format) -> Opts {
+ Opts {
+ viewport,
+ mode: CaptureMode::Element {
+ selector: selector.into(),
+ padding,
+ },
+ dark: false,
+ wait_ms: 0,
+ wait_for: None,
+ timeout: Duration::from_secs(3),
+ format,
+ }
+ }
+
+ fn png_dimensions(bytes: &[u8]) -> (u32, u32) {
+ assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
+ (
+ u32::from_be_bytes(bytes[16..20].try_into().unwrap()),
+ u32::from_be_bytes(bytes[20..24].try_into().unwrap()),
+ )
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 0abf82d..bde61ab 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -7,9 +7,10 @@ use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result, bail};
-use capture::{Format, Opts, Session, Viewport};
+use capture::{CaptureMode, Format, Opts, Session, Shot, Viewport};
use clap::Parser;
use futures::StreamExt;
+use serde::Serialize;
use url::Url;
/// Screenshot live websites. Minimal interface, powerful engine:
@@ -23,6 +24,7 @@ use url::Url;
Examples:
iris example.com 1440\u{d7}900 @2x \u{2192} example.com.png
iris --full --dark tailwindcss.com full page, dark color scheme
+ iris --selector '#hero' --padding 24 app.dev
cat urls.txt | iris - -o shots/ concurrent batch from stdin"
)]
struct Cli {
@@ -42,6 +44,14 @@ struct Cli {
#[arg(long)]
full: bool,
+ /// Capture the first element matching this CSS selector
+ #[arg(long, value_name = "CSS", conflicts_with = "full")]
+ selector: Option<String>,
+
+ /// Uniform CSS-pixel padding around a selected element
+ #[arg(long, value_name = "PX", requires = "selector")]
+ padding: Option<u32>,
+
/// Emulate prefers-color-scheme: dark
#[arg(long)]
dark: bool,
@@ -73,6 +83,40 @@ struct Cli {
/// Chrome/Chromium binary [auto-detected]
#[arg(long, env = "CHROME", value_name = "PATH")]
chrome: Option<PathBuf>,
+
+ /// Emit one JSON object per completed capture
+ #[arg(long)]
+ json: bool,
+}
+
+#[derive(Serialize)]
+struct SuccessReport<'a> {
+ status: &'static str,
+ url: &'a str,
+ output: String,
+ mode: &'static str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ selector: Option<&'a str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ padding: Option<u32>,
+ css_width: u32,
+ css_height: u32,
+ scale: f64,
+ format: &'static str,
+ bytes: u64,
+}
+
+#[derive(Serialize)]
+struct ErrorReport<'a> {
+ status: &'static str,
+ url: &'a str,
+ output: String,
+ mode: &'static str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ selector: Option<&'a str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ padding: Option<u32>,
+ error: String,
}
#[tokio::main]
@@ -81,13 +125,14 @@ async fn main() -> Result<()> {
let urls = collect_urls(&cli.urls)?;
let viewport = parse_size(&cli.size, cli.scale)?;
+ let mode = capture_mode(&cli);
let flag_format = cli.format.as_deref().and_then(Format::from_ext);
let (targets, format) = resolve_outputs(&urls, cli.out.as_deref(), flag_format).await?;
let jobs = cli.jobs.unwrap_or_else(|| urls.len().min(4)).max(1);
let opts = Arc::new(Opts {
viewport,
- full: cli.full,
+ mode: mode.clone(),
dark: cli.dark,
wait_ms: cli.wait,
wait_for: cli.wait_for,
@@ -115,17 +160,44 @@ async fn main() -> Result<()> {
while let Some((url, path, result)) = stream.next().await {
match result {
- Ok(shot) => println!(
- "\u{2713} {} \u{2014} {}\u{d7}{} @{}x, {}",
- path.display(),
- viewport.width,
- shot.height,
- shot.scale,
- human_size(shot.bytes),
- ),
+ Ok(shot) => {
+ if cli.json {
+ println!(
+ "{}",
+ serde_json::to_string(&success_report(
+ url.as_str(),
+ &path,
+ &mode,
+ format,
+ &shot,
+ ))?
+ );
+ } else {
+ println!(
+ "\u{2713} {} \u{2014} {}\u{d7}{} @{}x, {}",
+ path.display(),
+ shot.width,
+ shot.height,
+ shot.scale,
+ human_size(shot.bytes),
+ );
+ }
+ }
Err(err) => {
failed += 1;
- eprintln!("\u{2717} {url} \u{2014} {err:#}");
+ if cli.json {
+ println!(
+ "{}",
+ serde_json::to_string(&error_report(
+ url.as_str(),
+ &path,
+ &mode,
+ format!("{err:#}"),
+ ))?
+ );
+ } else {
+ eprintln!("\u{2717} {url} \u{2014} {err:#}");
+ }
}
}
}
@@ -141,6 +213,65 @@ async fn main() -> Result<()> {
Ok(())
}
+fn capture_mode(cli: &Cli) -> CaptureMode {
+ if let Some(selector) = &cli.selector {
+ CaptureMode::Element {
+ selector: selector.clone(),
+ padding: cli.padding.unwrap_or(0),
+ }
+ } else if cli.full {
+ CaptureMode::FullPage
+ } else {
+ CaptureMode::Viewport
+ }
+}
+
+fn success_report<'a>(
+ url: &'a str,
+ path: &std::path::Path,
+ mode: &'a CaptureMode,
+ format: Format,
+ shot: &Shot,
+) -> SuccessReport<'a> {
+ SuccessReport {
+ status: "ok",
+ url,
+ output: absolute_output(path),
+ mode: mode.name(),
+ selector: mode.selector(),
+ padding: mode.padding(),
+ css_width: shot.width,
+ css_height: shot.height,
+ scale: shot.scale,
+ format: format.ext(),
+ bytes: shot.bytes,
+ }
+}
+
+fn error_report<'a>(
+ url: &'a str,
+ path: &std::path::Path,
+ mode: &'a CaptureMode,
+ error: String,
+) -> ErrorReport<'a> {
+ ErrorReport {
+ status: "error",
+ url,
+ output: absolute_output(path),
+ mode: mode.name(),
+ selector: mode.selector(),
+ padding: mode.padding(),
+ error,
+ }
+}
+
+fn absolute_output(path: &std::path::Path) -> String {
+ std::path::absolute(path)
+ .unwrap_or_else(|_| path.to_path_buf())
+ .to_string_lossy()
+ .into_owned()
+}
+
fn collect_urls(args: &[String]) -> Result<Vec<Url>> {
let mut raw = Vec::new();
for arg in args {
@@ -264,3 +395,96 @@ fn human_size(bytes: u64) -> String {
format!("{} KB", bytes.div_ceil(1024))
}
}
+
+#[cfg(test)]
+mod tests {
+ use clap::error::ErrorKind;
+
+ use super::*;
+
+ #[test]
+ fn selector_conflicts_with_full_page() {
+ let error = Cli::try_parse_from(["iris", "example.com", "--selector", "h1", "--full"])
+ .err()
+ .unwrap();
+ assert_eq!(error.kind(), ErrorKind::ArgumentConflict);
+ }
+
+ #[test]
+ fn padding_requires_a_selector_and_rejects_negative_values() {
+ let missing_selector = Cli::try_parse_from(["iris", "example.com", "--padding", "12"])
+ .err()
+ .unwrap();
+ assert_eq!(missing_selector.kind(), ErrorKind::MissingRequiredArgument);
+
+ let negative =
+ Cli::try_parse_from(["iris", "example.com", "--selector", "h1", "--padding=-1"])
+ .err()
+ .unwrap();
+ assert_eq!(negative.kind(), ErrorKind::ValueValidation);
+ }
+
+ #[test]
+ fn capture_mode_is_constructed_once_from_validated_cli() {
+ let element = Cli::try_parse_from([
+ "iris",
+ "example.com",
+ "--selector",
+ "main > h1",
+ "--padding",
+ "24",
+ ])
+ .unwrap();
+ assert_eq!(
+ capture_mode(&element),
+ CaptureMode::Element {
+ selector: "main > h1".into(),
+ padding: 24,
+ }
+ );
+
+ let full = Cli::try_parse_from(["iris", "example.com", "--full"]).unwrap();
+ assert_eq!(capture_mode(&full), CaptureMode::FullPage);
+
+ let viewport = Cli::try_parse_from(["iris", "example.com"]).unwrap();
+ assert_eq!(capture_mode(&viewport), CaptureMode::Viewport);
+ }
+
+ #[test]
+ fn json_reports_have_stable_typed_fields() {
+ let mode = CaptureMode::Element {
+ selector: "h1".into(),
+ padding: 24,
+ };
+ let shot = Shot {
+ width: 180,
+ height: 72,
+ scale: 2.0,
+ bytes: 14_231,
+ };
+ let success = serde_json::to_string(&success_report(
+ "https://example.com/",
+ std::path::Path::new("/tmp/example.png"),
+ &mode,
+ Format::Png,
+ &shot,
+ ))
+ .unwrap();
+ assert_eq!(
+ success,
+ r#"{"status":"ok","url":"https://example.com/","output":"/tmp/example.png","mode":"element","selector":"h1","padding":24,"css_width":180,"css_height":72,"scale":2.0,"format":"png","bytes":14231}"#
+ );
+
+ let failure = serde_json::to_string(&error_report(
+ "https://example.com/",
+ std::path::Path::new("/tmp/example.png"),
+ &mode,
+ "selector never appeared: h1".into(),
+ ))
+ .unwrap();
+ assert_eq!(
+ failure,
+ r#"{"status":"error","url":"https://example.com/","output":"/tmp/example.png","mode":"element","selector":"h1","padding":24,"error":"selector never appeared: h1"}"#
+ );
+ }
+}
diff --git a/tests/cli.rs b/tests/cli.rs
new file mode 100644
index 0000000..28463c9
--- /dev/null
+++ b/tests/cli.rs
@@ -0,0 +1,82 @@
+use std::process::Command;
+
+use serde_json::Value;
+use url::Url;
+
+#[test]
+fn json_batch_reports_success_and_failure_on_stdout() {
+ let temp = std::env::temp_dir().join(format!("iris-json-batch-{}", std::process::id()));
+ std::fs::create_dir_all(&temp).unwrap();
+
+ let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures/precise-capture.html")
+ .canonicalize()
+ .unwrap();
+ let success_url = Url::from_file_path(&fixture).unwrap();
+ let mut missing_url = success_url.clone();
+ missing_url.set_query(Some("missing=1"));
+
+ let output = Command::new(env!("CARGO_BIN_EXE_iris"))
+ .current_dir(&temp)
+ .args([
+ "--selector",
+ ".capture-target",
+ "--padding",
+ "8",
+ "--scale",
+ "1",
+ "--timeout",
+ "3",
+ "--jobs",
+ "2",
+ "--json",
+ "-o",
+ "shots",
+ success_url.as_str(),
+ missing_url.as_str(),
+ ])
+ .output()
+ .unwrap();
+
+ assert_eq!(output.status.code(), Some(1));
+ assert!(
+ output.stderr.is_empty(),
+ "JSON capture errors must not leak to stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ let reports: Vec<Value> = stdout
+ .lines()
+ .map(|line| serde_json::from_str(line).unwrap())
+ .collect();
+ assert_eq!(reports.len(), 2);
+
+ let success = reports
+ .iter()
+ .find(|report| report["status"] == "ok")
+ .unwrap();
+ let failure = reports
+ .iter()
+ .find(|report| report["status"] == "error")
+ .unwrap();
+
+ assert_eq!(success["mode"], "element");
+ assert_eq!(success["selector"], ".capture-target");
+ assert_eq!(success["padding"], 8);
+ assert!(success["output"].as_str().unwrap().starts_with('/'));
+ assert!(std::path::Path::new(success["output"].as_str().unwrap()).exists());
+
+ assert_eq!(failure["mode"], "element");
+ assert_eq!(failure["selector"], ".capture-target");
+ assert_eq!(failure["padding"], 8);
+ assert!(failure["output"].as_str().unwrap().starts_with('/'));
+ assert!(
+ failure["error"]
+ .as_str()
+ .unwrap()
+ .contains("selector never appeared: .capture-target")
+ );
+
+ std::fs::remove_dir_all(temp).unwrap();
+}
diff --git a/tests/fixtures/precise-capture.html b/tests/fixtures/precise-capture.html
new file mode 100644
index 0000000..6f368a7
--- /dev/null
+++ b/tests/fixtures/precise-capture.html
@@ -0,0 +1,74 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Iris precise capture fixture</title>
+ <style>
+ html,
+ body {
+ margin: 0;
+ min-height: 100%;
+ background: #f5f3ee;
+ }
+
+ .spacer {
+ height: 1100px;
+ }
+
+ .capture-target {
+ box-sizing: border-box;
+ margin-left: 40.25px;
+ width: 80.5px;
+ height: 60.5px;
+ border: 4px solid #10231b;
+ background: #2bc477;
+ opacity: 0;
+ transition: width 180ms linear, opacity 180ms linear;
+ }
+
+ .capture-target.visible {
+ width: 120.5px;
+ opacity: 1;
+ }
+
+ .capture-target.second {
+ width: 240px;
+ height: 100px;
+ margin-top: 300px;
+ opacity: 1;
+ transition: none;
+ }
+
+ #zero-size {
+ width: 0;
+ height: 0;
+ overflow: hidden;
+ }
+
+ .tail {
+ height: 500px;
+ }
+ </style>
+ </head>
+ <body>
+ <div class="spacer"></div>
+ <div class="capture-target">first</div>
+ <div class="capture-target second">second</div>
+ <div id="zero-size"></div>
+ <div class="tail"></div>
+ <script>
+ if (new URLSearchParams(location.search).has("missing")) {
+ document.querySelectorAll(".capture-target").forEach((element) => element.remove());
+ } else {
+ const first = document.querySelector(".capture-target");
+ new IntersectionObserver((entries, observer) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ first.classList.add("visible");
+ observer.disconnect();
+ }
+ }).observe(first);
+ }
+ </script>
+ </body>
+</html>