UI Caliper
by ShellMonster
README.md
# UI Caliper (`ui-caliper` / `caliper`)
[](https://github.com/ShellMonster/ui-caliper/actions/workflows/ci.yml)
[](https://github.com/ShellMonster/ui-caliper/releases)
[](./LICENSE)
**English** | [简体中文](./README.zh-CN.md)
A cross-platform **invisible pixel-rail geometry, pixel-ink optical centering, spacing, and multi-layer layout analyzer** for **Web (React / Vue / native HTML / Electron / Wails), native iOS, and native Android** (CLI · stdio MCP Server · TypeScript SDK).
Instead of relying on brittle full-page pixel diffs, UI Caliper measures **runtime logical coordinates (`px` / `pt` / `dp`) combined with high-DPI local pixel ink** to automatically catch subtle visual defects that look "off" to the human eye yet are tedious to audit manually: 2–10 px near-miss alignment drifts, uneven sibling gaps, asymmetric card padding, vertically or horizontally off-center text inside pills/buttons/inputs, icon-to-text misalignment, element collisions & clipping, misaligned dropdown/popover layers, and mobile safe-area or touch-target violations — and generates an interactive HTML report featuring a **side-by-side high-DPI redline close-up wall**.
---
## Visual Showcase
### Interactive HTML Report · Side-by-Side Redline Close-Up Wall

### Typical Detection Close-Ups (Captured Directly by UI Caliper)
| Cross-Card Invisible X-Rail Drift (`x-rail-right-drift` / `x-rail-left-drift`) | Same-Row Baseline Drift & Height Mismatch (`y-rail-row-misalign` / `row-height-inconsistent`) |
| :---: | :---: |
|  |  |
| **Pill Text Vertical Optical Asymmetry (`pill-text-vertical-asymmetry`)** | **Uneven Sibling Spacing (`sibling-gap-inconsistent`)** |
|  |  |
| **Multi-Layer Dropdown Auto-Exploration (`popover-anchor-misalign` + option spacing)** | **Redline Legend** |
|  | <ul><li><strong>Blue Box</strong>: Reference anchor / visual pill boundary / popover trigger</li><li><strong>Red / Amber Box</strong>: Off-rail element / actual ink bounding box / misaligned overlay</li><li><strong>Dashed Rails & Rulers</strong>: Invisible pixel rails, top/bottom optical padding, and gap delta callouts</li></ul> |
---
## Architecture Overview
UI Caliper enforces a strict **four-layer unidirectional architecture**: `src/core/` is a 100% platform-agnostic pure computation kernel (zero `../` reverse imports, zero native C++ addon dependencies). Every platform adapter normalizes its runtime capture into a shared `CaptureSnapshot` consumed by the core engine.
```text
┌─────────────────────────────────────────┐
│ interfaces/ (Entry Layer) │
│ cli.ts (caliper CLI) | mcp.ts (MCP) │
└────────────────────┬────────────────────┘
│
┌─────────────────────────┴─────────────────────────┐
▼ ▼
┌─────────────────────────────────────────┐ ┌─────────────────────────────────┐
│ adapters/ (Platform Capture) │ │ report/ (Reporting) │
│ web/ : Playwright DOM + Canvas │──────▶│ html-report.ts │
│ android/ : UIAutomator XML + ADB (dp) │ emits │ (writes report.json/report.html)│
│ ios/ : WDA / idb + simctl (pt) │report └─────────────────────────────────┘
│ mobile.ts: Android/iOS orchestrator │
└────────────────────┬────────────────────┘
│ Normalized CaptureSnapshot (atoms + rawScreenshotPng + layer)
▼
┌───────────────────────────────────────────────────────────────────────────────────┐
│ core/ (100% Platform-Agnostic Kernel · Zero ../ Imports) │
│ rails.ts Sparse global pixel rails (O(N log N) bounded clustering) │
│ spacing-rules.ts Spacing / padding / 2D X-bucket collisions / mobile safe-area │
│ layer-rules.ts Cross-layer popover anchor alignment, gap & viewport overflow │
│ pill-optical.ts Pixel-ink optical centering for pills, buttons, inputs & icons │
│ crops.ts Union-bbox close-up crop planner (padding, clamping, merging) │
│ png-codec.ts Zero-dependency PNG codec (node:zlib + CRC32 + OOM/zip-bomb) │
│ offscreen-redline Pure-TS Node offline redline compositor & cropper (1x/2x/3x) │
│ pipeline.ts Unified entry points: analyzeAtomsAndOptical / CaptureSnapshot │
└───────────────────────────────────────────────────────────────────────────────────┘
```
---
## Rule Catalog (26 Rules)
### 1. Sparse Pixel Rails & Dimension Alignment (6 Rules · `src/core/rails.ts`)
| Rule ID | Platforms | What It Detects |
| :--- | :---: | :--- |
| `x-rail-left-drift` | Web / iOS / Android | Same-region or cross-card left edge drifts off a global X rail (2–10 px/pt/dp near-miss) |
| `x-rail-right-drift` | Web / iOS / Android | Same-region or cross-card right edge drifts off a global X rail |
| `y-rail-row-misalign` | Web / iOS / Android | Controls in the same visual row fail to share a bottom edge or vertical centerline |
| `y-rail-card-top-drift` | Web / iOS / Android | Side-by-side cards have slightly misaligned top edges |
| `y-rail-card-bottom-drift` | Web / iOS / Android | Side-by-side cards have nearly-aligned but drifted bottom edges |
| `row-height-inconsistent` | Web / iOS / Android | Controls on the same visual row have inconsistent heights (e.g., 32px input next to 28px button) |
### 2. Spacing, Padding, Collisions, Overflow & Mobile Guidelines (10 Rules · `src/core/spacing-rules.ts`)
| Rule ID | Platforms | What It Detects |
| :--- | :---: | :--- |
| `sibling-gap-inconsistent` | Web / iOS / Android | Uneven adjacent gaps among sibling elements in a row or column (retains `0`-gap samples) |
| `card-padding-asymmetry` | Web / iOS / Android | Asymmetric left vs. right inner padding within a single card or section |
| `card-padding-inconsistent` | Web / iOS / Android | Inconsistent inner padding across peer cards at the same nesting depth (isolates nested cards) |
| `viewport-margin-asymmetry` | Web / iOS / Android | Asymmetric left vs. right viewport margins around the main content area |
| `element-overlap` | Web / iOS / Android | Non-ancestor elements overlapping/colliding (2D X-bucket sweep-line, including cross-region collisions) |
| `element-crowded` | Web / iOS / Android | Controls, pills, or headings in a row packed uncomfortably close (`< 2px/pt/dp`) |
| `content-clipped-or-overflow` | Web / iOS / Android | Child extends beyond parent bounds (geometry) or glyph ink clips against container edge (pixel) |
| `safe-area-violation` | iOS / Android | Interactive control intrudes into notch / Dynamic Island / Home Indicator / system bars (exempts navigation bar subtrees) |
| `touch-target-too-small` | iOS / Android | Raw touch target smaller than iOS `44×44pt` or Android `48×48dp` guidelines (configurable) |
| `spacing-off-grid` | Web / iOS / Android | **Off by default**; enabled via `--grid-step <n>` to verify spacing and card padding align to the grid step |
### 3. Pixel-Ink Optical Centering for Pills, Buttons & Inputs (7 Rules · `src/core/pill-optical.ts`)
Uses per-row rounded-corner contour clipping plus real foreground glyph ink bounding boxes — completely bypassing Android `includeFontPadding`, iOS 44pt expanded hit areas, and CSS `line-height` box distortion, with automatic descender protection for Latin letters (`g`, `j`, `p`, `q`, `y`):
| Rule ID | Platforms | What It Detects |
| :--- | :---: | :--- |
| `pill-text-vertical-asymmetry` | Web / iOS / Android | Uneven optical top vs. bottom text padding inside a pill or button (visually shifted up/down) |
| `pill-group-text-padding-drift` | Web / iOS / Android | Inconsistent vertical optical text padding across multiple pills on the same row |
| `pill-text-horizontal-asymmetry` | Web / iOS / Android | Asymmetric left vs. right optical padding of content (icon + label) inside a pill or button |
| `icon-text-misalign` | Web / iOS / Android | Icon and text optical centerlines are not vertically aligned inside a button or pill |
| `icon-text-gap-drift` | Web / iOS / Android | Inconsistent icon-to-text spacing across sibling icon+label controls in the same region |
| `field-text-optical-drift` | Web / iOS / Android | Vertically off-center text inside text inputs / search fields (including border-only white-bg inputs) |
| `field-group-text-inset-drift` | Web / iOS / Android | Left-aligned stacked input fields with mismatched internal left text insets |
### 4. Multi-Layer Popover & Overlay Rules (3 Rules · `src/core/layer-rules.ts`)
With `--explore-layers` (Web) or native overlay splitting (Android/iOS), the base page and every overlay layer are analyzed in strict isolation while also checking cross-layer geometry between each overlay and its trigger:
| Rule ID | Platforms | What It Detects |
| :--- | :---: | :--- |
| `popover-anchor-misalign` | Web / iOS / Android | Dropdown/menu/popover edge misses its trigger's left, right, or center reference line by 2–16 px/pt/dp |
| `popover-anchor-gap` | Web / iOS / Android | Dropdown/menu/popover overlaps its trigger, sits flush with zero gap, or floats excessively far away |
| `popover-viewport-overflow` | Web / iOS / Android | Expanded popover, dialog, drawer, or sheet overflows any of the four viewport edges |
---
## Quick Start
### Installation & Environment Check
```bash
# Option A: Install directly from the latest GitHub Release tarball
npm i -g https://github.com/ShellMonster/ui-caliper/releases/download/v0.2.1/ui-caliper-0.2.1.tgz
# Option B: Clone, build, and link the global `caliper` command from source
pnpm install && pnpm build && npm link
# Verify Node / Playwright Chromium / adb / xcrun simctl / idb / WDA toolchain
caliper doctor
```
### 1. Web Scanning (Multi-Viewport, Safe Multi-Layer Exploration & Optional Grid)
```bash
# Scan live URLs or a local dev server and open the interactive redline close-up report
caliper scan http://127.0.0.1:5173/#/dashboard http://127.0.0.1:5173/#/settings \
--viewports 13inch,27inch-1080p,iphone-15 \
--explore-layers \
--max-layers 6 \
--grid-step 8 \
--out ./reports/web-check \
--open
# One-shot workflow: start dev server -> wait until ready -> scan all routes -> tear down process tree
caliper dev "pnpm preview --host 127.0.0.1 --port 4173" \
--port 4173 \
--routes "#/dashboard,#/settings" \
--viewports 13inch,27inch-1080p \
--explore-layers \
--open
```
Built-in viewport presets: `13inch` (1280×800), `14inch` (1440×900), `27inch-1080p` (1920×1080), `27inch-2k` (2560×1440), `iphone-15` (393×852), `pixel-8` (412×915), or any custom `WxH` (e.g., `1024x768`).
### 2. Native Android / iOS Scanning (Live Device/Simulator + Offline Dump)
```bash
# Native Android (live ADB device or emulator; auto-normalizes to logical dp & renders offline redline PNGs)
caliper mobile --platform android --out ./reports/android --open
# Native iOS (via WebDriverAgent or Meta idb + simctl; logical pt)
caliper mobile --platform ios \
--udid booted \
--wda-url http://127.0.0.1:8100 \
--out ./reports/ios \
--open
# Offline mode (consumes exported UIAutomator XML / WDA JSON / idb JSON + screenshot PNG; ideal for CI/Appium)
caliper mobile --platform android \
--tree ./window_dump.xml \
--screenshot ./screen.png \
--density 3 \
--min-touch-target 48 \
--out ./reports/android-ci
```
### 3. CI Gate & Config Initialization
```bash
# Generate a default caliper.config.json in the current project
caliper init
# Machine-readable JSON output; exits with code 1 if any layout finding or scan error occurs
caliper scan http://127.0.0.1:4173/ --json --fail-on-finding
```
---
## AI Agent / MCP Server Integration
UI Caliper ships with a zero-extra-dependency stdio JSON-RPC MCP Server (`caliper mcp`) that plugs directly into Claude Code, Cursor, Codex, T3 Code, and other MCP clients so AI agents can automatically run geometric and optical self-checks after editing UI code:
```json
{
"mcpServers": {
"ui-caliper": {
"command": "caliper",
"args": ["mcp"]
}
}
}
```
Exposed MCP tools:
- `layout_probe_scan`: Scans one or more Web URLs (`viewports`, `exploreLayers`, `maxLayersPerPage`, `checkPillOptical`, `gridStep`, `outDir`).
- `layout_probe_mobile_scan`: Scans live native iOS / Android devices or offline `treePath` + `screenshotPath` artifacts (`density`, `minTouchTarget`, `safeAreaTop`, `safeAreaBottom`, `gridStep`, `checkPillOptical`).
- `layout_probe_doctor`: Checks Node, Playwright Chromium, and `adb` / `simctl` / `idb` / `WDA` mobile toolchain readiness.
---
## TypeScript SDK
Use the high-level scanners directly, or feed your own `CaptureSnapshot` into the browser-free `src/core/` engine for custom platforms:
```ts
import {
analyzeCaptureSnapshot,
scanUrls,
scanMobileTarget,
VIEWPORT_PRESETS,
} from 'ui-caliper';
// 1. Web multi-layer scan (also supports declarative custom layer interactions)
const webReport = await scanUrls({
urls: ['http://127.0.0.1:5173/'],
viewports: [VIEWPORT_PRESETS['13inch']],
exploreLayers: true,
maxLayersPerPage: 6,
analyzerOptions: { gridStepPx: 8 },
outDir: './reports/web',
});
// 2. Feed any custom platform's CaptureSnapshot directly into the core pipeline
const customResult = await analyzeCaptureSnapshot(snapshot, {
outDir: './reports/custom',
checkPillOptical: true,
});
```
---
## Report Artifacts
- `report.html`: Self-contained interactive HTML report — opens with a **side-by-side high-DPI redline close-up wall** (click to zoom, tagged with platform and layer badges), followed by optical padding/spacing tables and collapsible full-page blue/red global rail overlays.
- `report.json`: Complete structured analysis output (`platform`, `unit`, `layer`, `metrics`, `perf`, `crops`, and per-finding `opticalMetrics`, `spacingAnnotation`, and `cropScreenshotPath`).
- `screenshots/crops/*.png`: 2x/3x high-DPI local redline crops for every alignment, spacing, optical, or popover issue.
- `screenshots/*.png`: Full-page global pixel-rail overview screenshots.
## Development & Verification
```bash
# Core zero reverse-dependency check + clean build + typecheck + full unit & Chromium integration test suite
! grep -rnE "from ['\"]\.\./" src/core/ && rm -rf dist && pnpm typecheck && pnpm build && pnpm test
```
## License
[MIT](./LICENSE) © 2026 ShellMonster
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues