diff --git a/docs/AUTHORING-DEVELOPMENT.md b/docs/AUTHORING-DEVELOPMENT.md index 192a6cc..faa9d64 100644 --- a/docs/AUTHORING-DEVELOPMENT.md +++ b/docs/AUTHORING-DEVELOPMENT.md @@ -83,3 +83,15 @@ project and exact exported file hash. The KiCad exporter retains library Reference/Value positions and effects, transforms them with the placed component, and directs pin-attached net labels away from the symbol body. A rotation test covers all four right-angle orientations and preserves electrical anchors. Native revision-21 SVG inspection confirms the central TMF8829 artwork is no longer covered by its value. The Text layout controls and matching typed operations now support per-instance Reference/Value placement and existing-label orientation. Field coordinates are component-local millimetres, Y-up, rotated with the component; label angles are absolute sheet angles. Only right angles are accepted. These operations preserve electrical pin and label anchors, connections, net names and source library hashes, and survive persistence and undo. An omitted override keeps the source field placement or outward pin-label orientation. Overrides use visible 1.27 mm left-justified fields. The local preview uses the exported field positions and text angles, so accepted text edits are visible through SSE. Its browser font differs from KiCad's native stroke font; native rendering remains the visual reference. Toolbar height follows wrapping and expanded text controls so it does not cover the canvas. Automatic text collision detection, default-field reset and a complete text typography editor remain open. Native rendering is not electrical qualification. + + +### Exact footprint binding and portable project files + +`bind_footprint {key,footprint}` retains the original `.kicad_mod` text and its SHA-256 in the revisioned library. Every numbered footprint pad must correspond to a symbol pin; unnumbered mechanical pads are allowed. Repeated physical pads with the same number share that electrical pin. A mismatch rejects the entire batch. Library replacement retains and revalidates the existing footprint binding. + +The Library links UI uses the same operation through a file picker. `/state.author.footprintBindings` reports each bound source hash. `/export/project` returns a JSON map of relative text files, including the exact current schematic, `Adom.kicad_sym`, `Adom.pretty`, and local symbol/footprint tables. It refuses an unbound used component. Symbol and footprint nicknames are qualified consistently without changing original source hashes or pin geometry. No user-global library installation is needed. + +Model paths in the footprint exports use `${KIPRJMOD}/models//` with preserved transforms. The response lists `modelCopyRequests`; the caller must copy the matching original model bytes and validate their provenance. `footprintsWithoutModels` remains an explicit missing-model list. This response is a text-file transport, not a ZIP or a completed 3D package. File copying, native library resolution, physical model seating, component dimensions and electrical correctness remain separate checks. + + +`set_label_net {endpoint,net}` explicitly changes an existing pin-attached label's electrical net while preserving its anchor and text angle. Unlike `style_label`, this is an electrical edit: merging with an existing named net is intentional and requires native ERC/connectivity review. The Text layout panel exposes a separate Change net control. Undo restores the prior assignment. Empty/control-character names are rejected. diff --git a/src/author.rs b/src/author.rs index 466e4fb..433027e 100644 --- a/src/author.rs +++ b/src/author.rs @@ -130,6 +130,13 @@ fn id(doc: &str, key: &str) -> String { pub struct Library { pub symbol: String, pub source_sha256: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub footprint: Option, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Footprint { + pub source: String, + pub source_sha256: String, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Component { @@ -200,6 +207,10 @@ pub enum Operation { key: String, symbol: String, }, + BindFootprint { + key: String, + footprint: String, + }, Place { component: Component, }, @@ -226,6 +237,10 @@ pub enum Operation { endpoint: PinRef, angle: u16, }, + SetLabelNet { + endpoint: PinRef, + net: String, + }, Undo, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -277,6 +292,72 @@ fn library_root(s: &str) -> Result { } Ok(a) } +fn asset_key(key: &str) -> Result<()> { + if key.is_empty() + || key == "." + || key == ".." + || !key + .chars() + .all(|c| c.is_ascii_alphanumeric() || "_- .".contains(c)) + { + bail!("invalid_asset_key: use a simple unqualified library name without path separators") + } + Ok(()) +} +fn footprint_root(source: &str, symbol: &str) -> Result { + let root = parse(source)?; + if root.tag() != Some("footprint") { + bail!("Expected a KiCad footprint") + } + let pads: BTreeSet = root + .list() + .iter() + .filter(|p| p.tag() == Some("pad")) + .map(|p| p.arg(1).map(str::to_string)) + .collect::>()?; + let pins: BTreeSet = pins(symbol)?.into_iter().map(|p| p.number).collect(); + let electrical_pads: BTreeSet = pads.into_iter().filter(|p| !p.is_empty()).collect(); + if electrical_pads != pins { + bail!( + "pin_pad_mismatch: symbol pins {pins:?} differ from footprint pads {electrical_pads:?}" + ) + } + Ok(root) +} +/// Export the same renamed definition both inside the sheet and in Adom.kicad_sym. +fn exported_library(key: &str, lib: &Library, embedded: bool) -> Result { + let mut root = library_root(&lib.symbol)?; + let source_name = root.arg(1)?.to_string(); + if let S::List(items) = &mut root { + items[1] = S::Text(if embedded { + format!("Adom:{key}") + } else { + key.into() + }); + for unit in items.iter_mut().filter(|p| p.tag() == Some("symbol")) { + let suffix = unit + .arg(1)? + .strip_prefix(&format!("{source_name}_")) + .context("Library unit does not match its root symbol name")? + .to_string(); + if let S::List(parts) = unit { + parts[1] = S::Text(format!("{key}_{suffix}")); + } + } + if lib.footprint.is_some() { + let value = S::Text(format!("Adom:{key}")); + if let Some(S::List(property)) = items + .iter_mut() + .find(|p| p.tag() == Some("property") && p.arg(1).ok() == Some("Footprint")) + { + property[2] = value; + } else { + items.push(parse(&format!("(property \"Footprint\" {} (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes)))", q(&format!("Adom:{key}"))))?); + } + } + } + Ok(root) +} fn pins(s: &str) -> Result> { let a = library_root(s)?; let mut out = vec![]; @@ -400,9 +481,7 @@ impl Document { fn apply(&mut self, op: &Operation) -> Result<()> { match op { Operation::AddLibrary { key, symbol } => { - if key.is_empty() || key.contains(':') { - bail!("Use a nonempty unqualified library key") - } + asset_key(key)?; if self.libraries.contains_key(key) { bail!("Library already registered; in-use library replacement requires an explicit migration") } @@ -412,6 +491,7 @@ impl Document { Library { symbol: symbol.clone(), source_sha256: digest(symbol), + footprint: None, }, ); } @@ -431,9 +511,19 @@ impl Document { Library { symbol: symbol.clone(), source_sha256: digest(symbol), + footprint: old.footprint.clone(), }, ); } + Operation::BindFootprint { key, footprint } => { + asset_key(key)?; + let lib = self.libraries.get_mut(key).context("Unknown library")?; + footprint_root(footprint, &lib.symbol)?; + lib.footprint = Some(Footprint { + source: footprint.clone(), + source_sha256: digest(footprint), + }); + } Operation::Place { component: c } => { if c.reference.is_empty() || !c @@ -520,6 +610,16 @@ impl Document { .context("Unknown label endpoint; create its net label first")? .angle = Some(*angle); } + Operation::SetLabelNet { endpoint, net } => { + if net.trim().is_empty() || net.len() > 128 || net.chars().any(char::is_control) { + bail!("Use a nonempty printable net name of at most 128 bytes") + } + self.labels + .iter_mut() + .find(|l| &l.endpoint == endpoint) + .context("Unknown label endpoint; create its label first")? + .net = net.clone(); + } Operation::Undo => bail!("Undo must be the sole operation in a transaction"), }; Ok(()) @@ -556,6 +656,15 @@ impl Document { Ok(out) } fn validate(&self) -> Result<()> { + for (key, lib) in &self.libraries { + asset_key(key)?; + if let Some(fp) = &lib.footprint { + if digest(&fp.source) != fp.source_sha256 { + bail!("Footprint source hash mismatch") + } + footprint_root(&fp.source, &lib.symbol)?; + } + } for c in self.components.values() { coords(c.x, c.y, c.rotation)?; for (name, f) in &c.fields { @@ -671,26 +780,70 @@ impl Document { } Ok(issues) } + /// Portable text files plus explicit model-copy requests; never claims models loaded. + pub fn export_project(&self) -> Result { + self.validate()?; + let used: BTreeSet<_> = self + .components + .values() + .map(|c| c.library.as_str()) + .collect(); + let mut files = BTreeMap::::new(); + let mut models = Vec::new(); + let mut no_model = Vec::new(); + let mut sources = BTreeMap::new(); + let mut symbols = + String::from("(kicad_symbol_lib (version 20231120) (generator \"adom-schematic\")\n"); + for key in used { + let lib = &self.libraries[key]; + let fp = lib + .footprint + .as_ref() + .with_context(|| format!("footprint_unbound: bind {key} before project export"))?; + symbols.push_str(&exported_library(key, lib, false)?.emit()); + symbols.push('\n'); + let mut footprint = footprint_root(&fp.source, &lib.symbol)?; + let mut count = 0; + if let S::List(items) = &mut footprint { + items[1] = S::Text(key.into()); + for model in items.iter_mut().filter(|m| m.tag() == Some("model")) { + let original = model.arg(1)?.to_string(); + let filename = original + .rsplit(['/', '\\']) + .next() + .context("Empty model reference")?; + asset_key(filename)?; + let path = format!("models/{key}/{filename}"); + models.push(serde_json::json!({"libraryKey":key,"sourceReference":original,"exportPath":path})); + if let S::List(m) = model { + m[1] = S::Text(format!("${{KIPRJMOD}}/{path}")); + } + count += 1; + } + } + if count == 0 { + no_model.push(key); + } + files.insert(format!("Adom.pretty/{key}.kicad_mod"), footprint.emit()); + sources.insert(key, serde_json::json!({"symbolSha256":lib.source_sha256,"footprintSha256":fp.source_sha256})); + } + symbols.push_str(")\n"); + files.insert("Adom.kicad_sym".into(), symbols); + files.insert("schematic.kicad_sch".into(), self.export_kicad()?); + files.insert("schematic.kicad_pro".into(), "{}\n".into()); + files.insert("sym-lib-table".into(), "(sym_lib_table (version 7) (lib (name \"Adom\") (type \"KiCad\") (uri \"${KIPRJMOD}/Adom.kicad_sym\") (options \"\") (descr \"Project exact components\")))\n".into()); + files.insert("fp-lib-table".into(), "(fp_lib_table (version 7) (lib (name \"Adom\") (type \"KiCad\") (uri \"${KIPRJMOD}/Adom.pretty\") (options \"\") (descr \"Project exact footprints\")))\n".into()); + Ok( + serde_json::json!({"files":files,"modelCopyRequests":models,"footprintsWithoutModels":no_model,"sourceHashes":sources, + "hints":["Write files preserving relative paths, then copy the exact provenanced model bytes for every modelCopyRequest.","No model files are embedded in this text response. Report missing models separately; never substitute generic geometry.","Pin-number coverage is checked; dimensions, model seating, electrical correctness and native ERC require separate validation."]}), + ) + } pub fn export_kicad(&self) -> Result { self.validate()?; let root = id(&self.id, "sheet"); let mut out=format!("(kicad_sch (version 20250114) (generator \"adom-schematic\") (uuid {root}) (paper \"A4\")\n(title_block (title {}))\n(lib_symbols\n",q(&self.name)); for (key, lib) in &self.libraries { - let mut a = library_root(&lib.symbol)?; - let source_name = a.arg(1)?.to_string(); - if let S::List(v) = &mut a { - v[1] = S::Text(format!("Adom:{key}")); - for unit in v.iter_mut().filter(|x| x.tag() == Some("symbol")) { - let suffix = unit - .arg(1)? - .strip_prefix(&format!("{source_name}_")) - .context("Library unit does not match its root symbol name")? - .to_string(); - if let S::List(u) = unit { - u[1] = S::Text(format!("{key}_{suffix}")); - } - } - } + let a = exported_library(key, lib, true)?; out += &a.emit(); out += '\n'.to_string().as_str(); } @@ -698,7 +851,7 @@ impl Document { for c in self.components.values() { let sid = id(&self.id, &format!("component:{}", c.reference)); out+=&format!("(symbol (lib_id {}) (at {} {} {}) (unit 1) (in_bom yes) (on_board yes) (dnp no) (uuid {sid})\n",q(&format!("Adom:{}",c.library)),c.x,c.y,c.rotation); - let lib = library_root(&self.libraries[&c.library].symbol)?; + let lib = exported_library(&c.library, &self.libraries[&c.library], false)?; // Field locations are part of the component library. Putting every // value at the instance origin covers chip artwork and pin names. for (key, value, fallback_y) in [ @@ -922,6 +1075,171 @@ mod tests { assert_eq!(p.document.libraries["cap"].symbol, CAP); } #[test] + fn label_net_edit_preserves_geometry_and_undo() { + let p = placed(); + let endpoint = PinRef { + reference: "C1".into(), + pin: "1".into(), + }; + let p = p + .stage(&tx( + &p, + "old-net", + vec![Operation::Label { + label: Label { + endpoint: endpoint.clone(), + net: "OLD_RAIL".into(), + angle: Some(180), + }, + }], + )) + .unwrap(); + let q = p + .stage(&tx( + &p, + "new-net", + vec![Operation::SetLabelNet { + endpoint: endpoint.clone(), + net: "SUPPLY".into(), + }], + )) + .unwrap(); + assert_eq!( + q.document.pin_inventory().unwrap(), + p.document.pin_inventory().unwrap() + ); + assert_eq!(q.document.labels[0].angle, Some(180)); + assert_eq!(q.document.labels[0].net, "SUPPLY"); + assert!(!q.document.export_kicad().unwrap().contains("OLD_RAIL")); + assert!(q + .stage(&tx( + &q, + "empty", + vec![Operation::SetLabelNet { + endpoint, + net: "\n".into() + }] + )) + .is_err()); + let undone = q.stage(&tx(&q, "undo-net", vec![Operation::Undo])).unwrap(); + assert_eq!( + undone.document.export_kicad().unwrap(), + p.document.export_kicad().unwrap() + ); + } + #[test] + fn portable_project_links_exact_libraries_and_rejects_mismatched_pads() { + let p = placed(); + let footprint = r#"(footprint "VendorCap" (version 20241229) (layer "F.Cu") + (pad "1" smd rect (at -1 0) (size 1 1) (layers "F.Cu" "F.Paste" "F.Mask")) + (pad "2" smd rect (at 1 0) (size 1 1) (layers "F.Cu" "F.Paste" "F.Mask")) + (model "vendor.step" (offset (xyz 0.1 0.2 0.3)) (scale (xyz 1 1 1)) (rotate (xyz 0 0 90))))"#; + assert!(p + .document + .export_project() + .unwrap_err() + .to_string() + .contains("footprint_unbound")); + let q = p + .stage(&tx( + &p, + "bind", + vec![Operation::BindFootprint { + key: "cap".into(), + footprint: footprint.into(), + }], + )) + .unwrap(); + assert_eq!( + q.document.pin_inventory().unwrap(), + p.document.pin_inventory().unwrap() + ); + assert_eq!( + q.document.libraries["cap"].source_sha256, + p.document.libraries["cap"].source_sha256 + ); + let bundle = q.document.export_project().unwrap(); + let sch = parse(bundle["files"]["schematic.kicad_sch"].as_str().unwrap()).unwrap(); + let mut embedded = sch + .child("lib_symbols") + .unwrap() + .list() + .iter() + .find(|s| s.tag() == Some("symbol")) + .unwrap() + .clone(); + if let S::List(items) = &mut embedded { + items[1] = S::Text("cap".into()); + } + let external = library_root(bundle["files"]["Adom.kicad_sym"].as_str().unwrap()).unwrap(); + assert_eq!(embedded, external); + assert!(external + .emit() + .contains("(property \"Footprint\" \"Adom:cap\"")); + let source_fp = parse(footprint).unwrap(); + let export_fp = parse( + bundle["files"]["Adom.pretty/cap.kicad_mod"] + .as_str() + .unwrap(), + ) + .unwrap(); + let pads = |s: &S| { + s.list() + .iter() + .filter(|p| p.tag() == Some("pad")) + .cloned() + .collect::>() + }; + assert_eq!(pads(&source_fp), pads(&export_fp)); + assert_eq!( + bundle["modelCopyRequests"][0]["exportPath"], + "models/cap/vendor.step" + ); + assert!(export_fp.emit().contains("(offset (xyz 0.1 0.2 0.3))")); + assert!(export_fp + .emit() + .contains("${KIPRJMOD}/models/cap/vendor.step")); + let bad = footprint.replace("(pad \"2\"", "(pad \"3\""); + assert!(q + .stage(&tx( + &q, + "bad-footprint", + vec![Operation::BindFootprint { + key: "cap".into(), + footprint: bad + }] + )) + .is_err()); + assert_eq!( + q.document.libraries["cap"] + .footprint + .as_ref() + .unwrap() + .source, + footprint + ); + let folder = std::env::temp_dir().join(format!("adom-bundle-{}", Uuid::new_v4())); + q.persist(&folder).unwrap(); + assert_eq!( + Project::restore(&folder) + .unwrap() + .document + .export_project() + .unwrap(), + bundle + ); + let undone = q + .stage(&tx(&q, "undo-binding", vec![Operation::Undo])) + .unwrap(); + assert_eq!( + undone.document.export_kicad().unwrap(), + p.document.export_kicad().unwrap() + ); + std::fs::remove_dir_all(folder).unwrap(); + assert!(asset_key("../escape").is_err()); + assert!(asset_key("..\\escape").is_err()); + } + #[test] fn text_layout_preserves_electrical_anchors_and_survives_restore() { let p = placed(); let endpoint = PinRef { @@ -973,7 +1291,9 @@ mod tests { assert!(preview.contains(">VDD")); let crop = crate::sch_parse::parse(&export).content_bbox; assert!(crop.0 <= 50.0 && crop.0 + crop.2 > 55.08); - let left_label = export.replace("(justify left bottom)", "(justify right bottom)").replace("\"VDD\"", "\"A_LONG_NET_LABEL\""); + let left_label = export + .replace("(justify left bottom)", "(justify right bottom)") + .replace("\"VDD\"", "\"A_LONG_NET_LABEL\""); assert!(crate::sch_parse::parse(&left_label).content_bbox.0 < 35.0); let native = parse(&export).unwrap(); diff --git a/src/author_server.rs b/src/author_server.rs index 5ef6b78..4b30d32 100644 --- a/src/author_server.rs +++ b/src/author_server.rs @@ -37,7 +37,7 @@ fn snapshot(p: &Project, owner: &str) -> Result { inner ); Ok( - json!({"name":p.document.name,"svg":svg,"meta":serde_json::from_str::(&crate::kicad_sch::meta_json(&sch)?)?,"author":{"revision":p.revision,"documentId":p.document.id,"aiThread":owner,"libraries":p.document.libraries.keys().collect::>(),"components":p.document.components,"pins":p.document.pin_inventory()?,"contactIssues":p.document.contact_issues()?,"connections":p.document.connections,"labels":p.document.labels,"status":"Development authoring slice; circuit/ERC and native parity pending","hints":["Use expectedRevision and operationId for every edit; read state on conflicts.","Endpoints are stable reference/pin identities; moving a component updates connected wire endpoints.","Local Rust preview is not a native KiCad render or ERC result.","Inspect contactIssues for unintended pin or wire contacts. Body clearance and native netlist equivalence remain separate checks."]}}), + json!({"name":p.document.name,"svg":svg,"meta":serde_json::from_str::(&crate::kicad_sch::meta_json(&sch)?)?,"author":{"revision":p.revision,"documentId":p.document.id,"aiThread":owner,"libraries":p.document.libraries.keys().collect::>(),"footprintBindings":p.document.libraries.iter().filter_map(|(k,l)|l.footprint.as_ref().map(|f|(k.clone(),f.source_sha256.clone()))).collect::>(),"components":p.document.components,"pins":p.document.pin_inventory()?,"contactIssues":p.document.contact_issues()?,"connections":p.document.connections,"labels":p.document.labels,"status":"Development authoring slice; circuit/ERC and native parity pending","hints":["Use expectedRevision and operationId for every edit; read state on conflicts.","Endpoints are stable reference/pin identities; moving a component updates connected wire endpoints.","Local Rust preview is not a native KiCad render or ERC result.","Inspect contactIssues for unintended pin or wire contacts. Body clearance and native netlist equivalence remain separate checks."]}}), ) } fn error(e: impl std::fmt::Display) -> Value { @@ -209,6 +209,15 @@ pub fn run(folder: PathBuf, name: String, owner: String, port: u16, ttl_hours: f )), ); } + "/export/project" => match p.document.export_project() { + Ok(mut result) => { + result["ok"] = json!(true); + result["revision"] = json!(p.revision); + result["documentId"] = json!(p.document.id); + send(req, 200, result); + } + Err(e) => send(req, 409, error(e)), + }, _ => send(req, 404, error("unknown_endpoint")), }; continue; diff --git a/src/author_ui.js b/src/author_ui.js index c6334e3..5ca5131 100644 --- a/src/author_ui.js +++ b/src/author_ui.js @@ -5,17 +5,19 @@ body.author #svgbox{top:var(--author-canvas-top,152px)!important}body.author #side{display:none!important}#authorBar{position:absolute;top:44px;left:0;right:0;min-height:92px;z-index:10;padding:6px 12px;background:var(--panel,#15202b);border-bottom:1px solid var(--edge,#39434d);font:12px sans-serif;color:var(--ink,#eee)} #authorBar .row{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin:4px 0}#authorBar input,#authorBar select,#authorBar button{font:inherit;background:var(--bg,#18232e);color:inherit;border:1px solid var(--edge,#40505d);border-radius:4px;padding:4px}#authorBar input[type=number]{width:48px}#authorBar .ref{width:44px}#authorStatus{color:var(--muted,#abb7c2)}#authorBar a{color:var(--accent,#73caca)} `;document.head.append(style);document.body.classList.add('author'); - const bar=document.createElement('section');bar.id='authorBar';bar.innerHTML=`
Development circuit • not releasedKiCad file
Text layout
Text only; electrical anchors stay fixed.
`;document.body.append(bar);new ResizeObserver(()=>document.body.style.setProperty('--author-canvas-top',`${44+bar.getBoundingClientRect().height}px`)).observe(bar); + const bar=document.createElement('section');bar.id='authorBar';bar.innerHTML=`
Development circuit • not releasedKiCad file
Library links
Project files JSON
Fields and net labels
Change net edits electrical connectivity. Field placement and angles keep nets unchanged.
`;document.body.append(bar);new ResizeObserver(()=>document.body.style.setProperty('--author-canvas-top',`${44+bar.getBoundingClientRect().height}px`)).observe(bar); const $=s=>document.getElementById(s);function options(el,rows){const old=el.value;el.replaceChildren(...rows.map(([v,t])=>{const o=document.createElement('option');o.value=v;o.textContent=t;return o}));if(rows.some(([v])=>v===old))el.value=old;} - function update(s){if(!s.author)return;latest=s.author;window.AdomAuthorSnapshot=s;window.AdomAuthorState=latest;window.AdomSch.mount(s.svg,s.meta);$('authorRevision').textContent=`${s.name} · revision ${latest.revision}`;options($('authorLib'),latest.libraries.map(k=>[k,k]));const pins=latest.pins.map(p=>[JSON.stringify(p.endpoint),`${p.endpoint.reference}.${p.endpoint.pin}`]);options($('authorFrom'),pins);options($('authorTo'),pins);options($('authorFieldRef'),Object.keys(latest.components).map(r=>[r,r]));options($('authorLabelPin'),latest.labels.map(l=>[JSON.stringify(l.endpoint),`${l.endpoint.reference}.${l.endpoint.pin}: ${l.net}`]));requestAnimationFrame(()=>requestAnimationFrame(()=>fetch('author/ack',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision:latest.revision,componentCount:latest.pins.length?Object.keys(latest.components).length:0,paintedAt:new Date().toISOString()})})));} + function update(s){if(!s.author)return;latest=s.author;window.AdomAuthorSnapshot=s;window.AdomAuthorState=latest;window.AdomSch.mount(s.svg,s.meta);$('authorRevision').textContent=`${s.name} · revision ${latest.revision}`;options($('authorLib'),latest.libraries.map(k=>[k,k]));options($('authorBindKey'),latest.libraries.map(k=>[k,k]));$('authorLinkStatus').textContent=`${Object.keys(latest.footprintBindings||{}).length}/${latest.libraries.length} footprints linked`;const pins=latest.pins.map(p=>[JSON.stringify(p.endpoint),`${p.endpoint.reference}.${p.endpoint.pin}`]);options($('authorFrom'),pins);options($('authorTo'),pins);options($('authorFieldRef'),Object.keys(latest.components).map(r=>[r,r]));options($('authorLabelPin'),latest.labels.map(l=>[JSON.stringify(l.endpoint),`${l.endpoint.reference}.${l.endpoint.pin}: ${l.net}`]));requestAnimationFrame(()=>requestAnimationFrame(()=>fetch('author/ack',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision:latest.revision,componentCount:latest.pins.length?Object.keys(latest.components).length:0,paintedAt:new Date().toISOString()})})));} async function transact(operations){const r=await fetch('author/transaction',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({aiThread:'Schematic UI',expectedRevision:latest.revision,operationId:crypto.randomUUID(),operations})});const s=await r.json();if(!s.ok){window.AdomSch.toast(s.error,'error');return}window.AdomSch.toast(`Saved revision ${s.revision}`,'success');} $('authorPlace').onclick=()=>transact([{op:'place',component:{reference:$('authorRef').value,library:$('authorLib').value,value:$('authorLib').value,x:Number($('authorX').value),y:Number($('authorY').value),rotation:0}}]); $('authorConnect').onclick=()=>{if(!$('authorFrom').value||!$('authorTo').value)return;transact([{op:'connect',connection:{id:crypto.randomUUID(),from:JSON.parse($('authorFrom').value),to:JSON.parse($('authorTo').value)}}]);}; + $('authorBind').onclick=async()=>{const file=$('authorBindFile').files[0];if(!file){window.AdomSch.toast('Choose the exact component footprint file','error');return;}await transact([{op:'bind_footprint',key:$('authorBindKey').value,footprint:await file.text()}]);}; $('authorFieldApply').onclick=()=>transact([{op:'place_field',reference:$('authorFieldRef').value,field:$('authorFieldName').value,x:Number($('authorFieldX').value),y:Number($('authorFieldY').value),rotation:Number($('authorFieldAngle').value)}]); $('authorLabelApply').onclick=()=>{if($('authorLabelPin').value)transact([{op:'style_label',endpoint:JSON.parse($('authorLabelPin').value),angle:Number($('authorLabelAngle').value)}]);}; + $('authorNetApply').onclick=()=>{if($('authorLabelPin').value)transact([{op:'set_label_net',endpoint:JSON.parse($('authorLabelPin').value),net:$('authorLabelNet').value}]);}; function fieldSelection(){const f=latest.components[$('authorFieldRef').value]?.fields?.[$('authorFieldName').value];if(f){$('authorFieldX').value=f.x;$('authorFieldY').value=f.y;$('authorFieldAngle').value=f.rotation;}} $('authorFieldRef').onchange=fieldSelection;$('authorFieldName').onchange=fieldSelection; - $('authorLabelPin').onchange=()=>{const l=latest.labels.find(l=>JSON.stringify(l.endpoint)===$('authorLabelPin').value);if(l?.angle!==undefined)$('authorLabelAngle').value=l.angle;}; + $('authorLabelPin').onchange=()=>{const l=latest.labels.find(l=>JSON.stringify(l.endpoint)===$('authorLabelPin').value);if(l){$('authorLabelNet').value=l.net;if(l.angle!==undefined)$('authorLabelAngle').value=l.angle;}}; $('authorNative').onclick=async()=>{const r=await fetch('author/native');const v=await r.json();if(!v.ok){window.AdomSch.toast(v.error,'error');return}window.AdomSch.mount(v.svg,v.meta);$('authorStatus').textContent=`KiCad ${v.report.kicadVersion} service render • revision ${v.report.revision} • ${v.report.violationCount} ERC findings`;}; $('authorLocal').onclick=()=>{update({name:initial.name,author:latest,...window.AdomAuthorSnapshot});$('authorStatus').textContent='Live Rust preview • native checks separate';}; $('authorUndo').onclick=()=>transact([{op:'undo'}]);update(initial);const events=new EventSource('events');events.addEventListener('state',e=>update(JSON.parse(e.data)));events.onerror=()=>{$('authorStatus').textContent='Reconnecting… saved document retained';};events.onopen=()=>{$('authorStatus').textContent='Live • development circuit • ERC pending';};