Skip to main content

xpict_core/doc/
mod.rs

1//! Declarative document — one [`render`] entry for every spec.
2//!
3//! Wire types live in [`spec`] (opts cascade + DepictSpec collocated).
4//! Product path: CoordGen layout, mol-spec paint (chem + annotations +
5//! caption), then pack cells (reaction schemes compose). Annotations are
6//! fields on [`MolNode`], not a parallel paint API.
7
8mod caption;
9mod chrome;
10mod chrome_paint;
11mod clash_grid;
12mod compose;
13mod depict_doc;
14mod edge_resolve;
15mod fit;
16pub(crate) mod layout_constraints;
17mod layout_items;
18mod scheme_layout;
19mod spec;
20mod text_paint;
21
22pub use chrome::{
23    annotations_from_overlay, canonicalize_overlay, overlay_from_annotations, overlay_from_mol,
24    Annotation, AtomLabelDetailed, AtomLabelSpec, AtomNumberBy, AtomNumberPolicy, AtomNumberSpec,
25    CalloutField, CalloutSpec, CircleField, CircleSpec, FillSpec, LabelRole, MolOverlayFields,
26    MolText, MolTextSpec, RegionField, RegionSpec, RegionStyle, RegionTextPlace, StrokeSpec,
27    Z_ATOMS, Z_ATOM_LABEL, Z_BACKGROUND, Z_BONDS, Z_CALLOUT, Z_CIRCLE, Z_HALO, Z_NAME, Z_REGION,
28    Z_SHADE,
29};
30pub use compose::compose_scheme;
31pub use depict_doc::{depict, render, Rendered as DepictRendered, SvgAtom, SvgBond};
32pub use edge_resolve::{process_edge_plan, process_edge_plan_with_frames};
33pub use fit::{fit_scene, resolve_viewport_margin, VIEWPORT_MARGIN_DEFAULT};
34pub use layout_constraints::{
35    atom_number_kit, bezier_path_from_proxy, callout_kit, caption_kit, edge_signed_distance,
36    energy, hard_g, hull_proxy, install_chem, install_chem_under, max_hard_violation,
37    push_clear_leaves, refine_atom_number, refine_callout, refine_caption, refine_region_text,
38    region_text_kit, solve, suggest_route_points, Constraint, HardConstraint, LayoutWorld,
39    ObjectType, Shape, SolveOpts, SolveResult,
40};
41pub use spec::*;
42
43use std::collections::HashMap;
44
45use crate::cxsmiles::{apply_cx_by_index, cx_source};
46use crate::depict::depict_chem;
47use crate::edge::{
48    AlignOpts, CoordGenMoleculeResult, EdgePlan, EdgeResult, EdgeTask, EdgeTaskResult, MolTemplate,
49};
50use crate::scene::{MoleculeIn, Scene};
51
52/// Assign stable unique ids (`user id` or `m_<i>`) in document order.
53pub fn assign_mol_ids(mols: &[MolNode]) -> Result<Vec<String>, String> {
54    let mut used = std::collections::HashSet::new();
55    let mut out = Vec::with_capacity(mols.len());
56    for (i, m) in mols.iter().enumerate() {
57        let id = match m.id.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
58            Some(s) => s.to_string(),
59            None => format!("m_{i}"),
60        };
61        if !used.insert(id.clone()) {
62            return Err(format!("duplicate mol id {id}"));
63        }
64        out.push(id);
65    }
66    Ok(out)
67}
68
69/// Ensure edge endpoints and label refs resolve to the right node kinds.
70pub fn validate_edges(spec: &DepictSpec) -> Result<(), String> {
71    if let DepictSpec::Grid { children, .. } = spec {
72        for (i, row) in children.iter().enumerate() {
73            validate_edges(row).map_err(|e| format!("grid children[{i}]: {e}"))?;
74        }
75        assign_mol_ids(&spec.mols())?;
76        return Ok(());
77    }
78
79    // Groups must not contain edge children.
80    if matches!(spec, DepictSpec::Group { .. }) {
81        for (i, n) in spec.nodes().iter().enumerate() {
82            if n.as_edge().is_some() {
83                return Err(format!("group children[{i}] cannot be an edge"));
84            }
85        }
86    }
87
88    let mol_ids = assign_mol_ids(&spec.mols())?;
89    let mol_set: std::collections::HashSet<&str> = mol_ids.iter().map(String::as_str).collect();
90
91    // Collect labelable ids (mol + text).
92    let mut labelable = mol_set.clone();
93    for t in spec.texts() {
94        let Some(id) = t.id.as_deref().map(str::trim).filter(|s| !s.is_empty()) else {
95            continue;
96        };
97        if !labelable.insert(id) {
98            return Err(format!("duplicate node id {id}"));
99        }
100    }
101
102    for m in spec.mols() {
103        if let Some(ref lab) = m.label {
104            for (id, _pos) in lab.placements() {
105                let id = id.trim();
106                if id.is_empty() {
107                    return Err("mol label ref must be non-empty".into());
108                }
109                match spec.node_by_id(id) {
110                    Some(Node::Text(_)) => {}
111                    Some(Node::Mol(_)) => {
112                        return Err(format!("mol label {id} must ref a text node, not a mol"));
113                    }
114                    Some(Node::Edge(_)) => {
115                        return Err(format!("mol label {id} must ref a text node, not an edge"));
116                    }
117                    None => return Err(format!("mol label unknown text id {id}")),
118                }
119            }
120        }
121    }
122
123    for e in spec.edges() {
124        if e.sources.is_empty() {
125            return Err("edge sources must be non-empty".into());
126        }
127        if e.targets.is_empty() {
128            return Err("edge targets must be non-empty".into());
129        }
130        for id in e.sources.iter() {
131            let id = id.trim();
132            if id.is_empty() {
133                return Err("edge source id must be non-empty".into());
134            }
135            if !mol_set.contains(id) {
136                return Err(format!("edge source unknown id {id}"));
137            }
138        }
139        for id in e.targets.iter() {
140            let id = id.trim();
141            if id.is_empty() {
142                return Err("edge target id must be non-empty".into());
143            }
144            if !mol_set.contains(id) {
145                return Err(format!("edge target unknown id {id}"));
146            }
147        }
148        // The layered layout (elkrs 0.1) panics on a self-loop: say so instead of aborting.
149        if let Some(id) = e.sources.iter().find(|s| e.targets.iter().any(|t| t.trim() == s.trim())) {
150            return Err(format!("edge from {} to itself", id.trim()));
151        }
152        if let Some(ref lab) = e.label {
153            for (id, pos) in lab.placements() {
154                let id = id.trim();
155                if id.is_empty() {
156                    return Err("edge label ref must be non-empty".into());
157                }
158                match spec.node_by_id(id) {
159                    Some(Node::Text(_)) | Some(Node::Mol(_)) => {}
160                    Some(Node::Edge(_)) => {
161                        return Err(format!("edge label ({pos:?}) id {id} cannot ref an edge"));
162                    }
163                    None => return Err(format!("edge label ({pos:?}) unknown id {id}")),
164                }
165            }
166        }
167    }
168    Ok(())
169}
170
171/// Pass 1: build an [`EdgePlan`] for every mol that needs coord gen.
172///
173/// - No align: each mol is its own free-layout root.
174/// - `align: true`: forest — default parent = previous mol; `align_to` overrides.
175///
176/// Returns `None` only when the document has no molecules.
177pub fn plan_edge(spec: &DepictSpec) -> Result<Option<EdgePlan>, String> {
178    validate_edges(spec)?;
179    let mols = spec.mols();
180    if mols.is_empty() {
181        return Ok(None);
182    }
183    let ids = assign_mol_ids(&mols)?;
184    let id_to_idx: HashMap<&str, usize> = ids
185        .iter()
186        .enumerate()
187        .map(|(i, id)| (id.as_str(), i))
188        .collect();
189
190    let align = spec.align_enabled();
191
192    // parent_of[i] = None → root; Some(j) → align onto j.
193    // Explicit ``align_to`` always wins; ``align: true`` defaults others to previous.
194    let mut parent_of: Vec<Option<usize>> = vec![None; mols.len()];
195    for i in 0..mols.len() {
196        if let Some(ref target) = mols[i].align_to {
197            let name = target.ref_id();
198            let j = *id_to_idx
199                .get(name)
200                .ok_or_else(|| format!("align_to unknown id {name}"))?;
201            if j == i {
202                return Err(format!("mol {} cannot align_to itself", ids[i]));
203            }
204            parent_of[i] = Some(j);
205        } else if align && i > 0 {
206            parent_of[i] = Some(i - 1);
207        }
208    }
209
210    let mut nodes: Vec<MolTemplate> = mols
211        .iter()
212        .enumerate()
213        .map(|(i, m)| {
214            let align_opts = parent_of[i].map(|_| match &m.align_to {
215                Some(a) => a.align_opts(),
216                None => AlignOpts::default(),
217            });
218            MolTemplate {
219                id: ids[i].clone(),
220                smiles: m.smiles.clone(),
221                cxsmiles: m.cxsmiles.clone(),
222                molfile: m.molfile.clone(),
223                align: align_opts,
224                template_for: vec![],
225            }
226        })
227        .collect();
228
229    // Attach children (drain from leaves upward by building ownership via indices).
230    // Collect children indices per parent, then move nodes into place.
231    let mut children_of: Vec<Vec<usize>> = vec![vec![]; mols.len()];
232    let mut roots_idx: Vec<usize> = Vec::new();
233    for (i, p) in parent_of.iter().enumerate() {
234        match p {
235            None => roots_idx.push(i),
236            Some(j) => children_of[*j].push(i),
237        }
238    }
239
240    fn build_tree(
241        i: usize,
242        nodes: &mut Vec<Option<MolTemplate>>,
243        children_of: &[Vec<usize>],
244    ) -> MolTemplate {
245        let mut node = nodes[i].take().expect("node");
246        for &c in &children_of[i] {
247            node.template_for.push(build_tree(c, nodes, children_of));
248        }
249        node
250    }
251
252    let mut slots: Vec<Option<MolTemplate>> = nodes.drain(..).map(Some).collect();
253    let roots: Vec<MolTemplate> = roots_idx
254        .iter()
255        .map(|&i| build_tree(i, &mut slots, &children_of))
256        .collect();
257
258    let plan = EdgePlan::new_v1(vec![EdgeTask::CoordGen { roots }]);
259    plan.validate()?;
260    Ok(Some(plan))
261}
262
263fn edge_molecules(edge: &EdgeResult) -> HashMap<&str, &CoordGenMoleculeResult> {
264    let mut map = HashMap::new();
265    for r in &edge.results {
266        let EdgeTaskResult::CoordGen { molecules, .. } = r;
267        for m in molecules {
268            map.insert(m.id.as_str(), m);
269        }
270    }
271    map
272}
273
274/// Apply ``star_labels`` onto ``*`` atoms in layout encounter order.
275pub fn apply_star_labels(mol: &mut MoleculeIn, labels: &[Option<String>]) {
276    if labels.is_empty() {
277        return;
278    }
279    let stars: Vec<usize> = mol
280        .atoms
281        .iter()
282        .enumerate()
283        .filter(|(_, a)| a.z == Some(0) || a.element.as_deref() == Some("*"))
284        .map(|(i, _)| i)
285        .collect();
286    if stars.is_empty() {
287        return;
288    }
289    for (slot, lab) in labels.iter().enumerate() {
290        if slot >= stars.len() {
291            break;
292        }
293        let text = match lab {
294            None => "*".to_string(),
295            Some(s) if s.trim().is_empty() => "*".to_string(),
296            Some(s) => s.trim().to_string(),
297        };
298        if let Some(atom) = mol.atoms.get_mut(stars[slot]) {
299            atom.label = Some(text);
300        }
301    }
302}
303
304/// House shade colormap (only name paint applies). Omit / empty / this → ok.
305const SHADE_COLORMAP_SUPPORTED: &str = "xenosite";
306
307/// Reject colormap names that paint would ignore (no silent no-op).
308pub fn validate_shade_colormap(name: Option<&str>) -> Result<(), String> {
309    let Some(raw) = name.map(str::trim).filter(|s| !s.is_empty()) else {
310        return Ok(());
311    };
312    if raw.eq_ignore_ascii_case(SHADE_COLORMAP_SUPPORTED) {
313        return Ok(());
314    }
315    Err(format!(
316        "unsupported shade colormap {raw:?}; only \"{SHADE_COLORMAP_SUPPORTED}\" (default) is supported"
317    ))
318}
319
320fn validate_mol_shade_colormap(node: &MolNode, chrome: &MolOpts) -> Result<(), String> {
321    if let Some(ref shade) = node.shade {
322        validate_shade_colormap(shade.colormap.as_deref())?;
323    }
324    if let Some(ref style) = chrome.shade {
325        validate_shade_colormap(style.colormap.as_deref())?;
326    }
327    Ok(())
328}
329
330fn apply_doc_chrome(mut mol: MoleculeIn, node: &MolNode, id: &str, chrome: &MolOpts) -> MoleculeIn {
331    mol.id = Some(id.to_string());
332    if let Some(ref c) = chrome.color {
333        mol.color = Some(c.clone());
334    }
335    // Scores always from the node (non-cascading); window from resolved chrome.
336    if let Some(ref shade) = node.shade {
337        mol.atom_shade = shade.atoms.clone();
338        mol.bond_shade = shade.bonds.clone();
339    }
340    if let Some(ref style) = chrome.shade {
341        if let Some(v) = style.vmin {
342            mol.shade_vmin = Some(v);
343        } else if let Some(ref shade) = node.shade {
344            mol.shade_vmin = Some(shade.vmin);
345        }
346        if let Some(v) = style.vmax {
347            mol.shade_vmax = Some(v);
348        } else if let Some(ref shade) = node.shade {
349            mol.shade_vmax = Some(shade.vmax);
350        }
351    } else if let Some(ref shade) = node.shade {
352        mol.shade_vmin = Some(shade.vmin);
353        mol.shade_vmax = Some(shade.vmax);
354    }
355    if let Some(s) = chrome.scale {
356        mol.scale = s;
357    }
358    if let Some(w) = chrome.weight {
359        mol.weight = w;
360    }
361    if let Some(a) = chrome.aromatic {
362        mol.aromatic = a;
363    }
364    if let Some(d) = chrome.debug_box {
365        mol.debug_box = d;
366    }
367    if let Some(d) = chrome.debug_align {
368        mol.debug_align = d;
369    }
370    // halo reserved on chrome for future paint; MoleculeIn has no halo flag yet.
371    let _ = chrome.halo;
372    if let Some(ref labels) = node.star_labels {
373        apply_star_labels(&mut mol, labels);
374    } else if let Some(src) = cx_source(node.cxsmiles.as_deref(), node.smiles.as_deref()) {
375        mol = apply_cx_by_index(mol, src);
376    }
377    mol
378}
379
380/// One painted molecule from [`render_doc`] / [`depict`].
381#[derive(Debug, Clone)]
382pub struct DocPaint {
383    pub id: String,
384    pub molecule: MoleculeIn,
385    pub scene: Scene,
386    /// Unscaled pose frame JSON (filled by [`depict`]; empty from [`render_doc`]).
387    pub frame_json: String,
388}
389
390/// Paint each mol in a document from already-laid coords.
391///
392/// Same steps for every mol spec: chem paint, then annotations, then
393/// captions, then fit. Empty overlay fields are a no-op, not a second path.
394pub(crate) fn paint_laid_mols(
395    spec: &DepictSpec,
396    laid: &HashMap<String, MoleculeIn>,
397) -> Result<Vec<DocPaint>, String> {
398    validate_edges(spec)?;
399    let mols = spec.mols();
400    if mols.is_empty() {
401        return Ok(vec![]);
402    }
403    let ids = assign_mol_ids(&mols)?;
404    let mut out = Vec::with_capacity(mols.len());
405
406    for (i, node) in mols.iter().enumerate() {
407        let id = &ids[i];
408        let base = laid
409            .get(id)
410            .cloned()
411            .ok_or_else(|| format!("missing laid molecule id {id}"))?;
412        let chrome = spec.resolve_mol_chrome(i);
413        validate_mol_shade_colormap(node, &chrome)?;
414        let molecule = apply_doc_chrome(base, node, id, &chrome);
415        // Chrome constraints first (regions/callouts/labels) in the same
416        // unscaled chem space. Then one mol-tree scale so hub `scale` applies
417        // to regions, aromatic circles, and bonds together. Mol `name` is
418        // **not** in the solver — place it afterward clear of structure + chrome
419        // (including regions). Fit last. Do **not** mutate chem atom text for
420        // `atom_label` — that is `star_labels` on `*` atoms only.
421        let scene = depict_chem(&molecule);
422        let scene = chrome_paint::apply_mol_chrome(node, &molecule, scene);
423        let scene = caption::apply_mol_captions(spec, node, scene);
424        let scene = scene.scale_uniform(molecule.diagram_scale());
425        // House pad scales with mol.scale so the fitted SVG doubles; an
426        // explicit `pad` is output pixels and stays as given.
427        let margin = match chrome.pad {
428            Some(p) if p.is_finite() && p >= 0.0 => p,
429            _ => fit::VIEWPORT_MARGIN_DEFAULT * molecule.diagram_scale(),
430        };
431        let scene = fit::fit_scene(scene, margin);
432        out.push(DocPaint {
433            id: id.clone(),
434            molecule,
435            scene,
436            frame_json: String::new(),
437        });
438    }
439    Ok(out)
440}
441
442/// Pass 2: stitch host [`EdgeResult`] coords onto the document and paint.
443pub fn render_doc(spec: &DepictSpec, edge: &EdgeResult) -> Result<Vec<DocPaint>, String> {
444    let mols = spec.mols();
445    let ids = assign_mol_ids(&mols)?;
446    let by_id = edge_molecules(edge);
447    let mut laid = HashMap::new();
448    for id in &ids {
449        let row = by_id
450            .get(id.as_str())
451            .ok_or_else(|| format!("EdgeResult missing molecule id {id}"))?;
452        if !row.ok {
453            return Err(format!(
454                "EdgeResult {id} has ok=false: {}",
455                row.error.as_deref().unwrap_or("coord gen failed")
456            ));
457        }
458        let mol = row
459            .molecule
460            .clone()
461            .ok_or_else(|| format!("EdgeResult {id} missing molecule"))?;
462        laid.insert(id.clone(), mol);
463    }
464    paint_laid_mols(spec, &laid)
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470    use crate::edge::{CoordMethod, EdgeTaskResult};
471    use crate::scene::{AromaticStyle, AtomIn, BondIn};
472
473    fn ethanol_mol(id: &str) -> MoleculeIn {
474        MoleculeIn {
475            id: Some(id.into()),
476            atoms: vec![
477                AtomIn {
478                    index: 0,
479                    element: Some("C".into()),
480                    z: Some(6),
481                    x: 0.0,
482                    y: 0.0,
483                    label: None,
484                    charge: 0,
485                    mapno: None,
486                },
487                AtomIn {
488                    index: 1,
489                    element: Some("C".into()),
490                    z: Some(6),
491                    x: 1.5,
492                    y: 0.0,
493                    label: None,
494                    charge: 0,
495                    mapno: None,
496                },
497                AtomIn {
498                    index: 2,
499                    element: Some("O".into()),
500                    z: Some(8),
501                    x: 2.2,
502                    y: 1.0,
503                    label: Some("OH".into()),
504                    charge: 0,
505                    mapno: None,
506                },
507            ],
508            bonds: vec![
509                BondIn {
510                    index: 0,
511                    begin: 0,
512                    end: 1,
513                    order: 1.0,
514                    stereo: None,
515                    interior: None,
516                },
517                BondIn {
518                    index: 1,
519                    begin: 1,
520                    end: 2,
521                    order: 1.0,
522                    stereo: None,
523                    interior: None,
524                },
525            ],
526            color: None,
527            atom_shade: None,
528            bond_shade: None,
529            shade_vmin: None,
530            shade_vmax: None,
531            scale: 1.0,
532            weight: 1.0,
533            aromatic: Default::default(),
534            debug_box: false,
535            debug_align: false,
536            align_debug: None,
537            ..Default::default()
538        }
539    }
540
541    #[test]
542    fn plan_edge_no_align_independent_roots() {
543        let spec = DepictSpec::Group {
544            id: None,
545            align: false,
546            children: vec![
547                Node::Mol(MolNode {
548                    smiles: Some("CCO".into()),
549                    ..Default::default()
550                }),
551                Node::Mol(MolNode {
552                    smiles: Some("CCCO".into()),
553                    ..Default::default()
554                }),
555            ],
556            opts: None,
557            color: None,
558            scale: None,
559            aromatic: None,
560            debug_box: None,
561            debug_align: None,
562            pad: None,
563        };
564        let plan = plan_edge(&spec).unwrap().unwrap();
565        match &plan.tasks[0] {
566            EdgeTask::CoordGen { roots } => {
567                assert_eq!(roots.len(), 2);
568                assert!(roots[0].template_for.is_empty());
569                assert!(roots[1].template_for.is_empty());
570            }
571        }
572    }
573
574    #[test]
575    fn plan_edge_align_forest_default_first() {
576        let spec = DepictSpec::Group {
577            id: None,
578            align: true,
579            children: vec![
580                Node::Mol(MolNode {
581                    id: Some("ref".into()),
582                    smiles: Some("c1ccccc1".into()),
583                    ..Default::default()
584                }),
585                Node::Mol(MolNode {
586                    smiles: Some("Cc1ccccc1".into()),
587                    align_to: Some(AlignTo::Spec(AlignToSpec {
588                        ref_id: "ref".into(),
589                        atom_map: Some(vec![(1, 0), (2, 1), (3, 2)]),
590                        min_atoms: None,
591                        mode: None,
592                        timeout_ms: None,
593                    })),
594                    ..Default::default()
595                }),
596            ],
597            opts: None,
598            color: None,
599            scale: None,
600            aromatic: None,
601            debug_box: None,
602            debug_align: None,
603            pad: None,
604        };
605        let plan = plan_edge(&spec).unwrap().unwrap();
606        match &plan.tasks[0] {
607            EdgeTask::CoordGen { roots } => {
608                assert_eq!(roots.len(), 1);
609                assert_eq!(roots[0].id, "ref");
610                assert_eq!(roots[0].template_for.len(), 1);
611                let child = &roots[0].template_for[0];
612                assert_eq!(child.id, "m_1");
613                assert_eq!(
614                    child
615                        .align
616                        .as_ref()
617                        .unwrap()
618                        .atom_map
619                        .as_ref()
620                        .unwrap()
621                        .len(),
622                    3
623                );
624            }
625        }
626    }
627
628    #[test]
629    fn render_doc_stitches_edge_result() {
630        let spec = DepictSpec::Mol(MolNode {
631            label: None,
632            name: None,
633            atom_number: None,
634            atom_label: None,
635            region: None,
636            circle: None,
637            callout: None,
638            smiles: Some("CCO".into()),
639            cxsmiles: None,
640            molfile: None,
641            id: Some("e".into()),
642            color: Some("#0b6e4f".into()),
643            shade: None,
644            star_labels: None,
645            scale: None,
646            weight: None,
647            align_to: None,
648            halo: None,
649            aromatic: None,
650            debug_box: None,
651            debug_align: None,
652            pad: None,
653            opts: None,
654            ..Default::default()
655        });
656        let plan = plan_edge(&spec).unwrap().unwrap();
657        let id = match &plan.tasks[0] {
658            EdgeTask::CoordGen { roots } => roots[0].id.clone(),
659        };
660        let edge = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
661            ok: true,
662            molecules: vec![CoordGenMoleculeResult {
663                id: id.clone(),
664                ok: true,
665                method: CoordMethod::Free,
666                used_map: None,
667                molecule: Some(ethanol_mol(&id)),
668                error: None,
669            }],
670        }]);
671        let painted = render_doc(&spec, &edge).unwrap();
672        assert_eq!(painted.len(), 1);
673        assert!(painted[0].scene.width > 0.0);
674        assert_eq!(painted[0].molecule.color.as_deref(), Some("#0b6e4f"));
675    }
676
677    #[test]
678    fn render_doc_applies_cx_when_no_star_labels() {
679        let spec = DepictSpec::Mol(MolNode {
680            label: None,
681            name: None,
682            atom_number: None,
683            atom_label: None,
684            region: None,
685            circle: None,
686            callout: None,
687            smiles: None,
688            cxsmiles: Some("*C |$R1;$|".into()),
689            molfile: None,
690            id: Some("m".into()),
691            color: None,
692            shade: None,
693            star_labels: None,
694            scale: None,
695            weight: None,
696            align_to: None,
697            halo: None,
698            aromatic: None,
699            debug_box: None,
700            debug_align: None,
701            pad: None,
702            opts: None,
703            ..Default::default()
704        });
705        let mol = MoleculeIn {
706            id: Some("m".into()),
707            atoms: vec![
708                AtomIn {
709                    index: 0,
710                    element: Some("*".into()),
711                    z: Some(0),
712                    x: 0.0,
713                    y: 0.0,
714                    label: Some("*".into()),
715                    charge: 0,
716                    mapno: None,
717                },
718                AtomIn {
719                    index: 1,
720                    element: Some("C".into()),
721                    z: Some(6),
722                    x: 1.5,
723                    y: 0.0,
724                    label: None,
725                    charge: 0,
726                    mapno: None,
727                },
728            ],
729            bonds: vec![BondIn {
730                index: 0,
731                begin: 0,
732                end: 1,
733                order: 1.0,
734                stereo: None,
735                interior: None,
736            }],
737            color: None,
738            atom_shade: None,
739            bond_shade: None,
740            shade_vmin: None,
741            shade_vmax: None,
742            scale: 1.0,
743            weight: 1.0,
744            aromatic: Default::default(),
745            debug_box: false,
746            debug_align: false,
747            align_debug: None,
748            ..Default::default()
749        };
750        let edge = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
751            ok: true,
752            molecules: vec![CoordGenMoleculeResult {
753                id: "m".into(),
754                ok: true,
755                method: CoordMethod::Free,
756                used_map: None,
757                molecule: Some(mol),
758                error: None,
759            }],
760        }]);
761        let painted = render_doc(&spec, &edge).unwrap();
762        assert_eq!(painted[0].molecule.atoms[0].label.as_deref(), Some("R1"));
763    }
764
765    #[test]
766    fn structure_prefers_molfile_then_cx_then_smiles() {
767        let mut n = MolNode {
768            smiles: Some("CCO".into()),
769            cxsmiles: Some("CCO |$;$|".into()),
770            molfile: Some("molblock".into()),
771            ..Default::default()
772        };
773        assert_eq!(n.structure().unwrap(), "molblock");
774        n.molfile = None;
775        assert_eq!(n.structure().unwrap(), "CCO |$;$|");
776        n.cxsmiles = None;
777        assert_eq!(n.structure().unwrap(), "CCO");
778        n.smiles = Some("  ".into());
779        assert!(n.structure().unwrap_err().contains("needs smiles"));
780    }
781
782    #[test]
783    fn assign_mol_ids_rejects_duplicates_and_trims() {
784        let mols = vec![
785            MolNode {
786                id: Some("  a  ".into()),
787                smiles: Some("C".into()),
788                ..Default::default()
789            },
790            MolNode {
791                id: Some("a".into()),
792                smiles: Some("CC".into()),
793                ..Default::default()
794            },
795        ];
796        assert!(assign_mol_ids(&mols).unwrap_err().contains("duplicate"));
797        let auto = assign_mol_ids(&[
798            MolNode {
799                smiles: Some("C".into()),
800                ..Default::default()
801            },
802            MolNode {
803                id: Some("".into()),
804                smiles: Some("CC".into()),
805                ..Default::default()
806            },
807        ])
808        .unwrap();
809        assert_eq!(auto, ["m_0", "m_1"]);
810    }
811
812    #[test]
813    fn plan_edge_empty_group_is_none() {
814        let spec = DepictSpec::Group {
815            id: None,
816            align: false,
817            children: vec![],
818            opts: None,
819            color: None,
820            scale: None,
821            aromatic: None,
822            debug_box: None,
823            debug_align: None,
824            pad: None,
825        };
826        assert!(plan_edge(&spec).unwrap().is_none());
827    }
828
829    #[test]
830    fn plan_edge_align_to_unknown_and_self_error() {
831        let unknown = DepictSpec::Group {
832            id: None,
833            align: true,
834            children: vec![
835                Node::Mol(MolNode {
836                    id: Some("a".into()),
837                    smiles: Some("C".into()),
838                    ..Default::default()
839                }),
840                Node::Mol(MolNode {
841                    smiles: Some("CC".into()),
842                    align_to: Some(AlignTo::Ref("missing".into())),
843                    ..Default::default()
844                }),
845            ],
846            opts: None,
847            color: None,
848            scale: None,
849            aromatic: None,
850            debug_box: None,
851            debug_align: None,
852            pad: None,
853        };
854        assert!(plan_edge(&unknown).unwrap_err().contains("unknown id"));
855
856        let self_align = DepictSpec::Group {
857            id: None,
858            align: true,
859            children: vec![
860                Node::Mol(MolNode {
861                    id: Some("a".into()),
862                    smiles: Some("C".into()),
863                    ..Default::default()
864                }),
865                Node::Mol(MolNode {
866                    id: Some("b".into()),
867                    smiles: Some("CC".into()),
868                    align_to: Some(AlignTo::Ref("b".into())),
869                    ..Default::default()
870                }),
871            ],
872            opts: None,
873            color: None,
874            scale: None,
875            aromatic: None,
876            debug_box: None,
877            debug_align: None,
878            pad: None,
879        };
880        assert!(plan_edge(&self_align).unwrap_err().contains("itself"));
881    }
882
883    #[test]
884    fn plan_edge_align_to_explicit_parent() {
885        let spec = DepictSpec::Group {
886            id: None,
887            align: true,
888            children: vec![
889                Node::Mol(MolNode {
890                    id: Some("left".into()),
891                    smiles: Some("C".into()),
892                    ..Default::default()
893                }),
894                Node::Mol(MolNode {
895                    id: Some("mid".into()),
896                    smiles: Some("CC".into()),
897                    ..Default::default()
898                }),
899                Node::Mol(MolNode {
900                    id: Some("q".into()),
901                    smiles: Some("CCC".into()),
902                    align_to: Some(AlignTo::Ref("mid".into())),
903                    ..Default::default()
904                }),
905            ],
906            opts: None,
907            color: None,
908            scale: None,
909            aromatic: None,
910            debug_box: None,
911            debug_align: None,
912            pad: None,
913        };
914        let plan = plan_edge(&spec).unwrap().unwrap();
915        match &plan.tasks[0] {
916            EdgeTask::CoordGen { roots } => {
917                assert_eq!(roots.len(), 1);
918                assert_eq!(roots[0].id, "left");
919                assert_eq!(roots[0].template_for.len(), 1);
920                assert_eq!(roots[0].template_for[0].id, "mid");
921                assert_eq!(roots[0].template_for[0].template_for[0].id, "q");
922            }
923        }
924    }
925
926    #[test]
927    fn apply_star_labels_covers_null_empty_and_overflow() {
928        let mut mol = MoleculeIn {
929            id: None,
930            atoms: vec![
931                AtomIn {
932                    index: 0,
933                    element: Some("*".into()),
934                    z: Some(0),
935                    x: 0.0,
936                    y: 0.0,
937                    label: Some("*".into()),
938                    charge: 0,
939                    mapno: None,
940                },
941                AtomIn {
942                    index: 1,
943                    element: Some("C".into()),
944                    z: Some(6),
945                    x: 1.0,
946                    y: 0.0,
947                    label: None,
948                    charge: 0,
949                    mapno: None,
950                },
951                AtomIn {
952                    index: 2,
953                    element: Some("*".into()),
954                    z: Some(0),
955                    x: 2.0,
956                    y: 0.0,
957                    label: Some("*".into()),
958                    charge: 0,
959                    mapno: None,
960                },
961            ],
962            bonds: vec![],
963            color: None,
964            atom_shade: None,
965            bond_shade: None,
966            shade_vmin: None,
967            shade_vmax: None,
968            scale: 1.0,
969            weight: 1.0,
970            aromatic: Default::default(),
971            debug_box: false,
972            debug_align: false,
973            align_debug: None,
974            ..Default::default()
975        };
976        apply_star_labels(&mut mol, &[]);
977        assert_eq!(mol.atoms[0].label.as_deref(), Some("*"));
978        apply_star_labels(
979            &mut mol,
980            &[
981                None,
982                Some("  ".into()),
983                Some("R2".into()),
984                Some("extra".into()),
985            ],
986        );
987        // Two stars: slot0 → "*", slot1 empty → "*"; R2/extra overflow ignored.
988        assert_eq!(mol.atoms[0].label.as_deref(), Some("*"));
989        assert_eq!(mol.atoms[2].label.as_deref(), Some("*"));
990    }
991
992    #[test]
993    fn shade_colormap_xenosite_or_omit_ok_others_err() {
994        assert!(validate_shade_colormap(None).is_ok());
995        assert!(validate_shade_colormap(Some("")).is_ok());
996        assert!(validate_shade_colormap(Some("xenosite")).is_ok());
997        assert!(validate_shade_colormap(Some("Xenosite")).is_ok());
998        let err = validate_shade_colormap(Some("viridis")).unwrap_err();
999        assert!(
1000            err.contains("viridis") && err.contains("xenosite"),
1001            "unexpected err: {err}"
1002        );
1003    }
1004
1005    #[test]
1006    fn render_doc_rejects_unsupported_shade_colormap() {
1007        let spec: DepictSpec = serde_json::from_str(
1008            r#"{
1009              "type": "mol",
1010              "smiles": "CCO",
1011              "id": "a",
1012              "shade": {"atoms": [0.1, 0.5, 0.9], "colormap": "viridis"}
1013            }"#,
1014        )
1015        .unwrap();
1016        let edge = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
1017            ok: true,
1018            molecules: vec![CoordGenMoleculeResult {
1019                id: "a".into(),
1020                ok: true,
1021                method: CoordMethod::Free,
1022                used_map: None,
1023                molecule: Some(ethanol_mol("a")),
1024                error: None,
1025            }],
1026        }]);
1027        let err = render_doc(&spec, &edge).unwrap_err();
1028        assert!(
1029            err.contains("viridis") && err.contains("unsupported"),
1030            "expected colormap rejection, got: {err}"
1031        );
1032    }
1033
1034    #[test]
1035    fn render_doc_star_labels_shade_scale_weight() {
1036        let spec = DepictSpec::Mol(MolNode {
1037            label: None,
1038            name: None,
1039            atom_number: None,
1040            atom_label: None,
1041            region: None,
1042            circle: None,
1043            callout: None,
1044            smiles: Some("*C".into()),
1045            cxsmiles: None,
1046            molfile: None,
1047            id: Some("s".into()),
1048            color: None,
1049            shade: Some(ShadeSpec {
1050                atoms: Some(vec![0.2, 0.8]),
1051                bonds: Some(vec![0.5]),
1052                colormap: Some("xenosite".into()),
1053                vmin: 0.0,
1054                vmax: 1.0,
1055            }),
1056            star_labels: Some(vec![Some("R1".into())]),
1057            scale: Some(1.5),
1058            weight: Some(1.2),
1059            align_to: None,
1060            halo: None,
1061            aromatic: None,
1062            debug_box: None,
1063            debug_align: None,
1064            pad: None,
1065            opts: None,
1066            ..Default::default()
1067        });
1068        let mut mol = ethanol_mol("s");
1069        mol.atoms[0].element = Some("*".into());
1070        mol.atoms[0].z = Some(0);
1071        mol.atoms[0].label = Some("*".into());
1072        let edge = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
1073            ok: true,
1074            molecules: vec![CoordGenMoleculeResult {
1075                id: "s".into(),
1076                ok: true,
1077                method: CoordMethod::Free,
1078                used_map: None,
1079                molecule: Some(mol),
1080                error: None,
1081            }],
1082        }]);
1083        let painted = render_doc(&spec, &edge).unwrap();
1084        let m = &painted[0].molecule;
1085        assert_eq!(m.atoms[0].label.as_deref(), Some("R1"));
1086        assert_eq!(m.atom_shade.as_ref().unwrap()[0], 0.2);
1087        assert_eq!(m.scale, 1.5);
1088        assert!((m.weight - 1.2).abs() < 1e-12);
1089    }
1090
1091    #[test]
1092    fn render_doc_errors_on_missing_or_failed_edge_row() {
1093        let spec = DepictSpec::Mol(MolNode {
1094            label: None,
1095            name: None,
1096            atom_number: None,
1097            atom_label: None,
1098            region: None,
1099            circle: None,
1100            callout: None,
1101            smiles: Some("C".into()),
1102            cxsmiles: None,
1103            molfile: None,
1104            id: Some("x".into()),
1105            color: None,
1106            shade: None,
1107            star_labels: None,
1108            scale: None,
1109            weight: None,
1110            align_to: None,
1111            halo: None,
1112            aromatic: None,
1113            debug_box: None,
1114            debug_align: None,
1115            pad: None,
1116            opts: None,
1117            ..Default::default()
1118        });
1119        let missing = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
1120            ok: false,
1121            molecules: vec![],
1122        }]);
1123        assert!(render_doc(&spec, &missing).unwrap_err().contains("missing"));
1124
1125        let failed = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
1126            ok: false,
1127            molecules: vec![CoordGenMoleculeResult {
1128                id: "x".into(),
1129                ok: false,
1130                method: CoordMethod::None,
1131                used_map: None,
1132                molecule: None,
1133                error: Some("boom".into()),
1134            }],
1135        }]);
1136        assert!(render_doc(&spec, &failed).unwrap_err().contains("ok=false"));
1137
1138        let no_mol = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
1139            ok: true,
1140            molecules: vec![CoordGenMoleculeResult {
1141                id: "x".into(),
1142                ok: true,
1143                method: CoordMethod::Free,
1144                used_map: None,
1145                molecule: None,
1146                error: None,
1147            }],
1148        }]);
1149        assert!(render_doc(&spec, &no_mol)
1150            .unwrap_err()
1151            .contains("missing molecule"));
1152    }
1153
1154    #[test]
1155    fn shade_spec_default_and_group_align_flag() {
1156        let s = ShadeSpec::default();
1157        assert_eq!(s.vmin, 0.0);
1158        assert_eq!(s.vmax, 1.0);
1159        let g = DepictSpec::Group {
1160            id: Some("g".into()),
1161            align: true,
1162            children: vec![],
1163            opts: None,
1164            color: None,
1165            scale: None,
1166            aromatic: None,
1167            debug_box: None,
1168            debug_align: None,
1169            pad: None,
1170        };
1171        assert!(g.align_enabled());
1172        assert!(g.mols().is_empty());
1173    }
1174
1175    #[test]
1176    fn align_to_json_string_or_object() {
1177        let s: AlignTo = serde_json::from_str(r#""ref""#).unwrap();
1178        assert_eq!(s.ref_id(), "ref");
1179        let o: AlignTo =
1180            serde_json::from_str(r#"{"ref":"mid","atom_map":[[1,0],[2,1]],"min_atoms":4}"#)
1181                .unwrap();
1182        assert_eq!(o.ref_id(), "mid");
1183        let opts = o.align_opts();
1184        assert_eq!(opts.atom_map.as_ref().unwrap().len(), 2);
1185        assert_eq!(opts.min_atoms, Some(4));
1186        let timed: AlignTo =
1187            serde_json::from_str(r#"{"ref":"mid","mode":"greedy","timeout_ms":50}"#).unwrap();
1188        let t = timed.align_opts();
1189        assert_eq!(t.mode, Some(crate::edge::AlignMode::Greedy));
1190        assert_eq!(t.timeout_ms, Some(50));
1191        let skip: AlignTo = serde_json::from_str(r#"{"ref":"mid","mode":"skip"}"#).unwrap();
1192        assert_eq!(skip.align_opts().mode, Some(crate::edge::AlignMode::Skip));
1193    }
1194
1195    #[test]
1196    fn opts_patch_json_discriminated_and_list() {
1197        // Universal singleton (MolOpts — mol-only keys allowed without type tag)
1198        let u: Opts = serde_json::from_str(r##"{"color":"#111","weight":1.2}"##).unwrap();
1199        match &u {
1200            Opts::One(OptsPatch::Universal(m)) => {
1201                assert_eq!(m.color.as_deref(), Some("#111"));
1202                assert_eq!(m.weight, Some(1.2));
1203            }
1204            _ => panic!("expected universal"),
1205        }
1206        // Typed mol patch
1207        let t: OptsPatch =
1208            serde_json::from_str(r#"{"type":"mol","weight":1.5,"halo":false}"#).unwrap();
1209        match t {
1210            OptsPatch::Typed(TypedOptsPatch::Mol { opts }) => {
1211                assert_eq!(opts.weight, Some(1.5));
1212                assert_eq!(opts.halo, Some(false));
1213            }
1214            _ => panic!("expected typed mol"),
1215        }
1216        // for_types multi
1217        let f: OptsPatch =
1218            serde_json::from_str(r##"{"for_types":["mol","group"],"color":"#0b6e4f"}"##).unwrap();
1219        match f {
1220            OptsPatch::ForTypes(p) => {
1221                assert_eq!(p.for_types, vec![NodeType::Mol, NodeType::Group]);
1222                assert_eq!(p.opts.color.as_deref(), Some("#0b6e4f"));
1223            }
1224            _ => panic!("expected for_types"),
1225        }
1226        // List container
1227        let list: Opts = serde_json::from_str(
1228            r##"[{"color":"#111"},{"type":"mol","weight":1.2},{"for_types":["mol"],"scale":2.0}]"##,
1229        )
1230        .unwrap();
1231        assert!(matches!(list, Opts::Many(ref v) if v.len() == 3));
1232    }
1233
1234    #[test]
1235    fn cascade_universal_mol_opts_from_group_bag() {
1236        // Untyped bag entry carries weight/halo — no `{ "type": "mol", … }` needed.
1237        let spec: DepictSpec = serde_json::from_str(
1238            r##"{
1239              "type": "group",
1240              "align": false,
1241              "opts": {"color": "#333", "weight": 1.5, "halo": true},
1242              "children": [
1243                {"type": "mol", "id": "a", "smiles": "CCO"},
1244                {"type": "mol", "id": "b", "smiles": "CCC"}
1245              ]
1246            }"##,
1247        )
1248        .unwrap();
1249        for i in 0..2 {
1250            let c = spec.resolve_mol_chrome(i);
1251            assert_eq!(c.color.as_deref(), Some("#333"));
1252            assert_eq!(c.weight, Some(1.5));
1253            assert_eq!(c.halo, Some(true));
1254        }
1255    }
1256
1257    #[test]
1258    fn cascade_group_opts_list_inherits_then_child_overrides() {
1259        let spec: DepictSpec = serde_json::from_str(
1260            r##"{
1261              "type": "group",
1262              "align": false,
1263              "opts": [
1264                {"color": "#111", "scale": 1.0},
1265                {"type": "mol", "weight": 1.0, "halo": true},
1266                {"type": "mol", "weight": 1.25},
1267                {"for_types": ["mol"], "scale": 1.5}
1268              ],
1269              "children": [
1270                {
1271                  "type": "mol",
1272                  "id": "a",
1273                  "smiles": "CCO",
1274                  "opts": {"type": "mol", "color": "#0b6e4f"}
1275                },
1276                {
1277                  "type": "mol",
1278                  "id": "b",
1279                  "smiles": "CCC",
1280                  "weight": 2.0,
1281                  "opts": [
1282                    {"type": "mol", "halo": false},
1283                    {"for_types": ["group"], "color": "#fff"}
1284                  ]
1285                }
1286              ]
1287            }"##,
1288        )
1289        .unwrap();
1290
1291        let a = spec.resolve_mol_chrome(0);
1292        assert_eq!(a.color.as_deref(), Some("#0b6e4f")); // child typed patch wins
1293        assert_eq!(a.weight, Some(1.25)); // later typed patch in group list wins
1294        assert_eq!(a.scale, Some(1.5)); // later for_types common key overrides universal
1295        assert_eq!(a.halo, Some(true));
1296
1297        let b = spec.resolve_mol_chrome(1);
1298        assert_eq!(b.color.as_deref(), Some("#111")); // group universal; child for_types group ignored
1299        assert_eq!(b.weight, Some(2.0)); // local flat last
1300        assert_eq!(b.halo, Some(false)); // child opts list
1301        assert_eq!(b.scale, Some(1.5)); // inherited from group for_types
1302    }
1303
1304    #[test]
1305    fn cascade_group_flat_overrides_group_opts_list() {
1306        let spec: DepictSpec = serde_json::from_str(
1307            r##"{
1308              "type": "group",
1309              "opts": [{"color": "#111", "scale": 1.0}],
1310              "color": "#222",
1311              "children": [{"type": "mol", "smiles": "C", "scale": 3.0}]
1312            }"##,
1313        )
1314        .unwrap();
1315        let chrome = spec.resolve_mol_chrome(0);
1316        assert_eq!(chrome.color.as_deref(), Some("#222")); // group flat after opts list
1317        assert_eq!(chrome.scale, Some(3.0)); // node local last
1318    }
1319
1320    #[test]
1321    fn cascade_grid_root_inherits_onto_row_mols() {
1322        let spec: DepictSpec = serde_json::from_str(
1323            r##"{
1324              "type": "grid",
1325              "color": "red",
1326              "debug_box": true,
1327              "debug_align": true,
1328              "children": [
1329                {"type": "mol", "id": "a", "smiles": "CCCCCC"},
1330                {
1331                  "type": "group",
1332                  "aromatic": "kekule",
1333                  "children": [
1334                    {"type": "mol", "id": "b", "smiles": "c1ccccc1"},
1335                    {"type": "mol", "id": "c", "smiles": "c1ccccc1", "color": "blue"}
1336                  ]
1337                }
1338              ]
1339            }"##,
1340        )
1341        .unwrap();
1342        assert_eq!(spec.mols().len(), 3);
1343        let a = spec.resolve_mol_chrome(0);
1344        assert_eq!(a.color.as_deref(), Some("red"));
1345        assert_eq!(a.debug_box, Some(true));
1346        assert_eq!(a.debug_align, Some(true));
1347        let b = spec.resolve_mol_chrome(1);
1348        assert_eq!(b.color.as_deref(), Some("red"));
1349        assert_eq!(b.debug_box, Some(true));
1350        assert_eq!(b.debug_align, Some(true));
1351        assert_eq!(b.aromatic, Some(AromaticStyle::Kekule));
1352        let c = spec.resolve_mol_chrome(2);
1353        assert_eq!(
1354            c.color.as_deref(),
1355            Some("blue"),
1356            "local flat overrides grid"
1357        );
1358        assert_eq!(c.debug_box, Some(true));
1359        assert_eq!(c.debug_align, Some(true));
1360        assert_eq!(c.aromatic, Some(AromaticStyle::Kekule));
1361    }
1362
1363    #[test]
1364    fn cascade_aromatic_global_inherits_local_overrides() {
1365        let spec: DepictSpec = serde_json::from_str(
1366            r##"{
1367              "type": "group",
1368              "aromatic": "kekule",
1369              "opts": [{"aromatic": "kekule"}],
1370              "children": [
1371                {"type": "mol", "id": "a", "smiles": "c1ccccc1"},
1372                {"type": "mol", "id": "b", "smiles": "c1ccccc1", "aromatic": "circle"},
1373                {
1374                  "type": "mol",
1375                  "id": "c",
1376                  "smiles": "c1ccccc1",
1377                  "opts": {"type": "mol", "aromatic": "circle"}
1378                }
1379              ]
1380            }"##,
1381        )
1382        .unwrap();
1383        assert_eq!(
1384            spec.resolve_mol_chrome(0).aromatic,
1385            Some(AromaticStyle::Kekule),
1386            "global group aromatic inherits"
1387        );
1388        assert_eq!(
1389            spec.resolve_mol_chrome(1).aromatic,
1390            Some(AromaticStyle::Circle),
1391            "local flat aromatic overrides group"
1392        );
1393        assert_eq!(
1394            spec.resolve_mol_chrome(2).aromatic,
1395            Some(AromaticStyle::Circle),
1396            "local typed mol opts override group"
1397        );
1398    }
1399
1400    #[test]
1401    fn render_doc_stamps_cascaded_aromatic_onto_molecule() {
1402        let spec: DepictSpec = serde_json::from_str(
1403            r##"{
1404              "type": "group",
1405              "aromatic": "kekule",
1406              "children": [{"type": "mol", "id": "e", "smiles": "CCO"}]
1407            }"##,
1408        )
1409        .unwrap();
1410        let edge = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
1411            ok: true,
1412            molecules: vec![CoordGenMoleculeResult {
1413                id: "e".into(),
1414                ok: true,
1415                method: CoordMethod::Free,
1416                used_map: None,
1417                molecule: Some(ethanol_mol("e")),
1418                error: None,
1419            }],
1420        }]);
1421        let painted = render_doc(&spec, &edge).unwrap();
1422        assert_eq!(painted[0].molecule.aromatic, AromaticStyle::Kekule);
1423    }
1424
1425    #[test]
1426    fn cascade_shade_style_deep_merges_across_list() {
1427        let spec: DepictSpec = serde_json::from_str(
1428            r#"{
1429              "type": "group",
1430              "opts": [
1431                {"type": "mol", "shade": {"vmin": 0.0, "vmax": 1.0}},
1432                {"type": "mol", "shade": {"vmax": 0.5, "colormap": "xenosite"}}
1433              ],
1434              "children": [
1435                {
1436                  "type": "mol",
1437                  "smiles": "C",
1438                  "shade": {"atoms": [0.2], "vmin": -1.0, "vmax": 1.0}
1439                }
1440              ]
1441            }"#,
1442        )
1443        .unwrap();
1444        let chrome = spec.resolve_mol_chrome(0);
1445        let s = chrome.shade.as_ref().unwrap();
1446        // Local shade.style() merges last → vmin/vmax from node ShadeSpec
1447        assert_eq!(s.vmin, Some(-1.0));
1448        assert_eq!(s.vmax, Some(1.0));
1449        // colormap from group list still present unless local cleared it
1450        assert_eq!(s.colormap.as_deref(), Some("xenosite"));
1451    }
1452
1453    #[test]
1454    fn cascade_typed_group_patch_does_not_apply_to_mol() {
1455        let spec: DepictSpec = serde_json::from_str(
1456            r##"{
1457              "type": "group",
1458              "opts": [
1459                {"type": "group", "color": "#ff0000"},
1460                {"type": "mol", "color": "#00ff00"}
1461              ],
1462              "children": [{"type": "mol", "smiles": "C"}]
1463            }"##,
1464        )
1465        .unwrap();
1466        let chrome = spec.resolve_mol_chrome(0);
1467        assert_eq!(chrome.color.as_deref(), Some("#00ff00"));
1468    }
1469
1470    #[test]
1471    fn render_doc_uses_cascaded_color_from_group_opts_list() {
1472        let spec: DepictSpec = serde_json::from_str(
1473            r##"{
1474              "type": "group",
1475              "opts": [{"color": "#abcdef"}, {"type": "mol", "weight": 1.5}],
1476              "children": [{"type": "mol", "id": "e", "smiles": "CCO"}]
1477            }"##,
1478        )
1479        .unwrap();
1480        let edge = EdgeResult::new_v1(vec![EdgeTaskResult::CoordGen {
1481            ok: true,
1482            molecules: vec![CoordGenMoleculeResult {
1483                id: "e".into(),
1484                ok: true,
1485                method: CoordMethod::Free,
1486                used_map: None,
1487                molecule: Some(ethanol_mol("e")),
1488                error: None,
1489            }],
1490        }]);
1491        let painted = render_doc(&spec, &edge).unwrap();
1492        assert_eq!(painted[0].molecule.color.as_deref(), Some("#abcdef"));
1493        assert!((painted[0].molecule.weight - 1.5).abs() < 1e-12);
1494    }
1495
1496    #[test]
1497    fn reaction_scheme_nodes_and_edges_json() {
1498        let spec: DepictSpec = serde_json::from_str(
1499            r##"{
1500              "type": "reaction_scheme",
1501              "opts": [{"color": "#111"}, {"type": "mol", "weight": 1.2}],
1502              "children": [
1503                {"type": "text", "id": "adh", "text": "ADH"},
1504                {"type": "text", "id": "aldh", "text": "ALDH"},
1505                {"type": "mol", "id": "a", "smiles": "CCO", "label": "adh"},
1506                {
1507                  "type": "edge",
1508                  "source": "a",
1509                  "target": "b",
1510                  "label": {
1511                    "above": ["adh"],
1512                    "below": ["rt"],
1513                    "left": ["nabh4"]
1514                  },
1515                  "arrow": "forward"
1516                },
1517                {"type": "text", "id": "rt", "text": "rt"},
1518                {"type": "mol", "id": "nabh4", "smiles": "[BH4-]", "scale": 0.4},
1519                {"type": "mol", "id": "b", "smiles": "CC=O"},
1520                {
1521                  "type": "edge",
1522                  "source": "b",
1523                  "target": "c",
1524                  "label": [
1525                    "aldh",
1526                    {"id": "nad", "pos": "right"}
1527                  ],
1528                  "arrow": "equilibrium",
1529                  "color": "#064",
1530                  "dashed": true
1531                },
1532                {"type": "text", "id": "nad", "text": "NAD+"},
1533                {"type": "mol", "id": "c", "smiles": "CC(=O)O"}
1534              ]
1535            }"##,
1536        )
1537        .unwrap();
1538
1539        assert_eq!(spec.mols().len(), 4);
1540        assert_eq!(spec.texts().len(), 4);
1541        assert_eq!(spec.nodes().len(), 10);
1542        let edges = spec.edges();
1543        assert_eq!(edges.len(), 2);
1544        assert_eq!(edges[0].sources.as_slice(), &["a".to_string()]);
1545        assert_eq!(edges[0].targets.as_slice(), &["b".to_string()]);
1546        let e0 = edges[0].label.as_ref().unwrap().placements();
1547        assert_eq!(
1548            e0,
1549            vec![
1550                ("adh".into(), crate::doc::LabelPos::Above),
1551                ("rt".into(), crate::doc::LabelPos::Below),
1552                ("nabh4".into(), crate::doc::LabelPos::Left),
1553            ]
1554        );
1555        assert_eq!(edges[0].arrow, EdgeArrow::Forward);
1556        assert_eq!(edges[1].arrow, EdgeArrow::Equilibrium);
1557        let e1 = edges[1].label.as_ref().unwrap().placements();
1558        assert_eq!(
1559            e1,
1560            vec![
1561                ("aldh".into(), crate::doc::LabelPos::Above),
1562                ("nad".into(), crate::doc::LabelPos::Right),
1563            ]
1564        );
1565        assert_eq!(edges[1].color.as_deref(), Some("#064"));
1566        assert!(edges[1].dashed);
1567        assert_eq!(
1568            spec.mols()[0].label.as_ref().unwrap().placements(),
1569            vec![("adh".into(), crate::doc::LabelPos::Above)]
1570        );
1571        validate_edges(&spec).unwrap();
1572
1573        let chrome = spec.resolve_mol_chrome(0);
1574        assert_eq!(chrome.color.as_deref(), Some("#111"));
1575        assert_eq!(chrome.weight, Some(1.2));
1576    }
1577
1578    #[test]
1579    fn group_mol_label_refs_text_node() {
1580        let spec: DepictSpec = serde_json::from_str(
1581            r#"{
1582              "type": "group",
1583              "children": [
1584                {"type": "text", "id": "cap", "text": "ethanol"},
1585                {"type": "mol", "id": "a", "smiles": "CCO", "label": "cap"}
1586              ]
1587            }"#,
1588        )
1589        .unwrap();
1590        assert_eq!(spec.mols().len(), 1);
1591        assert_eq!(spec.texts().len(), 1);
1592        assert_eq!(
1593            spec.mols()[0].label.as_ref().unwrap().placements(),
1594            vec![("cap".into(), LabelPos::Above)]
1595        );
1596        validate_edges(&spec).unwrap();
1597    }
1598
1599    #[test]
1600    fn edge_label_string_list_and_placed_json() {
1601        let spec: DepictSpec = serde_json::from_str(
1602            r#"{
1603              "type": "reaction_scheme",
1604              "children": [
1605                {"type": "text", "id": "adh", "text": "ADH"},
1606                {"type": "text", "id": "rt", "text": "rt"},
1607                {"type": "mol", "id": "a", "smiles": "C"},
1608                {"type": "mol", "id": "b", "smiles": "CC"},
1609                {
1610                  "type": "edge",
1611                  "source": "a",
1612                  "target": "b",
1613                  "label": "adh"
1614                },
1615                {
1616                  "type": "edge",
1617                  "source": "b",
1618                  "target": "a",
1619                  "label": {"id": "rt", "pos": "below"}
1620                }
1621              ]
1622            }"#,
1623        )
1624        .unwrap();
1625        let edges = spec.edges();
1626        assert_eq!(
1627            edges[0].label.as_ref().unwrap().placements(),
1628            vec![("adh".into(), LabelPos::Above)]
1629        );
1630        assert_eq!(
1631            edges[1].label.as_ref().unwrap().placements(),
1632            vec![("rt".into(), LabelPos::Below)]
1633        );
1634        validate_edges(&spec).unwrap();
1635    }
1636
1637    #[test]
1638    fn reaction_scheme_edge_unknown_id_errors() {
1639        let spec: DepictSpec = serde_json::from_str(
1640            r#"{
1641              "type": "reaction_scheme",
1642              "children": [
1643                {"type": "mol", "id": "a", "smiles": "C"},
1644                {"type": "edge", "source": "a", "target": "missing"}
1645              ]
1646            }"#,
1647        )
1648        .unwrap();
1649        let err = validate_edges(&spec).unwrap_err();
1650        assert!(err.contains("unknown id missing"));
1651        assert!(plan_edge(&spec).unwrap_err().contains("unknown id"));
1652    }
1653
1654    #[test]
1655    fn mol_label_unknown_text_id_errors() {
1656        let spec: DepictSpec = serde_json::from_str(
1657            r#"{
1658              "type": "group",
1659              "children": [
1660                {"type": "mol", "id": "a", "smiles": "C", "label": "nope"}
1661              ]
1662            }"#,
1663        )
1664        .unwrap();
1665        let err = validate_edges(&spec).unwrap_err();
1666        assert!(err.contains("unknown text id nope"));
1667    }
1668
1669    #[test]
1670    fn reaction_scheme_layout_defaults_and_overrides() {
1671        let bare: DepictSpec = serde_json::from_str(
1672            r#"{"type":"reaction_scheme","children":[{"type":"mol","id":"a","smiles":"C"}]}"#,
1673        )
1674        .unwrap();
1675        let layout = match &bare {
1676            DepictSpec::ReactionScheme { layout, .. } => layout.clone().unwrap_or_default(),
1677            _ => panic!("expected reaction_scheme"),
1678        };
1679        assert_eq!(layout.direction_or_default(), LayoutDirection::Right);
1680        assert_eq!(layout.edge_routing_or_default(), EdgeRouting::Polyline);
1681        assert_eq!(layout.algorithm_or_default(), LayoutAlgorithm::Layered);
1682
1683        let custom: DepictSpec = serde_json::from_str(
1684            r#"{
1685              "type": "reaction_scheme",
1686              "layout": {
1687                "direction": "down",
1688                "edge_routing": "orthogonal",
1689                "algorithm": "force"
1690              },
1691              "children": [{"type":"mol","id":"a","smiles":"C"}]
1692            }"#,
1693        )
1694        .unwrap();
1695        let layout = match &custom {
1696            DepictSpec::ReactionScheme {
1697                layout: Some(l), ..
1698            } => l,
1699            _ => panic!("expected layout"),
1700        };
1701        assert_eq!(layout.direction, Some(LayoutDirection::Down));
1702        assert_eq!(layout.edge_routing, Some(EdgeRouting::Orthogonal));
1703        assert_eq!(layout.algorithm, Some(LayoutAlgorithm::Force));
1704    }
1705
1706    #[test]
1707    fn edge_routing_overrides_scheme_layout() {
1708        let spec: DepictSpec = serde_json::from_str(
1709            r#"{
1710              "type": "reaction_scheme",
1711              "layout": { "edge_routing": "polyline" },
1712              "children": [
1713                {"type": "mol", "id": "a", "smiles": "C"},
1714                {"type": "mol", "id": "b", "smiles": "CC"},
1715                {
1716                  "type": "edge",
1717                  "source": "a",
1718                  "target": "b",
1719                  "edge_routing": "orthogonal"
1720                },
1721                {
1722                  "type": "edge",
1723                  "source": "b",
1724                  "target": "a"
1725                }
1726              ]
1727            }"#,
1728        )
1729        .unwrap();
1730        let layout = match &spec {
1731            DepictSpec::ReactionScheme {
1732                layout: Some(l), ..
1733            } => l.clone(),
1734            _ => LayoutOpts::default(),
1735        };
1736        let edges = spec.edges();
1737        assert_eq!(edges[0].edge_routing, Some(EdgeRouting::Orthogonal));
1738        assert_eq!(edges[0].edge_routing_or(&layout), EdgeRouting::Orthogonal);
1739        assert_eq!(edges[1].edge_routing, None);
1740        assert_eq!(edges[1].edge_routing_or(&layout), EdgeRouting::Polyline);
1741    }
1742
1743    #[test]
1744    fn edge_multi_reactants_and_products() {
1745        let spec: DepictSpec = serde_json::from_str(
1746            r#"{
1747              "type": "reaction_scheme",
1748              "children": [
1749                {"type": "mol", "id": "a", "smiles": "C"},
1750                {"type": "mol", "id": "b", "smiles": "O"},
1751                {"type": "mol", "id": "c", "smiles": "CO"},
1752                {"type": "mol", "id": "d", "smiles": "O=O"},
1753                {
1754                  "type": "edge",
1755                  "sources": ["a", "b"],
1756                  "targets": ["c", "d"],
1757                  "arrow": "forward"
1758                }
1759              ]
1760            }"#,
1761        )
1762        .unwrap();
1763        let e = &spec.edges()[0];
1764        assert_eq!(e.sources.as_slice(), &["a".to_string(), "b".to_string()]);
1765        assert_eq!(e.targets.as_slice(), &["c".to_string(), "d".to_string()]);
1766        validate_edges(&spec).unwrap();
1767    }
1768
1769    #[test]
1770    fn cascade_reaction_scheme_typed_patch_does_not_paint_mol() {
1771        let spec: DepictSpec = serde_json::from_str(
1772            r##"{
1773              "type": "reaction_scheme",
1774              "opts": [
1775                {"type": "reaction_scheme", "color": "#ff0000"},
1776                {"type": "mol", "color": "#00ff00"}
1777              ],
1778              "children": [{"type": "mol", "id": "n", "smiles": "C"}]
1779            }"##,
1780        )
1781        .unwrap();
1782        let chrome = spec.resolve_mol_chrome(0);
1783        assert_eq!(chrome.color.as_deref(), Some("#00ff00"));
1784    }
1785}