← Commit history
.gitignoreadded+1
@@ -0,0 +1 @@+/target
Cargo.tomladded+25
@@ -0,0 +1,25 @@+[package]+name = "adom-schematic"+version = "0.5.0"+edition = "2021"+description = "Interactive schematic viewer (.kicad_sch): KiCad-native render + per-component hover with MPN, stock & price"++[[bin]]+name = "adom-schematic"+path = "src/main.rs"++[dependencies]+tiny_http = "0.12"+regex = "1"+anyhow = "1"+clap = { version = "4", features = ["derive"] }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+ureq = "2"+roxmltree = "0.20"+cfb = "0.10"++[profile.release]+opt-level = "z"+lto = true+strip = true
LICENSEadded+21
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Adom Industries Inc.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
README.md+90−2
@@ -1,3 +1,91 @@-# Adom Schematic+# adom-schematic -Interactive schematic viewer: your EDA's own render plus per-symbol highlighting and live MPN, stock and price on hover+Interactive **schematic viewer**. The drawing is your EDA's *own* export — real+symbols, real fonts, real wire routing — with an invisible interaction layer over+it that knows which strokes belong to which component. Hover a symbol and it+haloes the way it does when you select it in KiCad, and tells you what the part+costs and whether it is in stock.++![U1 selected in adom-schematic](screenshots/shot.png)++The untouched sheet — this is service-kicad's own export, not a redraw:++![The schematic sheet](screenshots/sheet.png)++## Why it works this way++Same architecture as its sibling **adom-2dboard**: authenticity from the+EDA's render, interactivity from parsed geometry.++- **Visual base** — the whole sheet as SVG from the shared **service-kicad**+  container (`POST /kicad/sch/export/svg`).+- **Interaction overlay** — the `.kicad_sch` parsed in Rust into per-component+  regions (symbol body *plus* a box per visible property text), used both for+  invisible hotspots and to tag each drawing element with `data-cref` so the+  highlight can act on the symbol's real lines.++## What you get++- **KiCad-style selection** — hovering haloes that symbol's own strokes,+  including its reference and value text. Its colours don't change and the rest+  of the sheet is left completely alone.+- **Hover card** — reference, value, description, footprint, LCSC part, plus+  live **MPN, stock, price, tier, popularity**, a JLCPCB link, a wiki page link+  and the datasheet. The card follows the cursor and flips at the viewport edges.+- **Click to pin** — the card stays where it is and becomes clickable, so you+  can actually follow those links. On small or embedded screens the hover card is+  abridged to reference · MPN · stock; pinning always expands it.+- **Component list** — every part on the sheet, hover-linked to the drawing.+- **Embeddable** — `embed` emits one self-contained interactive HTML file, so any+  app can use it as a live schematic view. (adom-nucleus does.)++## Install++```+adom-wiki pkg install adom/adom-schematic+```++## Use++```bash+# one self-contained interactive HTML (what you embed in another app)+adom-schematic embed --file sheet.kicad_sch --out sheet.html++# a composed interactive SVG (+ sheet.meta.json with --meta)+adom-schematic render --file sheet.kicad_sch --out sheet.svg --meta++# the live app+adom-schematic serve --file sheet.kicad_sch --port 8793++# one part's stock/price/MPN/wiki as JSON — lets a HOST app serve /enrich+# on behalf of an embedded view, which has no server of its own+adom-schematic enrich --mpn 100nF --lcsc C1525+```++### Embedding in your own app++```html+<iframe src="/board-view/my-board/sch" style="border:0;width:100%;height:100%"></iframe>+```++The embed's `fetch("enrich")` is **relative**, so it resolves against whoever+serves the page. Point that route at `adom-schematic enrich` and the+embedded card gets live stock and price; answer nothing and it degrades to+identity only.++## Enrichment++- `adom-jlcpcb search <Cnnn>` — stock, unit price, Basic/Preferred/Extended+  tier, popularity, manufacturer, the real MPN and a JLCPCB link+- `adom-wiki discover search --query <mpn> --json` — wiki page, and vouch count+  as popularity when JLCPCB has none. Matched conservatively (close name match+  only) so passives don't pick up unrelated pages.++## Notes++- Requires network access to **service-kicad**; override with `KICAD_SERVICE_API`.+  Override the JLCPCB endpoint with `JLCPCB_API`.+- KiCad today; Altium and Fusion exports are the next step.++See also: **adom-2dboard** — the same idea for `.kicad_pcb`, with net and+trace highlighting.
SKILL.mdadded+91
@@ -0,0 +1,91 @@+---+name: adom-schematic+description: "Use when the user asks to view, open, preview, or inspect a schematic or .kicad_sch sheet; to find out what a symbol/reference designator on a schematic is; to get stock, price, MPN, LCSC part, datasheet or wiki page for parts on a schematic; or to embed an interactive schematic view inside another app or web page. Also trigger for 'show me the schematic', 'what is U1', 'how much does this BOM cost', or 'make the schematic preview clickable'."+---++# adom-schematic++Interactive schematic viewer for `.kicad_sch`. The drawing is the EDA's OWN+render (authentic symbols, fonts, wire routing); an overlay parsed from the sheet+adds per-component highlighting and live part data.++## Architecture++```+adom-schematic (single Rust binary, no Node, no local KiCad)+  |+  +-- visual base      whole-sheet SVG from service-kicad+  |                    POST /kicad/sch/export/svg       (KICAD_SERVICE_API)+  |+  +-- interaction      .kicad_sch parsed in Rust -> per-component REGIONS+  |   overlay          (symbol body + one box per visible property text), used to+  |                    (a) place invisible hotspots and (b) tag every drawing+  |                    element with data-cref by bbox containment, so the+  |                    highlight acts on the symbol's real strokes+  |+  +-- enrichment       GET /enrich?mpn=&lcsc=   (async, cached)+                         adom-jlcpcb search <Cnnn>    -> stock, price, tier,+                                                         popularity, mfr, real MPN+                         adom-wiki discover search    -> wiki page, vouch count+```++## Quick start++```bash+# self-contained interactive HTML for embedding in another app+adom-schematic embed --file sheet.kicad_sch --out sheet.html++# composed interactive SVG (+ sheet.meta.json)+adom-schematic render --file sheet.kicad_sch --out sheet.svg --meta++# live app+adom-schematic serve --file sheet.kicad_sch --port 8793++# one part's data as JSON (host apps use this to serve /enrich for an embed)+adom-schematic enrich --mpn 100nF --lcsc C1525+```++## Commands++| Command | Description |+|---|---|+| `embed --file F [--out O]` | One self-contained interactive HTML file |+| `render --file F --out O [--meta]` | Composed interactive SVG, optional `<out>.meta.json` |+| `serve [--file F] [--port P]` | Live app server (default :8785) |+| `enrich [--mpn M] [--lcsc C]` | Stock / price / MPN / wiki as JSON on stdout |++## Interactions++- **Hover** a symbol -> KiCad-style selection: its own strokes (including the+  reference and value text) gain a bright halo. Colours are unchanged and the+  rest of the sheet is untouched.+- **Hover card** -> reference, value, description, footprint, LCSC, plus live+  MPN, stock, price, tier, popularity, JLCPCB link, wiki link, datasheet. It+  follows the cursor and flips at viewport edges.+- **Click** -> pins the card where it is and makes it clickable, so the links can+  be followed. On small/embedded screens (<=620px) the hover card is abridged to+  reference · MPN · stock; pinning always expands it to full detail.+- **Component list** -> every part on the sheet, hover-linked to the drawing.++## Embedding in another app++```html+<iframe src="/board-view/<slug>/sch" style="border:0;width:100%;height:100%"></iframe>+```++The embed's `fetch("enrich")` is RELATIVE, so it resolves against whoever serves+the page. Point that route at `adom-schematic enrich` and the embedded+card gets live stock and price (adom-nucleus does this); answer nothing+and it degrades to identity only.++## Environment++| Variable | Purpose |+|---|---|+| `KICAD_SERVICE_API` | service-kicad base URL |+| `JLCPCB_API` | adom-jlcpcb API endpoint |++## Notes++- KiCad today; Altium and Fusion exports are the planned next step.+- Sibling app: **adom-2dboard** (`.kicad_pcb`, with net/trace highlighting).
build.shadded+11
@@ -0,0 +1,11 @@+#!/bin/bash+# build.sh — compile the release binary and stage it into bin/ for packaging.+set -euo pipefail++DIR="$(cd "$(dirname "$0")" && pwd)"+cd "$DIR"++cargo build --release+mkdir -p bin+install -m 0755 "target/release/adom-schematic" "bin/adom-schematic"+echo "staged bin/adom-schematic ($(du -h bin/adom-schematic | cut -f1))"
install.shadded+16
@@ -0,0 +1,16 @@+#!/bin/bash+# install.sh for adom-schematic (app).+# Runs from the extracted module directory (~/project/adom_modules/adom-schematic/).+set -euo pipefail++DIR="$(cd "$(dirname "$0")" && pwd)"+cd "$DIR"++BIN_DIR="${HOME}/.local/bin"+mkdir -p "$BIN_DIR"+install -m 0755 "$DIR/bin/adom-schematic" "$BIN_DIR/adom-schematic"+echo "Installed adom-schematic -> $BIN_DIR/adom-schematic"++# Renamed from adom-schematic-viewer: drop the old command so upgraders don't keep a+# stale binary shadowing this one.+rm -f "$BIN_DIR/adom-schematic-viewer"
package.jsonadded+66
@@ -0,0 +1,66 @@+{+  "slug": "adom-schematic",+  "version": "0.5.0",+  "type": "app",+  "description": "Interactive schematic viewer: your EDA's own render plus per-symbol highlighting and live MPN, stock and price on hover",+  "dependencies": {+    "adom/adom-jlcpcb": "*"+  },+  "scripts": {+    "install": "./install.sh",+    "uninstall": "./uninstall.sh"+  },+  "needs_sudo": false,+  "hero": {+    "type": "image",+    "path": "docs/hero.png"+  },+  "discovery_triggers": [+    "show me the schematic",+    "open this kicad_sch",+    "what is U1",+    "what part is this symbol",+    "how much does this part cost",+    "is this chip in stock",+    "view the schematic for this board",+    "interactive schematic view",+    "embed a schematic in my app",+    "price out the parts on this sheet"+  ],+  "discovery_pitch": "Use to view or embed a schematic that looks exactly like the user's EDA drew it, where hovering a symbol identifies the part and shows its live MPN, stock and price.",+  "sample_prompts": [+    {+      "label": "Open a schematic",+      "prompt": "open this kicad_sch so I can see what each symbol is"+    },+    {+      "label": "Identify a part",+      "prompt": "what is U1 on this schematic and what does it cost?"+    },+    {+      "label": "Check stock",+      "prompt": "are all the parts on this sheet in stock at JLCPCB?"+    },+    {+      "label": "Embed it",+      "prompt": "replace the flat schematic image in my app with an interactive view"+    }+  ],+  "tags": [+    "kicad",+    "schematic",+    "eda",+    "viewer",+    "bom",+    "stock",+    "price",+    "jlcpcb",+    "interactive",+    "embed",+    "altium",+    "fusion",+    "eagle",+    "pcbdoc",+    "schdoc"+  ]+}
release.shadded+87
@@ -0,0 +1,87 @@+#!/bin/bash+#+# Canonical release.sh for an adompkg source repo.+#+# Reads version from package.json, optionally bumps it (--bump patch|minor|major),+# runs build.sh if present, then runs `adompkg publish` and prints the resulting+# package URL.+#+# Usage:+#   ADOMPKG_TOKEN=<carbon-api-key> ./release.sh                # publish current version+#   ADOMPKG_TOKEN=<carbon-api-key> ./release.sh --bump patch   # bump + publish+#+set -euo pipefail++DIR="$(cd "$(dirname "$0")" && pwd)"+cd "$DIR"++if [ ! -f package.json ]; then+  echo "release.sh: no package.json found in $DIR" >&2+  exit 1+fi++REGISTRY="${ADOMPKG_REGISTRY:-https://git-wiki-ktqxite5iglh.adom.cloud}"++if [ -z "${ADOMPKG_TOKEN:-}" ]; then+  if [ -r /var/run/adom/api-key ]; then+    ADOMPKG_TOKEN="$(cat /var/run/adom/api-key)"+    export ADOMPKG_TOKEN+  else+    echo "release.sh: ADOMPKG_TOKEN is required (set ADOMPKG_TOKEN=<carbon-api-key>)" >&2+    exit 1+  fi+fi++# Read current version.+CUR_VERSION=$(node -e "console.log(require('./package.json').version)")+SLUG=$(node -e "console.log(require('./package.json').slug || require('./package.json').name)")++BUMP=""+for a in "$@"; do+  case "$a" in+    --bump)+      shift+      BUMP="${1:-patch}"+      shift || true+      ;;+    --bump=*)+      BUMP="${a#--bump=}"+      shift+      ;;+  esac+done++if [ -n "$BUMP" ]; then+  NEXT=$(node -e "+    const [maj, min, pat] = process.argv[1].split('.').map(n => parseInt(n, 10));+    const b = process.argv[2];+    let out;+    if (b === 'major') out = (maj + 1) + '.0.0';+    else if (b === 'minor') out = maj + '.' + (min + 1) + '.0';+    else out = maj + '.' + min + '.' + (pat + 1);+    console.log(out);+  " "$CUR_VERSION" "$BUMP")+  echo "release.sh: bumping $CUR_VERSION -> $NEXT ($BUMP)"+  node -e "+    const fs = require('fs');+    const p = JSON.parse(fs.readFileSync('package.json', 'utf8'));+    p.version = process.argv[1];+    fs.writeFileSync('package.json', JSON.stringify(p, null, 2) + '\n');+  " "$NEXT"+  CUR_VERSION="$NEXT"+fi++# Optional build step.+if [ -x ./build.sh ]; then+  echo "release.sh: running build.sh"+  ./build.sh+fi++# Publish.+echo "release.sh: publishing $SLUG@$CUR_VERSION to $REGISTRY"+adompkg publish . --org adom --public --yes++# Print published URL.+echo+echo "Published: $REGISTRY/pages/$SLUG"+echo "Install:   adompkg install $SLUG"
screenshots/sheet.pngadded
⋯ 1 unchanged line ⋯
screenshots/shot.pngadded
⋯ 1 unchanged line ⋯
scripts/rasterize.mjsadded+14
@@ -0,0 +1,14 @@+import puppeteer from 'puppeteer';+import fs from 'fs';+const svg = fs.readFileSync(process.argv[2], 'utf8');+const bg = process.argv[4] || '#0a0f0c';+const html = `<!doctype html><html><body style="margin:0;background:${bg};display:grid;place-items:center;height:100vh">${svg}</body></html>`;+const b = await puppeteer.launch({headless:'new', args:['--no-sandbox']});+const p = await b.newPage();+await p.setViewport({width:700, height:700, deviceScaleFactor:2});+await p.setContent(html, {waitUntil:'networkidle0'});+const el = await p.$('svg');+await el.evaluate(s=>{s.style.width='640px';s.style.height='640px';});+await p.screenshot({path: process.argv[3]});+await b.close();+console.log('shot →', process.argv[3]);
src/altium_sch.rsadded+384
@@ -0,0 +1,384 @@+//! Altium `.SchDoc` schematic parser + renderer.+//!+//! A SchDoc is an OLE2 compound file whose `FileHeader` stream is a flat list of+//! `[u32 len][ASCII |KEY=VAL|…]` records — no binary decoding needed at all.+//! Every record has a numeric `RECORD` type; the ones we draw:+//!+//!   1 Component   2 Pin        4 Label     6 Polyline   7 Polygon+//!   8 Ellipse    12 Arc       13 Line     14 Rectangle 17 Power port+//!  25 Net label  27 Wire      29 Junction 34 Designator 41 Parameter+//!+//! Child primitives (pins, graphics, designators) point at their component with+//! `OwnerIndex`, and — crucially — their coordinates are already ABSOLUTE sheet+//! coordinates, so no per-symbol transform is needed.+//!+//! Units: Altium schematic coordinates are 1/100 inch (10 mil) with an optional+//! `_Frac` field out of 100000. Y is up, ours is down, so Y is negated.+//!+//! Altium has no headless renderer (no CLI at all), so we draw the sheet+//! ourselves in Altium's own colour convention and tag every primitive with its+//! component — the frontend's halo highlight then works unchanged.++use crate::sch_parse::{Comp, Sheet};+use std::collections::HashMap;+use std::fmt::Write as _;+use std::io::{Cursor, Read};++/// 10 mil -> mm+const U: f64 = 0.254;++pub fn looks_like_altium(bytes: &[u8]) -> bool {+    bytes.len() > 8 && bytes[..8] == [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]+}++fn esc(s: &str) -> String {+    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")+}++type Rec = HashMap<String, String>;++fn kv(rec: &str) -> Rec {+    rec.trim_matches('|')+        .split('|')+        .filter_map(|p| p.split_once('='))+        .map(|(k, v)| (k.to_uppercase(), v.to_string()))+        .collect()+}++fn s<'a>(r: &'a Rec, k: &str) -> &'a str { r.get(k).map(|v| v.as_str()).unwrap_or("") }+fn i(r: &Rec, k: &str) -> i64 { s(r, k).parse().unwrap_or(0) }++/// A coordinate: `<KEY>` in 10-mil units plus optional `<KEY>_FRAC` out of 100000.+fn coord(r: &Rec, k: &str) -> f64 {+    let base = i(r, k) as f64;+    let frac = i(r, &format!("{k}_FRAC")) as f64 / 100_000.0;+    (base + frac) * U+}+fn cx(r: &Rec, k: &str) -> f64 { coord(r, k) }+fn cy(r: &Rec, k: &str) -> f64 { -coord(r, k) }++// Altium's default schematic colours (BGR ints in the file; we just use its palette)+const C_WIRE: &str = "#0000c8";   // wires: blue+const C_SYM: &str = "#800000";    // symbol graphics: dark red+const C_PIN: &str = "#800000";+const C_DESIG: &str = "#800000";+const C_PARAM: &str = "#0000c8";+const C_NETLBL: &str = "#0000c8";++pub fn render_sheet(bytes: &[u8]) -> Result<(String, Sheet), String> {+    let mut cf = cfb::CompoundFile::open(Cursor::new(bytes.to_vec()))+        .map_err(|e| format!("altium .SchDoc: not a compound file ({e})"))?;+    let mut raw = Vec::new();+    cf.open_stream("/FileHeader")+        .map_err(|e| format!("altium .SchDoc: no FileHeader ({e})"))?+        .read_to_end(&mut raw)+        .map_err(|e| format!("altium .SchDoc: {e}"))?;++    // [u32 len][ascii] repeated+    let mut recs: Vec<Rec> = Vec::new();+    let mut off = 0usize;+    while off + 4 <= raw.len() {+        let ln = u32::from_le_bytes([raw[off], raw[off + 1], raw[off + 2], raw[off + 3]]) as usize;+        off += 4;+        if ln == 0 || off + ln > raw.len() { break; }+        let txt = String::from_utf8_lossy(&raw[off..off + ln]).trim_end_matches('\0').to_string();+        recs.push(kv(&txt));+        off += ln;+    }+    if recs.is_empty() { return Err("altium .SchDoc: no records".into()); }++    // ── components, by record ordinal (that's what OwnerIndex references) ────+    // value comes from the "Comment" parameter, footprint from the implementation+    // OwnerIndex is 0-based over records EXCLUDING the leading HEADER record,+    // so a component sitting at recs[29] is referenced as OwnerIndex=28.+    let mut comp_of: HashMap<usize, usize> = HashMap::new(); // owner-index -> comps idx+    let mut comps: Vec<Comp> = Vec::new();+    for (idx, r) in recs.iter().enumerate() {+        if s(r, "RECORD") != "1" { continue; }+        comp_of.insert(idx.saturating_sub(1), comps.len());+        comps.push(Comp {+            reference: String::new(), // from the RECORD=34 designator+            value: String::new(),+            footprint: String::new(),+            lcsc: String::new(),+            description: s(r, "COMPONENTDESCRIPTION").to_string(),+            datasheet: String::new(),+            x: cx(r, "LOCATION.X"), y: cy(r, "LOCATION.Y"),+            bbox: [f64::MAX, f64::MAX, f64::MIN, f64::MIN],+            pin_count: 0,+            regions: Vec::new(),+        });+    }++    // owner lookup for any child record+    let owner = |r: &Rec| -> Option<usize> {+        let oi = s(r, "OWNERINDEX");+        if oi.is_empty() { return None; }+        oi.parse::<usize>().ok().and_then(|k| comp_of.get(&k).copied())+    };++    // ── designator / parameters attach identity to components ───────────────+    for r in &recs {+        match s(r, "RECORD") {+            "34" => {+                if let Some(c) = owner(r) { comps[c].reference = s(r, "TEXT").to_string(); }+            }+            "41" => {+                if let Some(c) = owner(r) {+                    let name = s(r, "NAME").to_uppercase();+                    let text = s(r, "TEXT").to_string();+                    match name.as_str() {+                        "COMMENT" | "VALUE" => if comps[c].value.is_empty() { comps[c].value = text },+                        "HELPURL" | "DATASHEET" | "DATASHEETURL" => comps[c].datasheet = text,+                        n if n.contains("LCSC") || n.contains("JLC") => comps[c].lcsc = text,+                        _ => {}+                    }+                }+            }+            "45" => {+                // implementation: footprint model+                if let Some(c) = owner(r) {+                    if comps[c].footprint.is_empty() { comps[c].footprint = s(r, "MODELNAME").to_string(); }+                }+            }+            _ => {}+        }+    }++    let mut body = String::new();+    let mut ext: Vec<(f64, f64)> = Vec::new();+    // per-component extents, so the halo covers exactly that symbol+    let mut cext: Vec<Vec<(f64, f64)>> = vec![Vec::new(); comps.len()];++    let mut fit = |pts: &[(f64, f64)], c: Option<usize>, ext: &mut Vec<(f64, f64)>, cext: &mut Vec<Vec<(f64, f64)>>| {+        ext.extend_from_slice(pts);+        if let Some(ci) = c { cext[ci].extend_from_slice(pts); }+    };++    for r in &recs {+        let rt = s(r, "RECORD");+        let c = owner(r);+        let tag = match c {+            Some(ci) if !comps[ci].reference.is_empty() => format!(r##" data-cref="{}""##, esc(&comps[ci].reference)),+            _ => String::new(),+        };+        match rt {+            // pin: a stub from its root, direction from PinConglomerate bits 0-1+            "2" => {+                let (x, y) = (cx(r, "LOCATION.X"), cy(r, "LOCATION.Y"));+                let len = i(r, "PINLENGTH") as f64 * U;+                let dir = (i(r, "PINCONGLOMERATE") & 0x03) as u8;+                let (x2, y2) = match dir {+                    0 => (x + len, y),+                    1 => (x, y - len),+                    2 => (x - len, y),+                    _ => (x, y + len),+                };+                if let Some(ci) = c { comps[ci].pin_count += 1; }+                fit(&[(x, y), (x2, y2)], c, &mut ext, &mut cext);+                let _ = write!(body, r##"<line{} x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="0.15"/>"##,+                    tag, x, y, x2, y2, C_PIN);++                // Pin NAME sits inside the body (opposite the stub) and the pin+                // DESIGNATOR just outside it — same convention as KiCad/Altium.+                // PinConglomerate bit 3 = designator visible, bit 4 = name visible.+                let cong = i(r, "PINCONGLOMERATE");+                let (name, desig) = (s(r, "NAME"), s(r, "DESIGNATOR"));+                let gap = 0.5;+                // unit vector along the stub, so we can step inward / outward+                let (ux, uy) = match dir { 0 => (1.0, 0.0), 1 => (0.0, -1.0), 2 => (-1.0, 0.0), _ => (0.0, 1.0) };+                if cong & 0x10 != 0 && !name.is_empty() {+                    // inward from the root = into the symbol body+                    let (nx, ny) = (x - ux * gap, y - uy * gap);+                    let anchor = if ux > 0.5 { "end" } else if ux < -0.5 { "start" } else { "middle" };+                    let _ = write!(body, r##"<text{} x="{:.3}" y="{:.3}" font-size="1.8" fill="{}" text-anchor="{}" dominant-baseline="middle">{}</text>"##,+                        tag, nx, ny, C_PIN, anchor, esc(name));+                    if let Some(ci) = c { cext[ci].push((nx, ny)); }+                }+                if cong & 0x08 != 0 && !desig.is_empty() {+                    // just above the outer end of the stub+                    let (dx2, dy2) = (x2 - ux * gap, y2 - uy * gap - 0.4);+                    let anchor = if ux > 0.5 { "end" } else if ux < -0.5 { "start" } else { "middle" };+                    let _ = write!(body, r##"<text{} x="{:.3}" y="{:.3}" font-size="2.1" fill="{}" text-anchor="{}">{}</text>"##,+                        tag, dx2, dy2, C_DESIG, anchor, esc(desig));+                    if let Some(ci) = c { cext[ci].push((dx2, dy2)); }+                }+            }+            // polyline / polygon: X1..Xn, Y1..Yn+            "6" | "7" => {+                let n = i(r, "LOCATIONCOUNT") as usize;+                let mut pts = Vec::new();+                for k in 1..=n {+                    let xk = format!("X{k}");+                    let yk = format!("Y{k}");+                    if !r.contains_key(&xk) { break; }+                    pts.push((coord(r, &xk), -coord(r, &yk)));+                }+                if pts.len() < 2 { continue; }+                let mut d = String::new();+                for (j, (x, y)) in pts.iter().enumerate() {+                    let _ = write!(d, "{} {:.3} {:.3} ", if j == 0 { "M" } else { "L" }, x, y);+                }+                if rt == "7" { d.push('Z'); }+                fit(&pts, c, &mut ext, &mut cext);+                let fill = if rt == "7" { C_SYM } else { "none" };+                let _ = write!(body, r##"<path{} d="{}" fill="{}" fill-opacity="0.2" stroke="{}" stroke-width="0.15"/>"##, tag, d, fill, C_SYM);+            }+            // line+            "13" => {+                let (x1, y1) = (cx(r, "LOCATION.X"), cy(r, "LOCATION.Y"));+                let (x2, y2) = (cx(r, "CORNER.X"), cy(r, "CORNER.Y"));+                fit(&[(x1, y1), (x2, y2)], c, &mut ext, &mut cext);+                let _ = write!(body, r##"<line{} x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="0.15"/>"##,+                    tag, x1, y1, x2, y2, C_SYM);+            }+            // rectangle (10 = rounded)+            "14" | "10" => {+                let (x1, y1) = (cx(r, "LOCATION.X"), cy(r, "LOCATION.Y"));+                let (x2, y2) = (cx(r, "CORNER.X"), cy(r, "CORNER.Y"));+                fit(&[(x1, y1), (x2, y2)], c, &mut ext, &mut cext);+                let _ = write!(body, r##"<rect{} x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="#fffbc8" fill-opacity="0.7" stroke="{}" stroke-width="0.15"/>"##,+                    tag, x1.min(x2), y1.min(y2), (x2 - x1).abs(), (y2 - y1).abs(), C_SYM);+            }+            // ellipse / arc+            "8" | "12" | "11" => {+                let (x, y) = (cx(r, "LOCATION.X"), cy(r, "LOCATION.Y"));+                let rr = coord(r, "RADIUS").max(coord(r, "SECONDARYRADIUS")).max(0.2);+                fit(&[(x - rr, y - rr), (x + rr, y + rr)], c, &mut ext, &mut cext);+                let _ = write!(body, r##"<circle{} cx="{:.3}" cy="{:.3}" r="{:.3}" fill="none" stroke="{}" stroke-width="0.15"/>"##,+                    tag, x, y, rr, C_SYM);+            }+            // wire (net) — the sheet's connectivity+            "27" => {+                let n = i(r, "LOCATIONCOUNT") as usize;+                let mut pts = Vec::new();+                for k in 1..=n {+                    let xk = format!("X{k}");+                    if !r.contains_key(&xk) { break; }+                    pts.push((coord(r, &xk), -coord(r, &format!("Y{k}"))));+                }+                if pts.len() < 2 { continue; }+                let mut d = String::new();+                for (j, (x, y)) in pts.iter().enumerate() {+                    let _ = write!(d, "{} {:.3} {:.3} ", if j == 0 { "M" } else { "L" }, x, y);+                }+                ext.extend_from_slice(&pts);+                let _ = write!(body, r##"<path class="adom-wire" d="{}" fill="none" stroke="{}" stroke-width="0.2" stroke-linecap="round"/>"##, d, C_WIRE);+            }+            // junction+            "29" => {+                let (x, y) = (cx(r, "LOCATION.X"), cy(r, "LOCATION.Y"));+                ext.push((x, y));+                let _ = write!(body, r##"<circle cx="{:.3}" cy="{:.3}" r="0.4" fill="{}"/>"##, x, y, C_WIRE);+            }+            // power port: stem + the actual GND / earth / bar glyph, then its text+            "17" => {+                let (x, y) = (cx(r, "LOCATION.X"), cy(r, "LOCATION.Y"));+                // Orientation: 0 right, 1 up, 2 left, 3 down (our Y points down)+                let (dx, dy) = match i(r, "ORIENTATION") { 0 => (1.0, 0.0), 1 => (0.0, -1.0), 2 => (-1.0, 0.0), _ => (0.0, 1.0) };+                let (px, py) = (-dy, dx); // perpendicular, for the bars+                let stem = 2.0;+                let (ex2, ey2) = (x + dx * stem, y + dy * stem);+                ext.push((x, y)); ext.push((ex2 + px * 2.0, ey2 + py * 2.0)); ext.push((ex2 - px * 2.0, ey2 - py * 2.0));+                let _ = write!(body, r##"<line x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="0.15"/>"##,+                    x, y, ex2, ey2, C_NETLBL);+                let bar = |out: &mut String, along: f64, half: f64| {+                    let (bx, by) = (x + dx * along, y + dy * along);+                    let _ = write!(out, r##"<line x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="0.18"/>"##,+                        bx + px * half, by + py * half, bx - px * half, by - py * half, C_NETLBL);+                };+                match i(r, "STYLE") {+                    // 4 = Power Ground: three shortening bars+                    4 => { bar(&mut body, stem, 1.6); bar(&mut body, stem + 0.55, 1.0); bar(&mut body, stem + 1.1, 0.45); }+                    // 5 = Signal Ground: solid triangle+                    5 => {+                        let (ax, ay) = (x + dx * (stem + 1.6), y + dy * (stem + 1.6));+                        let _ = write!(body, r##"<path d="M {:.3} {:.3} L {:.3} {:.3} L {:.3} {:.3} Z" fill="{}"/>"##,+                            ex2 + px * 1.5, ey2 + py * 1.5, ex2 - px * 1.5, ey2 - py * 1.5, ax, ay, C_NETLBL);+                    }+                    // 6 = Earth: one bar plus hatch strokes+                    6 => {+                        bar(&mut body, stem, 1.6);+                        for k in 0..3 {+                            let o = -1.0 + k as f64;+                            let (sx, sy) = (x + dx * stem + px * o, y + dy * stem + py * o);+                            let _ = write!(body, r##"<line x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="0.15"/>"##,+                                sx, sy, sx + dx * 0.9 - px * 0.6, sy + dy * 0.9 - py * 0.6, C_NETLBL);+                        }+                    }+                    // 1 = Arrow+                    1 => {+                        let (ax, ay) = (x + dx * (stem + 1.0), y + dy * (stem + 1.0));+                        let _ = write!(body, r##"<path d="M {:.3} {:.3} L {:.3} {:.3} L {:.3} {:.3} Z" fill="{}"/>"##,+                            ex2 + px * 0.8, ey2 + py * 0.8, ex2 - px * 0.8, ey2 - py * 0.8, ax, ay, C_NETLBL);+                    }+                    // 0 = Circle+                    0 => { let _ = write!(body, r##"<circle cx="{:.3}" cy="{:.3}" r="0.6" fill="none" stroke="{}" stroke-width="0.15"/>"##, ex2, ey2, C_NETLBL); }+                    // 2 = Bar (and anything else)+                    _ => bar(&mut body, stem, 1.6),+                }+                if s(r, "SHOWNETNAME") == "T" && !s(r, "TEXT").is_empty() {+                    let t = s(r, "TEXT");+                    let (tx, ty) = (x + dx * (stem + 2.4), y + dy * (stem + 2.4));+                    ext.push((tx, ty));+                    let _ = write!(body, r##"<text x="{:.3}" y="{:.3}" font-size="2.1" fill="{}" text-anchor="middle" dominant-baseline="middle">{}</text>"##,+                        tx, ty, C_NETLBL, esc(t));+                }+            }+            // designator / net label / free label+            "34" | "25" | "4" => {+                let text = if rt == "17" { s(r, "TEXT") } else { s(r, "TEXT") };+                if text.is_empty() { continue; }+                let (x, y) = (cx(r, "LOCATION.X"), cy(r, "LOCATION.Y"));+                let color = match rt { "34" => C_DESIG, "25" | "17" => C_NETLBL, _ => C_PARAM };+                ext.push((x, y)); ext.push((x + text.chars().count() as f64 * 0.9, y - 1.6));+                if let Some(ci) = c { cext[ci].push((x, y)); cext[ci].push((x + text.chars().count() as f64 * 0.9, y - 1.6)); }+                let _ = write!(body, r##"<text{} x="{:.3}" y="{:.3}" font-size="2.2" fill="{}">{}</text>"##, tag, x, y, color, esc(text));+            }+            // visible parameter (e.g. the value under a part)+            "41" => {+                if s(r, "ISHIDDEN") == "T" { continue; }+                let text = s(r, "TEXT");+                if text.is_empty() || text.starts_with('=') { continue; }+                let (x, y) = (cx(r, "LOCATION.X"), cy(r, "LOCATION.Y"));+                ext.push((x, y));+                if let Some(ci) = c { cext[ci].push((x, y)); cext[ci].push((x + text.chars().count() as f64 * 0.9, y - 1.6)); }+                let _ = write!(body, r##"<text{} x="{:.3}" y="{:.3}" font-size="2.1" fill="{}">{}</text>"##, tag, x, y, C_PARAM, esc(text));+            }+            _ => {}+        }+    }++    // component bboxes / halo regions from what we actually drew+    for (ci, pts) in cext.iter().enumerate() {+        if pts.is_empty() {+            let (x, y) = (comps[ci].x, comps[ci].y);+            comps[ci].bbox = [x - 2.0, y - 2.0, x + 2.0, y + 2.0];+        } else {+            let (mut mnx, mut mny, mut mxx, mut mxy) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+            for (x, y) in pts { mnx = mnx.min(*x); mxx = mxx.max(*x); mny = mny.min(*y); mxy = mxy.max(*y); }+            comps[ci].bbox = [mnx, mny, mxx, mxy];+        }+        comps[ci].regions = vec![comps[ci].bbox];+    }+    // components without a designator can't be hovered meaningfully+    comps.retain(|c| !c.reference.is_empty());++    if ext.is_empty() { ext.push((0.0, 0.0)); ext.push((100.0, 100.0)); }+    let m = 5.0;+    let minx = ext.iter().map(|p| p.0).fold(f64::INFINITY, f64::min) - m;+    let miny = ext.iter().map(|p| p.1).fold(f64::INFINITY, f64::min) - m;+    let maxx = ext.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max) + m;+    let maxy = ext.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max) + m;+    let sheet = Sheet { comps, sub_sheets: Vec::new(), content_bbox: (minx, miny, maxx - minx, maxy - miny) };++    let mut out = String::new();+    let _ = write!(out, r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{:.3} {:.3} {:.3} {:.3}" preserveAspectRatio="xMidYMid meet" font-family="Times New Roman, Times, serif">"##,+        minx, miny, maxx - minx, maxy - miny);+    let _ = write!(out, r##"<rect class="adom-sheet-bg" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="#ffffff"/>"##,+        minx, miny, maxx - minx, maxy - miny);+    let _ = write!(out, r##"<g class="adom-sheet">{}</g>"##, body);+    out.push_str(&crate::sch_parse::build_overlay(&sheet));+    out.push_str("</svg>");+    Ok((out, sheet))+}
src/app.htmladded+182
@@ -0,0 +1,182 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1" />+<title>adom-schematic</title>+<style>+  /* Canonical Adom design tokens (adom-ui-design). Legacy names kept as aliases so+     the rest of this stylesheet is untouched. Primary accent is #00b8b0; #00e6dc is+     the bright hover variant. */+  :root { color-scheme: dark;+    --bg:#0d1117; --panel:#161b22; --elevated:#1c2128; --overlay:#21262d; --edge:#30363d;+    --ink:#e6edf3; --mut:#8b949e; --acc:#00b8b0; --acc2:#00e6dc;+    --green:#3fb950; --red:#f85149; --yellow:#d29922;+    --line:var(--edge); --txt:var(--ink); --muted:var(--mut); --accent:var(--acc); }+  * { box-sizing: border-box; }+  /* Three fonts by role (declared by name w/ system fallbacks, matching APM): body+     Satoshi, headers Familjen Grotesk, data/meta JetBrains Mono. */+  html, body { margin: 0; height: 100%; background: var(--bg); color: var(--txt); font: 13px/1.45 'Satoshi', -apple-system, 'Segoe UI', Roboto, sans-serif; overflow: hidden; }+  /* dragging to pan shouldn't select the sheet's text/labels */+  #svgbox, #svgbox * { user-select: none; -webkit-user-select: none; }+  /* match the sheet colour so the drawing reads as one infinite sheet, not a+     white page floating on a dark viewport */+  #svgbox { position: absolute; inset: 0; cursor: grab; background: #fbfbf6; }+  #svgbox:active { cursor: grabbing; }+  #svgbox svg { display: block; }+  .empty { position: absolute; inset: 0; display: grid; place-items: center; color: var(--muted); }++  /* component hotspots: transparent hit targets (no visual). */+  #svgbox svg .adom-comp { pointer-events: fill; cursor: pointer; }+  /* hierarchical-sheet links: highlight the box on hover, click to descend */+  #svgbox svg .adom-sheet-link { pointer-events: fill; cursor: pointer; }+  #svgbox svg .adom-sheet-link:hover { fill: var(--accent); fill-opacity: .12; stroke: var(--accent); stroke-width: .4; }+  /* sheet breadcrumb, top-left */+  #crumb { position: fixed; right: 12px; top: 12px; z-index: 40; display: none; align-items: center; gap: 6px;+           background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 5px 10px; font-size: 12px; }+  #crumb a { color: var(--accent); cursor: pointer; text-decoration: none; }+  #crumb a:hover { text-decoration: underline; }+  #crumb .sep { color: var(--muted); }+  #crumb .cur { color: var(--txt); }+  #crumb .sheetlbl { color: var(--muted); font-size: 10px; letter-spacing: .06em; text-transform: uppercase; }+  #crumb select { background: var(--elevated, #1c2128); color: var(--txt); border: 1px solid var(--line); border-radius: 6px; padding: 3px 6px; font: inherit; font-size: 12px; cursor: pointer; }+  #crumb select:focus { outline: none; border-color: var(--accent); }+  /* Hover highlight: recolour the hovered symbol's real KiCad strokes to the+     accent teal. This is a plain paint (a `stroke` swap), NOT an SVG `filter` —+     per-element drop-shadow filters forced an offscreen render for EACH of a+     symbol's strokes (a connector like J3 has ~1500), which made hovering crawl.+     A stroke recolour reads just as clearly and repaints almost for free.+     `paint-order:stroke` + a hairline widen makes it pop without a filter. */+  #svgbox svg .adom-sheet .symhl {+    stroke: #00b3a6 !important;+    stroke-width: .28 !important;+    paint-order: stroke;+  }+  /* keep the body fill readable: recolour its outline but don't fatten the fill */+  #svgbox svg .adom-sheet rect.symhl { stroke-width: .2 !important; }++  .panel { position: absolute; background: rgba(22,27,34,.82); backdrop-filter: blur(8px); border: 1px solid var(--line); border-radius: 10px; }+  #side { top: 12px; right: 12px; width: 220px; max-height: 94vh; padding: 10px 12px; display: flex; flex-direction: column; }+  #side h1 { margin: 0 0 8px; font-size: 12px; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); font-weight: 600; }+  .sec-h { font-size: 10px; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); font-weight: 600; margin: 2px 0 5px; border-bottom: 1px solid var(--line); padding-bottom: 3px; }+  #complist { overflow-y: auto; max-height: 74vh; }+  .crow { padding: 3px 7px; border-radius: 5px; cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+  .crow b { color: var(--accent); }+  .crow:hover { background: #1c2a2a; }+  .crow.sel { background: var(--accent); color: #06232a; }+  .crow.sel b { color: #06232a; }+  #fitbtn { margin-top: 8px; width: 100%; background: #17231c; color: var(--txt); border: 1px solid var(--line); border-radius: 7px; padding: 5px; cursor: pointer; }+  #fitbtn:hover { border-color: var(--accent); }+  #stat { bottom: 12px; left: 12px; padding: 6px 11px; color: var(--muted); }+  .muted { color: var(--muted); }++  /* follows the cursor and flips away from the viewport edges (same as the+     layout viewer); a click pins it where it currently sits, and only then does+     it accept pointer events so the JLC/wiki/datasheet links are clickable. */+  #card { position: fixed; z-index: 9999; display: none; min-width: 210px; max-width: 300px; padding: 10px 12px; pointer-events: none; }+  /* abridged hover card (small/embedded screens): ref · MPN · stock only */+  #card.brief { min-width: 0; max-width: 230px; padding: 7px 9px; }+  #card.brief .ci-h { margin-bottom: 4px; padding-bottom: 4px; }+  #card.brief .ci-ref { font-size: 13px; }+  #card.pinned { pointer-events: auto; box-shadow: 0 0 0 1px var(--accent); }+  .ci-h { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; margin-bottom: 5px; padding-bottom: 5px; border-bottom: 1px solid var(--line); }+  .ci-ref { font-weight: 700; color: var(--accent); font-size: 15px; }+  .ci-val { color: var(--txt); }+  .ci-desc { color: var(--muted); font-size: 12px; margin-bottom: 6px; }+  .ci-row { display: flex; justify-content: space-between; gap: 10px; padding: 1px 0; }+  .ci-k { color: var(--muted); }+  .ci-v { text-align: right; word-break: break-word; }+  .ci-enrich { margin-top: 7px; padding-top: 7px; border-top: 1px solid var(--line); }+  .pills { display: flex; flex-wrap: wrap; gap: 5px; }+  .pill { background: #17231c; border: 1px solid var(--line); border-radius: 999px; padding: 1px 8px; font-size: 11px; }+  .pill.ok { color: #57d97e; border-color: #2c5a3a; }+  .pill.no { color: #e08a8a; border-color: #5a2c2c; }+  .pill.tier { color: #f2d060; }+  .pill.pop { color: #cba6ff; }+  .ci-mfr { color: var(--txt); font-size: 12px; margin-bottom: 5px; }+  .ci-links { margin-top: 6px; display: flex; gap: 12px; }+  .ci-lnk, .ci-ds { color: #6bb3ff; text-decoration: none; font-size: 12px; }+  .ci-ds { display: inline-block; margin-top: 6px; }+  #side h1, .sec-h { font-family: 'Familjen Grotesk', -apple-system, sans-serif; }++  /* ── canonical Adom 44px three-zone header (brand · subject · actions) ──+     Shown standalone / fullscreened; hidden in APM's small embedded panes+     (body.chrome gate, same as the side panels). */+  header.app { display: none; position: fixed; top: 0; left: 0; right: 0; height: 44px; z-index: 50;+    grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 14px;+    background: var(--panel); border-bottom: 1px solid var(--edge); }+  body.chrome header.app { display: grid; }+  body.chrome #svgbox { top: 44px; }+  body.chrome #side { top: 56px; }+  body.chrome #crumb { top: 56px; }+  header.app .brand { display: flex; align-items: center; gap: 8px; min-width: 0; position: relative; cursor: default; padding-right: 14px; border-right: 1px solid var(--edge); }+  header.app .brand svg { width: 16px; height: 16px; color: var(--ink); flex: 0 0 16px; }+  header.app .app-name { font-family: 'Familjen Grotesk', -apple-system, sans-serif; font-weight: 600; font-size: 13px; color: var(--acc); white-space: nowrap; }+  header.app .app-sub { color: var(--mut); font-size: 12px; white-space: nowrap; }+  header.app .app-sub::before { content: "·"; margin: 0 6px; color: var(--mut); }+  header.app .subject { justify-self: center; display: flex; align-items: baseline; gap: 10px; min-width: 0; }+  header.app .subject-name { font-weight: 600; font-size: 13px; max-width: 44vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+  header.app .subject-meta { font-family: 'JetBrains Mono', ui-monospace, monospace; font-size: 11px; color: var(--mut); white-space: nowrap; }+  header.app .actions { justify-self: end; display: flex; align-items: center; gap: 8px; }+  header.app .actions button { background: var(--elevated); color: var(--ink); border: 1px solid var(--edge); border-radius: 7px; width: 30px; height: 26px; cursor: pointer; display: grid; place-items: center; }+  header.app .actions button:hover { border-color: var(--acc); }+  header.app .actions button svg { width: 15px; height: 15px; }+  header.app .appinfo { position: absolute; top: calc(100% + 6px); left: 0; min-width: 220px; background: var(--overlay); border: 1px solid var(--edge);+    border-radius: 10px; box-shadow: 0 12px 34px #000a; padding: 12px 14px; font-size: 12px; opacity: 0; visibility: hidden; transition: opacity .18s ease; pointer-events: none; z-index: 60; }+  header.app .brand:hover .appinfo { opacity: 1; visibility: visible; pointer-events: auto; transition-delay: .6s; }+  header.app .appinfo .ai-row { display: flex; justify-content: space-between; gap: 16px; padding: 2px 0; }+  header.app .appinfo .ai-k { color: var(--mut); }+  header.app .appinfo .ai-v { font-family: 'JetBrains Mono', ui-monospace, monospace; }+  header.app .appinfo a { color: var(--acc); text-decoration: none; }+  header.app .appinfo a:hover { text-decoration: underline; }++  /* ── toasts: transient feedback, bottom-center; also the AI's live channel ── */+  #toasts { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); z-index: 3000; display: flex; flex-direction: column-reverse; gap: 8px; align-items: center; pointer-events: none; }+  .toast { pointer-events: auto; min-width: 200px; max-width: min(420px,90vw); display: flex; align-items: center; gap: 10px; padding: 10px 13px; border-radius: 10px;+    background: var(--overlay); border: 1px solid var(--edge); color: var(--ink); font-size: 13px; box-shadow: 0 10px 30px #000a; cursor: pointer; animation: toastin .18s ease; }+  @keyframes toastin { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }+  .toast.out { opacity: 0; transform: translateY(8px); transition: opacity .2s ease, transform .2s ease; }+  .toast .ti { flex: 0 0 16px; width: 16px; height: 16px; }+  .toast.success .ti { color: var(--green); } .toast.success { border-color: #2c5a3a; }+  .toast.error .ti { color: var(--red); } .toast.error { border-color: #5a2c2c; }+  .toast.info .ti { color: var(--acc); }+  .toast .tmsg { flex: 1; min-width: 0; }++  /* ── tooltips: body-appended fixed div, 600ms reveal, viewport-clamped both axes.+     Never a ::after (clipped by panel overflow/backdrop-filter). ── */+  #tt { position: fixed; z-index: 99999; max-width: 260px; background: var(--overlay); color: var(--ink); border: 1px solid var(--edge);+    border-radius: 7px; padding: 6px 9px; font-size: 12px; line-height: 1.4; box-shadow: 0 8px 22px #000b; pointer-events: none;+    opacity: 0; transform: translateY(3px); transition: opacity .18s ease, transform .18s ease; text-transform: none; }+  #tt.show { opacity: 1; transform: none; }+  @media (hover: none), (pointer: coarse) { #tt { display: none; } }+</style>+</head>+<body>+  <header class="app">+    <div class="brand">+      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12h4l2-5 3 10 2-5h7"/><circle cx="19" cy="12" r="1.4"/></svg>+      <span class="app-name">Schematic Viewer</span><span class="app-sub">interactive sheet</span>+      <div class="appinfo">+        <div class="ai-row"><span class="ai-k">version</span><span class="ai-v" id="ai-ver">-</span></div>+        <div class="ai-row"><span class="ai-k">engine</span><span class="ai-v">KiCad · Altium · Fusion</span></div>+        <div class="ai-row"><span class="ai-k">source</span><a href="https://wiki.adom.inc/adom/adom-schematic" target="_blank" rel="noopener">wiki page ↗</a></div>+      </div>+    </div>+    <div class="subject"><span class="subject-name" id="hdr-name"></span><span class="subject-meta" id="hdr-meta"></span></div>+    <div class="actions">+      <button id="hdr-fit" data-tip="Fit the whole sheet to the view (also: the Fit button, or press F)"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg></button>+    </div>+  </header>+  <div id="svgbox"><div class="empty">loading…</div></div>+  <div id="crumb"></div>+  <div id="side" class="panel">+    <div class="sec-h">Components</div>+    <div id="complist"></div>+    <button id="fitbtn" data-tip="Zoom to fit the entire sheet">Fit</button>+  </div>+  <div id="stat" class="panel"></div>+  <div id="card" class="panel"></div>+  <div id="toasts"></div>+  <script src="viewer.js"></script>+</body>+</html>
src/eagle_sch.rsadded+416
@@ -0,0 +1,416 @@+//! Fusion 360 Electronics / EAGLE `.sch` schematic parser + renderer.+//!+//! Fusion Electronics is EAGLE underneath, so one parser serves both. Unlike the+//! KiCad path there is no headless renderer to produce the visual base, so we+//! draw the sheet ourselves in EAGLE's own colour convention (green nets, red+//! symbol outlines, dark-red pins on a light sheet).+//!+//! The upside of self-rendering: we KNOW which primitive belongs to which+//! instance, so every element is tagged `data-cref` directly instead of being+//! inferred by bbox containment the way the KiCad path has to. The frontend's+//! halo highlight then works unchanged.+//!+//! Coordinates: EAGLE is mm, Y-up; we emit Y-down, so every Y is negated.++use crate::sch_parse::{Comp, Sheet};+use roxmltree::{Document, Node};+use std::collections::HashMap;+use std::fmt::Write as _;++pub fn looks_like_eagle(text: &str) -> bool {+    let head = &text[..text.len().min(4096)];+    head.contains("<eagle") && text.contains("<schematic")+}++fn at(n: Node, k: &str) -> String { n.attribute(k).unwrap_or("").to_string() }+fn num(n: Node, k: &str) -> f64 { n.attribute(k).and_then(|v| v.parse().ok()).unwrap_or(0.0) }++fn rot_of(s: &str) -> (f64, bool) {+    let mirror = s.contains('M');+    let deg: f64 = s.chars().filter(|c| c.is_ascii_digit() || *c == '.').collect::<String>().parse().unwrap_or(0.0);+    (deg, mirror)+}++/// Place a symbol-local point onto the sheet (and flip Y for SVG).+fn place(px: f64, py: f64, ix: f64, iy: f64, deg: f64, mirror: bool) -> (f64, f64) {+    let x = if mirror { -px } else { px };+    let r = deg.to_radians();+    let (s, c) = (r.sin(), r.cos());+    (ix + x * c - py * s, -(iy + x * s + py * c))+}++// EAGLE layer colours, as the EDA itself draws them+const C_NET: &str = "#1a9648";     // layer 91 Nets — Fusion green+const C_SYM: &str = "#b11313";     // layer 94 Symbols — Fusion red body outline+const C_PIN: &str = "#1a9648";     // layer 93 Pins — green stub+const C_PINEND: &str = "#e01010";  // unconnected pin-end tick — red+const C_NAME: &str = "#141414";    // layer 95 Names — near-black+const C_VALUE: &str = "#7d828b";   // layer 96 Values — gray+const C_TEXT: &str = "#444444";+const C_INFO: &str = "#8a8f98";    // layer 97/98 Info/Guide — EAGLE draws these gray++fn esc(s: &str) -> String {+    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")+}++/// EAGLE layer number -> the colour the EDA draws it, so a symbol's own primitives+/// keep their layer identity (94 body dark-red, 93/91 green, 95/96 name/value,+/// 97/98 info gray) instead of being flattened to one colour.+fn layer_color(n: i32) -> Option<&'static str> {+    match n {+        91 => Some(C_NET), 93 => Some(C_PIN), 94 => Some(C_SYM),+        95 => Some(C_NAME), 96 => Some(C_VALUE), 97 | 98 => Some(C_INFO),+        _ => None,+    }+}++/// Emit one EAGLE text primitive FAITHFULLY: honour size, alignment and rotation+/// with EAGLE's "keep readable" rule — text whose angle lands in (90,270] is+/// un-flipped and BOTH alignments mirrored, so it never renders upside down. This+/// is what stops smashed NAME/VALUE labels (often rot=R180) from flowing back over+/// their own symbol. `x,y` are already sheet coords (Y-down).+#[allow(clippy::too_many_arguments)]+fn draw_text(out: &mut String, tag: &str, x: f64, y: f64, text: &str, size: f64,+             color: &str, rot: f64, align: &str, mirror: bool) {+    if text.is_empty() { return; }+    // EAGLE align is "<v>-<h>" (bottom-left is the default), or a bare "center".+    let a = if align.is_empty() { "bottom-left" } else { align };+    let (mut valign, mut halign) = ("bottom", "left");+    if a == "center" { valign = "center"; halign = "center"; }+    else {+        for part in a.split('-') {+            match part { "top" | "center" | "bottom" => valign = part, "left" | "right" => halign = part, _ => {} }+        }+    }+    let mut r = ((rot % 360.0) + 360.0) % 360.0;+    if mirror {+        halign = if halign == "left" { "right" } else if halign == "right" { "left" } else { halign };+        r = (360.0 - r) % 360.0;+    }+    // Readability: 90 < r <= 270 → drop 180deg of glyph rotation, mirror both aligns.+    let mut glyph_rot = r;+    if r > 90.0 && r <= 270.0 {+        glyph_rot = r - 180.0;+        halign = if halign == "left" { "right" } else if halign == "right" { "left" } else { halign };+        valign = if valign == "top" { "bottom" } else if valign == "bottom" { "top" } else { valign };+    }+    let anchor = match halign { "center" => "middle", "right" => "end", _ => "start" };+    // Y is flipped, so EAGLE "bottom" (text sits above the anchor) is the alphabetic+    // baseline; "top" hangs below; "center" is central.+    let baseline = match valign { "center" => "central", "top" => "hanging", _ => "auto" };+    let transform = if glyph_rot.abs() > 0.01 {+        format!(r##" transform="rotate({:.2} {:.3} {:.3})""##, glyph_rot, x, y)+    } else { String::new() };+    let _ = write!(out, r##"<text{tag} x="{:.3}" y="{:.3}" font-size="{:.3}" fill="{}" text-anchor="{}" dominant-baseline="{}"{}>{}</text>"##,+        x, y, size, color, anchor, baseline, transform, esc(text));+}++struct Sym<'a, 'i> { nodes: Vec<Node<'a, 'i>> }++/// Parse + render in one pass. Returns (svg, sheet).+pub fn render_sheet(xml: &str) -> Result<(String, Sheet), String> {+    let opts = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };+    let doc = Document::parse_with_options(xml, opts).map_err(|e| format!("eagle .sch: {e}"))?;+    let root = doc.root_element();+    let schem = root.descendants().find(|n| n.has_tag_name("schematic")).ok_or("eagle: no <schematic>")?;++    // symbols, keyed "library:symbol"+    let mut syms: HashMap<String, Sym> = HashMap::new();+    // deviceset -> (gate name -> symbol name), and deviceset+device -> package+    let mut gate_sym: HashMap<String, String> = HashMap::new();+    let mut dev_pkg: HashMap<String, String> = HashMap::new();+    let mut dev_desc: HashMap<String, String> = HashMap::new();+    for lib in schem.descendants().filter(|n| n.has_tag_name("library")) {+        let lname = at(lib, "name");+        for s in lib.descendants().filter(|n| n.has_tag_name("symbol")) {+            syms.insert(format!("{}:{}", lname, at(s, "name")), Sym { nodes: s.children().filter(|c| c.is_element()).collect() });+        }+        for ds in lib.descendants().filter(|n| n.has_tag_name("deviceset")) {+            let dsn = at(ds, "name");+            if let Some(d) = ds.children().find(|c| c.has_tag_name("description")) {+                dev_desc.insert(format!("{}:{}", lname, dsn), d.text().unwrap_or("").trim().to_string());+            }+            for g in ds.descendants().filter(|n| n.has_tag_name("gate")) {+                gate_sym.insert(format!("{}:{}:{}", lname, dsn, at(g, "name")), format!("{}:{}", lname, at(g, "symbol")));+            }+            for d in ds.descendants().filter(|n| n.has_tag_name("device")) {+                dev_pkg.insert(format!("{}:{}:{}", lname, dsn, at(d, "name")), at(d, "package"));+            }+        }+    }++    // parts+    struct Part { library: String, deviceset: String, device: String, value: String, lcsc: String, datasheet: String }+    let mut parts: HashMap<String, Part> = HashMap::new();+    for p in schem.descendants().filter(|n| n.has_tag_name("part")) {+        let mut lcsc = String::new();+        let mut datasheet = String::new();+        for a in p.children().filter(|c| c.has_tag_name("attribute")) {+            let k = at(a, "name").to_uppercase();+            let v = at(a, "value");+            if k.contains("LCSC") || k.contains("JLC") { lcsc = v; }+            else if k.contains("DATASHEET") { datasheet = v; }+        }+        parts.insert(at(p, "name"), Part {+            library: at(p, "library"), deviceset: at(p, "deviceset"), device: at(p, "device"),+            value: at(p, "value"), lcsc, datasheet,+        });+    }++    let mut body = String::new();  // sheet graphics (wires, symbols)+    let mut comps: Vec<Comp> = Vec::new();+    let mut ext: Vec<(f64, f64)> = Vec::new();++    // ── nets: wires, junctions, labels ──────────────────────────────────────+    for net in schem.descendants().filter(|n| n.has_tag_name("net")) {+        let nname = at(net, "name");+        for seg in net.children().filter(|c| c.has_tag_name("segment")) {+            for w in seg.children().filter(|c| c.has_tag_name("wire")) {+                let (x1, y1) = (num(w, "x1"), -num(w, "y1"));+                let (x2, y2) = (num(w, "x2"), -num(w, "y2"));+                ext.push((x1, y1)); ext.push((x2, y2));+                let _ = write!(body, r##"<line class="adom-wire" data-net="{}" x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="{:.3}" stroke-linecap="round"/>"##,+                    esc(&nname), x1, y1, x2, y2, C_NET, num(w, "width").max(0.15));+            }+            for j in seg.children().filter(|c| c.has_tag_name("junction")) {+                let _ = write!(body, r##"<circle cx="{:.3}" cy="{:.3}" r="0.5" fill="{}"/>"##, num(j, "x"), -num(j, "y"), C_NET);+            }+            for l in seg.children().filter(|c| c.has_tag_name("label")) {+                let (x, y) = (num(l, "x"), -num(l, "y"));+                let size = if num(l, "size") > 0.0 { num(l, "size") } else { 1.778 };+                let (deg, _) = rot_of(&at(l, "rot"));+                ext.push((x - 12.0, y - 3.0)); ext.push((x + 12.0, y + 3.0));+                if at(l, "xref").eq_ignore_ascii_case("yes") {+                    draw_xref_flag(&mut body, "", x, y, &nname, size, deg);+                } else {+                    draw_text(&mut body, "", x + 0.4, y, &nname, size, C_NET, deg, "bottom-left", false);+                }+            }+        }+    }++    // ── free graphics on the sheet (frame, notes) ───────────────────────────+    for pl in schem.descendants().filter(|n| n.has_tag_name("plain")) {+        for n in pl.children().filter(|c| c.is_element()) {+            draw_prim(&mut body, n, 0.0, 0.0, 0.0, false, C_TEXT, "", &mut ext, "");+        }+    }++    // ── instances: the actual components ────────────────────────────────────+    for inst in schem.descendants().filter(|n| n.has_tag_name("instance")) {+        let pname = at(inst, "part");+        let (ix, iy) = (num(inst, "x"), num(inst, "y"));+        let (deg, mirror) = rot_of(&at(inst, "rot"));+        let part = match parts.get(&pname) { Some(p) => p, None => continue };+        let skey = format!("{}:{}:{}", part.library, part.deviceset, at(inst, "gate"));+        let sym = gate_sym.get(&skey).and_then(|k| syms.get(k));++        let mut my: Vec<(f64, f64)> = Vec::new();+        let mut pin_count = 0usize;+        let cref = esc(&pname);+        // The symbol's >NAME / >VALUE placeholders (local x, y, size, align, rot) —+        // used to place the label when the instance didn't smash it out explicitly.+        let mut name_ph: Option<(f64, f64, f64, String, f64)> = None;+        let mut value_ph: Option<(f64, f64, f64, String, f64)> = None;+        let ctag = format!(r##" data-cref="{}""##, cref);+        let _ = write!(body, r##"<g class="adom-sym" data-cref="{}">"##, cref);+        if let Some(sym) = sym {+            for n in &sym.nodes {+                let n = *n;+                if n.has_tag_name("pin") {+                    pin_count += 1;+                    let len = match at(n, "length").as_str() { "point" => 0.0, "short" => 2.54, "long" => 7.62, _ => 5.08 };+                    let (pdeg, _) = rot_of(&at(n, "rot"));+                    let (x0, y0) = (num(n, "x"), num(n, "y"));+                    let a = pdeg.to_radians();+                    let (x1, y1) = (x0 + len * a.cos(), y0 + len * a.sin());+                    let (sx, sy) = place(x0, y0, ix, iy, deg, mirror);+                    let (ex2, ey2) = place(x1, y1, ix, iy, deg, mirror);+                    my.push((sx, sy)); my.push((ex2, ey2));+                    let _ = write!(body, r##"<line data-cref="{}" x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="0.15"/>"##,+                        cref, sx, sy, ex2, ey2, C_PIN);+                    // EAGLE draws the pin junction as a small red mark at the connect point.+                    let _ = write!(body, r##"<circle data-cref="{}" cx="{:.3}" cy="{:.3}" r="0.35" fill="none" stroke="{}" stroke-width="0.18"/>"##,+                        cref, sx, sy, C_PINEND);+                    continue;+                }+                if n.has_tag_name("text") {+                    let t = n.text().unwrap_or("").trim().to_string();+                    let ph = (num(n, "x"), num(n, "y"), if num(n, "size") > 0.0 { num(n, "size") } else { 1.4224 }, at(n, "align"), rot_of(&at(n, "rot")).0);+                    if t.eq_ignore_ascii_case(">NAME") { name_ph = Some(ph); continue; }+                    if t.eq_ignore_ascii_case(">VALUE") { value_ph = Some(ph); continue; }+                }+                draw_prim(&mut body, n, ix, iy, deg, mirror, C_SYM, &cref, &mut my, &pname);+            }+        }+        // NAME / VALUE. Priority: a smashed instance <attribute> (ABSOLUTE coords ++        // its own size/align/rot) → the symbol's >NAME/>VALUE placeholder placed by+        // the instance → a sensible default. This is what stops labels flowing back+        // over their own symbol.+        let inst_attr = |want: &str| inst.children().find(|c| c.has_tag_name("attribute") && at(*c, "name").eq_ignore_ascii_case(want));+        let (nx, ny) = if let Some(a) = inst_attr("NAME") {+            let sz = if num(a, "size") > 0.0 { num(a, "size") } else { 1.778 };+            let (x, y) = (num(a, "x"), -num(a, "y"));+            draw_text(&mut body, &ctag, x, y, &pname, sz, C_NAME, rot_of(&at(a, "rot")).0, &at(a, "align"), false);+            (x, y)+        } else if let Some((px, py, sz, al, pr)) = name_ph.clone() {+            let (x, y) = place(px, py, ix, iy, deg, mirror);+            draw_text(&mut body, &ctag, x, y, &pname, sz, C_NAME, deg + pr, &al, mirror);+            (x, y)+        } else {+            let (x, y) = place(0.0, 2.2, ix, iy, deg, mirror);+            draw_text(&mut body, &ctag, x, y, &pname, 1.778, C_NAME, 0.0, "bottom-left", false);+            (x, y)+        };+        let (vx, vy) = if part.value.is_empty() { (nx, ny) } else if let Some(a) = inst_attr("VALUE") {+            let sz = if num(a, "size") > 0.0 { num(a, "size") } else { 1.778 };+            let (x, y) = (num(a, "x"), -num(a, "y"));+            draw_text(&mut body, &ctag, x, y, &part.value, sz, C_VALUE, rot_of(&at(a, "rot")).0, &at(a, "align"), false);+            (x, y)+        } else if let Some((px, py, sz, al, pr)) = value_ph.clone() {+            let (x, y) = place(px, py, ix, iy, deg, mirror);+            draw_text(&mut body, &ctag, x, y, &part.value, sz, C_VALUE, deg + pr, &al, mirror);+            (x, y)+        } else {+            let (x, y) = place(0.0, -2.2, ix, iy, deg, mirror);+            draw_text(&mut body, &ctag, x, y, &part.value, 1.778, C_VALUE, 0.0, "bottom-left", false);+            (x, y)+        };+        body.push_str("</g>");+        my.push((nx - 3.0, ny - 2.0)); my.push((nx + 8.0, ny + 2.0));+        my.push((vx - 3.0, vy - 2.0)); my.push((vx + 8.0, vy + 2.0));++        if my.is_empty() { my.push((ix - 2.54, -iy - 2.54)); my.push((ix + 2.54, -iy + 2.54)); }+        let (mut mnx, mut mny, mut mxx, mut mxy) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+        for (x, y) in &my { mnx = mnx.min(*x); mxx = mxx.max(*x); mny = mny.min(*y); mxy = mxy.max(*y); }+        ext.extend(my.iter().copied());++        let pkgkey = format!("{}:{}:{}", part.library, part.deviceset, part.device);+        comps.push(Comp {+            reference: pname.clone(),+            value: part.value.clone(),+            footprint: dev_pkg.get(&pkgkey).cloned().unwrap_or_default(),+            lcsc: part.lcsc.clone(),+            description: dev_desc.get(&format!("{}:{}", part.library, part.deviceset)).cloned().unwrap_or_default(),+            datasheet: part.datasheet.clone(),+            x: ix, y: -iy,+            bbox: [mnx, mny, mxx, mxy],+            pin_count,+            regions: vec![[mnx, mny, mxx, mxy]],+        });+    }++    // ── compose ─────────────────────────────────────────────────────────────+    if ext.is_empty() { ext.push((0.0, 0.0)); ext.push((100.0, 100.0)); }+    let m = 5.0;+    let minx = ext.iter().map(|p| p.0).fold(f64::INFINITY, f64::min) - m;+    let miny = ext.iter().map(|p| p.1).fold(f64::INFINITY, f64::min) - m;+    let maxx = ext.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max) + m;+    let maxy = ext.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max) + m;+    let (w, h) = (maxx - minx, maxy - miny);+    let sheet = Sheet { comps, sub_sheets: Vec::new(), content_bbox: (minx, miny, w, h) };++    let mut s = String::new();+    let _ = write!(s, r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{:.3} {:.3} {:.3} {:.3}" preserveAspectRatio="xMidYMid meet" font-family="ui-monospace,Menlo,monospace">"##, minx, miny, w, h);+    let _ = write!(s, r##"<rect class="adom-sheet-bg" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="#fbfbf6"/>"##, minx, miny, w, h);+    let _ = write!(s, r##"<g class="adom-sheet">{}</g>"##, body);+    s.push_str(&crate::sch_parse::build_overlay(&sheet));+    s.push_str("</svg>");+    Ok((s, sheet))+}++/// Draw an EAGLE cross-reference net LABEL as the gray pointed pennant Fusion+/// draws (a rectangle with a triangular point at the net-attachment end). `x,y`+/// are already sheet coords (Y-down); `rot` selects the point direction+/// (R0 right, R90 up, R180 left, R270 down).+fn draw_xref_flag(out: &mut String, tag: &str, x: f64, y: f64, name: &str, size: f64, rot: f64) {+    // Fusion draws the net-label text noticeably larger than the plain label size,+    // filling the flag; bump it and fit the pennant tightly around it.+    let ts = size * 1.4;                                           // flag text size+    let w = name.chars().count() as f64 * ts * 0.62 + ts * 0.7;    // body width+    let h = ts * 1.35;                                             // body height+    let pl = h * 0.5;                                              // point length+    // Local pennant: attach tip at (0,0) pointing -x (LEFT), body to the RIGHT — so+    // an R0 label points left toward its net and its text sits in clear space; R180+    // rotates it to point right (e.g. into U$1), matching how Fusion draws them.+    let local = [(0.0, 0.0), (pl, -h / 2.0), (pl + w, -h / 2.0), (pl + w, h / 2.0), (pl, h / 2.0)];+    // EAGLE rot is CCW in Y-up; on our Y-down sheet that's a CW screen rotation of+    // the same magnitude, so screen theta = -rot puts R90 pointing up.+    let th = (-rot).to_radians();+    let (s, c) = (th.sin(), th.cos());+    let mut d = String::new();+    for (i, (lx, ly)) in local.iter().enumerate() {+        let (rx, ry) = (lx * c - ly * s + x, lx * s + ly * c + y);+        let _ = write!(d, "{} {:.3} {:.3} ", if i == 0 { "M" } else { "L" }, rx, ry);+    }+    d.push('Z');+    let _ = write!(out, r##"<path{tag} d="{}" fill="none" stroke="{}" stroke-width="0.18"/>"##, d, C_INFO);+    // Net name centred in the body, rotated with the flag.+    let (bx, by) = (pl + w / 2.0, 0.0);+    let (tx, ty) = (bx * c - by * s + x, bx * s + by * c + y);+    let mut r = ((rot % 360.0) + 360.0) % 360.0;+    if r > 90.0 && r <= 270.0 { r -= 180.0; }+    let transform = if r.abs() > 0.01 { format!(r##" transform="rotate({:.2} {:.3} {:.3})""##, r, tx, ty) } else { String::new() };+    let _ = write!(out, r##"<text{tag} x="{:.3}" y="{:.3}" font-size="{:.3}" fill="{}" text-anchor="middle" dominant-baseline="central"{}>{}</text>"##,+        tx, ty, ts, C_NAME, transform, esc(name));+}++/// Draw one EAGLE primitive (wire/rect/circle/polygon/text) into `out`.+#[allow(clippy::too_many_arguments)]+fn draw_prim(out: &mut String, n: Node, ix: f64, iy: f64, deg: f64, mirror: bool,+             color: &str, cref: &str, ext: &mut Vec<(f64, f64)>, _owner: &str) {+    let p = |x: f64, y: f64| place(x, y, ix, iy, deg, mirror);+    let tag = if cref.is_empty() { String::new() } else { format!(r##" data-cref="{}""##, cref) };+    let layer = num(n, "layer") as i32;+    // Each primitive keeps its EAGLE layer colour (94 body red, 97 info gray, …),+    // falling back to the caller's colour for unmapped layers.+    let lc = layer_color(layer).unwrap_or(color);+    match n.tag_name().name() {+        "wire" => {+            let (x1, y1) = p(num(n, "x1"), num(n, "y1"));+            let (x2, y2) = p(num(n, "x2"), num(n, "y2"));+            ext.push((x1, y1)); ext.push((x2, y2));+            let _ = write!(out, r##"<line{} x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="{:.3}" stroke-linecap="round"/>"##,+                tag, x1, y1, x2, y2, lc, num(n, "width").max(0.15));+        }+        "rectangle" => {+            let (x1, y1) = p(num(n, "x1"), num(n, "y1"));+            let (x2, y2) = p(num(n, "x2"), num(n, "y2"));+            ext.push((x1, y1)); ext.push((x2, y2));+            let _ = write!(out, r##"<rect{} x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="none" stroke="{}" stroke-width="0.2"/>"##,+                tag, x1.min(x2), y1.min(y2), (x2 - x1).abs(), (y2 - y1).abs(), lc);+        }+        "circle" => {+            let (cx, cy) = p(num(n, "x"), num(n, "y"));+            let r = num(n, "radius");+            ext.push((cx - r, cy - r)); ext.push((cx + r, cy + r));+            let _ = write!(out, r##"<circle{} cx="{:.3}" cy="{:.3}" r="{:.3}" fill="none" stroke="{}" stroke-width="{:.3}"/>"##,+                tag, cx, cy, r, lc, num(n, "width").max(0.15));+        }+        "polygon" | "polygonshape" => {+            let pts: Vec<(f64, f64)> = n.children().filter(|c| c.has_tag_name("vertex"))+                .map(|v| p(num(v, "x"), num(v, "y"))).collect();+            if pts.len() < 2 { return; }+            let mut d = String::new();+            for (i, (x, y)) in pts.iter().enumerate() {+                let _ = write!(d, "{} {:.3} {:.3} ", if i == 0 { "M" } else { "L" }, x, y);+            }+            d.push('Z');+            ext.extend(pts.iter().copied());+            // A pour=solid polygon (the mechanical-pin connector shapes on the Info+            // layer) fills solidly like Fusion draws it; other polygons stay light.+            let opacity = if at(n, "pour") == "solid" { 0.7 } else { 0.25 };+            let _ = write!(out, r##"<path{} d="{}" fill="{}" fill-opacity="{}" stroke="{}" stroke-width="0.15"/>"##, tag, d, lc, opacity, lc);+        }+        "text" => {+            let (x, y) = p(num(n, "x"), num(n, "y"));+            let t = n.text().unwrap_or("").trim().to_string();+            // >NAME / >VALUE placeholders are drawn from the instance instead+            if t.is_empty() || t.starts_with('>') { return; }+            let size = if num(n, "size") > 0.0 { num(n, "size") } else { 1.4 };+            ext.push((x, y - size)); ext.push((x + t.chars().count() as f64 * size * 0.6, y));+            draw_text(out, &tag, x, y, &t, size, lc, deg + rot_of(&at(n, "rot")).0, &at(n, "align"), mirror);+        }+        _ => {}+    }+}
src/enrich.rsadded+101
@@ -0,0 +1,101 @@+//! Component enrichment: MPN → { price, stock, tier, popularity, wiki_url }.+//!+//! Sources (sibling Adom CLIs, shelled with a hard timeout so a slow/absent CLI+//! never hangs the UI):+//!   • popularity + wiki page — `adom-wiki discover search --query <mpn> --json`+//!     (vouch_count / star_count → popularity; owner/slug → wiki_url)+//!   • price + stock — `adom-parts-search search <mpn>` (max stock across+//!     vendors; first real unit price; JLCPCB tier from flags)+//!+//! Because the vendor lookup is slow (~30 s, live APIs), the server PRE-WARMS the+//! cache for every board MPN in a background thread at load time; hover then hits+//! the cache. `lookup()` is the (slow) cache-fill; `/enrich` reads the result.++use serde_json::{json, Value};+use std::process::{Command, Stdio};+use std::sync::mpsc;+use std::time::Duration;++/// Run a command, capping wall-clock at `secs`. Returns stdout on success.+fn run_capped(bin: &str, args: &[&str], secs: u64) -> Option<String> {+    let bin = bin.to_string();+    let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();+    let (tx, rx) = mpsc::channel();+    std::thread::spawn(move || {+        let out = Command::new(&bin).args(&args).stdin(Stdio::null()).output();+        let _ = tx.send(out.ok().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).into_owned()));+    });+    rx.recv_timeout(Duration::from_secs(secs)).ok().flatten()+}++/// Strip any leading non-JSON preamble (parts-search prints an "OK: …" summary+/// line before its JSON) and parse.+fn parse_json_tail(s: &str) -> Option<Value> {+    let start = s.find(['{', '['])?;+    serde_json::from_str(&s[start..]).ok()+}++const JLCPCB_DEFAULT: &str = "https://jlcpcb-wela51osctvp.adom.cloud";++/// Enrich a schematic component: JLCPCB stock/price/tier by LCSC part number+/// (the molecule parts carry `LCSC PN` C-numbers), plus a wiki page ONLY on a+/// close name match (so passives don't match random pages). `value` is the+/// symbol Value (e.g. "BME690"); `lcsc` is the LCSC C-number.+pub fn lookup(value: &str, lcsc: &str) -> String {+    let mut out = json!({});+    let o = out.as_object_mut().unwrap();+    let mut mpn = String::new(); // real MPN, learned from JLCPCB++    // ── JLCPCB by LCSC PN — stock / price / tier / popularity / mfr ──+    let is_lcsc = lcsc.starts_with('C') && lcsc.len() > 1 && lcsc[1..].chars().all(|c| c.is_ascii_digit());+    if is_lcsc {+        let api = std::env::var("JLCPCB_API").unwrap_or_else(|_| JLCPCB_DEFAULT.to_string());+        if let Some(txt) = run_capped("adom-jlcpcb", &["search", lcsc, "--limit", "1", "--api", &api], 20) {+            if let Some(v) = parse_json_tail(&txt) {+                if let Some(c) = v.get("components").and_then(|c| c.as_array()).and_then(|a| a.first()) {+                    if let Some(s) = c.get("stock").and_then(|x| x.as_i64()) { o.insert("stock".into(), json!(s)); }+                    if let Some(p) = c.get("unit_price_usd").and_then(|x| x.as_f64()) { o.insert("price".into(), json!(format!("${:.4}", p))); }+                    let tier = if c.get("is_basic").and_then(|x| x.as_bool()).unwrap_or(false) { Some("Basic") }+                        else if c.get("is_preferred").and_then(|x| x.as_bool()).unwrap_or(false) { Some("Preferred") } else { Some("Extended") };+                    if let Some(t) = tier { o.insert("tier".into(), json!(t)); }+                    if let Some(pop) = c.get("popularity").and_then(|x| x.as_i64()) { o.insert("popularity".into(), json!(pop)); }+                    if let Some(u) = c.get("jlcpcb_url").and_then(|x| x.as_str()) { o.insert("jlc_url".into(), json!(u)); }+                    if let Some(m) = c.get("mfr").and_then(|x| x.as_str()) { mpn = m.to_string(); }+                    if let Some(mf) = c.get("manufacturer").and_then(|x| x.as_str()) { o.insert("mfr".into(), json!(mf)); }+                }+            }+        }+    }++    // ── wiki page — ONLY on a close name match (avoids garbage for passives) ──+    let wq = if !mpn.is_empty() { mpn.clone() } else { value.to_string() };+    if wq.len() > 2 {+        if let Some(txt) = run_capped("adom-wiki", &["discover", "search", "--query", &wq, "--limit", "5", "--json"], 12) {+            if let Some(v) = parse_json_tail(&txt) {+                if let Some(results) = v.get("data").and_then(|d| d.get("results")).and_then(|r| r.as_array()) {+                    let ql = wq.to_lowercase();+                    let pick = results.iter().find(|r| {+                        let t = r.get("title").and_then(|t| t.as_str()).unwrap_or("").to_lowercase();+                        t.len() > 2 && (t == ql || ql.contains(&t) || t.contains(&ql))+                    });+                    if let Some(r) = pick {+                        let owner = r.get("owner").and_then(|x| x.as_str()).unwrap_or("");+                        let slug = r.get("slug").and_then(|x| x.as_str()).unwrap_or("");+                        if !slug.is_empty() { o.insert("wiki_url".into(), json!(format!("https://wiki.adom.inc/{owner}/{slug}"))); }+                        if !o.contains_key("popularity") {+                            let vouch = r.get("vouch_count").and_then(|x| x.as_i64()).unwrap_or(0);+                            o.insert("popularity".into(), json!(vouch));+                        }+                    }+                }+            }+        }+    }++    // the real manufacturer part number (learned from JLCPCB) — the abridged+    // hover card shows this instead of the schematic's `value`.+    if !mpn.is_empty() { o.insert("mpn".into(), json!(mpn)); }++    if o.is_empty() { return "{\"error\":\"no data\"}".into(); }+    out.to_string()+}
src/kicad_sch.rsadded+501
@@ -0,0 +1,501 @@+//! Fetch a `.kicad_sch` rendered to an authentic KiCad SVG from service-kicad,+//! and compose it (cropped to the drawing) with our component hotspot overlay.+//!+//! Like the layout viewer: the visual is the EDA's own export; we only add an+//! invisible interaction layer aligned to the same page-mm coordinate system.++use crate::sch_parse::{self, Sheet};+use crate::sexpr::esc;+use anyhow::{bail, Result};+use serde::Serialize;+use std::collections::HashMap;+use std::fmt::Write as _;+use std::time::Duration;++const SERVICE_DEFAULT: &str = "https://kicad-rk5ue5pcfemi.adom.cloud";++#[derive(Serialize)]+pub struct RenderMeta {+    pub view_box: [f64; 4],+    pub components: Vec<sch_parse::Comp>,+    pub comp_count: usize,+    #[serde(default)]+    pub sub_sheets: Vec<sch_parse::SubSheet>,+}++fn base() -> String {+    std::env::var("KICAD_SERVICE_API").unwrap_or_else(|_| SERVICE_DEFAULT.to_string()).trim_end_matches('/').to_string()+}++/// Fetch the KiCad SVG for the whole sheet.+fn fetch_svg(sch: &str) -> Result<String> {+    let url = format!("{}/kicad/sch/export/svg", base());+    let resp = ureq::post(&url)+        .set("Content-Type", "application/octet-stream")+        .timeout(Duration::from_secs(30))+        .send_bytes(sch.as_bytes())+        .map_err(|e| anyhow::anyhow!("service-kicad sch export: {e}"))?;+    let svg = resp.into_string()?;+    if !svg.contains("<path") { bail!("service-kicad returned an empty sheet"); }+    Ok(svg)+}++fn extract_inner(svg: &str) -> String {+    let open_end = match svg.find("<svg").and_then(|s| svg[s..].find('>').map(|e| s + e + 1)) { Some(i) => i, None => return String::new() };+    let close = svg.rfind("</svg>").unwrap_or(svg.len());+    svg[open_end..close].to_string()+}++/// Tag each KiCad drawing element (path / circle / stroked-text group) with the+/// component whose bbox CONTAINS the element (`data-cref`), so the frontend can+/// recolour just that symbol's real lines on hover. Wires (which span outside any+/// one symbol) and the page frame are never captured.+fn tag_symbols(inner: &str,+               segs: &HashMap<crate::kicad_self::SegKey, String>,+               circles: &HashMap<(i32, i32, i32), String>,+               fields: &[(String, String, f64, f64)],+               pins: &[(String, f64, f64)],+               labels: &[(f64, f64)]) -> String {+    use regex::Regex;+    let num = Regex::new(r"-?\d+\.?\d*").unwrap();+    // bbox of a coordinate string (from a `d`/`points` attr; NOT the whole tag)+    let ebbox = |coords: &str| -> Option<(f64, f64, f64, f64)> {+        let ns: Vec<f64> = num.find_iter(coords).filter_map(|m| m.as_str().parse().ok()).collect();+        if ns.len() < 2 { return None; }+        let (mut mnx, mut mny, mut mxx, mut mxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+        for p in ns.chunks_exact(2) { mnx = mnx.min(p[0]); mxx = mxx.max(p[0]); mny = mny.min(p[1]); mxy = mxy.max(p[1]); }+        if mnx.is_finite() { Some((mnx, mny, mxx, mxy)) } else { None }+    };+    // The ONLY text that is a symbol's own is its Reference/Value field, placed at+    // an exact `(at)` position (`fields`). Given a rendered text group's page bbox,+    // return the reference whose Reference/Value anchor sits inside it (closest to+    // centre when several qualify). Pin names/numbers, net & power labels have no+    // field anchor there, so they stay standalone — exactly the user's rule.+    let field_at = |bb: (f64, f64, f64, f64)| -> Option<&str> {+        let (x0, y0, x1, y1) = bb;+        let t = 1.5;+        let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);+        let mut best: Option<(&str, f64)> = None;+        for (rf, _txt, fx, fy) in fields {+            if *fx >= x0 - t && *fx <= x1 + t && *fy >= y0 - t && *fy <= y1 + t {+                let d = (fx - cx).powi(2) + (fy - cy).powi(2);+                if best.map_or(true, |(_, bd)| d < bd) { best = Some((rf.as_str(), d)); }+            }+        }+        best.map(|(r, _)| r)+    };+    // PIN NAME / NUMBER text: symbol geometry too. A pin's body-end anchors its+    // name, its stub-midpoint anchors its number; a text group covering either (a+    // bit of slack) belongs to that symbol. Net/power labels sit at the pin's+    // CONNECTION point, which is NOT an anchor here, so they stay standalone.+    let pin_at = |bb: (f64, f64, f64, f64)| -> Option<&str> {+        let (x0, y0, x1, y1) = bb;+        let t = 1.6;+        let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);+        let mut best: Option<(&str, f64)> = None;+        for (rf, ax, ay) in pins {+            if *ax >= x0 - t && *ax <= x1 + t && *ay >= y0 - t && *ay <= y1 + t {+                let d = (ax - cx).powi(2) + (ay - cy).powi(2);+                if best.map_or(true, |(_, bd)| d < bd) { best = Some((rf.as_str(), d)); }+            }+        }+        best.map(|(r, _)| r)+    };++    // Injecting an attribute must PRESERVE self-closing tags: KiCad emits+    // `<path … />`, so the captured tail ends in `/`. Strip it and re-emit `/>`,+    // otherwise the element stops being self-closed and the rest of the sheet+    // nests inside it (which mangles the whole drawing).+    let split_close = |tail: &str| -> (String, &'static str) {+        let t = tail.trim_end();+        match t.strip_suffix('/') {+            Some(rest) => (rest.to_string(), "/>"),+            None => (tail.to_string(), ">"),+        }+    };++    // Only SYMBOL graphics belong to a component. KiCad wraps each primitive in a+    // `<g style="…stroke:#RRGGBB…">`: symbol bodies + fields are RED-family+    // (#840000, #A90000), while WIRES/junctions/no-connects are GREEN/TEAL+    // (#006464, #009600) and the paper is near-white. A big connector like J3 has+    // a 25x35mm bbox that ENCLOSES lots of wires and labels; tagging by bbox alone+    // captured them all, so hovering J3 lit half the sheet. Track the enclosing+    // group's stroke colour and only tag inside red-family (or stroked-text)+    // groups — a wire is never part of a component.+    let gcolor = Regex::new(r#"stroke:\s*#([0-9A-Fa-f]{6})"#).unwrap();+    // red-family = R channel clearly the largest → a symbol/field stroke+    let is_symbol_color = |hex: &str| -> bool {+        let (r, g, b) = (+            u8::from_str_radix(&hex[0..2], 16).unwrap_or(0),+            u8::from_str_radix(&hex[2..4], 16).unwrap_or(0),+            u8::from_str_radix(&hex[4..6], 16).unwrap_or(0),+        );+        r as i32 > g as i32 + 20 && r as i32 > b as i32 + 20+    };++    let tag_re = Regex::new(r#"<g\b[^>]*>|</g>|<path\b[^>]*>|<rect\b[^>]*>|<circle\b[^>]*>"#).unwrap();+    let path_d = Regex::new(r#"\bd="([^"]*)""#).unwrap();+    let rect_xywh = Regex::new(r#"x="([-\d.]+)"\s*y="([-\d.]+)"\s*width="([-\d.]+)"\s*height="([-\d.]+)""#).unwrap();+    let circ_cxy = Regex::new(r#"cx="([-\d.]+)"\s*cy="([-\d.]+)""#).unwrap();+    let circ_r = Regex::new(r#"cx="([-\d.]+)"\s*cy="([-\d.]+)"\s*r="([-\d.]+)""#).unwrap();+    let tf_re = Regex::new(r#"transform="([^"]*)""#).unwrap();++    // KiCad rotates symbols/text with `transform="rotate(a cx cy)"`; the element's+    // raw coords are in the PRE-rotation frame, so we must compose the group+    // transform stack and map coords to PAGE space before containment-testing —+    // otherwise a rotated label lands in a random bbox (this is what lit up J3).+    #[derive(Clone, Copy)]+    struct M { a: f64, b: f64, c: f64, d: f64, e: f64, f: f64 } // [a c e; b d f]+    let ident = M { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 };+    let mul = |p: M, q: M| M {+        a: p.a * q.a + p.c * q.b, b: p.b * q.a + p.d * q.b,+        c: p.a * q.c + p.c * q.d, d: p.b * q.c + p.d * q.d,+        e: p.a * q.e + p.c * q.f + p.e, f: p.b * q.e + p.d * q.f + p.f,+    };+    let apply = |m: &M, x: f64, y: f64| (m.a * x + m.c * y + m.e, m.b * x + m.d * y + m.f);+    let parse_tf = |s: &str, base: M| -> M {+        let mut cur = base;+        for cap in Regex::new(r"(\w+)\s*\(([^)]*)\)").unwrap().captures_iter(s) {+            let args: Vec<f64> = cap[2].split([',', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.parse().ok()).collect();+            let t = match (&cap[1], args.as_slice()) {+                ("translate", [x, y, ..]) => M { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: *x, f: *y },+                ("translate", [x]) => M { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: *x, f: 0.0 },+                ("scale", [sx, sy, ..]) => M { a: *sx, b: 0.0, c: 0.0, d: *sy, e: 0.0, f: 0.0 },+                ("scale", [sx]) => M { a: *sx, b: 0.0, c: 0.0, d: *sx, e: 0.0, f: 0.0 },+                ("rotate", [deg, cx, cy, ..]) => {+                    let r = deg.to_radians(); let (co, si) = (r.cos(), r.sin());+                    // translate(cx,cy) * rotate * translate(-cx,-cy)+                    M { a: co, b: si, c: -si, d: co, e: cx - co * cx + si * cy, f: cy - si * cx - co * cy }+                }+                ("rotate", [deg]) => { let r = deg.to_radians(); M { a: r.cos(), b: r.sin(), c: -r.sin(), d: r.cos(), e: 0.0, f: 0.0 } }+                _ => M { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 },+            };+            cur = mul(cur, t);+        }+        cur+    };++    // each group pushes (taggable colour flag, accumulated page transform)+    let mut stack: Vec<(Option<bool>, M)> = Vec::new();+    let taggable = |st: &[(Option<bool>, M)]| st.iter().rev().find_map(|x| x.0).unwrap_or(false);+    let curm = |st: &[(Option<bool>, M)]| st.last().map(|x| x.1).unwrap_or(ident);+    // transform a raw-coord bbox into page space (all four corners)+    let to_page = |m: &M, bb: (f64, f64, f64, f64)| -> (f64, f64, f64, f64) {+        let (x0, y0, x1, y1) = bb;+        let cs = [apply(m, x0, y0), apply(m, x1, y0), apply(m, x1, y1), apply(m, x0, y1)];+        let (mut mnx, mut mny, mut mxx, mut mxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+        for (x, y) in cs { mnx = mnx.min(x); mxx = mxx.max(x); mny = mny.min(y); mxy = mxy.max(y); }+        (mnx, mny, mxx, mxy)+    };+    let inject = |tag: &str, cref: &str| -> String {+        let t = tag.trim_end();+        if let Some(rest) = t.strip_suffix("/>") { format!(r#"{} data-cref="{}"/>"#, rest.trim_end(), cref) }+        else if let Some(rest) = t.strip_suffix('>') { format!(r#"{} data-cref="{}">"#, rest.trim_end(), cref) }+        else { tag.to_string() }+    };++    // raw-coord bbox of any single element tag+    let elem_bbox = |tag: &str| -> Option<(f64, f64, f64, f64)> {+        if tag.starts_with("<path") { path_d.captures(tag).and_then(|c| ebbox(&c[1])) }+        else if tag.starts_with("<rect") { rect_xywh.captures(tag).map(|c| { let (x, y, w, h) = (f2(&c[1]), f2(&c[2]), f2(&c[3]), f2(&c[4])); (x, y, x + w, y + h) }) }+        else if tag.starts_with("<circle") { circ_cxy.captures(tag).map(|c| { let (x, y) = (f2(&c[1]), f2(&c[2])); (x, y, x, y) }) }+        else { None }+    };++    let mut out = String::with_capacity(inner.len() + 4096);+    let mut last = 0;+    let bytes = inner.as_bytes();+    for m in tag_re.find_iter(inner) {+        if m.start() < last { continue; } // inside a block we already consumed+        out.push_str(&inner[last..m.start()]);+        last = m.end();+        let tag = m.as_str();+        if tag.starts_with("<g") {+            // A stroked-text group is ONE text string (a ref/value/pin-name/net-label).+            // Tag the WHOLE group by its combined position so a label is never split+            // across components and stray text can't be claimed letter-by-letter by a+            // big symbol like J3. Consume the whole group here.+            if tag.contains(r#"class="stroked-text""#) {+                let base = curm(&stack);+                let mat = tf_re.captures(tag).map(|c| parse_tf(&c[1], base)).unwrap_or(base);+                // find the matching </g> (stroked-text groups don't nest)+                let mut depth = 1i32; let mut i = m.end();+                while i < inner.len() && depth > 0 {+                    if inner[i..].starts_with("<g") { depth += 1; i += 2; }+                    else if inner[i..].starts_with("</g>") { depth -= 1; if depth == 0 { break; } i += 4; }+                    else { i += 1; }+                }+                let close_end = (i + 4).min(inner.len());+                let block = &inner[m.end()..i.min(inner.len())];+                // combined page-space bbox of every stroke in the group+                let (mut mnx, mut mny, mut mxx, mut mxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+                for em in tag_re.find_iter(block) {+                    if let Some(bb) = elem_bbox(em.as_str()) {+                        let (a, b, c, d) = to_page(&mat, bb);+                        mnx = mnx.min(a); mny = mny.min(b); mxx = mxx.max(c); mxy = mxy.max(d);+                    }+                }+                // A text group belongs to a symbol when a Reference/Value field+                // anchor sits inside it, OR when it lands on one of the symbol's pin+                // name/number anchors. But if it sits on a power/net LABEL anchor it's+                // a label (e.g. GND) — never tag it, even if a nearby pin anchor would+                // otherwise claim it.+                // `labels` are the ACTUAL label-text positions, so a tight radius+                // catches the label itself without swallowing a nearby pin number.+                let on_label = mnx.is_finite() && {+                    let (cx, cy) = ((mnx + mxx) / 2.0, (mny + mxy) / 2.0);+                    labels.iter().any(|&(lx, ly)| (cx - lx).abs() < 1.5 && (cy - ly).abs() < 1.5)+                };+                let cref = if mnx.is_finite() && !on_label {+                    field_at((mnx, mny, mxx, mxy)).or_else(|| pin_at((mnx, mny, mxx, mxy)))+                } else { None };+                out.push_str(tag);+                match cref {+                    Some(r) => { // tag every path in the group with the same cref+                        let mut bl = block.to_string();+                        // inject cref into each element tag+                        let mut o2 = String::with_capacity(bl.len() + 256); let mut l2 = 0;+                        for em in tag_re.find_iter(&bl) {+                            o2.push_str(&bl[l2..em.start()]); l2 = em.end();+                            let et = em.as_str();+                            if et.starts_with("<path") || et.starts_with("<rect") || et.starts_with("<circle") { o2.push_str(&inject(et, r)); }+                            else { o2.push_str(et); }+                        }+                        o2.push_str(&bl[l2..]); bl = o2;+                        out.push_str(&bl);+                    }+                    None => out.push_str(block),+                }+                out.push_str("</g>");+                last = close_end;+                let _ = bytes; // (kept for clarity)+                continue;+            }+            let flag = gcolor.captures(tag).map(|c| is_symbol_color(&c[1]));+            let base = curm(&stack);+            let mat = tf_re.captures(tag).map(|c| parse_tf(&c[1], base)).unwrap_or(base);+            stack.push((flag, mat));+            out.push_str(tag);+        } else if tag == "</g>" {+            stack.pop();+            out.push_str(tag);+        } else if !gcolor.captures(tag).map(|c| is_symbol_color(&c[1])).unwrap_or_else(|| taggable(&stack)) {+            // Taggable when the element carries its OWN symbol-colour stroke inline,+            // else fall back to the enclosing group's colour. KiCad emits some thick+            // symbol strokes (cap plates, ferrite bodies) as standalone+            // `<path style="stroke:#840000">` outside any coloured <g>; without the+            // inline-colour check those were skipped and never highlighted.+            out.push_str(tag);+        } else {+            // SYMBOL GRAPHIC: tag by GEOMETRY, not by region. Map the stroke's+            // segments to page space and match them to a symbol's exact segments —+            // a wire or another part's line never coincides, so it's never claimed.+            let m0 = curm(&stack);+            let mt = (m0.a, m0.b, m0.c, m0.d, m0.e, m0.f);+            let _ = &elem_bbox; // (bbox helper retained for the text branch)+            let cref = if tag.starts_with("<path") {+                path_d.captures(tag).and_then(|c| match_path_segments(&c[1], &mt, segs, circles))+            } else if tag.starts_with("<rect") {+                // KiCad draws symbol bodies as <rect> (fill + outline). Match its 4+                // edges to the symbol's segments exactly like a path — the page frame+                // and title-block rects span no symbol so they're never claimed.+                rect_xywh.captures(tag).and_then(|c| {+                    let (x, y, w, h) = (f2(&c[1]), f2(&c[2]), f2(&c[3]), f2(&c[4]));+                    let d = format!("M {x} {y} L {} {y} L {} {} L {x} {} L {x} {y}", x + w, x + w, y + h, y + h);+                    match_path_segments(&d, &mt, segs, circles)+                })+            } else if tag.starts_with("<circle") {+                // KiCad draws test-point / switch-contact circles as <circle cx cy r>.+                // Map the centre to page space and match against the symbol circles+                // (centre+radius). Without this, those circles never highlighted.+                circ_r.captures(tag).and_then(|c| {+                    let (cx, cy, r) = (f2(&c[1]), f2(&c[2]), f2(&c[3]));+                    let (px, py) = apply(&m0, cx, cy);+                    let q = |v: f64| (v * 20.0).round() as i32;+                    let mut found = None;+                    for dx in -1..=1 { for dy in -1..=1 { for dr in -1..=1 {+                        if let Some(rf) = circles.get(&(q(px) + dx, q(py) + dy, q(r) + dr)) { found = Some(rf.clone()); }+                    }}}+                    found+                })+            } else { None };+            match cref {+                Some(r) => out.push_str(&inject(tag, &r)),+                None => out.push_str(tag),+            }+        }+    }+    out.push_str(&inner[last..]);+    out+}+fn f2(s: &str) -> f64 { s.parse().unwrap_or(0.0) }++/// Extract the point sequence a path `d` visits (M/L/A endpoints), map to page+/// space, form segments, and return the component whose segments they match.+fn match_path_segments(d: &str, m: &(f64, f64, f64, f64, f64, f64),+                       segs: &HashMap<crate::kicad_self::SegKey, String>,+                       circles: &HashMap<(i32, i32, i32), String>) -> Option<String> {+    // Parse the path into the points it visits. KiCad's SVG export is NOT uniform:+    //   - thin lines:  "M177.0022 166.0072\nL285.0022 166.0072"  (glued cmd, spaces)+    //   - thick lines: "M 211.3280,52.8320 211.3280,48.7680"     (COMMAS + IMPLICIT+    //                   lineto — the 2nd pair has no `L`) ← caps/ferrite plates+    //   - arcs:        "M76.20 86.36 A0.635 0.635 0 0 0 74.93 86.36"+    // Handle all three: commas → spaces, split the command letter off its digits,+    // then walk a tiny state machine where a bare coordinate pair repeats the last+    // command (so implicit linetos after M/L are captured). Missing this is exactly+    // why cap plates and ferrite bodies never highlighted.+    let norm: String = d.chars().map(|c| if c == ',' { ' ' } else { c }).collect();+    let spaced: String = norm.chars().flat_map(|c| match c {+        'M' | 'L' | 'A' | 'Z' | 'H' | 'V' | 'C' | 'm' | 'l' | 'a' | 'z' | 'h' | 'v' | 'c' => vec![' ', c, ' '],+        _ => vec![c],+    }).collect();+    let toks: Vec<&str> = spaced.split_whitespace().collect();+    let numf = |t: &str| t.parse::<f64>().ok();+    let mut pts: Vec<(f64, f64)> = Vec::new();+    let mut cmd = 'M';+    let mut k = 0;+    while k < toks.len() {+        let t = toks[k];+        let ch = t.chars().next().unwrap_or(' ');+        if t.len() == 1 && ch.is_ascii_alphabetic() {+            cmd = ch;+            k += 1;+            if cmd == 'Z' || cmd == 'z' { if let Some(&p0) = pts.first() { pts.push(p0); } }+            continue;+        }+        match cmd {+            'M' | 'L' | 'm' | 'l' => {+                if let (Some(x), Some(y)) = (numf(t), toks.get(k + 1).and_then(|s| numf(s))) { pts.push((x, y)); }+                k += 2;+            }+            'A' | 'a' => { // rx ry rot large sweep x y → take the endpoint+                if let (Some(x), Some(y)) = (toks.get(k + 5).and_then(|s| numf(s)), toks.get(k + 6).and_then(|s| numf(s))) { pts.push((x, y)); }+                k += 7;+            }+            _ => { k += 1; } // H/V/C rare in symbol graphics — skip+        }+    }+    // page-space points+    let (a, b, c, d2, e, f) = *m;+    let page: Vec<(f64, f64)> = pts.iter().map(|&(x, y)| (a * x + c * y + e, b * x + d2 * y + f)).collect();+    // vote across this path's segments+    let mut votes: HashMap<&str, u32> = HashMap::new();+    for w in page.windows(2) {+        if let Some(r) = segs.get(&crate::kicad_self::seg_key_pub(w[0], w[1])) { *votes.entry(r.as_str()).or_insert(0) += 1; }+    }+    // an arc/circle stroke: match by its bbox centre + radius+    if votes.is_empty() && page.len() >= 2 {+        let (mut mnx, mut mny, mut mxx, mut mxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+        for (x, y) in &page { mnx = mnx.min(*x); mxx = mxx.max(*x); mny = mny.min(*y); mxy = mxy.max(*y); }+        let (cx, cy, r) = ((mnx + mxx) / 2.0, (mny + mxy) / 2.0, ((mxx - mnx) + (mxy - mny)) / 4.0);+        let q = |v: f64| (v * 20.0).round() as i32;+        for dx in -1..=1 { for dy in -1..=1 { for dr in -1..=1 {+            if let Some(r0) = circles.get(&(q(cx) + dx, q(cy) + dy, q(r) + dr)) { return Some(r0.clone()); }+        }}}+    }+    votes.into_iter().max_by_key(|(_, n)| *n).map(|(r, _)| r.to_string())+}++fn build_meta(sheet: &Sheet) -> RenderMeta {+    let (x, y, w, h) = sheet.content_bbox;+    RenderMeta { view_box: [x, y, w, h], comp_count: sheet.comps.len(), components: sheet.comps.clone(), sub_sheets: sheet.sub_sheets.clone() }+}++/// Top-level render: parse identity → fetch KiCad SVG → crop to the drawing →+/// overlay component hotspots. All share the page-mm coordinate system.+/// Bytes-level entry point. Altium `.SchDoc` is a BINARY compound file, so it+/// cannot come in through the text path; everything else is UTF-8 text.+pub fn render_sheet_bytes(bytes: &[u8]) -> Result<(String, RenderMeta)> { render_sheet_bytes_base(bytes, None) }++pub fn render_sheet_bytes_base(bytes: &[u8], base: Option<&str>) -> Result<(String, RenderMeta)> {+    if crate::altium_sch::looks_like_altium(bytes) {+        match crate::altium_sch::render_sheet(bytes) {+            Ok((svg, sheet)) => { let meta = build_meta(&sheet); return Ok((svg, meta)); }+            Err(e) => eprintln!("[adom-schematic] altium parse failed ({e})"),+        }+    }+    render_sheet_with_base(&String::from_utf8_lossy(bytes), base)+}++pub fn render_sheet(sch: &str) -> Result<(String, RenderMeta)> { render_sheet_with_base(sch, None) }++/// `base` is an AUTHENTIC pre-rendered KiCad SVG for this exact sheet (from the+/// wiki page's `render/sheet-NNN.svg`, produced by molecule-publish against the+/// FULL project). When present we use it verbatim as the visual base — real KiCad+/// fonts, and hierarchical roots render correctly — instead of asking service-kicad+/// (which can't render a lone hierarchical root). We NEVER self-draw text when a+/// base is available: the export must look exactly like the EDA.+pub fn render_sheet_with_base(sch: &str, base: Option<&str>) -> Result<(String, RenderMeta)> {+    // Fusion 360 Electronics / EAGLE `.sch`: no headless renderer exists, so we+    // draw the sheet ourselves (in EAGLE's own colours) and tag each primitive+    // with its component directly — no bbox inference needed.+    if crate::eagle_sch::looks_like_eagle(sch) {+        match crate::eagle_sch::render_sheet(sch) {+            Ok((svg, sheet)) => { let meta = build_meta(&sheet); return Ok((svg, meta)); }+            Err(e) => eprintln!("[adom-schematic] eagle/fusion parse failed ({e}); trying KiCad"),+        }+    }+    let sheet = sch_parse::parse(sch);+    let meta = build_meta(&sheet);+    // Prefer the authentic pre-rendered base; else the shared service-kicad export.+    let raw_base = match base {+        Some(b) if b.contains("<path") || b.contains("<text") => b.to_string(),+        _ => fetch_svg(sch).unwrap_or_default(),+    };+    // GROUND TRUTH for hover highlighting: each symbol's exact line segments, from+    // lib_symbols transformed to the instance placement. A stroke in the export+    // belongs to a component IFF it coincides with one of these segments — a wire+    // or another part's line never does. (Text is still matched by position.)+    let (segs, circles) = crate::kicad_self::symbol_segments(sch);+    // the only TEXT that is a symbol's own: its Reference + Value fields, at their+    // exact `(at)` positions. Everything else (pin names/numbers, net/power labels)+    // is standalone and stays untagged.+    let fields = crate::kicad_self::field_anchors(sch);+    // pin names (inside the body) + pin numbers (on the stubs) are symbol geometry+    // too, so tag any text landing on a pin's body-end / stub-midpoint anchor.+    let pins = crate::kicad_self::pin_anchors(sch);+    // power/net label positions — text sitting on one is a LABEL (e.g. GND), never a+    // symbol's own field/pin text, so it must not be tagged to a nearby component.+    let labels = crate::kicad_self::label_anchors(sch);+    let inner = tag_symbols(&extract_inner(&raw_base), &segs, &circles, &fields, &pins, &labels);+    // LAST RESORT ONLY (no authentic base AND service-kicad returned empty — e.g. a+    // hierarchical root on a page with no pre-render): self-draw so it isn't blank.+    let inner = if base.is_none() && inner.matches("stroke:").count() < 60 && (!sheet.sub_sheets.is_empty() || !sheet.comps.is_empty()) {+        let self_render = crate::kicad_self::render_inner(sch);+        if self_render.is_empty() { inner } else { format!("{}{}", self_render, sheet_nav_svg(&sheet)) }+    } else { inner };+    let (x, y, w, h) = sheet.content_bbox;++    let mut s = String::new();+    let _ = write!(s, r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{:.3} {:.3} {:.3} {:.3}" preserveAspectRatio="xMidYMid meet">"##, x, y, w, h);+    let _ = write!(s, r##"<rect class="adom-sheet-bg" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="#fbfbf6"/>"##, x, y, w, h);+    let _ = write!(s, r##"<g class="adom-sheet">{}</g>"##, inner);+    s.push_str(&sch_parse::build_overlay(&sheet));+    s.push_str("</svg>");+    Ok((s, meta))+}++/// Self-drawn hierarchical navigation base: one KiCad-style sheet box per child+/// (border + sheet name inside the top edge + filename below), used when+/// service-kicad returns an empty root page. The clickable overlay sits on top.+fn sheet_nav_svg(sheet: &Sheet) -> String {+    let mut s = String::new();+    for sh in &sheet.sub_sheets {+        let [x0, y0, x1, y1] = sh.bbox;+        let (w, h) = ((x1 - x0).max(2.0), (y1 - y0).max(2.0));+        // KiCad sheet-symbol colours: brown/red border + name, blue file text.+        let _ = write!(s, r##"<rect x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="none" stroke="#843c39" stroke-width="0.15"/>"##, x0, y0, w, h);+        let _ = write!(s, r##"<text x="{:.3}" y="{:.3}" font-size="2.0" fill="#843c39" font-family="monospace">{}</text>"##, x0, y0 - 0.8, esc(&sh.name));+        let _ = write!(s, r##"<text x="{:.3}" y="{:.3}" font-size="1.5" fill="#0d6d6d" font-family="monospace">File: {}</text>"##, x0, y1 + 2.0, esc(&sh.file));+    }+    s+}++/// Meta-only (for callers that already have an SVG or want the component list).+pub fn meta_json(sch: &str) -> Result<String> {+    Ok(serde_json::to_string(&build_meta(&sch_parse::parse(sch)))?)+}++// small helper so the map type is available if needed later+#[allow(dead_code)]+type _M = HashMap<String, String>;
src/kicad_self.rsadded+445
@@ -0,0 +1,445 @@+//! Self-render a `.kicad_sch` into the `.adom-sheet` inner SVG WITHOUT+//! service-kicad. Used as the fallback when the shared KiCad export can't render+//! a sheet — most importantly a HIERARCHICAL ROOT, which kicad-cli renders empty+//! when its child files aren't present. Draws every symbol from its `lib_symbols`+//! definition (rectangles / polylines / circles / arcs / pins) transformed to the+//! instance placement, plus wires, junctions, power symbols and labels, in+//! KiCad's own light-sheet colours. Each component is wrapped `<g data-cref>` so+//! the existing halo-on-hover works unchanged.+//!+//! Ported from adom-2dboard's sch_render.rs; here it only emits the inner+//! content (the caller wraps it in `<g class="adom-sheet">` + overlay).++use crate::sexpr::{blocks, esc, f};+use regex::Regex;+use std::collections::HashMap;+use std::fmt::Write as _;++// KiCad default schematic colours+const C_SYM: &str = "#840000";   // symbol bodies + pins (dark red)+const C_WIRE: &str = "#008484";  // wires + junctions (teal-green)+const C_NAME: &str = "#840000";  // reference designators+const C_VALUE: &str = "#008484"; // values+const C_LABEL: &str = "#840000"; // net / power labels++#[derive(Clone)]+struct Prim { kind: u8, pts: Vec<(f64, f64)>, r: f64 } // 0 poly/rect, 1 circle, 2 pin+struct LibSym { prims: Vec<Prim> }++/// lib Y-up -> screen Y-down, ROTATE CCW by `rot` (screen matrix uses -rot), then+/// MIRROR in the world/page frame, then translate to (px,py). KiCad applies the+/// mirror AFTER the rotation (in page space), not before — doing it before put a+/// rotated+mirrored symbol's body/pins on the wrong side while its axis-symmetric+/// features (e.g. a pin-1 socket arc) still matched, so a mirrored connector lit up+/// only by its text + pin-1 arc. `mirror==2` is KiCad `(mirror x)` = flip page Y;+/// `mirror==1` is `(mirror y)` = flip page X.+fn xf(lx: f64, ly: f64, px: f64, py: f64, rot: f64, mirror: u8) -> (f64, f64) {+    let (x, y) = (lx, -ly);+    let a = (-rot).to_radians();+    let (c, s) = (a.cos(), a.sin());+    let (mut rx, mut ry) = (x * c - y * s, x * s + y * c);+    if mirror == 1 { rx = -rx; } // (mirror y) → flip page X+    if mirror == 2 { ry = -ry; } // (mirror x) → flip page Y+    (px + rx, py + ry)+}++fn quoted(s: &str) -> Option<String> {+    let q1 = s.find('"')?; let rest = &s[q1 + 1..]; let q2 = rest.find('"')?; Some(rest[..q2].to_string())+}+fn capture1(s: &str, re: &str) -> Option<String> { Regex::new(re).ok()?.captures(s).map(|c| c[1].to_string()) }++/// Normalize a symbol name / lib_id to a bare key for FALLBACK lookup. KiCad+/// usually stores each `lib_symbols` entry under its full lib_id ("Device:LED"),+/// but on a name collision it renames the stored entry to a bare, dedup-suffixed+/// name ("LED_2") while INSTANCES still reference the original lib_id+/// ("Device:LED"). An exact lookup then misses and the symbol gets no geometry.+/// This drops the "Lib:" prefix and a trailing "_<digits>" so both sides collapse+/// to the same key ("LED"). Used ONLY as a fallback after the exact lookup fails.+pub fn lib_bare_key(name: &str) -> String {+    let base = name.rsplit(':').next().unwrap_or(name);+    if let Some(pos) = base.rfind('_') {+        if pos + 1 < base.len() && base[pos + 1..].chars().all(|c| c.is_ascii_digit()) {+            return base[..pos].to_string();+        }+    }+    base.to_string()+}+/// Resolve a lib def by exact lib_id, falling back to the bare-key alias (see+/// `lib_bare_key`) so dedup-renamed symbols like "LED_2" still resolve.+fn resolve_lib<'a, T>(libs: &'a HashMap<String, T>, bare: &HashMap<String, String>, lib_id: &str) -> Option<&'a T> {+    libs.get(lib_id).or_else(|| bare.get(&lib_bare_key(lib_id)).and_then(|n| libs.get(n)))+}+/// Build the bare-key → stored-name index for the fallback lookup.+fn bare_index<T>(libs: &HashMap<String, T>) -> HashMap<String, String> {+    let mut m = HashMap::new();+    for k in libs.keys() { m.entry(lib_bare_key(k)).or_insert_with(|| k.clone()); }+    m+}++/// Top-level `(symbol …)` blocks (not nested).+fn top_symbols(s: &str) -> Vec<&str> {+    let bytes = s.as_bytes();+    let mut out = vec![];+    let mut i = 0;+    while let Some(rel) = s[i..].find("(symbol") {+        let start = i + rel;+        let after = start + 7;+        if bytes.get(after).map(|c| !c.is_ascii_whitespace()).unwrap_or(true) { i = after; continue; }+        let mut depth = 0i32; let mut end = start;+        for j in start..s.len() { match bytes[j] { b'(' => depth += 1, b')' => { depth -= 1; if depth == 0 { end = j; break; } } _ => {} } }+        out.push(&s[start..=end.min(s.len() - 1)]);+        i = end + 1;+    }+    out+}+fn strip_first_block(s: &str, tag: &str) -> String {+    if let Some(b) = blocks(s, tag).into_iter().next() { return s.replacen(b, "", 1); }+    s.to_string()+}+fn poly_d(pts: &[(f64, f64)]) -> String {+    let mut d = String::new();+    for (i, &(x, y)) in pts.iter().enumerate() { let _ = write!(d, "{}{:.3} {:.3} ", if i == 0 { "M" } else { "L" }, x, y); }+    d+}++/// A quantized line-segment key (both endpoints to 0.05mm, order-independent) so+/// export strokes can be matched to the exact symbol geometry regardless of which+/// end KiCad drew first.+pub type SegKey = (i32, i32, i32, i32);+pub fn seg_key_pub(a: (f64, f64), b: (f64, f64)) -> SegKey { seg_key(a, b) }+fn seg_key(a: (f64, f64), b: (f64, f64)) -> SegKey {+    let q = |v: f64| (v * 20.0).round() as i32; // 0.05mm grid+    let (ax, ay, bx, by) = (q(a.0), q(a.1), q(b.0), q(b.1));+    if (ax, ay) <= (bx, by) { (ax, ay, bx, by) } else { (bx, by, ax, ay) }+}++/// The EXACT set of line segments that make up each symbol on the sheet, keyed by+/// reference. Built from `lib_symbols` (rectangle / polyline / pin edges)+/// transformed to each instance's placement. This is the ground truth for hover+/// highlighting: a stroke in the KiCad export belongs to a component IFF it+/// coincides with one of that component's segments — a wire or another part's line+/// never will. (Circles/arcs are matched separately by centre+radius.)+pub fn symbol_segments(content: &str) -> (HashMap<SegKey, String>, HashMap<(i32, i32, i32), String>) {+    let at3 = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?\)").unwrap();+    let se = Regex::new(r"\(start\s+(-?[\d.]+)\s+(-?[\d.]+)\)\s*\(end\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    // arc: (start x y) (mid x y) (end x y) — capture start (1,2), mid (3,4), end (5,6)+    let arc_se = Regex::new(r"\(start\s+(-?[\d.]+)\s+(-?[\d.]+)\)\s*\(mid\s+(-?[\d.]+)\s+(-?[\d.]+)\)\s*\(end\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let xy = Regex::new(r"\(xy\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let center = Regex::new(r"\(center\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let radius = Regex::new(r"\(radius\s+(-?[\d.]+)\)").unwrap();+    let length = Regex::new(r"\(length\s+(-?[\d.]+)\)").unwrap();+    let mirror_re = Regex::new(r"\(mirror\s+(x|y)\)").unwrap();++    let mut libs: HashMap<String, LibSym> = HashMap::new();+    if let Some(libblk) = blocks(content, "lib_symbols").into_iter().next() {+        for def in top_symbols(libblk) {+            let name = quoted(def).unwrap_or_default();+            if name.is_empty() { continue; }+            let mut prims = vec![];+            for r in blocks(def, "rectangle") {+                if let Some(c) = se.captures(r) {+                    let (x1, y1, x2, y2) = (f(c.get(1)), f(c.get(2)), f(c.get(3)), f(c.get(4)));+                    prims.push(Prim { kind: 0, pts: vec![(x1, y1), (x2, y1), (x2, y2), (x1, y2), (x1, y1)], r: 0.0 });+                }+            }+            for p in blocks(def, "polyline") {+                let pts: Vec<(f64, f64)> = xy.captures_iter(p).map(|c| (f(c.get(1)), f(c.get(2)))).collect();+                if pts.len() >= 2 { prims.push(Prim { kind: 0, pts, r: 0.0 }); }+            }+            for c in blocks(def, "circle") {+                if let (Some(ce), Some(ra)) = (center.captures(c), radius.captures(c)) {+                    prims.push(Prim { kind: 1, pts: vec![(f(ce.get(1)), f(ce.get(2)))], r: f(ra.get(1)) });+                }+            }+            // arcs (inductor coils, curved cap plates, crystal): KiCad's SVG export+            // draws each as an `A` command giving only its start+end, so match on the+            // CHORD (start→end). Without this, arc-bodied parts (L, ferrite, crystal)+            // never highlighted their body.+            for a in blocks(def, "arc") {+                if let Some(c) = arc_se.captures(a) {+                    let (sx, sy, ex, ey) = (f(c.get(1)), f(c.get(2)), f(c.get(5)), f(c.get(6)));+                    prims.push(Prim { kind: 0, pts: vec![(sx, sy), (ex, ey)], r: 0.0 });+                }+            }+            for pin in blocks(def, "pin") {+                if let Some(a) = at3.captures(pin) {+                    let (lx, ly, ang) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+                    let len = length.captures(pin).map(|c| f(c.get(1))).unwrap_or(2.54);+                    let (dx, dy) = (ang.to_radians().cos() * len, ang.to_radians().sin() * len);+                    prims.push(Prim { kind: 2, pts: vec![(lx, ly), (lx + dx, ly + dy)], r: 0.0 });+                }+            }+            libs.insert(name, LibSym { prims });+        }+    }++    let bare = bare_index(&libs);+    let content_wo_lib = strip_first_block(content, "lib_symbols");+    let mut segs: HashMap<SegKey, String> = HashMap::new();+    let mut circles: HashMap<(i32, i32, i32), String> = HashMap::new();+    for inst in top_symbols(&content_wo_lib) {+        let lib_id = match capture1(inst, r##"\(lib_id\s+"([^"]+)"\)"##) { Some(s) => s, None => continue };+        let a = match at3.captures(inst) { Some(a) => a, None => continue };+        let (px, py, rot) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+        let mirror = mirror_re.captures(inst).map(|c| if &c[1] == "x" { 2u8 } else { 1u8 }).unwrap_or(0);+        let reference = capture1(inst, r##"\(property\s+"Reference"\s+"([^"]*)""##).unwrap_or_default();+        if reference.is_empty() || lib_id.starts_with("power:") { continue; }+        if let Some(lib) = resolve_lib(&libs, &bare, &lib_id) {+            for pr in &lib.prims {+                match pr.kind {+                    1 => { // circle: centre+radius key+                        let (cx, cy) = xf(pr.pts[0].0, pr.pts[0].1, px, py, rot, mirror);+                        let q = |v: f64| (v * 20.0).round() as i32;+                        circles.insert((q(cx), q(cy), q(pr.r)), reference.clone());+                    }+                    _ => { // polyline/rect/pin: consecutive segments+                        let tp: Vec<(f64, f64)> = pr.pts.iter().map(|&(x, y)| xf(x, y, px, py, rot, mirror)).collect();+                        for w in tp.windows(2) { segs.insert(seg_key(w[0], w[1]), reference.clone()); }+                    }+                }+            }+        }+    }+    (segs, circles)+}++/// Anchor points of things that are NOT a component's own text: power-symbol+/// labels (power:GND, power:+3V3 …) and net / global / hierarchical labels. Text+/// in the export sitting on one of these is a NET/POWER label, never a symbol's+/// pin-name or field, so it must not be tagged to a component.+pub fn label_anchors(content: &str) -> Vec<(f64, f64)> {+    let at = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)").unwrap();+    let mut out = Vec::new();+    let cw = strip_first_block(content, "lib_symbols");+    // schematic `(at)` is Y-DOWN, same frame as the export/page — do NOT negate Y.+    for tag in ["label", "global_label", "hierarchical_label"] {+        for l in blocks(&cw, tag) {+            if let Some(c) = at.captures(l) { out.push((f(c.get(1)), f(c.get(2)))); }+        }+    }+    // Power symbols: the VISIBLE label is the Value property's text (e.g. "GND"),+    // which sits at its OWN `(at)`, NOT the symbol origin (the origin can be closer+    // to a neighbouring component's pin number than to its own label — using it made+    // the exclusion grab pin numbers). The Value `(at)` is exactly where the text is.+    let val_at = Regex::new(r##"\(property\s+"Value"\s+"[^"]*"\s*\(at\s+(-?[\d.]+)\s+(-?[\d.]+)"##).unwrap();+    for inst in top_symbols(&cw) {+        if capture1(inst, r##"\(lib_id\s+"(power:[^"]+)"\)"##).is_some() {+            if let Some(c) = val_at.captures(inst) { out.push((f(c.get(1)), f(c.get(2)))); }+            else if let Some(c) = at.captures(inst) { out.push((f(c.get(1)), f(c.get(2)))); }+        }+    }+    out+}++/// Page-space anchor points for each symbol's PIN TEXT (names inside the body,+/// numbers along the stubs). A pin is `(at lx ly ang) (length L)`: `(lx,ly)` is+/// the CONNECTION point (where wires / net labels attach — deliberately excluded),+/// the pin runs inward to the BODY point `B = (lx+L·cosang, ly+L·sinang)` where the+/// pin NAME sits, and the pin NUMBER sits at the stub MIDPOINT `M`. We return B and+/// M (per pin) so a text group landing on one is tagged to that symbol — while a+/// net/power label at the connection point never is. Skips power symbols.+pub fn pin_anchors(content: &str) -> Vec<(String, f64, f64)> {+    let at3 = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?\)").unwrap();+    let length = Regex::new(r"\(length\s+(-?[\d.]+)\)").unwrap();+    let mirror_re = Regex::new(r"\(mirror\s+(x|y)\)").unwrap();++    // lib_name -> Vec<(lx, ly, ang, len)>+    let mut libpins: HashMap<String, Vec<(f64, f64, f64, f64)>> = HashMap::new();+    if let Some(libblk) = blocks(content, "lib_symbols").into_iter().next() {+        for def in top_symbols(libblk) {+            let name = quoted(def).unwrap_or_default();+            if name.is_empty() { continue; }+            let mut pins = vec![];+            for pin in blocks(def, "pin") {+                if let Some(a) = at3.captures(pin) {+                    let (lx, ly, ang) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+                    let len = length.captures(pin).map(|c| f(c.get(1))).unwrap_or(2.54);+                    pins.push((lx, ly, ang, len));+                }+            }+            libpins.insert(name, pins);+        }+    }+    let bare = bare_index(&libpins);++    let cw = strip_first_block(content, "lib_symbols");+    let mut out = Vec::new();+    for inst in top_symbols(&cw) {+        let lib_id = match capture1(inst, r##"\(lib_id\s+"([^"]+)"\)"##) { Some(s) => s, None => continue };+        if lib_id.starts_with("power:") { continue; }+        let a = match at3.captures(inst) { Some(a) => a, None => continue };+        let (px, py, rot) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+        let mirror = mirror_re.captures(inst).map(|c| if &c[1] == "x" { 2u8 } else { 1u8 }).unwrap_or(0);+        let reference = capture1(inst, r##"\(property\s+"Reference"\s+"([^"]*)""##).unwrap_or_default();+        if reference.is_empty() { continue; }+        if let Some(pins) = resolve_lib(&libpins, &bare, &lib_id) {+            for &(lx, ly, ang, len) in pins {+                let (dx, dy) = (ang.to_radians().cos() * len, ang.to_radians().sin() * len);+                // body point (pin name) and stub midpoint (pin number), in page space+                let b = xf(lx + dx, ly + dy, px, py, rot, mirror);+                let m = xf(lx + dx / 2.0, ly + dy / 2.0, px, py, rot, mirror);+                out.push((reference.clone(), b.0, b.1));+                out.push((reference.clone(), m.0, m.1));+            }+        }+    }+    out+}++/// The ON-SHEET TEXT that belongs to each symbol: its Reference and Value fields.+/// KiCad stores each as `(property "Reference"|"Value" "<text>" (at x y …))` with+/// an ABSOLUTE page position; that's the ONLY text that is the symbol's own (pin+/// names/numbers are the symbol GRAPHIC, and net/power labels are standalone).+/// Returns (ref-designator, field text, x, y) for each VISIBLE Reference/Value.+pub fn field_anchors(content: &str) -> Vec<(String, String, f64, f64)> {+    let at = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)").unwrap();+    let cw = strip_first_block(content, "lib_symbols");+    let mut out = Vec::new();+    for inst in top_symbols(&cw) {+        if capture1(inst, r##"\(lib_id\s+"(power:[^"]+)"\)"##).is_some() { continue; }+        let reference = capture1(inst, r##"\(property\s+"Reference"\s+"([^"]*)""##).unwrap_or_default();+        if reference.is_empty() { continue; }+        // each `(property "Name" "Value" (at x y ..) (effects .. [ (hide yes) ]))`+        for pb in blocks(inst, "property") {+            let name = quoted(pb).unwrap_or_default();+            if name != "Reference" && name != "Value" { continue; }+            // the field text is the SECOND quoted string+            let text = nth_quoted(pb, 1).unwrap_or_default();+            // skip hidden fields (not rendered on the sheet)+            if pb.contains("(hide yes)") || pb.contains("hide)") { continue; }+            if let Some(c) = at.captures(pb) {+                out.push((reference.clone(), text, f(c.get(1)), f(c.get(2))));+            }+        }+    }+    out+}+fn nth_quoted(s: &str, n: usize) -> Option<String> {+    let mut rest = s; let mut i = 0;+    loop {+        let q1 = rest.find('"')? + 1;+        let after = &rest[q1..];+        let q2 = after.find('"')?;+        let val = after[..q2].to_string();+        if i == n { return Some(val); }+        rest = &after[q2 + 1..]; i += 1;+    }+}++/// Render the sheet's drawable content (symbols + wires + power + labels) as the+/// inner SVG for `<g class="adom-sheet">`. Returns "" if there's nothing to draw.+pub fn render_inner(content: &str) -> String {+    let at3 = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?\)").unwrap();+    let se = Regex::new(r"\(start\s+(-?[\d.]+)\s+(-?[\d.]+)\)\s*\(end\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let xy = Regex::new(r"\(xy\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let center = Regex::new(r"\(center\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let radius = Regex::new(r"\(radius\s+(-?[\d.]+)\)").unwrap();+    let length = Regex::new(r"\(length\s+(-?[\d.]+)\)").unwrap();+    let prop = Regex::new(r##"\(property\s+"([^"]+)"\s+"([^"]*)""##).unwrap();+    let mirror_re = Regex::new(r"\(mirror\s+(x|y)\)").unwrap();++    // ── lib_symbols ──+    let mut libs: HashMap<String, LibSym> = HashMap::new();+    if let Some(libblk) = blocks(content, "lib_symbols").into_iter().next() {+        for def in top_symbols(libblk) {+            let name = quoted(def).unwrap_or_default();+            if name.is_empty() { continue; }+            let mut prims = vec![];+            for r in blocks(def, "rectangle") {+                if let Some(c) = se.captures(r) {+                    let (x1, y1, x2, y2) = (f(c.get(1)), f(c.get(2)), f(c.get(3)), f(c.get(4)));+                    prims.push(Prim { kind: 0, pts: vec![(x1, y1), (x2, y1), (x2, y2), (x1, y2), (x1, y1)], r: 0.0 });+                }+            }+            for p in blocks(def, "polyline") {+                let pts: Vec<(f64, f64)> = xy.captures_iter(p).map(|c| (f(c.get(1)), f(c.get(2)))).collect();+                if pts.len() >= 2 { prims.push(Prim { kind: 0, pts, r: 0.0 }); }+            }+            for c in blocks(def, "circle") {+                if let (Some(ce), Some(ra)) = (center.captures(c), radius.captures(c)) {+                    prims.push(Prim { kind: 1, pts: vec![(f(ce.get(1)), f(ce.get(2)))], r: f(ra.get(1)) });+                }+            }+            for pin in blocks(def, "pin") {+                if let Some(a) = at3.captures(pin) {+                    let (lx, ly, ang) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+                    let len = length.captures(pin).map(|c| f(c.get(1))).unwrap_or(2.54);+                    let (dx, dy) = (ang.to_radians().cos() * len, ang.to_radians().sin() * len);+                    prims.push(Prim { kind: 2, pts: vec![(lx, ly), (lx + dx, ly + dy)], r: 0.0 });+                }+            }+            libs.insert(name, LibSym { prims });+        }+    }+    let bare = bare_index(&libs);++    let content_wo_lib = strip_first_block(content, "lib_symbols");+    let mut out = String::new();++    // ── wires + junctions ──+    for w in blocks(&content_wo_lib, "wire") {+        let pts: Vec<(f64, f64)> = xy.captures_iter(w).map(|c| (f(c.get(1)), f(c.get(2)))).collect();+        if pts.len() >= 2 {+            let _ = write!(out, r##"<line x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="0.15" stroke-linecap="round"/>"##,+                pts[0].0, pts[0].1, pts[1].0, pts[1].1, C_WIRE);+        }+    }+    for j in blocks(&content_wo_lib, "junction") {+        if let Some(a) = at3.captures(j) {+            let _ = write!(out, r##"<circle cx="{:.3}" cy="{:.3}" r="0.4" fill="{}"/>"##, f(a.get(1)), f(a.get(2)), C_WIRE);+        }+    }+    // net / global / hierarchical labels+    for l in blocks(&content_wo_lib, "label").into_iter()+        .chain(blocks(&content_wo_lib, "global_label"))+        .chain(blocks(&content_wo_lib, "hierarchical_label")) {+        if let Some(a) = at3.captures(l) {+            let text = quoted(l).unwrap_or_default();+            if !text.is_empty() {+                let _ = write!(out, r##"<text x="{:.3}" y="{:.3}" font-size="1.4" fill="{}" font-family="monospace" dominant-baseline="middle">{}</text>"##,+                    f(a.get(1)) + 0.5, f(a.get(2)), C_LABEL, esc(&text));+            }+        }+    }++    // ── symbol instances ──+    for inst in top_symbols(&content_wo_lib) {+        let lib_id = match capture1(inst, r##"\(lib_id\s+"([^"]+)"\)"##) { Some(s) => s, None => continue };+        let a = match at3.captures(inst) { Some(a) => a, None => continue };+        let (px, py, rot) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+        let mirror = mirror_re.captures(inst).map(|c| if &c[1] == "x" { 2u8 } else { 1u8 }).unwrap_or(0);++        let (mut reference, mut value) = (String::new(), String::new());+        for c in prop.captures_iter(inst) {+            match &c[1] { "Reference" => reference = c[2].to_string(), "Value" => value = c[2].to_string(), _ => {} }+        }+        let is_power = lib_id.starts_with("power:");+        let lib = resolve_lib(&libs, &bare, &lib_id);+        let mut body = String::new();+        let (mut minx, mut miny, mut maxx, mut maxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+        if let Some(lib) = lib {+            for pr in &lib.prims {+                let tp: Vec<(f64, f64)> = pr.pts.iter().map(|&(x, y)| xf(x, y, px, py, rot, mirror)).collect();+                for &(x, y) in &tp { minx = minx.min(x); miny = miny.min(y); maxx = maxx.max(x); maxy = maxy.max(y); }+                match pr.kind {+                    1 => { let _ = write!(body, r##"<circle cx="{:.3}" cy="{:.3}" r="{:.3}" fill="none" stroke="{}" stroke-width="0.15"/>"##, tp[0].0, tp[0].1, pr.r, C_SYM); }+                    2 => { let _ = write!(body, r##"<line x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="{}" stroke-width="0.15"/>"##, tp[0].0, tp[0].1, tp[1].0, tp[1].1, C_SYM); }+                    _ => { let _ = write!(body, r##"<path d="{}" fill="none" stroke="{}" stroke-width="0.15"/>"##, poly_d(&tp), C_SYM); }+                }+            }+        }+        if !minx.is_finite() { minx = px - 1.27; miny = py - 1.27; maxx = px + 1.27; maxy = py + 1.27; }+        // power symbols show their net name; regular parts show ref + value+        if is_power {+            if !value.is_empty() {+                let _ = write!(body, r##"<text x="{:.3}" y="{:.3}" font-size="1.4" fill="{}" font-family="monospace" text-anchor="middle">{}</text>"##, px, maxy + 1.6, C_LABEL, esc(&value));+            }+        } else if !reference.is_empty() {+            let _ = write!(body, r##"<text x="{:.3}" y="{:.3}" font-size="1.3" fill="{}" font-family="monospace">{}</text>"##, maxx + 0.4, miny + 1.2, C_NAME, esc(&reference));+            if !value.is_empty() { let _ = write!(body, r##"<text x="{:.3}" y="{:.3}" font-size="1.1" fill="{}" font-family="monospace">{}</text>"##, maxx + 0.4, miny + 2.7, C_VALUE, esc(&value)); }+        }+        let _ = write!(out, r##"<g data-cref="{}">{}</g>"##, esc(&reference), body);+    }++    out+}
src/main.rsadded+174
@@ -0,0 +1,174 @@+//! adom-schematic — interactive schematic viewer for a whole `.kicad_sch`.+//!+//! Sibling of adom-2dboard. The visual base is the EDA's OWN render+//! (service-kicad `sch/export/svg` — authentic symbols/wires/fonts); we overlay+//! a per-component hotspot layer so hovering a symbol shows what it is plus live+//! stock & price. Meant to be embedded as a live schematic "view" in any app.++mod sexpr;+mod sch_parse;+mod kicad_sch;+mod kicad_self;+mod eagle_sch;+mod altium_sch;+mod enrich;+mod server;++use anyhow::{Context, Result};+use clap::{Parser, Subcommand};+use std::fs;+use std::path::PathBuf;++#[derive(Parser)]+#[command(name = "adom-schematic", version, about = "Interactive schematic viewer (.kicad_sch): KiCad-native render + per-component hover with stock & price")]+struct Cli { #[command(subcommand)] command: Cmd }++#[derive(Subcommand)]+enum Cmd {+    /// Render a `.kicad_sch` to a composed interactive SVG (+ optional -meta.json).+    Render { #[arg(long)] file: PathBuf, #[arg(long)] out: PathBuf, #[arg(long)] meta: bool },+    /// Export a self-contained INTERACTIVE HTML for embedding as a schematic view.+    Embed { #[arg(long)] file: PathBuf, #[arg(long)] out: Option<PathBuf>,+            /// Directory holding this design's sibling `.kicad_sch` files. When+            /// given, every hierarchical child sheet is pre-rendered and bundled+            /// into the embed so navigating between sheets is instant (no reload).+            #[arg(long)] sheet_dir: Option<PathBuf> },+    /// Run the live app server (the embeddable live schematic view).+    Serve { #[arg(long)] file: Option<PathBuf>, #[arg(long, default_value_t = 8785)] port: u16 },+    /// Look up stock / price / MPN / wiki for one part, as JSON on stdout.+    /// Lets a HOST app (e.g. adom-project-manager) serve `/enrich` for an+    /// embedded view, which has no server of its own.+    Enrich { #[arg(long, default_value = "")] mpn: String, #[arg(long, default_value = "")] lcsc: String },+    /// Drive the running server's front-end (the AI's live UI channel) exactly as a+    /// user's click would: `ui toast "done"` · `ui fit` · `ui sheet Data` ·+    /// `ui highlight U1` · `ui clear`.+    Ui { /// toast | fit | sheet | highlight | clear+         action: String,+         /// message (toast) or argument (sheet file / component ref)+         arg: Option<String>,+         #[arg(long = "type", default_value = "info")] ty: String,+         #[arg(long, default_value_t = 8785)] port: u16 },+    /// Check the live server is up on --port (prints OK:/ERROR: + a Hint:).+    Health { #[arg(long, default_value_t = 8785)] port: u16 },+    /// Install this binary to ~/.local/bin so host apps can shell it by name.+    Install,+}++const APP_HTML: &str = include_str!("app.html");+const VIEWER_JS: &str = include_str!("viewer.js");++pub fn build_embed(svg: &str, meta_json: &str) -> String {+    let payload = format!(+        "<script>window.__SCH__={{svg:{},meta:{}}};</script>\n<script>{}</script>",+        serde_json::to_string(svg).unwrap_or_else(|_| "\"\"".into()), meta_json, VIEWER_JS);+    APP_HTML.replace(r#"<script src="viewer.js"></script>"#, &payload)+}++/// Like build_embed, but also inlines `window.__SHEETS__` = {filename: {svg,meta}}+/// (root under "__root__") so the frontend can switch sheets instantly.+pub fn build_embed_bundle(svg: &str, meta_json: &str, bundle_json: &str) -> String {+    let payload = format!(+        "<script>window.__SCH__={{svg:{},meta:{}}};window.__SHEETS__={};</script>\n<script>{}</script>",+        serde_json::to_string(svg).unwrap_or_else(|_| "\"\"".into()), meta_json, bundle_json, VIEWER_JS);+    APP_HTML.replace(r#"<script src="viewer.js"></script>"#, &payload)+}++// CLI contract: every response starts with `OK:` or `ERROR:`, and every error+// carries an actionable `Hint:` naming the next command.+fn main() {+    if let Err(e) = run() {+        println!("ERROR: {e}");+        println!("Hint: check the file path / arguments; run `adom-schematic --help`");+        std::process::exit(1);+    }+}++fn run() -> Result<()> {+    match Cli::parse().command {+        Cmd::Render { file, out, meta } => {+            let raw = fs::read(&file).with_context(|| format!("read {}", file.display()))?;+            let (svg, m) = kicad_sch::render_sheet_bytes(&raw)?;+            fs::write(&out, &svg)?;+            println!("OK: rendered {} -> {} ({} components)", file.display(), out.display(), m.comp_count);+            if meta { fs::write(out.with_extension("meta.json"), serde_json::to_string_pretty(&m)?)?; }+        }+        Cmd::Embed { file, out, sheet_dir } => {+            let raw = fs::read(&file).with_context(|| format!("read {}", file.display()))?;+            // an authentic pre-rendered base sits beside the file as `<name>.base.svg`+            let base_of = |p: &std::path::Path| -> Option<String> {+                fs::read_to_string(format!("{}.base.svg", p.display())).ok()+            };+            let (svg, m) = kicad_sch::render_sheet_bytes_base(&raw, base_of(&file).as_deref())?;+            // Bundle: the root plus every child sheet, keyed by filename, so the+            // frontend can swap sheets in-place with zero load time.+            let mut bundle = serde_json::Map::new();+            bundle.insert("__root__".into(), serde_json::json!({"svg": svg, "meta": m}));+            let mut n_sheets = 0usize;+            if let Some(dir) = &sheet_dir {+                for sh in &m.sub_sheets {+                    // render each child; a child may itself be hierarchical (its own+                    // sub_sheets carry into that sheet's meta for deeper nav).+                    let p = dir.join(&sh.file);+                    if let Ok(cbytes) = fs::read(&p) {+                        if let Ok((csvg, cm)) = kicad_sch::render_sheet_bytes_base(&cbytes, base_of(&p).as_deref()) {+                            bundle.insert(sh.file.clone(), serde_json::json!({"svg": csvg, "meta": cm}));+                            n_sheets += 1;+                        }+                    }+                }+            }+            let html = build_embed_bundle(&svg, &serde_json::to_string(&m)?, &serde_json::to_string(&bundle)?);+            let out = out.unwrap_or_else(|| file.with_extension("schview.html"));+            fs::write(&out, &html)?;+            println!("OK: embed -> {} ({} components, {} child sheets bundled)", out.display(), m.comp_count, n_sheets);+        }+        Cmd::Serve { file, port } => {+            if let Some(f) = file {+                let content = fs::read_to_string(&f).with_context(|| format!("read {}", f.display()))?;+                let name = f.file_stem().and_then(|s| s.to_str()).unwrap_or("sheet").to_string();+                server::load_sch(&name, &content)?;+                println!("OK: loaded {}", f.display());+            }+            server::run(port)?;+        }+        Cmd::Enrich { mpn, lcsc } => println!("{}", enrich::lookup(&mpn, &lcsc)),+        Cmd::Ui { action, arg, ty, port } => {+            let base = format!("http://127.0.0.1:{port}");+            let (path, payload) = match action.as_str() {+                "toast" => ("/ui/toast", serde_json::json!({ "message": arg.unwrap_or_default(), "type": ty }).to_string()),+                "fit" | "clear" => ("/ui/cmd", serde_json::json!({ "action": action }).to_string()),+                "sheet" | "highlight" => ("/ui/cmd", serde_json::json!({ "action": action, "arg": arg.unwrap_or_default() }).to_string()),+                other => {+                    println!("ERROR: unknown ui action '{other}'");+                    println!("Hint: use one of: toast <msg> | fit | sheet <file> | highlight <ref> | clear");+                    return Ok(());+                }+            };+            match ureq::post(&format!("{base}{path}")).set("Content-Type", "application/json").send_string(&payload) {+                Ok(_) => println!("OK: ui {action} sent to {base}"),+                Err(_) => {+                    println!("ERROR: could not reach the viewer server on port {port}");+                    println!("Hint: start it with `adom-schematic serve --port {port} &`");+                }+            }+        }+        Cmd::Health { port } => match ureq::get(&format!("http://127.0.0.1:{port}/version")).call() {+            Ok(r) => println!("OK: adom-schematic healthy on port {port} ({})", r.into_string().unwrap_or_default().trim()),+            Err(_) => {+                println!("ERROR: no adom-schematic server responding on port {port}");+                println!("Hint: start it with `adom-schematic serve --port {port} &`");+            }+        },+        Cmd::Install => {+            let exe = std::env::current_exe()?;+            let home = std::env::var("HOME").unwrap_or_default();+            let bin = format!("{home}/.local/bin");+            fs::create_dir_all(&bin)?;+            let dst = format!("{bin}/adom-schematic");+            fs::copy(&exe, &dst)?;+            println!("OK: installed adom-schematic to {dst}");+            println!("Hint: ensure ~/.local/bin is on your PATH");+        }+    }+    Ok(())+}
src/sch_parse.rsadded+281
@@ -0,0 +1,281 @@+//! Parse a `.kicad_sch` for the INTERACTION overlay: each placed symbol's+//! identity (ref / value / footprint / LCSC PN / description) and its bounding+//! box in schematic PAGE coordinates (mm), so we can drop a transparent hover+//! hotspot over it aligned to the KiCad-native SVG. We do NOT render the sheet —+//! service-kicad provides the authentic visual.++use crate::sexpr::{blocks, esc, f};+use regex::Regex;+use serde::Serialize;++#[derive(Serialize, Clone)]+pub struct Comp {+    pub reference: String,+    pub value: String,+    pub footprint: String,+    pub lcsc: String,+    pub description: String,+    pub datasheet: String,+    pub x: f64,+    pub y: f64,+    pub bbox: [f64; 4], // page mm: [minx,miny,maxx,maxy]+    pub pin_count: usize,+    /// Hit regions that belong to this symbol: the body bbox PLUS a box around+    /// each visible property text (reference/value), because KiCad's selection+    /// haloes that text too. Used only for tagging, not shipped in the meta.+    #[serde(skip)]+    pub regions: Vec<[f64; 4]>,+}++/// A hierarchical-sheet symbol on this sheet: a box that links to a child+/// `.kicad_sch`. Clicking it in the viewer navigates into that child.+#[derive(Serialize, Clone)]+pub struct SubSheet {+    pub name: String,+    pub file: String,+    pub bbox: [f64; 4], // page mm+}++pub struct Sheet {+    pub comps: Vec<Comp>,+    pub sub_sheets: Vec<SubSheet>,+    pub content_bbox: (f64, f64, f64, f64), // minx,miny,w,h (mm) with margin+}++struct LibSym { pts: Vec<(f64, f64)> } // all graphic/pin points (lib coords)++/// Transform a lib point to page coords (lib frame is Y-up; sheet is Y-down).+// KiCad applies the mirror in page space AFTER rotation (see kicad_self::xf) — do+// it in the same order here so a rotated+mirrored symbol's hit region is correct.+fn xf(lx: f64, ly: f64, px: f64, py: f64, rot: f64, mirror: u8) -> (f64, f64) {+    let (x, y) = (lx, -ly);+    let a = (-rot).to_radians();+    let (c, s) = (a.cos(), a.sin());+    let (mut rx, mut ry) = (x * c - y * s, x * s + y * c);+    if mirror == 1 { rx = -rx; }+    if mirror == 2 { ry = -ry; }+    (px + rx, py + ry)+}++fn quoted(s: &str) -> Option<String> {+    let q1 = s.find('"')?;+    let rest = &s[q1 + 1..];+    let q2 = rest.find('"')?;+    Some(rest[..q2].to_string())+}+/// The n-th (0-based) double-quoted string in `s` — property name = 0, value = 1.+fn nth_quoted(s: &str, n: usize) -> Option<String> {+    let mut rest = s;+    for i in 0.. {+        let q1 = rest.find('"')?;+        let after = &rest[q1 + 1..];+        let q2 = after.find('"')?;+        if i == n { return Some(after[..q2].to_string()); }+        rest = &after[q2 + 1..];+    }+    None+}+fn cap1(s: &str, re: &str) -> Option<String> { Regex::new(re).ok()?.captures(s).map(|c| c[1].to_string()) }++/// Top-level `(symbol …)` blocks (not nested).+fn top_symbols(s: &str) -> Vec<&str> {+    let bytes = s.as_bytes();+    let mut out = vec![];+    let mut i = 0;+    while let Some(rel) = s[i..].find("(symbol") {+        let start = i + rel;+        let after = start + 7;+        if bytes.get(after).map(|c| !c.is_ascii_whitespace()).unwrap_or(true) { i = after; continue; }+        let mut depth = 0i32; let mut end = start;+        for j in start..s.len() { match bytes[j] { b'(' => depth += 1, b')' => { depth -= 1; if depth == 0 { end = j; break; } } _ => {} } }+        out.push(&s[start..=end.min(s.len() - 1)]);+        i = end + 1;+    }+    out+}++pub fn parse(content: &str) -> Sheet {+    let at3 = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?\)").unwrap();+    let se = Regex::new(r"\(start\s+(-?[\d.]+)\s+(-?[\d.]+)\)\s*\(end\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let xy = Regex::new(r"\(xy\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let center = Regex::new(r"\(center\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let radius = Regex::new(r"\(radius\s+(-?[\d.]+)\)").unwrap();+    let arc_sme = Regex::new(r"\(start\s+(-?[\d.]+)\s+(-?[\d.]+)\)\s*\(mid\s+(-?[\d.]+)\s+(-?[\d.]+)\)\s*\(end\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let length = Regex::new(r"\(length\s+(-?[\d.]+)\)").unwrap();+    let prop = Regex::new(r##"\(property\s+"([^"]+)"\s+"([^"]*)""##).unwrap();+    let mirror_re = Regex::new(r"\(mirror\s+(x|y)\)").unwrap();++    // ── lib_symbols: collect each definition's graphic + pin points ──+    let mut libs: std::collections::HashMap<String, LibSym> = std::collections::HashMap::new();+    if let Some(libblk) = blocks(content, "lib_symbols").into_iter().next() {+        for def in top_symbols(libblk) {+            let name = match quoted(def) { Some(n) if !n.is_empty() => n, _ => continue };+            let mut pts: Vec<(f64, f64)> = vec![];+            for r in blocks(def, "rectangle") {+                if let Some(c) = se.captures(r) {+                    pts.push((f(c.get(1)), f(c.get(2))));+                    pts.push((f(c.get(3)), f(c.get(4))));+                }+            }+            for p in blocks(def, "polyline") { for c in xy.captures_iter(p) { pts.push((f(c.get(1)), f(c.get(2)))); } }+            for c in blocks(def, "circle") {+                if let (Some(ce), Some(ra)) = (center.captures(c), radius.captures(c)) {+                    let (cx, cy, r) = (f(ce.get(1)), f(ce.get(2)), f(ra.get(1)));+                    pts.push((cx - r, cy - r)); pts.push((cx + r, cy + r));+                }+            }+            // arcs (inductor coils, curved plates): include start/mid/end so the+            // symbol's hit region covers the ARC BULGES, not just the axis line —+            // otherwise hovering the curve of an inductor didn't select it.+            for a in blocks(def, "arc") {+                if let Some(c) = arc_sme.captures(a) {+                    pts.push((f(c.get(1)), f(c.get(2))));+                    pts.push((f(c.get(3)), f(c.get(4))));+                    pts.push((f(c.get(5)), f(c.get(6))));+                }+            }+            for pin in blocks(def, "pin") {+                if let Some(a) = at3.captures(pin) {+                    let (lx, ly, ang) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+                    let len = length.captures(pin).map(|c| f(c.get(1))).unwrap_or(2.54);+                    pts.push((lx, ly));+                    pts.push((lx + ang.to_radians().cos() * len, ly + ang.to_radians().sin() * len));+                }+            }+            libs.insert(name, LibSym { pts });+        }+    }+    // bare-key alias index so dedup-renamed lib entries (e.g. "LED_2" for an+    // instance's "Device:LED") still resolve — see kicad_self::lib_bare_key.+    let libs_bare: std::collections::HashMap<String, String> = {+        let mut m = std::collections::HashMap::new();+        for k in libs.keys() { m.entry(crate::kicad_self::lib_bare_key(k)).or_insert_with(|| k.clone()); }+        m+    };++    let content_wo_lib = strip_first(content, "lib_symbols");+    let mut comps: Vec<Comp> = vec![];+    let (mut gminx, mut gminy, mut gmaxx, mut gmaxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);++    for inst in top_symbols(&content_wo_lib) {+        let lib_id = match cap1(inst, r##"\(lib_id\s+"([^"]+)"\)"##) { Some(s) => s, None => continue };+        if lib_id.starts_with("power:") { continue; } // skip power/ground symbols+        let a = match at3.captures(inst) { Some(a) => a, None => continue };+        let (px, py, rot) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+        let mirror = mirror_re.captures(inst).map(|c| if &c[1] == "x" { 2u8 } else { 1u8 }).unwrap_or(0);++        let (mut reference, mut value, mut footprint) = (String::new(), String::new(), String::new());+        let (mut lcsc, mut description, mut datasheet) = (String::new(), String::new(), String::new());+        for c in prop.captures_iter(inst) {+            match &c[1] {+                "Reference" => reference = c[2].to_string(),+                "Value" => value = c[2].to_string(),+                "Footprint" => footprint = c[2].to_string(),+                "Description" => description = c[2].to_string(),+                "Datasheet" => datasheet = c[2].to_string(),+                k if k.eq_ignore_ascii_case("LCSC PN") || k.eq_ignore_ascii_case("LCSC") || k.eq_ignore_ascii_case("JLCPCB") => lcsc = c[2].to_string(),+                _ => {}+            }+        }+        // bbox from the lib def's points transformed to page coords+        let (mut minx, mut miny, mut maxx, mut maxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+        let mut pin_n = 0usize;+        let lib_resolved = libs.get(&lib_id)+            .or_else(|| libs_bare.get(&crate::kicad_self::lib_bare_key(&lib_id)).and_then(|n| libs.get(n)));+        if let Some(lib) = lib_resolved {+            for &(lx, ly) in &lib.pts {+                let (x, y) = xf(lx, ly, px, py, rot, mirror);+                minx = minx.min(x); miny = miny.min(y); maxx = maxx.max(x); maxy = maxy.max(y);+            }+            pin_n = blocks(libs_def(content, &lib_id).as_deref().unwrap_or(""), "pin").len();+        }+        if !minx.is_finite() { minx = px - 2.54; miny = py - 2.54; maxx = px + 2.54; maxy = py + 2.54; }+        gminx = gminx.min(minx); gminy = gminy.min(miny); gmaxx = gmaxx.max(maxx); gmaxy = gmaxy.max(maxy);++        // regions = symbol body + a box around each VISIBLE property text+        let mut regions = vec![[minx, miny, maxx, maxy]];+        for pb in blocks(inst, "property") {+            if pb.contains("(hide yes)") { continue; }+            let txt = nth_quoted(pb, 1).unwrap_or_default();+            if txt.is_empty() || txt == "~" { continue; }+            let a = match at3.captures(pb) { Some(a) => a, None => continue };+            let (tx, ty, trot) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+            let size = Regex::new(r"\(size\s+([\d.]+)").ok().and_then(|r| r.captures(pb).map(|c| f(c.get(1)))).unwrap_or(1.27);+            let w = txt.chars().count() as f64 * size * 0.9 + 1.2;+            let hh = size * 0.95;+            // justify decides which way the text runs from its anchor+            let (a0, a1) = if pb.contains("(justify right") { (-w, 0.0) }+                else if pb.contains("(justify left") { (0.0, w) }+                else { (-w / 2.0, w / 2.0) };+            let r = if (trot - 90.0).abs() < 1.0 || (trot - 270.0).abs() < 1.0 {+                [tx - hh, ty + a0, tx + hh, ty + a1] // vertical text+            } else {+                [tx + a0, ty - hh, tx + a1, ty + hh]+            };+            gminx = gminx.min(r[0]); gminy = gminy.min(r[1]); gmaxx = gmaxx.max(r[2]); gmaxy = gmaxy.max(r[3]);+            regions.push(r);+        }+        comps.push(Comp { reference, value, footprint, lcsc, description, datasheet, x: px, y: py, bbox: [minx, miny, maxx, maxy], pin_count: pin_n, regions });+    }++    // include wires in the content bounds so the crop isn't too tight+    for w in blocks(&content_wo_lib, "wire") {+        for c in xy.captures_iter(w) { let (x, y) = (f(c.get(1)), f(c.get(2))); gminx = gminx.min(x); gminy = gminy.min(y); gmaxx = gmaxx.max(x); gmaxy = gmaxy.max(y); }+    }+    // hierarchical-sheet symbols: `(sheet (at x y) (size w h) … (property "Sheetname" ..)+    // (property "Sheetfile" "child.kicad_sch"))`. Each is a clickable box.+    let mut sub_sheets = Vec::new();+    let sheet_at = Regex::new(r"\(at\s+([\d.-]+)\s+([\d.-]+)").unwrap();+    let sheet_sz = Regex::new(r"\(size\s+([\d.-]+)\s+([\d.-]+)").unwrap();+    let prop = |blk: &str, key: &str| -> String {+        Regex::new(&format!(r#"\(property\s+"{key}"\s+"([^"]*)""#)).ok()+            .and_then(|r| r.captures(blk).map(|c| c[1].to_string())).unwrap_or_default()+    };+    for blk in blocks(content, "sheet") {+        let file = prop(blk, "Sheetfile");+        if file.is_empty() { continue; } // not a hierarchical sheet symbol+        let (x, y) = match sheet_at.captures(blk) { Some(c) => (f(c.get(1)), f(c.get(2))), None => continue };+        let (w, h) = sheet_sz.captures(blk).map(|c| (f(c.get(1)), f(c.get(2)))).unwrap_or((25.4, 25.4));+        let bbox = [x, y, x + w, y + h];+        gminx = gminx.min(x); gminy = gminy.min(y); gmaxx = gmaxx.max(x + w); gmaxy = gmaxy.max(y + h);+        sub_sheets.push(SubSheet { name: prop(blk, "Sheetname"), file, bbox });+    }++    if !gminx.is_finite() { gminx = 0.0; gminy = 0.0; gmaxx = 100.0; gmaxy = 100.0; }+    let m = 5.0;+    let content_bbox = (gminx - m, gminy - m, (gmaxx - gminx) + 2.0 * m, (gmaxy - gminy) + 2.0 * m);+    Sheet { comps, sub_sheets, content_bbox }+}++/// Number of pins for a lib — pulled from the raw lib def (rough, for the card).+fn libs_def(content: &str, lib_id: &str) -> Option<String> {+    let libblk = blocks(content, "lib_symbols").into_iter().next()?;+    for def in top_symbols(libblk) {+        if quoted(def).as_deref() == Some(lib_id) { return Some(def.to_string()); }+    }+    None+}++fn strip_first(s: &str, tag: &str) -> String {+    if let Some(b) = blocks(s, tag).into_iter().next() { return s.replacen(b, "", 1); }+    s.to_string()+}++/// Build the transparent hover-hotspot overlay (one rect per component).+pub fn build_overlay(sheet: &Sheet) -> String {+    use std::fmt::Write as _;+    let mut s = String::from(r##"<g class="adom-overlay">"##);+    for c in &sheet.comps {+        let [x0, y0, x1, y1] = c.bbox;+        let _ = write!(s, r##"<rect class="adom-comp" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" data-ref="{}" fill="transparent"/>"##,+            x0, y0, (x1 - x0).max(0.5), (y1 - y0).max(0.5), esc(&c.reference));+    }+    // hierarchical sheet symbols: a clickable box that navigates into the child+    for sh in &sheet.sub_sheets {+        let [x0, y0, x1, y1] = sh.bbox;+        let _ = write!(s, r##"<rect class="adom-sheet-link" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" data-sheet="{}" data-sheet-name="{}" fill="transparent"/>"##,+            x0, y0, (x1 - x0).max(0.5), (y1 - y0).max(0.5), esc(&sh.file), esc(&sh.name));+    }+    s.push_str("</g>");+    s+}
src/server.rsadded+180
@@ -0,0 +1,180 @@+//! adom-schematic live app server — the embeddable live schematic view.+//! GET / (UI), /viewer.js, /favicon.svg, /state, POST /load (.kicad_sch),+//! GET /enrich, POST /shutdown. Same app-creator shape as the layout viewer.++use anyhow::Result;+use serde_json::{json, Value};+use std::collections::{HashMap, HashSet};+use std::io::Read;+use std::sync::Mutex;+use tiny_http::{Header, Method, Response, Server};++#[derive(Default, Clone)]+pub struct AppState { pub name: String, pub svg: String, pub meta_json: String }++static STATE: Mutex<Option<AppState>> = Mutex::new(None);+static ENRICH_CACHE: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);+static ENRICH_PENDING: Mutex<Option<HashSet<String>>> = Mutex::new(None);+// AI-drivability: the AI narrates over the running UI (POST /ui/toast) and drives it+// (POST /ui/cmd — same paths a user's click takes); the frontend drains both via+// GET /ui/pull. CONSOLE is the observability ring buffer the UI mirrors into.+static TOASTS: Mutex<Vec<Value>> = Mutex::new(Vec::new());+static CMDS: Mutex<Vec<Value>> = Mutex::new(Vec::new());+static CONSOLE: Mutex<Vec<Value>> = Mutex::new(Vec::new());++const APP_HTML: &str = include_str!("app.html");+const VIEWER_JS: &str = include_str!("viewer.js");+const FAVICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#00e6dc" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="1.5"/><path d="M7 9h3v6H7zM14 12h3M14 12l-2-2M14 12l-2 2"/></svg>"##;++pub fn set_state(s: AppState) { *STATE.lock().unwrap() = Some(s); }++pub fn load_sch(name: &str, sch: &str) -> Result<()> {+    let (svg, meta) = crate::kicad_sch::render_sheet(sch)?;+    let lcscs: Vec<(String, String)> = meta.components.iter()+        .filter(|c| !c.lcsc.is_empty() || !c.value.is_empty())+        .map(|c| (c.value.clone(), c.lcsc.clone())).collect();+    set_state(AppState { name: name.into(), svg, meta_json: serde_json::to_string(&meta)? });+    if !lcscs.is_empty() {+        std::thread::spawn(move || { for (v, l) in lcscs { let _ = enrich_fill(&v, &l); } });+    }+    Ok(())+}++fn enrich_fill(value: &str, lcsc: &str) -> String {+    let key = format!("{value}|{lcsc}");+    let out = crate::enrich::lookup(value, lcsc);+    if let Some(m) = ENRICH_CACHE.lock().unwrap().as_mut() { m.insert(key.clone(), out.clone()); }+    if let Some(p) = ENRICH_PENDING.lock().unwrap().as_mut() { p.remove(&key); }+    out+}++fn state_json() -> String {+    match &*STATE.lock().unwrap() {+        Some(s) => format!(r#"{{"name":{},"svg":{},"meta":{}}}"#,+            serde_json::to_string(&s.name).unwrap(), serde_json::to_string(&s.svg).unwrap(),+            if s.meta_json.is_empty() { "{}" } else { &s.meta_json }),+        None => "{}".into(),+    }+}++pub fn run(port: u16) -> Result<()> {+    *ENRICH_CACHE.lock().unwrap() = Some(HashMap::new());+    *ENRICH_PENDING.lock().unwrap() = Some(HashSet::new());+    let server = Server::http(format!("0.0.0.0:{port}")).map_err(|e| anyhow::anyhow!("bind {port}: {e}"))?;+    eprintln!("[adom-schematic] serving on http://127.0.0.1:{port}");+    register_port(port);+    for mut req in server.incoming_requests() {+        let raw = req.url().to_string();+        let url = raw.split('?').next().unwrap_or("/").to_string();+        let query = raw.splitn(2, '?').nth(1).unwrap_or("").to_string();+        let method = req.method().clone();+        let mut body = String::new();+        if matches!(method, Method::Post) { let _ = req.as_reader().read_to_string(&mut body); }+        let resp = route(&method, &url, &query, &body);+        let _ = req.respond(resp);+        if url == "/shutdown" && matches!(method, Method::Post) { break; }+    }+    unregister_port(port);+    Ok(())+}++fn route(method: &Method, url: &str, query: &str, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {+    match (method, url) {+        (Method::Get, "/") | (Method::Get, "/index.html") => resp(APP_HTML, "text/html; charset=utf-8"),+        (Method::Get, "/viewer.js") => resp(VIEWER_JS, "application/javascript"),+        (Method::Get, "/favicon.svg") => resp(FAVICON, "image/svg+xml"),+        (Method::Get, "/state") => json_resp(&state_json()),+        (Method::Get, "/version") => json_resp(&json!({ "version": env!("CARGO_PKG_VERSION"), "name": "adom-schematic" }).to_string()),+        // observability ring buffer (GET to read, POST from the UI to append)+        (Method::Get, "/console") => json_resp(&json!({ "lines": *CONSOLE.lock().unwrap() }).to_string()),+        (Method::Post, "/console") => {+            if let Ok(v) = serde_json::from_str::<Value>(body) {+                let mut g = CONSOLE.lock().unwrap(); g.push(v);+                let n = g.len(); if n > 500 { g.drain(0..n - 500); }+            }+            json_resp("{\"ok\":true}")+        }+        // AI channel: narrate (toast) + drive (cmd); the UI drains both via /ui/pull.+        (Method::Post, "/ui/toast") => {+            if let Ok(v) = serde_json::from_str::<Value>(body) {+                let msg = v.get("message").and_then(|x| x.as_str()).unwrap_or("");+                let ty = v.get("type").and_then(|x| x.as_str()).unwrap_or("info");+                if !msg.is_empty() { TOASTS.lock().unwrap().push(json!({ "message": msg, "type": ty })); }+            }+            json_resp("{\"ok\":true}")+        }+        (Method::Post, "/ui/cmd") => {+            if let Ok(v) = serde_json::from_str::<Value>(body) {+                if v.get("action").and_then(|x| x.as_str()).map(|s| !s.is_empty()).unwrap_or(false) { CMDS.lock().unwrap().push(v); }+            }+            json_resp("{\"ok\":true}")+        }+        (Method::Get, "/ui/pull") => {+            let toasts: Vec<Value> = std::mem::take(&mut *TOASTS.lock().unwrap());+            let cmds: Vec<Value> = std::mem::take(&mut *CMDS.lock().unwrap());+            json_resp(&json!({ "toasts": toasts, "cmds": cmds }).to_string())+        }+        (Method::Get, "/enrich") => json_resp(&enrich(query)),+        (Method::Post, "/load") => {+            if let Ok(v) = serde_json::from_str::<Value>(body) {+                if let Some(sch) = v.get("kicadSch").and_then(|x| x.as_str()) {+                    let name = v.get("name").and_then(|x| x.as_str()).unwrap_or("sheet").to_string();+                    return match load_sch(&name, sch) { Ok(()) => json_resp("{\"ok\":true}"), Err(e) => json_err(422, &e.to_string()) };+                }+            }+            json_resp("{\"ok\":true}")+        }+        (Method::Post, "/shutdown") => json_resp("{\"ok\":true}"),+        _ => not_found(),+    }+}++fn enrich(query: &str) -> String {+    let params = parse_query(query);+    let value = params.get("mpn").cloned().unwrap_or_default();+    let lcsc = params.get("lcsc").cloned().unwrap_or_default();+    if value.is_empty() && lcsc.is_empty() { return "{}".into(); }+    let key = format!("{value}|{lcsc}");+    if let Some(hit) = ENRICH_CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { return hit; }+    let already = { let mut g = ENRICH_PENDING.lock().unwrap(); let set = g.get_or_insert_with(Default::default); !set.insert(key.clone()) };+    if !already { std::thread::spawn(move || { let _ = enrich_fill(&value, &lcsc); }); }+    "{\"pending\":true}".into()+}++fn parse_query(q: &str) -> HashMap<String, String> {+    q.split('&').filter_map(|kv| { let mut it = kv.splitn(2, '='); Some((it.next()?.to_string(), urldecode(it.next().unwrap_or("")))) }).collect()+}+fn urldecode(s: &str) -> String {+    let b = s.as_bytes(); let mut out = String::new(); let mut i = 0;+    while i < b.len() {+        match b[i] {+            b'%' if i + 2 < b.len() => { if let Ok(c) = u8::from_str_radix(&s[i + 1..i + 3], 16) { out.push(c as char); i += 3; } else { out.push('%'); i += 1; } }+            b'+' => { out.push(' '); i += 1; }+            c => { out.push(c as char); i += 1; }+        }+    }+    out+}++fn register_port(port: u16) {+    let body = format!("{{\"port\":{port},\"action\":\"register\",\"name\":\"adom-schematic\",\"reason\":\"Interactive schematic view\",\"expose\":\"internal\"}}");+    std::thread::spawn(move || hd_post(&body));+}+fn unregister_port(port: u16) { hd_post(&format!("{{\"port\":{port},\"action\":\"unregister\"}}")); }+fn hd_post(body: &str) {+    use std::io::Write;+    use std::net::{TcpStream, ToSocketAddrs};+    use std::time::Duration;+    let addr = match ("host.docker.internal", 47084u16).to_socket_addrs().ok().and_then(|mut a| a.next()) { Some(a) => a, None => return };+    if let Ok(mut s) = TcpStream::connect_timeout(&addr, Duration::from_millis(800)) {+        let _ = s.set_write_timeout(Some(Duration::from_millis(800)));+        let req = format!("POST /port-forward HTTP/1.1\r\nHost: host.docker.internal\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body);+        let _ = s.write_all(req.as_bytes());+    }+}++fn hdr(ct: &str) -> Header { Header::from_bytes(&b"Content-Type"[..], ct.as_bytes()).unwrap() }+fn resp(s: &str, ct: &str) -> Response<std::io::Cursor<Vec<u8>>> { Response::from_string(s).with_header(hdr(ct)) }+fn json_resp(s: &str) -> Response<std::io::Cursor<Vec<u8>>> { Response::from_string(s).with_header(hdr("application/json")) }+fn not_found() -> Response<std::io::Cursor<Vec<u8>>> { Response::from_string("{\"error\":\"not found\"}").with_status_code(404).with_header(hdr("application/json")) }+fn json_err(code: u16, msg: &str) -> Response<std::io::Cursor<Vec<u8>>> { Response::from_string(json!({ "ok": false, "error": msg }).to_string()).with_status_code(code).with_header(hdr("application/json")) }
src/sexpr.rsadded+35
@@ -0,0 +1,35 @@+//! Tiny shared S-expression helpers used by both the PCB and schematic+//! renderers (balanced-paren block slicing + escaping).++/// Balanced-paren slice of every `(<tag>` block whose tag is followed by a+/// whitespace/paren boundary (so `(net` never matches `(net_name`).+pub fn blocks<'a>(s: &'a str, tag: &str) -> Vec<&'a str> {+    let bytes = s.as_bytes();+    let needle = format!("({}", tag);+    let mut out = Vec::new();+    let mut search = 0;+    while let Some(rel) = s[search..].find(&needle) {+        let start = search + rel;+        let after = start + needle.len();+        let ok = bytes.get(after).map(|c| c.is_ascii_whitespace() || *c == b'(').unwrap_or(false);+        if !ok { search = after; continue; }+        let mut depth = 0i32;+        let mut end = start;+        for i in start..s.len() {+            match bytes[i] {+                b'(' => depth += 1,+                b')' => { depth -= 1; if depth == 0 { end = i; break; } }+                _ => {}+            }+        }+        out.push(&s[start..=end.min(s.len() - 1)]);+        search = end + 1;+    }+    out+}++pub fn esc(s: &str) -> String {+    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")+}++pub fn f(cap: Option<regex::Match>) -> f64 { cap.and_then(|m| m.as_str().parse().ok()).unwrap_or(0.0) }
src/viewer.jsadded+445
@@ -0,0 +1,445 @@+/* adom-schematic core — KiCad-native schematic SVG + a component hotspot+ * overlay. Hover a symbol → what it is (ref/value/footprint) + live stock & price.+ * Consumes window.__SCH__ = { svg, meta } (embed) OR fetches /state (live). */+(function () {+  "use strict";+  const $ = (s, r) => (r || document).querySelector(s);+  const state = { meta: null, pinned: null, enrichCache: {} };++  function mount(svgText, meta) {+    state.meta = meta || { components: [] };+    const box = $("#svgbox");+    box.innerHTML = svgText;+    const svg = box.querySelector("svg");+    if (!svg) return;+    svg.removeAttribute("width"); svg.removeAttribute("height");+    svg.style.width = "100%"; svg.style.height = "100%";+    state.svg = svg;+    state.hlRef = null; // fresh DOM: nothing is highlighted yet+    // Match the viewport to the sheet's own background so the drawing reads as one+    // infinite sheet. The fill differs per EDA (Altium #ffffff, KiCad/Eagle #fbfbf6),+    // so read it off the rendered sheet rather than hardcoding.+    const bg = svg.querySelector(".adom-sheet-bg");+    if (bg) { const f = bg.getAttribute("fill"); if (f) box.style.background = f; }+    state.vb = (svg.getAttribute("viewBox") || "0 0 100 100").split(/\s+/).map(Number);+    state.vb0 = state.vb.slice();+    wireHover(svg);+    wirePanZoom(svg);+    buildCompList();+    buildCrumb();+    setStat();+    updateChrome();+  }+  // Show the canonical header + Components panel + stat only when there's room+  // (standalone tab or a fullscreened pane); hide them in a small embedded+  // thumbnail (APM board view) so the sheet fills the pane.+  function updateChrome() {+    const big = innerWidth > 620;+    // Header only when standalone/large — inside APM's iframe (embed) APM already+    // wears the canonical header, so we'd double it. Panels still show when big.+    document.body.classList.toggle("chrome", big && !window.__EMBED__);+    ["#side", "#stat"].forEach((s) => { const e = $(s); if (e) e.style.display = big ? "" : "none"; });+  }+  addEventListener("resize", updateChrome);++  // ── POST helper + observability: mirror console + errors to the server ring+  // buffer (GET /console) so the AI can read what the UI is doing. Live-server only+  // (an embed has no server of its own). ──────────────────────────────────────+  function post(path, body) { try { fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); } catch (e) {} }+  function wireObservability() {+    if (window.__EMBED__) return;+    ["log", "warn", "error"].forEach((k) => { const orig = console[k]; console[k] = function () { try { post("console", { level: k, msg: [].slice.call(arguments).map(String).join(" ") }); } catch (e) {} return orig.apply(console, arguments); }; });+    addEventListener("error", (e) => post("console", { level: "error", msg: (e.message || "") + " @" + (e.filename || "") + ":" + (e.lineno || 0) }));+    addEventListener("unhandledrejection", (e) => post("console", { level: "error", msg: "unhandledrejection: " + (e.reason && e.reason.message || e.reason) }));+  }++  // ── toasts: every action answers back + the AI's live narration channel ──+  const TOAST_ICONS = {+    success: '<svg class="ti" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>',+    error: '<svg class="ti" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>',+    info: '<svg class="ti" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M12 8h.01M11 12h1v4h1"/><circle cx="12" cy="12" r="9"/></svg>',+  };+  function toast(msg, type) {+    type = type || "info";+    const box = $("#toasts"); if (!box || !msg) return;+    const el = document.createElement("div"); el.className = "toast " + type;+    el.innerHTML = (TOAST_ICONS[type] || TOAST_ICONS.info) + '<span class="tmsg"></span>';+    el.querySelector(".tmsg").textContent = msg;+    while (box.children.length >= 4) box.removeChild(box.firstChild);+    box.appendChild(el);+    const kill = () => { el.classList.add("out"); setTimeout(() => el.remove(), 200); };+    el.onclick = kill;+    if (type !== "error") setTimeout(kill, 4000); // errors stay until dismissed+  }+  // Drain AI-pushed toasts + drive-commands (POST /ui/toast, /ui/cmd). Live only.+  function pollUi() {+    if (window.__EMBED__) return;+    fetch("ui/pull").then((r) => r.json()).then((q) => {+      (q.toasts || []).forEach((t) => toast(t.message, t.type));+      (q.cmds || []).forEach(runCmd);+    }).catch(() => {});+    setTimeout(pollUi, 1000);+  }+  // The AI drives the front-end the same way a user would (see CLI `ui` verbs).+  function runCmd(c) {+    if (!c || !c.action) return;+    if (c.action === "fit") { fit(); toast("Fit to view", "info"); }+    else if (c.action === "sheet" && c.arg) { openSheet(c.arg); }+    else if (c.action === "highlight" && c.arg) { state.pinned = c.arg; compHl(c.arg); showCard(c.arg); toast("Highlight " + c.arg, "info"); }+    else if (c.action === "clear") { state.pinned = null; clearSym(); hideCard(); }+    else if (c.action === "toast") { toast(c.arg || "", c.type || "info"); }+  }++  // ── tooltip: body-appended fixed div, 600ms reveal, clamped to viewport on BOTH+  // axes, flips at the right/bottom edges. Never a ::after (clipped by panels). ──+  let ttEl = null, ttTimer = null;+  function showTip(target, e) {+    const msg = target.getAttribute("data-tip"); if (!msg) return;+    clearTimeout(ttTimer);+    const cx = e.clientX, cy = e.clientY;+    ttTimer = setTimeout(() => {+      if (!ttEl) { ttEl = document.createElement("div"); ttEl.id = "tt"; document.body.appendChild(ttEl); }+      ttEl.textContent = msg; ttEl.style.left = "-9999px"; ttEl.style.top = "0px"; ttEl.classList.add("show");+      const M = 8, w = ttEl.offsetWidth, h = ttEl.offsetHeight;+      let x = cx + 14, y = cy + 16;+      if (x + w > innerWidth - M) x = cx - w - 14;   // flip left at the right edge+      if (y + h > innerHeight - M) y = cy - h - 14;  // flip up at the bottom edge+      x = Math.max(M, Math.min(x, innerWidth - w - M)); // clamp both axes so it never+      y = Math.max(M, Math.min(y, innerHeight - h - M)); // runs off any edge+      ttEl.style.left = x + "px"; ttEl.style.top = y + "px";+    }, 600);+  }+  function hideTip() { clearTimeout(ttTimer); if (ttEl) ttEl.classList.remove("show"); }+  document.addEventListener("mouseover", (e) => { const t = e.target.closest && e.target.closest("[data-tip]"); if (t) showTip(t, e); });+  document.addEventListener("mouseout", (e) => { if (e.target.closest && e.target.closest("[data-tip]")) hideTip(); });+  document.addEventListener("mousedown", hideTip);++  // ── header subject (center zone) ──+  function setSubject(name, meta) {+    const n = $("#hdr-name"), m = $("#hdr-meta");+    if (n) n.textContent = name || "";+    if (m) m.textContent = meta || "";+  }+  function curSheetLabel() {+    if (!state.curSheet) return "Root sheet";+    const subs = (state.sheets && state.sheets.__root__ && state.sheets.__root__.meta && state.sheets.__root__.meta.sub_sheets) || state.meta.sub_sheets || [];+    const s = subs.find((x) => x.file === state.curSheet);+    return s ? (s.name || s.file) : state.curSheet;+  }++  // ── CROSS-PROBE with the sibling PCB view (host/APM relays between the two+  // same-origin iframes, keyed by the component reference). ──+  function xpost(ref) { try { if (window.parent && window.parent !== window) window.parent.postMessage({ adomXprobe: true, ref: ref }, "*"); } catch (e) {} }+  function centerOn(ref) {+    const c = (state.meta.components || []).find((k) => k.reference === ref);+    if (c && c.bbox) frameBBox(c.bbox);+  }+  // Zoom-to-fit a bbox: frame the part with margin (matching the viewport aspect),+  // keep some context for tiny parts, never zoom out past the whole sheet.+  function frameBBox(bb) {+    if (!bb || !state.svg) return;+    const x0 = bb[0], y0 = bb[1], x1 = bb[2], y1 = bb[3], cx = (x0 + x1) / 2, cy = (y0 + y1) / 2;+    const rc = state.svg.getBoundingClientRect();+    const aspect = (rc.width && rc.height) ? rc.width / rc.height : ((state.vb0[2] / state.vb0[3]) || 1);+    let span = Math.max(x1 - x0, y1 - y0, 0.5) * 3.2; // the part fills ~1/3 of the short side+    span = Math.max(span, 10);                         // don't over-zoom a tiny part+    let w = aspect >= 1 ? span * aspect : span;+    let h = aspect >= 1 ? span : span / aspect;+    if (w > state.vb0[2] && h > state.vb0[3]) { w = state.vb0[2]; h = state.vb0[3]; }+    state.vb = [cx - w / 2, cy - h / 2, w, h];+    state.svg.setAttribute("viewBox", state.vb.join(" "));+  }+  function xclear() { try { if (window.parent && window.parent !== window) window.parent.postMessage({ adomXprobe: true, clear: true }, "*"); } catch (e) {} }+  // Apply a cross-probe FROM the PCB view. If the referenced part lives on another+  // bundled sheet, switch to it first, then HIGHLIGHT ONLY + recenter — no info card+  // (the card shows only when the user clicks a part IN this app). No re-emit.+  function applyXprobe(ref) {+    if (!ref) return;+    if (!(state.meta.components || []).some((k) => k.reference === ref) && state.sheets) {+      for (const key in state.sheets) { const cs = state.sheets[key].meta && state.sheets[key].meta.components; if (cs && cs.some((k) => k.reference === ref)) { mountSheet(key); break; } }+    }+    state.pinned = ref; compHl(ref); centerOn(ref);+  }+  // deselect propagated from the sibling view → clear our highlight + card too+  function applyXclear() { state.pinned = null; clearSym(); hideCard(); }+  addEventListener("message", (e) => { const d = e.data; if (!d || !d.adomXprobe) return; if (d.clear) applyXclear(); else if (d.ref) applyXprobe(d.ref); });++  // ── component highlight: screen-blend teal over the symbol (turns the symbol+  // strokes teal, leaves the white sheet white — no box) + list sync ──────────+  function clearSym() {+    if (state.hlRef == null) return; // nothing highlighted — skip the DOM sweep+    state.hlRef = null;+    state.svg.querySelectorAll(".symhl").forEach((el) => el.classList.remove("symhl"));+    document.querySelectorAll("#complist .crow.sel").forEach((r) => r.classList.remove("sel"));+  }+  function compHl(ref) {+    if (state.hlRef === ref) return; // already highlighted — don't re-tag ~1500 nodes+    clearSym();+    state.hlRef = ref;+    // recolour the hovered symbol's real KiCad strokes teal (cheap paint, no filter)+    state.svg.querySelectorAll('.adom-sheet [data-cref="' + cssEsc(ref) + '"]').forEach((el) => el.classList.add("symhl"));+    document.querySelectorAll("#complist .crow").forEach((r) => r.classList.toggle("sel", r.getAttribute("data-ref") === ref));+  }+  function clearHl() { if (!state.pinned) clearSym(); }+  function wireHover(svg) {+    svg.addEventListener("mousemove", (e) => {+      state.mouse = e; // remembered so a pin lands where the card already is+      if (state.pinned) return; // keep the pinned card + highlight stable+      const c = e.target.closest(".adom-comp");+      if (c) {+        const ref = c.getAttribute("data-ref");+        // still on the SAME symbol: only trail the card. Don't re-highlight (a+        // ~1500-node re-tag) or rebuild the card / re-fire enrichment every frame.+        if (ref === state.hlRef) { placeCard($("#card"), e); return; }+        compHl(ref); showCard(ref, e); return;+      }+      clearHl(); hideCard();+    });+    svg.addEventListener("mouseleave", () => { if (!state.pinned) { clearHl(); hideCard(); } });+    svg.addEventListener("click", (e) => {+      // hierarchical-sheet box: descend into that child sheet+      const sh = e.target.closest(".adom-sheet-link");+      if (sh) { openSheet(sh.getAttribute("data-sheet")); return; }+      const c = e.target.closest(".adom-comp");+      // click empty space = deselect here AND in the sibling PCB view+      if (!c) { state.pinned = null; clearSym(); hideCard(); xclear(); return; }+      const ref = c.getAttribute("data-ref");+      state.pinned = state.pinned === ref ? null : ref;+      // pin: keep the card exactly where the hover card already sits, and expand+      // it to the full detail view so the links become reachable + cross-probe it.+      // Un-pinning (toggling off) deselects the PCB too.+      if (state.pinned) { compHl(ref); showCard(ref, e); xpost(ref); } else { clearSym(); hideCard(); xclear(); }+    });+  }++  // ── hierarchical sheet navigation ─────────────────────────────────────────+  // When every sheet is bundled (window.__SHEETS__, injected by `embed --sheet-dir`),+  // switching sheets is INSTANT: we just re-mount the pre-rendered svg/meta, no+  // reload, no fetch. The top-left is a dropdown of all sheets; sheet boxes are+  // also click-through. Without a bundle we fall back to ?sheet= URL navigation.+  function setQuery(key, val) {+    const u = new URL(window.location.href);+    if (val == null) u.searchParams.delete(key); else u.searchParams.set(key, val);+    return u.pathname + u.search;+  }+  function openSheet(file) {+    if (!file) return;+    if (state.sheets && state.sheets[file]) { mountSheet(file); return; } // instant+    window.location.href = setQuery("sheet", file); // fallback: server-rendered+  }+  // mount a bundled sheet in-place (key: filename, or "__root__")+  function mountSheet(key) {+    const s = state.sheets && state.sheets[key]; if (!s) return;+    state.curSheet = key === "__root__" ? null : key;+    mount(s.svg, s.meta);+    toast("Sheet: " + curSheetLabel(), "info");+  }+  // the sheet list is the ROOT's children (so you can jump anywhere from anywhere)+  function rootSubs() {+    const r = state.sheets && state.sheets.__root__;+    return (r && r.meta && r.meta.sub_sheets) || state.meta.sub_sheets || [];+  }+  function buildCrumb() {+    const el = document.getElementById("crumb"); if (!el) return;+    const subs = rootSubs();+    if (!subs.length) { el.style.display = "none"; return; }+    // a dropdown of every sheet (Root + children); selecting one switches instantly+    const cur = state.curSheet || "__root__";+    const opt = (v, label) => '<option value="' + escapeHtml(v) + '"' + (v === cur ? " selected" : "") + ">" + escapeHtml(label) + "</option>";+    const opts = [opt("__root__", "Root")].concat(subs.map((s) => opt(s.file, s.name || s.file.replace(/\.kicad_sch$/, ""))));+    el.innerHTML = '<span class="sheetlbl">Sheet</span><select id="sheetsel">' + opts.join("") + "</select>";+    el.style.display = "flex";+    // both the dropdown and the components panel live top-right; push the panel+    // below the dropdown so they don't overlap (the panel is hidden on small panes)+    const side = document.getElementById("side"); if (side) side.style.top = "52px";+    const sel = el.querySelector("#sheetsel");+    if (sel) sel.addEventListener("change", (e) => {+      const v = e.target.value;+      if (state.sheets && state.sheets[v]) mountSheet(v);+      else window.location.href = setQuery("sheet", v === "__root__" ? null : v);+    });+  }++  function comp(ref) { return (state.meta.components || []).find((k) => k.reference === ref); }+  // Abridged while merely hovering on a small/embedded screen (APM's board pane):+  // reference · MPN · stock, nothing else. Pinning always shows the full card.+  function isBrief(ref) { return state.pinned !== ref && innerWidth <= 620; }+  function showCard(ref, e) {+    const c = comp(ref); if (!c) return;+    const card = $("#card");+    const pinned = state.pinned === ref, brief = isBrief(ref);+    const rows = [];+    if (brief) {+      rows.push('<div class="ci-h"><span class="ci-ref">' + escapeHtml(ref) + "</span></div>");+      // real MPN arrives with enrichment; show the schematic value meanwhile+      rows.push('<div class="ci-mfr" id="ci-mpn">' + escapeHtml(c.value || "") + "</div>");+      rows.push('<div class="ci-enrich" id="ci-enrich">' + (c.lcsc || c.value ? '<span class="muted">stock…</span>' : "") + "</div>");+    } else {+      rows.push('<div class="ci-h"><span class="ci-ref">' + escapeHtml(ref) + '</span><span class="ci-val">' + escapeHtml(c.value || "") + "</span></div>");+      if (c.description) rows.push('<div class="ci-desc">' + escapeHtml(c.description) + "</div>");+      if (c.footprint) rows.push(row("footprint", c.footprint.split(":").pop()));+      if (c.lcsc) rows.push(row("lcsc", c.lcsc));+      rows.push('<div class="ci-enrich" id="ci-enrich">' + (c.lcsc || c.value ? '<span class="muted">loading stock · price…</span>' : "") + "</div>");+      if (c.datasheet && c.datasheet !== "~") rows.push('<a class="ci-ds" href="' + escapeHtml(c.datasheet) + '" target="_blank" rel="noopener">datasheet ↗</a>');+    }+    card.innerHTML = rows.join("");+    card.classList.toggle("brief", brief);+    card.style.display = "block";+    // clickable only when pinned, so hovering never eats the pointer+    card.classList.toggle("pinned", pinned);+    // follow the cursor while hovering; once pinned it stays put where it is —+    // but the pinned card is bigger than the brief one it replaced, so pull it+    // back inside the viewport if that growth pushed it off an edge.+    if (!pinned) placeCard(card, e || state.mouse); else clampCard(card);+    state.briefMode = brief;+    if (c.lcsc || c.value) enrich(c.value, c.lcsc);+  }+  // place near the cursor, flipping to the other side at the viewport edges+  function placeCard(card, e) {+    if (!e) { card.style.left = "12px"; card.style.top = "12px"; return; }+    const pad = 14, w = card.offsetWidth, h = card.offsetHeight;+    let x = e.clientX + pad, y = e.clientY + pad;+    if (x + w > innerWidth) x = e.clientX - w - pad;+    if (y + h > innerHeight) y = e.clientY - h - pad;+    card.style.left = Math.max(4, x) + "px";+    card.style.top = Math.max(4, y) + "px";+  }+  // keep an already-placed card fully inside the viewport+  function clampCard(card) {+    const w = card.offsetWidth, h = card.offsetHeight;+    const x = parseFloat(card.style.left) || 0, y = parseFloat(card.style.top) || 0;+    card.style.left = Math.max(4, Math.min(x, innerWidth - w - 4)) + "px";+    card.style.top = Math.max(4, Math.min(y, innerHeight - h - 4)) + "px";+  }+  function row(k, v) { return '<div class="ci-row"><span class="ci-k">' + k + '</span><span class="ci-v">' + escapeHtml(String(v)) + "</span></div>"; }+  function hideCard() { const c = $("#card"); if (c && !state.pinned) { c.style.display = "none"; c.classList.remove("pinned", "brief"); } }++  // ── enrichment (stock/price via LCSC PN, wiki page + popularity) ──────────+  function enrich(value, lcsc) {+    const key = (value || "") + "|" + (lcsc || "");+    const render = (d) => {+      const el = $("#ci-enrich"); if (!el || state.enrichKey !== key) return;+      // abridged card: the real MPN + stock, nothing else+      if (state.briefMode) {+        const m = $("#ci-mpn");+        if (m && d && d.mpn) m.textContent = d.mpn;+        if (!d || d.error || d.stock == null) { el.innerHTML = '<span class="muted">no stock data</span>'; return; }+        el.innerHTML = '<div class="pills"><span class="pill ' + (d.stock > 0 ? "ok" : "no") + '">' + (d.stock > 0 ? d.stock + " in stock" : "no stock") + "</span></div>";+        return;+      }+      if (!d || d.error) { el.innerHTML = '<span class="muted">no stock/price found</span>'; return; }+      const parts = [];+      if (d.stock != null) parts.push('<span class="pill ' + (d.stock > 0 ? "ok" : "no") + '">' + (d.stock > 0 ? d.stock + " in stock" : "no stock") + "</span>");+      if (d.price) parts.push('<span class="pill">' + escapeHtml(d.price) + "</span>");+      if (d.tier) parts.push('<span class="pill tier">' + escapeHtml(d.tier) + "</span>");+      if (d.popularity != null) parts.push('<span class="pill pop">★ ' + d.popularity + "</span>");+      let html = "";+      if (d.mpn) html += '<div class="ci-mfr">' + escapeHtml(d.mpn) + "</div>";+      if (d.mfr) html += '<div class="ci-mfr muted">' + escapeHtml(d.mfr) + "</div>";+      html += '<div class="pills">' + parts.join("") + "</div>";+      const links = [];+      if (d.jlc_url) links.push('<a class="ci-lnk" href="' + escapeHtml(d.jlc_url) + '" target="_blank" rel="noopener">JLCPCB ↗</a>');+      if (d.wiki_url) links.push('<a class="ci-lnk" href="' + escapeHtml(d.wiki_url) + '" target="_blank" rel="noopener">wiki page ↗</a>');+      if (links.length) html += '<div class="ci-links">' + links.join("") + "</div>";+      el.innerHTML = html || '<span class="muted">no data</span>';+    };+    state.enrichKey = key;+    if (state.enrichCache[key]) return render(state.enrichCache[key]);+    // NOTE: relative "enrich" resolves against whatever serves the page — our own+    // /enrich when running standalone, or the HOST app's (APM's+    // /board-view/<slug>/enrich) when embedded. So embeds get live stock too.+    if (typeof fetch !== "function") return render(null);+    const url = "enrich?mpn=" + encodeURIComponent(value || "") + (lcsc ? "&lcsc=" + encodeURIComponent(lcsc) : "");+    let tries = 0;+    const go = () => fetch(url).then((r) => r.json()).then((d) => {+      if (d && d.pending && tries++ < 25) { setTimeout(go, 1500); return; }+      state.enrichCache[key] = d; render(d);+    }).catch(() => render(null));+    go();+  }++  // ── pan / zoom ────────────────────────────────────────────────────────────+  // A schematic sheet is ~4500 nodes, so every viewBox write re-rasterizes a lot.+  // Coalesce writes to ONE per animation frame: a burst of wheel/drag events then+  // costs a single repaint per frame instead of 2-3, which is what makes panning+  // and zooming a dense sheet feel smooth.+  function wirePanZoom(svg) {+    let vbPending = false;+    const flushVB = () => {+      if (vbPending) return;+      vbPending = true;+      requestAnimationFrame(() => { vbPending = false; svg.setAttribute("viewBox", state.vb.join(" ")); });+    };+    svg.addEventListener("wheel", (e) => {+      e.preventDefault();+      const [x, y, w, h] = state.vb;+      const f = e.deltaY > 0 ? 1.12 : 0.893;+      const r = svg.getBoundingClientRect();+      const mx = x + ((e.clientX - r.left) / r.width) * w, my = y + ((e.clientY - r.top) / r.height) * h;+      const nw = Math.min(state.vb0[2] * 8, Math.max(state.vb0[2] / 200, w * f)), nh = nw * (h / w);+      state.vb = [mx - (mx - x) * (nw / w), my - (my - y) * (nh / h), nw, nh];+      flushVB();+    }, { passive: false });+    let drag = null;+    // cache the rect at grab time — it can't change mid-drag, so we avoid a forced+    // layout (getBoundingClientRect) on every single pan frame.+    svg.addEventListener("mousedown", (e) => {+      const r = svg.getBoundingClientRect();+      drag = { x: e.clientX, y: e.clientY, vb: state.vb.slice(), rw: r.width, rh: r.height };+    });+    addEventListener("mouseup", () => (drag = null));+    addEventListener("mousemove", (e) => {+      if (!drag) return;+      // preserveAspectRatio="…meet" scales the viewBox UNIFORMLY to fit the box, so+      // there is ONE viewBox-units-per-pixel factor for both axes: max(vbW/rw, vbH/rh)+      // (the larger ratio is the limiting one under "meet"). Using vbW/rw for x but+      // vbH/rh for y made horizontal and vertical drag move at different rates on any+      // non-matching aspect (i.e. every wide schematic).+      const upp = Math.max(drag.vb[2] / drag.rw, drag.vb[3] / drag.rh);+      state.vb = [drag.vb[0] - (e.clientX - drag.x) * upp, drag.vb[1] - (e.clientY - drag.y) * upp, drag.vb[2], drag.vb[3]];+      flushVB();+    });+  }+  function fit() { if (state.svg) { state.vb = state.vb0.slice(); state.svg.setAttribute("viewBox", state.vb.join(" ")); } }+  function fitToast() { fit(); toast("Fit to view", "info"); }++  // ── component list ────────────────────────────────────────────────────────+  function buildCompList() {+    const el = $("#complist"); if (!el) return;+    const cs = (state.meta.components || []).slice().sort((a, b) => a.reference.localeCompare(b.reference, undefined, { numeric: true }));+    el.innerHTML = cs.map((c) => '<div class="crow" data-ref="' + escapeHtml(c.reference) + '"><b>' + escapeHtml(c.reference) + "</b> " + escapeHtml(c.value || "") + "</div>").join("") || '<div class="muted">no components</div>';+    el.querySelectorAll(".crow").forEach((r) => {+      const ref = r.getAttribute("data-ref");+      r.addEventListener("mouseenter", () => { if (!state.pinned) compHl(ref); });+      r.addEventListener("mouseleave", () => { if (!state.pinned) clearHl(); });+      r.addEventListener("click", () => { state.pinned = state.pinned === ref ? null : ref; if (state.pinned) { compHl(ref); showCard(ref); } else { clearSym(); hideCard(); } });+    });+  }+  function setStat() {+    const n = state.meta.components ? state.meta.components.length : 0;+    const el = $("#stat"); if (el) el.textContent = n + " components";+    setSubject(curSheetLabel(), n + (n === 1 ? " component" : " components"));+  }++  // ── helpers ───────────────────────────────────────────────────────────────+  function escapeHtml(s) { return String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }+  function cssEsc(s) { return String(s).replace(/["\\]/g, "\\$&"); }++  window.AdomSch = { mount, fit, compHl, toast, runCmd };+  function boot() {+    $("#fitbtn") && $("#fitbtn").addEventListener("click", fitToast);+    $("#hdr-fit") && $("#hdr-fit").addEventListener("click", fitToast);+    state.sheets = window.__SHEETS__ || null; // pre-rendered bundle for instant nav+    if (window.__SCH__) { window.__EMBED__ = true; state.curSheet = null; mount(window.__SCH__.svg, window.__SCH__.meta); return; }+    // standalone live server: enable the AI channel (toasts + drive cmds), the+    // console ring buffer, and fill the header's app-info version.+    wireObservability();+    pollUi();+    fetch("version").then((r) => r.json()).then((v) => { const el = $("#ai-ver"); if (el && v && v.version) el.textContent = "v" + v.version; }).catch(() => {});+    fetch("state").then((r) => r.json()).then((s) => {+      if (s && s.svg) mount(s.svg, s.meta || {});+      else $("#svgbox").innerHTML = '<div class="empty">No schematic loaded. POST a .kicad_sch to /load.</div>';+    }).catch(() => { $("#svgbox").innerHTML = '<div class="empty">server unreachable</div>'; });+  }+  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot); else boot();+})();
uninstall.shadded+6
@@ -0,0 +1,6 @@+#!/bin/bash+# uninstall.sh for adom-schematic (app).+set -euo pipefail++rm -f "${HOME}/.local/bin/adom-schematic"+echo "Uninstalled adom-schematic"