Skip to main content

litz_editor/
lib.rs

1//! The editing model behind any Litz frontend.
2//!
3//! This crate owns the document — parts, wires and the undo history — and
4//! knows nothing about pixels, DOM or a particular UI toolkit. A browser
5//! canvas, a native window and a test can all drive the same operations.
6//!
7//! Every mutation goes through [`Editor::transact`]: the new circuit is built
8//! off to the side, validated, and only then committed. A refused edit leaves
9//! the document and its history untouched, which is what an undo stack needs
10//! to stay honest.
11//!
12//! Geometry is presentation only. [`route_wire`] produces an orthogonal path
13//! for drawing; nothing here feeds a simulation.
14
15#![forbid(unsafe_code)]
16
17use litz_diagram::{Circuit, Connection, Diagnostic, PartInstance, PinRef};
18use std::collections::BTreeMap;
19
20/// The grid a wire and a part snap to, in canvas units.
21pub const GRID: f64 = 20.0;
22
23/// Why an edit was refused.
24#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
25pub enum EditError {
26    #[error("part id {0:?} is already in use")]
27    DuplicateId(String),
28    #[error("part id is empty")]
29    EmptyId,
30    #[error("part {0:?} is not in the document")]
31    UnknownPart(String),
32    #[error("both ends of a wire are the same pin")]
33    SamePin,
34    #[error("that wire is already drawn")]
35    DuplicateWire,
36    #[error("wire {0} does not exist")]
37    NoSuchWire(usize),
38    #[error("{0}")]
39    Invalid(String),
40}
41
42/// A point on the canvas.
43#[derive(Debug, Clone, Copy, PartialEq)]
44pub struct Point {
45    pub x: f64,
46    pub y: f64,
47}
48
49impl Point {
50    pub fn new(x: f64, y: f64) -> Self {
51        Self { x, y }
52    }
53}
54
55/// Snap a coordinate to the nearest grid intersection.
56pub fn snap(value: f64) -> f64 {
57    (value / GRID).round() * GRID
58}
59
60/// An orthogonal path from `from` to `to`, snapped to the grid.
61///
62/// Two segments, horizontal first. A wire that already shares a row or column
63/// stays a single segment.
64pub fn route_wire(from: Point, to: Point) -> Vec<Point> {
65    let a = Point::new(snap(from.x), snap(from.y));
66    let b = Point::new(snap(to.x), snap(to.y));
67    if a.x == b.x || a.y == b.y {
68        return vec![a, b];
69    }
70    vec![a, Point::new(b.x, a.y), b]
71}
72
73/// One editable circuit plus its undo and redo history.
74#[derive(Debug, Clone)]
75pub struct Editor {
76    circuit: Circuit,
77    undo: Vec<Circuit>,
78    redo: Vec<Circuit>,
79    dirty: bool,
80}
81
82impl Editor {
83    /// Wrap an already-parsed circuit. The document starts clean and with an
84    /// empty history.
85    pub fn new(circuit: Circuit) -> Self {
86        Self {
87            circuit,
88            undo: Vec::new(),
89            redo: Vec::new(),
90            dirty: false,
91        }
92    }
93
94    /// An empty document.
95    pub fn blank() -> Self {
96        Self::new(Circuit {
97            version: 1,
98            author: None,
99            editor: None,
100            parts: Vec::new(),
101            connections: Vec::new(),
102            extra: BTreeMap::new(),
103        })
104    }
105
106    pub fn circuit(&self) -> &Circuit {
107        &self.circuit
108    }
109
110    /// Whether there are changes since the last [`Editor::mark_saved`].
111    pub fn is_dirty(&self) -> bool {
112        self.dirty
113    }
114
115    pub fn mark_saved(&mut self) {
116        self.dirty = false;
117    }
118
119    pub fn can_undo(&self) -> bool {
120        !self.undo.is_empty()
121    }
122
123    pub fn can_redo(&self) -> bool {
124        !self.redo.is_empty()
125    }
126
127    /// Apply `edit` to a copy of the circuit and commit it only if it returns
128    /// Ok. One call is one undo step.
129    pub fn transact<T>(
130        &mut self,
131        edit: impl FnOnce(&mut Circuit) -> Result<T, EditError>,
132    ) -> Result<T, EditError> {
133        let mut next = self.circuit.clone();
134        let value = edit(&mut next)?;
135        self.undo.push(std::mem::replace(&mut self.circuit, next));
136        self.redo.clear();
137        self.dirty = true;
138        Ok(value)
139    }
140
141    /// Undo the last committed edit. False when the history is empty.
142    pub fn undo(&mut self) -> bool {
143        let Some(previous) = self.undo.pop() else {
144            return false;
145        };
146        self.redo
147            .push(std::mem::replace(&mut self.circuit, previous));
148        self.dirty = true;
149        true
150    }
151
152    /// Re-apply the last undone edit. False when there is nothing to redo.
153    pub fn redo(&mut self) -> bool {
154        let Some(next) = self.redo.pop() else {
155            return false;
156        };
157        self.undo.push(std::mem::replace(&mut self.circuit, next));
158        self.dirty = true;
159        true
160    }
161
162    pub fn add_part(&mut self, part: PartInstance) -> Result<(), EditError> {
163        if part.id.trim().is_empty() {
164            return Err(EditError::EmptyId);
165        }
166        self.transact(|circuit| {
167            if circuit.parts.iter().any(|p| p.id == part.id) {
168                return Err(EditError::DuplicateId(part.id.clone()));
169            }
170            circuit.parts.push(part);
171            Ok(())
172        })
173    }
174
175    /// Remove a part and every wire attached to it. Returns the number of
176    /// wires removed as well.
177    pub fn remove_part(&mut self, id: &str) -> Result<usize, EditError> {
178        let id = id.to_string();
179        self.transact(|circuit| {
180            let before = circuit.parts.len();
181            circuit.parts.retain(|part| part.id != id);
182            if circuit.parts.len() == before {
183                return Err(EditError::UnknownPart(id.clone()));
184            }
185            let wires = circuit.connections.len();
186            circuit
187                .connections
188                .retain(|wire| wire.from.part != id && wire.to.part != id);
189            Ok(wires - circuit.connections.len())
190        })
191    }
192
193    /// Move a part to a canvas position, snapped to the grid.
194    pub fn move_part(&mut self, id: &str, left: f64, top: f64) -> Result<(), EditError> {
195        let id = id.to_string();
196        self.transact(|circuit| {
197            let part = circuit
198                .parts
199                .iter_mut()
200                .find(|p| p.id == id)
201                .ok_or(EditError::UnknownPart(id.clone()))?;
202            part.left = Some(snap(left));
203            part.top = Some(snap(top));
204            Ok(())
205        })
206    }
207
208    /// Set one attribute, creating it if needed.
209    pub fn set_attr(
210        &mut self,
211        id: &str,
212        key: impl Into<String>,
213        value: serde_json::Value,
214    ) -> Result<(), EditError> {
215        let id = id.to_string();
216        let key = key.into();
217        self.transact(|circuit| {
218            let part = circuit
219                .parts
220                .iter_mut()
221                .find(|p| p.id == id)
222                .ok_or(EditError::UnknownPart(id.clone()))?;
223            part.attrs.insert(key, value);
224            Ok(())
225        })
226    }
227
228    /// Draw a wire. Duplicate pins and duplicate wires are refused.
229    pub fn connect(
230        &mut self,
231        from: PinRef,
232        to: PinRef,
233        color: Option<String>,
234    ) -> Result<(), EditError> {
235        if from == to {
236            return Err(EditError::SamePin);
237        }
238        self.transact(|circuit| {
239            for id in [&from.part, &to.part] {
240                if !id.starts_with('$') && !circuit.parts.iter().any(|p| &p.id == id) {
241                    return Err(EditError::UnknownPart(id.clone()));
242                }
243            }
244            if circuit.connections.iter().any(|wire| {
245                (wire.from == from && wire.to == to) || (wire.from == to && wire.to == from)
246            }) {
247                return Err(EditError::DuplicateWire);
248            }
249            circuit.connections.push(Connection { from, to, color });
250            Ok(())
251        })
252    }
253
254    pub fn disconnect(&mut self, index: usize) -> Result<(), EditError> {
255        self.transact(|circuit| {
256            if index >= circuit.connections.len() {
257                return Err(EditError::NoSuchWire(index));
258            }
259            circuit.connections.remove(index);
260            Ok(())
261        })
262    }
263
264    /// Structural diagnostics. Electrical checks live in `litz-board`, which
265    /// owns the runtime and the catalog.
266    pub fn check(&self) -> Vec<Diagnostic> {
267        self.circuit.check_structure()
268    }
269
270    /// Validate against a catalog: unknown part types, pins that do not exist,
271    /// and connections the schema forbids.
272    pub fn validate(&self, registry: &litz_catalog::Registry) -> Vec<Diagnostic> {
273        self.circuit.validate(registry)
274    }
275
276    /// Serialize the document as `diagram.json`.
277    pub fn to_json(&self) -> Result<String, EditError> {
278        serde_json::to_string_pretty(&self.circuit).map_err(|e| EditError::Invalid(e.to_string()))
279    }
280
281    /// Parse a document from `diagram.json`.
282    pub fn from_json(text: &str) -> Result<Self, EditError> {
283        Circuit::from_json(text)
284            .map(Self::new)
285            .map_err(|e| EditError::Invalid(e.to_string()))
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use serde_json::json;
293
294    fn part(id: &str, kind: &str) -> PartInstance {
295        PartInstance::new(id, kind)
296    }
297
298    #[test]
299    fn adding_a_part_is_one_undo_step() {
300        let mut editor = Editor::blank();
301        editor.add_part(part("led1", "litz-led")).unwrap();
302        assert_eq!(editor.circuit().parts.len(), 1);
303        assert!(editor.is_dirty());
304        assert!(editor.undo());
305        assert!(editor.circuit().parts.is_empty());
306        assert!(editor.redo());
307        assert_eq!(editor.circuit().parts.len(), 1);
308    }
309
310    #[test]
311    fn a_refused_edit_leaves_no_history() {
312        let mut editor = Editor::blank();
313        editor.add_part(part("led1", "litz-led")).unwrap();
314        let before = editor.circuit().parts.len();
315        assert_eq!(
316            editor.add_part(part("led1", "litz-led")),
317            Err(EditError::DuplicateId("led1".into()))
318        );
319        assert_eq!(editor.circuit().parts.len(), before);
320        editor.undo();
321        assert!(
322            editor.circuit().parts.is_empty(),
323            "only the accepted add is undone"
324        );
325    }
326
327    #[test]
328    fn removing_a_part_takes_its_wires() {
329        let mut editor = Editor::blank();
330        editor
331            .add_part(part("esp", "board-esp32-c3-devkitm-1"))
332            .unwrap();
333        editor.add_part(part("led1", "litz-led")).unwrap();
334        editor
335            .connect(
336                PinRef::new("esp", "GPIO8"),
337                PinRef::new("led1", "A"),
338                Some("green".into()),
339            )
340            .unwrap();
341        assert_eq!(editor.remove_part("led1"), Ok(1));
342        assert!(editor.circuit().connections.is_empty());
343    }
344
345    #[test]
346    fn a_wire_between_one_pin_and_itself_is_refused() {
347        let mut editor = Editor::blank();
348        editor.add_part(part("led1", "litz-led")).unwrap();
349        let pin = PinRef::new("led1", "A");
350        assert_eq!(
351            editor.connect(pin.clone(), pin, None),
352            Err(EditError::SamePin)
353        );
354    }
355
356    #[test]
357    fn moving_a_part_snaps_to_the_grid() {
358        let mut editor = Editor::blank();
359        editor.add_part(part("led1", "litz-led")).unwrap();
360        editor.move_part("led1", 27.0, -13.0).unwrap();
361        let part = &editor.circuit().parts[0];
362        assert_eq!((part.left, part.top), (Some(20.0), Some(-20.0)));
363    }
364
365    #[test]
366    fn attributes_are_created_and_replaced() {
367        let mut editor = Editor::blank();
368        editor.add_part(part("r1", "litz-resistor")).unwrap();
369        editor.set_attr("r1", "value", json!("220")).unwrap();
370        editor.set_attr("r1", "value", json!("10k")).unwrap();
371        assert_eq!(editor.circuit().parts[0].attrs["value"], json!("10k"));
372    }
373
374    #[test]
375    fn a_wire_routes_orthogonally_on_the_grid() {
376        let path = route_wire(Point::new(3.0, 7.0), Point::new(46.0, 60.0));
377        assert_eq!(path.len(), 3);
378        assert_eq!(path[0], Point::new(0.0, 0.0));
379        assert_eq!(path[1], Point::new(40.0, 0.0));
380        assert_eq!(path[2], Point::new(40.0, 60.0));
381        for pair in path.windows(2) {
382            assert!(
383                pair[0].x == pair[1].x || pair[0].y == pair[1].y,
384                "not orthogonal"
385            );
386        }
387    }
388
389    #[test]
390    fn a_valid_circuit_validates_against_the_builtin_catalog() {
391        let editor = Editor::from_json(
392            r#"{
393              "parts": [
394                {"id": "esp", "type": "board-esp32-c3-devkitm-1", "attrs": {}},
395                {"id": "r1", "type": "litz-resistor", "attrs": {"value": "220"}},
396                {"id": "led1", "type": "litz-led", "attrs": {"color": "green"}}
397              ],
398              "connections": [
399                ["esp:GPIO8", "r1:1", "", []],
400                ["r1:2", "led1:A", "", []],
401                ["led1:C", "esp:GND.1", "", []]
402              ]
403            }"#,
404        )
405        .unwrap();
406        let diagnostics = editor.validate(&litz_catalog::Registry::builtin());
407        assert!(
408            diagnostics
409                .iter()
410                .all(|d| d.severity != litz_diagram::Severity::Error),
411            "{diagnostics:?}"
412        );
413    }
414
415    #[test]
416    fn an_unknown_part_is_an_error() {
417        let editor = Editor::from_json(
418            r#"{"parts":[{"id":"x","type":"litz-not-a-part","attrs":{}}],"connections":[]}"#,
419        )
420        .unwrap();
421        let diagnostics = editor.validate(&litz_catalog::Registry::builtin());
422        assert!(
423            diagnostics
424                .iter()
425                .any(|d| d.severity == litz_diagram::Severity::Error)
426        );
427    }
428
429    #[test]
430    fn save_and_open_round_trip() {
431        let mut editor = Editor::blank();
432        editor
433            .add_part(part("esp", "board-esp32-c3-devkitm-1"))
434            .unwrap();
435        editor.add_part(part("led1", "litz-led")).unwrap();
436        editor
437            .connect(PinRef::new("esp", "GPIO8"), PinRef::new("led1", "A"), None)
438            .unwrap();
439        let text = editor.to_json().unwrap();
440        let reopened = Editor::from_json(&text).unwrap();
441        assert_eq!(reopened.circuit().parts.len(), 2);
442        assert_eq!(reopened.circuit().connections, editor.circuit().connections);
443        assert!(!reopened.is_dirty());
444    }
445}