Skip to main content

xpict_core/doc/
spec.rs

1//! Live document wire types — **collocated** so opts + nodes stay aligned.
2//!
3//! # Cascade model
4//!
5//! - [`Opts`] is a **list** (or singleton) of [`OptsPatch`] rules.
6//! - Patches are discriminated by document node `type` (`TypedOptsPatch`) or
7//!   multi-select via reserved meta key `for_types` ([`ForTypesPatch`]).
8//!   Omitting both = universal [`MolOpts`] (applies to every kind, including
9//!   mol-only keys like `weight` / `halo` / `shade`).
10//! - Meta keys (`type`, `for_types`) are selectors — not paint options.
11//! - Resolve: walk ancestors → node; apply matching patches in order; child
12//!   wins; nested objects (`shade`) deep-merge.
13//! - [`MolNode`] / [`DepictSpec`] **extend** paint opts with non-cascading
14//!   identity keys (`smiles`, `id`, `align_to`, shade **scores**, …). Local
15//!   flat `color` / `weight` / `scale` / `halo` / `aromatic` are the leaf’s
16//!   own opts (same fields as [`MolOpts`]) and merge last.
17
18use serde::{Deserialize, Serialize};
19
20#[cfg(feature = "codegen")]
21use schemars::JsonSchema;
22#[cfg(feature = "codegen")]
23use ts_rs::TS;
24
25use crate::doc::chrome::{
26    annotations_from_overlay, overlay_from_mol, Annotation, AtomLabelSpec, AtomNumberSpec,
27    CalloutField, CircleField, MolOverlayFields, MolText, RegionField,
28};
29use crate::edge::{AlignMode, AlignOpts};
30use crate::scene::AromaticStyle;
31
32// ---------------------------------------------------------------------------
33// Shade: scores (non-cascading, on mol) vs style window (cascading, in opts)
34// ---------------------------------------------------------------------------
35
36/// Cascading shade window / LUT (not per-atom scores).
37#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
38#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
39#[cfg_attr(feature = "codegen", ts(export))]
40pub struct ShadeStyle {
41    /// Named colormap. Only ``"xenosite"`` (default) is painted; any other
42    /// name is rejected at depict time (not silently ignored).
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    #[cfg_attr(feature = "codegen", ts(optional))]
45    pub colormap: Option<String>,
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    #[cfg_attr(feature = "codegen", ts(optional))]
48    pub vmin: Option<f64>,
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    #[cfg_attr(feature = "codegen", ts(optional))]
51    pub vmax: Option<f64>,
52}
53
54impl ShadeStyle {
55    pub fn merge_from(&mut self, other: &ShadeStyle) {
56        if other.colormap.is_some() {
57            self.colormap = other.colormap.clone();
58        }
59        if other.vmin.is_some() {
60            self.vmin = other.vmin;
61        }
62        if other.vmax.is_some() {
63            self.vmax = other.vmax;
64        }
65    }
66}
67
68/// Per-atom / per-bond colormap scores (+ legacy window fields on the mol).
69///
70/// Prefer putting `colormap` / `vmin` / `vmax` in cascading [`MolOpts::shade`];
71/// values here still apply as local leaf overrides for compat.
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
74#[cfg_attr(feature = "codegen", ts(export))]
75pub struct ShadeSpec {
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    #[cfg_attr(feature = "codegen", ts(optional))]
78    pub atoms: Option<Vec<f64>>,
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    #[cfg_attr(feature = "codegen", ts(optional))]
81    pub bonds: Option<Vec<f64>>,
82    /// Named colormap. Only ``"xenosite"`` (default) is painted; any other
83    /// name is rejected at depict time (not silently ignored).
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    #[cfg_attr(feature = "codegen", ts(optional))]
86    pub colormap: Option<String>,
87    #[serde(default = "default_shade_vmin")]
88    pub vmin: f64,
89    #[serde(default = "default_shade_vmax")]
90    pub vmax: f64,
91}
92
93fn default_shade_vmin() -> f64 {
94    0.0
95}
96fn default_shade_vmax() -> f64 {
97    1.0
98}
99
100impl Default for ShadeSpec {
101    fn default() -> Self {
102        Self {
103            atoms: None,
104            bonds: None,
105            colormap: None,
106            vmin: 0.0,
107            vmax: 1.0,
108        }
109    }
110}
111
112impl ShadeSpec {
113    /// Hoist legacy window fields into a cascading [`ShadeStyle`].
114    pub fn style(&self) -> ShadeStyle {
115        ShadeStyle {
116            colormap: self.colormap.clone(),
117            vmin: Some(self.vmin),
118            vmax: Some(self.vmax),
119        }
120    }
121}
122
123// ---------------------------------------------------------------------------
124// Align (non-cascading topology)
125// ---------------------------------------------------------------------------
126
127/// Object form of document ``align_to`` (template ref + EdgePlan-style opts).
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
129#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
130#[cfg_attr(feature = "codegen", ts(export))]
131pub struct AlignToSpec {
132    /// Id of the template mol in this group.
133    #[serde(rename = "ref")]
134    #[cfg_attr(feature = "codegen", ts(rename = "ref"))]
135    pub ref_id: String,
136    /// Pairs `(query, template)` vs the template; skips MCS when set.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    #[cfg_attr(feature = "codegen", ts(optional))]
139    pub atom_map: Option<Vec<(u32, u32)>>,
140    /// Override [`crate::edge::MIN_MCS_ATOMS`] when set.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    #[cfg_attr(feature = "codegen", ts(optional))]
143    pub min_atoms: Option<u32>,
144    /// `exact` (default) / `greedy` / `skip`. Omit = exact with house timeout.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    #[cfg_attr(feature = "codegen", ts(optional))]
147    pub mode: Option<AlignMode>,
148    /// MCS budget in milliseconds. `None` = house 100 ms; `0` = unbounded.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    #[cfg_attr(feature = "codegen", ts(optional))]
151    pub timeout_ms: Option<u32>,
152}
153
154/// Document align target: id string or `{ "ref", "atom_map"?, "min_atoms"?, "mode"?, "timeout_ms"? }`.
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156#[serde(untagged)]
157#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
158#[cfg_attr(feature = "codegen", ts(export))]
159pub enum AlignTo {
160    /// Shorthand for `{ "ref": "…" }`.
161    Ref(String),
162    Spec(AlignToSpec),
163}
164
165impl AlignTo {
166    pub fn ref_id(&self) -> &str {
167        match self {
168            AlignTo::Ref(s) => s.as_str(),
169            AlignTo::Spec(s) => s.ref_id.as_str(),
170        }
171    }
172
173    pub fn align_opts(&self) -> AlignOpts {
174        match self {
175            AlignTo::Ref(_) => AlignOpts::default(),
176            AlignTo::Spec(s) => AlignOpts {
177                atom_map: s.atom_map.clone(),
178                min_atoms: s.min_atoms,
179                mode: s.mode,
180                timeout_ms: s.timeout_ms,
181            },
182        }
183    }
184}
185
186// ---------------------------------------------------------------------------
187// Cascading opts — list of patches; `type` / `for_types` are meta selectors
188// ---------------------------------------------------------------------------
189
190/// Document node kinds opts may target (matches wire `"type"` discriminants).
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
192#[serde(rename_all = "snake_case")]
193#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
194#[cfg_attr(feature = "codegen", ts(export))]
195pub enum NodeType {
196    Mol,
197    Group,
198    /// Multi-mol scheme with edge nodes in `children` (`"type": "reaction_scheme"`).
199    ReactionScheme,
200    /// Edge / reaction link node (`"type": "edge"`).
201    Edge,
202    /// Text caption / chrome node (`"type": "text"`).
203    Text,
204}
205
206impl NodeType {
207    pub fn as_str(self) -> &'static str {
208        match self {
209            NodeType::Mol => "mol",
210            NodeType::Group => "group",
211            NodeType::ReactionScheme => "reaction_scheme",
212            NodeType::Edge => "edge",
213            NodeType::Text => "text",
214        }
215    }
216}
217
218/// Universal cascading keys (any node kind).
219#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
220#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
221#[cfg_attr(feature = "codegen", ts(export))]
222pub struct CommonOpts {
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    #[cfg_attr(feature = "codegen", ts(optional))]
225    pub color: Option<String>,
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    #[cfg_attr(feature = "codegen", ts(optional))]
228    pub scale: Option<f64>,
229    /// Aromatic ring paint: ``circle`` (default) or ``kekule``.
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    #[cfg_attr(feature = "codegen", ts(optional))]
232    pub aromatic: Option<AromaticStyle>,
233    /// Paint dashed debug rectangles for layout boxes (labels / mol / scene).
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    #[cfg_attr(feature = "codegen", ts(optional))]
236    pub debug_box: Option<bool>,
237    /// Paint alignment correspondence (matched atom tags + mol role badge).
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    #[cfg_attr(feature = "codegen", ts(optional))]
240    pub debug_align: Option<bool>,
241    /// Post-layout SVG viewBox pad (px). Omit → small house default (rarely override).
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    #[cfg_attr(feature = "codegen", ts(optional))]
244    pub pad: Option<f64>,
245}
246
247/// Copy each ``Option`` field from ``$src`` onto ``$dst`` when ``Some``.
248/// Keep the field list next to the struct when adding a cascading opt.
249macro_rules! merge_opt_fields {
250    ($dst:expr, $src:expr, $($field:ident),+ $(,)?) => {
251        $(
252            if $src.$field.is_some() {
253                $dst.$field = $src.$field.clone();
254            }
255        )+
256    };
257}
258
259impl CommonOpts {
260    pub fn merge_from(&mut self, other: &CommonOpts) {
261        merge_opt_fields!(
262            self,
263            other,
264            color,
265            scale,
266            aromatic,
267            debug_box,
268            debug_align,
269            pad
270        );
271    }
272}
273
274/// Mol cascading paint opts — what a mol leaf consumes from the cascade.
275///
276/// [`MolNode`] carries the same fields at the top level (local leaf opts) plus
277/// non-cascading identity keys.
278#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
279#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
280#[cfg_attr(feature = "codegen", ts(export))]
281pub struct MolOpts {
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    #[cfg_attr(feature = "codegen", ts(optional))]
284    pub color: Option<String>,
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    #[cfg_attr(feature = "codegen", ts(optional))]
287    pub scale: Option<f64>,
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    #[cfg_attr(feature = "codegen", ts(optional))]
290    pub weight: Option<f64>,
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    #[cfg_attr(feature = "codegen", ts(optional))]
293    pub halo: Option<bool>,
294    #[serde(default, skip_serializing_if = "Option::is_none")]
295    #[cfg_attr(feature = "codegen", ts(optional))]
296    pub shade: Option<ShadeStyle>,
297    /// Aromatic ring paint: ``circle`` (default) or ``kekule``.
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    #[cfg_attr(feature = "codegen", ts(optional))]
300    pub aromatic: Option<AromaticStyle>,
301    /// Paint dashed debug rectangles for layout boxes (labels / mol / scene).
302    #[serde(default, skip_serializing_if = "Option::is_none")]
303    #[cfg_attr(feature = "codegen", ts(optional))]
304    pub debug_box: Option<bool>,
305    /// Paint alignment correspondence (matched atom tags + mol role badge).
306    #[serde(default, skip_serializing_if = "Option::is_none")]
307    #[cfg_attr(feature = "codegen", ts(optional))]
308    pub debug_align: Option<bool>,
309    /// Post-layout SVG viewBox pad (px). Omit → small house default (rarely override).
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    #[cfg_attr(feature = "codegen", ts(optional))]
312    pub pad: Option<f64>,
313}
314
315impl MolOpts {
316    pub fn merge_from(&mut self, other: &MolOpts) {
317        merge_opt_fields!(
318            self,
319            other,
320            color,
321            scale,
322            weight,
323            halo,
324            aromatic,
325            debug_box,
326            debug_align,
327            pad
328        );
329        if let Some(ref s) = other.shade {
330            self.shade
331                .get_or_insert_with(ShadeStyle::default)
332                .merge_from(s);
333        }
334    }
335
336    pub fn merge_common(&mut self, common: &CommonOpts) {
337        // Same keys as ``CommonOpts`` — update with that struct.
338        merge_opt_fields!(
339            self,
340            common,
341            color,
342            scale,
343            aromatic,
344            debug_box,
345            debug_align,
346            pad
347        );
348    }
349}
350
351/// Discriminated opts patch: `{ "type": "mol"|"group"|"reaction_scheme"|"edge"|"text", …opts }`.
352#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
353#[serde(tag = "type", rename_all = "snake_case")]
354#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
355#[cfg_attr(feature = "codegen", ts(export))]
356pub enum TypedOptsPatch {
357    Mol {
358        #[serde(flatten)]
359        opts: MolOpts,
360    },
361    Group {
362        #[serde(flatten)]
363        opts: CommonOpts,
364    },
365    ReactionScheme {
366        #[serde(flatten)]
367        opts: CommonOpts,
368    },
369    Edge {
370        #[serde(flatten)]
371        opts: CommonOpts,
372    },
373    Text {
374        #[serde(flatten)]
375        opts: CommonOpts,
376    },
377}
378
379/// Multi-kind patch: `{ "for_types": ["mol","group"], …mol opts }`.
380///
381/// Carries full [`MolOpts`] so mol-only keys (`weight` / `halo` / `shade`) can
382/// target mols via `for_types` without a separate typed mol patch.
383#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
384#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
385#[cfg_attr(feature = "codegen", ts(export))]
386pub struct ForTypesPatch {
387    pub for_types: Vec<NodeType>,
388    #[serde(flatten)]
389    pub opts: MolOpts,
390}
391
392/// One cascade rule. Untagged order: typed → for_types → universal.
393#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
394#[serde(untagged)]
395#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
396#[cfg_attr(feature = "codegen", ts(export))]
397pub enum OptsPatch {
398    /// `{ "type": "mol", "weight": 1.2 }` — discriminated kind.
399    Typed(TypedOptsPatch),
400    /// `{ "for_types": ["mol","group"], "color": "#111" }`.
401    ForTypes(ForTypesPatch),
402    /// `{ "color": "#111", "weight": 1.2 }` — applies to every kind ([`MolOpts`]).
403    ///
404    /// Universal is [`MolOpts`] (not [`CommonOpts`]) so container bags can stamp
405    /// mol-only keys without wrapping `{ "type": "mol", … }`.
406    Universal(MolOpts),
407}
408
409impl OptsPatch {
410    /// Whether this patch applies when resolving for `target`.
411    pub fn applies_to(&self, target: NodeType) -> bool {
412        match self {
413            OptsPatch::Typed(TypedOptsPatch::Mol { .. }) => target == NodeType::Mol,
414            OptsPatch::Typed(TypedOptsPatch::Group { .. }) => target == NodeType::Group,
415            OptsPatch::Typed(TypedOptsPatch::ReactionScheme { .. }) => {
416                target == NodeType::ReactionScheme
417            }
418            OptsPatch::Typed(TypedOptsPatch::Edge { .. }) => target == NodeType::Edge,
419            OptsPatch::Typed(TypedOptsPatch::Text { .. }) => target == NodeType::Text,
420            OptsPatch::ForTypes(p) => p.for_types.contains(&target),
421            OptsPatch::Universal(_) => true,
422        }
423    }
424
425    pub fn apply_to_mol(&self, out: &mut MolOpts) {
426        match self {
427            OptsPatch::Typed(TypedOptsPatch::Mol { opts }) => out.merge_from(opts),
428            OptsPatch::Typed(TypedOptsPatch::Group { .. }) => {}
429            OptsPatch::Typed(TypedOptsPatch::ReactionScheme { .. }) => {}
430            OptsPatch::Typed(TypedOptsPatch::Edge { .. }) => {}
431            OptsPatch::Typed(TypedOptsPatch::Text { .. }) => {}
432            OptsPatch::ForTypes(p) => out.merge_from(&p.opts),
433            OptsPatch::Universal(m) => out.merge_from(m),
434        }
435    }
436}
437
438/// Cascade bag: singleton patch or list of patches.
439#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
440#[serde(untagged)]
441#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
442#[cfg_attr(feature = "codegen", ts(export))]
443pub enum Opts {
444    One(OptsPatch),
445    Many(Vec<OptsPatch>),
446}
447
448impl Opts {
449    pub fn patches(&self) -> Vec<&OptsPatch> {
450        match self {
451            Opts::One(p) => vec![p],
452            Opts::Many(ps) => ps.iter().collect(),
453        }
454    }
455
456    pub fn apply_to_mol(&self, out: &mut MolOpts) {
457        for p in self.patches() {
458            if p.applies_to(NodeType::Mol) {
459                p.apply_to_mol(out);
460            }
461        }
462    }
463}
464
465/// Apply a chain of opts bags (ancestor → … → leaf) for a mol.
466pub fn resolve_mol_opts<'a, I>(bags: I) -> MolOpts
467where
468    I: IntoIterator<Item = Option<&'a Opts>>,
469{
470    let mut out = MolOpts::default();
471    for bag in bags {
472        if let Some(opts) = bag {
473            opts.apply_to_mol(&mut out);
474        }
475    }
476    out
477}
478
479// ---------------------------------------------------------------------------
480// Nodes — extend opts with non-cascading identity / topology keys
481// ---------------------------------------------------------------------------
482
483/// Discriminator for mol nodes (`"type": "mol"`).
484#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
485#[serde(rename_all = "lowercase")]
486#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
487#[cfg_attr(feature = "codegen", ts(export))]
488pub enum MolNodeKind {
489    #[default]
490    Mol,
491}
492
493/// Mol node — [`MolOpts`] fields + non-cascading identity / scores / align.
494#[derive(Debug, Clone, Default, Serialize, Deserialize)]
495#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
496#[cfg_attr(feature = "codegen", ts(export))]
497pub struct MolNode {
498    #[serde(rename = "type", default)]
499    pub type_: MolNodeKind,
500    // --- non-cascading identity / topology ---
501    #[serde(default, skip_serializing_if = "Option::is_none")]
502    #[cfg_attr(feature = "codegen", ts(optional))]
503    pub smiles: Option<String>,
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    #[cfg_attr(feature = "codegen", ts(optional))]
506    pub cxsmiles: Option<String>,
507    #[serde(default, skip_serializing_if = "Option::is_none")]
508    #[cfg_attr(feature = "codegen", ts(optional))]
509    pub molfile: Option<String>,
510    #[serde(default, skip_serializing_if = "Option::is_none")]
511    #[cfg_attr(feature = "codegen", ts(optional))]
512    pub id: Option<String>,
513    /// Shade **scores** (+ legacy window); window also cascades via [`Opts`].
514    #[serde(default, skip_serializing_if = "Option::is_none")]
515    #[cfg_attr(feature = "codegen", ts(optional))]
516    pub shade: Option<ShadeSpec>,
517    #[serde(default, skip_serializing_if = "Option::is_none")]
518    #[cfg_attr(feature = "codegen", ts(optional))]
519    pub star_labels: Option<Vec<Option<String>>>,
520    /// Template id string, or `{ "ref", "atom_map"?, "min_atoms"?, "mode"?, "timeout_ms"? }`.
521    #[serde(default, skip_serializing_if = "Option::is_none")]
522    #[cfg_attr(feature = "codegen", ts(optional))]
523    pub align_to: Option<AlignTo>,
524    /// Caption: [`Label`] (string id, list, or `{id, pos?}` — text-node refs).
525    ///
526    /// Prefer privileged [`Self::name`] for inline mol captions. `label` id-refs
527    /// remain for legacy / multi-caption layouts.
528    ///
529    /// `pos` on a placement chooses caption side (`above`/`below`/`left`/`right`);
530    /// hosts measure the resolved text and fold that into node size for layout.
531    #[serde(default, skip_serializing_if = "Option::is_none")]
532    #[cfg_attr(feature = "codegen", ts(optional))]
533    pub label: Option<Label>,
534    /// Privileged figure name / caption painted inside the mol SVG (default below).
535    #[serde(default, skip_serializing_if = "Option::is_none")]
536    #[cfg_attr(feature = "codegen", ts(optional))]
537    pub name: Option<MolText>,
538    /// Atom index / map-number labels (`"index"` | `"mapno"` | policy object).
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    #[cfg_attr(feature = "codegen", ts(optional))]
541    pub atom_number: Option<AtomNumberSpec>,
542    /// Per-atom arbitrary text map (`{ "1": "α" }` or `{ "labels": {…}, "scale"? }`).
543    #[serde(default, skip_serializing_if = "Option::is_none")]
544    #[cfg_attr(feature = "codegen", ts(optional))]
545    pub atom_label: Option<AtomLabelSpec>,
546    /// Region highlight(s) — one object or a list.
547    #[serde(default, skip_serializing_if = "Option::is_none")]
548    #[cfg_attr(feature = "codegen", ts(optional))]
549    pub region: Option<RegionField>,
550    /// Atom / bond / ring highlight circle(s).
551    #[serde(default, skip_serializing_if = "Option::is_none")]
552    #[cfg_attr(feature = "codegen", ts(optional))]
553    pub circle: Option<CircleField>,
554    /// Callout annotation(s).
555    #[serde(default, skip_serializing_if = "Option::is_none")]
556    #[cfg_attr(feature = "codegen", ts(optional))]
557    pub callout: Option<CalloutField>,
558    // --- local leaf opts (same keys as MolOpts; merge last) ---
559    #[serde(default, skip_serializing_if = "Option::is_none")]
560    #[cfg_attr(feature = "codegen", ts(optional))]
561    pub color: Option<String>,
562    #[serde(default, skip_serializing_if = "Option::is_none")]
563    #[cfg_attr(feature = "codegen", ts(optional))]
564    pub scale: Option<f64>,
565    #[serde(default, skip_serializing_if = "Option::is_none")]
566    #[cfg_attr(feature = "codegen", ts(optional))]
567    pub weight: Option<f64>,
568    #[serde(default, skip_serializing_if = "Option::is_none")]
569    #[cfg_attr(feature = "codegen", ts(optional))]
570    pub halo: Option<bool>,
571    /// Aromatic ring paint: ``circle`` (default) or ``kekule``.
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    #[cfg_attr(feature = "codegen", ts(optional))]
574    pub aromatic: Option<AromaticStyle>,
575    /// Paint dashed debug rectangles for layout boxes (labels / mol / scene).
576    #[serde(default, skip_serializing_if = "Option::is_none")]
577    #[cfg_attr(feature = "codegen", ts(optional))]
578    pub debug_box: Option<bool>,
579    /// Paint alignment correspondence (matched atom tags + mol role badge).
580    #[serde(default, skip_serializing_if = "Option::is_none")]
581    #[cfg_attr(feature = "codegen", ts(optional))]
582    pub debug_align: Option<bool>,
583    /// Post-layout SVG viewBox pad (px). Omit → small house default (rarely override).
584    #[serde(default, skip_serializing_if = "Option::is_none")]
585    #[cfg_attr(feature = "codegen", ts(optional))]
586    pub pad: Option<f64>,
587    /// Cascade patches for this node (list or singleton).
588    #[serde(default, skip_serializing_if = "Option::is_none")]
589    #[cfg_attr(feature = "codegen", ts(optional))]
590    pub opts: Option<Opts>,
591}
592
593impl MolNode {
594    /// Local leaf opts from flat fields (+ legacy shade window).
595    pub fn local_opts(&self) -> MolOpts {
596        let mut o = MolOpts {
597            color: self.color.clone(),
598            scale: self.scale,
599            weight: self.weight,
600            halo: self.halo,
601            shade: None,
602            aromatic: self.aromatic,
603            debug_box: self.debug_box,
604            debug_align: self.debug_align,
605            pad: self.pad,
606        };
607        if let Some(ref shade) = self.shade {
608            o.shade = Some(shade.style());
609        }
610        o
611    }
612
613    pub fn structure(&self) -> Result<&str, String> {
614        for s in [&self.molfile, &self.cxsmiles, &self.smiles] {
615            if let Some(t) = s.as_ref().filter(|x| !x.trim().is_empty()) {
616                return Ok(t.as_str());
617            }
618        }
619        Err("mol node needs smiles, cxsmiles, or molfile".into())
620    }
621
622    /// Wire overlay bag (excludes privileged [`Self::name`]).
623    pub fn overlay_fields(&self) -> MolOverlayFields {
624        overlay_from_mol(
625            &self.shade,
626            &self.atom_number,
627            &self.atom_label,
628            &self.region,
629            &self.circle,
630            &self.callout,
631        )
632    }
633
634    /// Internal Annotation IR for paint / occupancy (sorted by z).
635    pub fn annotations(&self) -> Vec<Annotation> {
636        annotations_from_overlay(&self.overlay_fields())
637    }
638}
639
640// ---------------------------------------------------------------------------
641// Edges / nodes — reaction links are edge nodes in `children`
642// ---------------------------------------------------------------------------
643
644/// Arrow head / shaft style for diagram edges.
645#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
646#[serde(rename_all = "snake_case")]
647#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
648#[cfg_attr(feature = "codegen", ts(export))]
649pub enum EdgeArrow {
650    /// Single →
651    #[default]
652    Forward,
653    /// ⇌ stacked half-arrows
654    Equilibrium,
655    /// ⇒ hollow head (retrosynthetic-style)
656    Open,
657    /// Connector without arrowhead
658    Line,
659}
660
661/// Discriminator for edge nodes (`"type": "edge"`).
662#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
663#[serde(rename_all = "snake_case")]
664#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
665#[cfg_attr(feature = "codegen", ts(export))]
666pub enum EdgeNodeKind {
667    #[default]
668    Edge,
669}
670
671/// Discriminator for text nodes (`"type": "text"`).
672#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
673#[serde(rename_all = "snake_case")]
674#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
675#[cfg_attr(feature = "codegen", ts(export))]
676pub enum TextNodeKind {
677    #[default]
678    Text,
679}
680
681/// Text **node** — caption / chrome referenced by mols and edges via id.
682///
683/// ```json
684/// { "type": "text", "id": "adh", "text": "ADH" }
685/// ```
686#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
687#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
688#[cfg_attr(feature = "codegen", ts(export))]
689pub struct TextNode {
690    #[serde(rename = "type")]
691    #[cfg_attr(feature = "codegen", ts(rename = "type"))]
692    pub type_: TextNodeKind,
693    /// Stable id — required when other nodes [`MolNode::label`] / edge lanes ref it.
694    #[serde(default, skip_serializing_if = "Option::is_none")]
695    #[cfg_attr(feature = "codegen", ts(optional))]
696    pub id: Option<String>,
697    /// Display text (markup-capable later).
698    pub text: String,
699    #[serde(default, skip_serializing_if = "Option::is_none")]
700    #[cfg_attr(feature = "codegen", ts(optional))]
701    pub color: Option<String>,
702    #[serde(default, skip_serializing_if = "Option::is_none")]
703    #[cfg_attr(feature = "codegen", ts(optional))]
704    pub scale: Option<f64>,
705    #[serde(default, skip_serializing_if = "Option::is_none")]
706    #[cfg_attr(feature = "codegen", ts(optional))]
707    pub opts: Option<Opts>,
708}
709
710/// Side of an edge shaft (or mol caption) for a label placement.
711#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
712#[serde(rename_all = "snake_case")]
713#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
714#[cfg_attr(feature = "codegen", ts(export))]
715pub enum LabelPos {
716    #[default]
717    Above,
718    Below,
719    Left,
720    Right,
721}
722
723/// Placed label: `{ "id": "adh", "pos": "below" }` (`pos` optional → above).
724#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
725#[serde(deny_unknown_fields)]
726#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
727#[cfg_attr(feature = "codegen", ts(export))]
728pub struct LabelPlacement {
729    /// Id of a [`TextNode`] or (on edges) [`MolNode`].
730    pub id: String,
731    #[serde(default, skip_serializing_if = "Option::is_none")]
732    #[cfg_attr(feature = "codegen", ts(optional))]
733    pub pos: Option<LabelPos>,
734}
735
736impl LabelPlacement {
737    pub fn pos_or_default(&self) -> LabelPos {
738        self.pos.unwrap_or(LabelPos::Above)
739    }
740}
741
742/// One entry in a label list: bare id or `{ id, pos? }`.
743#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
744#[serde(untagged)]
745#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
746#[cfg_attr(feature = "codegen", ts(export))]
747pub enum LabelItem {
748    Id(String),
749    Placed(LabelPlacement),
750}
751
752impl LabelItem {
753    pub fn id(&self) -> &str {
754        match self {
755            LabelItem::Id(s) => s.as_str(),
756            LabelItem::Placed(p) => p.id.as_str(),
757        }
758    }
759
760    pub fn pos(&self) -> LabelPos {
761        match self {
762            LabelItem::Id(_) => LabelPos::Above,
763            LabelItem::Placed(p) => p.pos_or_default(),
764        }
765    }
766}
767
768/// Lane bag: `{ "above": [...], "below": [...], "left": [...], "right": [...] }`.
769#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
770#[serde(deny_unknown_fields)]
771#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
772#[cfg_attr(feature = "codegen", ts(export))]
773pub struct LabelLanes {
774    #[serde(default, skip_serializing_if = "Vec::is_empty")]
775    pub above: Vec<String>,
776    #[serde(default, skip_serializing_if = "Vec::is_empty")]
777    pub below: Vec<String>,
778    #[serde(default, skip_serializing_if = "Vec::is_empty")]
779    pub left: Vec<String>,
780    #[serde(default, skip_serializing_if = "Vec::is_empty")]
781    pub right: Vec<String>,
782}
783
784/// Unified label: string id, list, placed object, or lane object.
785///
786/// ```json
787/// "label": "adh"
788/// "label": ["adh", {"id": "rt", "pos": "below"}]
789/// "label": { "id": "adh", "pos": "left" }
790/// "label": { "above": ["adh"], "below": ["rt"], "left": ["nabh4"] }
791/// ```
792#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
793#[serde(untagged)]
794#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
795#[cfg_attr(feature = "codegen", ts(export))]
796pub enum Label {
797    /// Bare node id (default position: above).
798    Id(String),
799    /// Ordered list of ids / placements.
800    Items(Vec<LabelItem>),
801    /// Single placement with optional `pos`.
802    Placed(LabelPlacement),
803    /// Explicit above / below / left / right id lists.
804    Lanes(LabelLanes),
805}
806
807impl Label {
808    /// Flatten to `(id, pos)` pairs in document order.
809    pub fn placements(&self) -> Vec<(String, LabelPos)> {
810        match self {
811            Label::Id(id) => vec![(id.clone(), LabelPos::Above)],
812            Label::Items(items) => items
813                .iter()
814                .map(|it| (it.id().to_string(), it.pos()))
815                .collect(),
816            Label::Placed(p) => vec![(p.id.clone(), p.pos_or_default())],
817            Label::Lanes(lanes) => {
818                let mut out = Vec::new();
819                for id in &lanes.above {
820                    out.push((id.clone(), LabelPos::Above));
821                }
822                for id in &lanes.below {
823                    out.push((id.clone(), LabelPos::Below));
824                }
825                for id in &lanes.left {
826                    out.push((id.clone(), LabelPos::Left));
827                }
828                for id in &lanes.right {
829                    out.push((id.clone(), LabelPos::Right));
830                }
831                out
832            }
833        }
834    }
835}
836
837/// One or more mol ids (reactants / products).
838///
839/// Wire: `"a"` or `["a", "b"]` — reactions may have multiple reactants and products.
840#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
841#[serde(untagged)]
842#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
843#[cfg_attr(feature = "codegen", ts(export))]
844pub enum MolIds {
845    One(String),
846    Many(Vec<String>),
847}
848
849impl MolIds {
850    pub fn as_slice(&self) -> &[String] {
851        match self {
852            MolIds::One(s) => std::slice::from_ref(s),
853            MolIds::Many(v) => v.as_slice(),
854        }
855    }
856
857    pub fn iter(&self) -> impl Iterator<Item = &str> {
858        self.as_slice().iter().map(String::as_str)
859    }
860
861    pub fn is_empty(&self) -> bool {
862        match self {
863            MolIds::One(s) => s.trim().is_empty(),
864            MolIds::Many(v) => v.is_empty() || v.iter().all(|s| s.trim().is_empty()),
865        }
866    }
867
868    pub fn len(&self) -> usize {
869        self.as_slice().len()
870    }
871}
872
873/// Edge **node** — a reaction / network link between mol ids.
874///
875/// [`Self::sources`] / [`Self::targets`] are one or many mol ids (A+B → C+D).
876/// Label chrome refs sibling text/mol nodes via [`Self::label`].
877#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
878#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
879#[cfg_attr(feature = "codegen", ts(export))]
880pub struct EdgeNode {
881    /// Wire discriminant — required so untagged [`Node`] does not absorb edges as mols.
882    #[serde(rename = "type")]
883    #[cfg_attr(feature = "codegen", ts(rename = "type"))]
884    pub type_: EdgeNodeKind,
885    /// Reactant mol id(s) — `"a"` or `["a","b"]` (alias: `source`).
886    #[serde(alias = "source")]
887    pub sources: MolIds,
888    /// Product mol id(s) — `"c"` or `["c","d"]` (alias: `target`).
889    #[serde(alias = "target")]
890    pub targets: MolIds,
891    /// Label chrome: id / list / `{id, pos?}` / `{above,below,left,right}`.
892    ///
893    /// Hosts should measure each placement’s text (or mol viewport) and pass
894    /// those boxes to the layout engine with the placement `pos` (edge side).
895    #[serde(default, skip_serializing_if = "Option::is_none")]
896    #[cfg_attr(feature = "codegen", ts(optional))]
897    pub label: Option<Label>,
898    /// Per-edge override of scheme [`LayoutOpts::edge_routing`].
899    #[serde(default, skip_serializing_if = "Option::is_none")]
900    #[cfg_attr(feature = "codegen", ts(optional))]
901    pub edge_routing: Option<EdgeRouting>,
902    /// Optional semantic role (e.g. enzyme) — not drawn by default.
903    #[serde(default, skip_serializing_if = "Option::is_none")]
904    #[cfg_attr(feature = "codegen", ts(optional))]
905    pub role: Option<String>,
906    #[serde(default)]
907    pub arrow: EdgeArrow,
908    #[serde(default, skip_serializing_if = "Option::is_none")]
909    #[cfg_attr(feature = "codegen", ts(optional))]
910    pub color: Option<String>,
911    #[serde(default, skip_serializing_if = "Option::is_none")]
912    #[cfg_attr(feature = "codegen", ts(optional))]
913    pub stroke_width: Option<f64>,
914    #[serde(default)]
915    pub dashed: bool,
916}
917
918impl EdgeNode {
919    /// Effective shaft routing: edge override, else scheme layout default.
920    pub fn edge_routing_or(&self, scheme: &LayoutOpts) -> EdgeRouting {
921        self.edge_routing
922            .unwrap_or_else(|| scheme.edge_routing_or_default())
923    }
924}
925
926/// Document **node**: mol, edge, or text.
927///
928/// Untagged so each variant keeps its own `"type"` field.
929/// - [`DepictSpec::Group`]: mol | text (no edges).
930/// - [`DepictSpec::ReactionScheme`]: mol | edge | text.
931#[derive(Debug, Clone, Serialize, Deserialize)]
932#[serde(untagged)]
933#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
934#[cfg_attr(feature = "codegen", ts(export))]
935pub enum Node {
936    Mol(MolNode),
937    Edge(EdgeNode),
938    Text(TextNode),
939}
940
941impl Node {
942    pub fn as_mol(&self) -> Option<&MolNode> {
943        match self {
944            Node::Mol(m) => Some(m),
945            _ => None,
946        }
947    }
948
949    pub fn as_edge(&self) -> Option<&EdgeNode> {
950        match self {
951            Node::Edge(e) => Some(e),
952            _ => None,
953        }
954    }
955
956    pub fn as_text(&self) -> Option<&TextNode> {
957        match self {
958            Node::Text(t) => Some(t),
959            _ => None,
960        }
961    }
962
963    /// Stable id when present (mol / text); edges have no id.
964    pub fn id(&self) -> Option<&str> {
965        match self {
966            Node::Mol(m) => m.id.as_deref().map(str::trim).filter(|s| !s.is_empty()),
967            Node::Text(t) => t.id.as_deref().map(str::trim).filter(|s| !s.is_empty()),
968            Node::Edge(_) => None,
969        }
970    }
971}
972
973// ---------------------------------------------------------------------------
974// Layout — reaction_scheme (backend-agnostic)
975// ---------------------------------------------------------------------------
976
977/// Flow axis for scheme layout.
978#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
979#[serde(rename_all = "snake_case")]
980#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
981#[cfg_attr(feature = "codegen", ts(export))]
982pub enum LayoutDirection {
983    #[default]
984    Right,
985    Left,
986    Up,
987    Down,
988}
989
990/// How edge shafts are drawn between nodes.
991#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
992#[serde(rename_all = "snake_case")]
993#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
994#[cfg_attr(feature = "codegen", ts(export))]
995pub enum EdgeRouting {
996    Orthogonal,
997    #[default]
998    Polyline,
999    Splines,
1000}
1001
1002/// Placement algorithm for scheme layout.
1003///
1004/// Hosts map these onto ELK (or another engine):
1005/// - [`Self::Layered`] — Sugiyama / layered (default; best for reactions)
1006/// - [`Self::Radial`] — hub-and-spoke / concentric rings (star-like nets)
1007/// - [`Self::Force`] — force-directed (undirected / cyclic networks)
1008/// - [`Self::Stress`] — stress majorization (compact network alternative)
1009#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1010#[serde(rename_all = "snake_case")]
1011#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
1012#[cfg_attr(feature = "codegen", ts(export))]
1013pub enum LayoutAlgorithm {
1014    #[default]
1015    Layered,
1016    Radial,
1017    Force,
1018    Stress,
1019}
1020
1021/// Layout for [`DepictSpec::ReactionScheme`].
1022///
1023/// Backend-agnostic knobs — hosts map these onto ELK, Dagre, or another engine.
1024/// Defaults when omitted: [`LayoutDirection::Right`], [`EdgeRouting::Polyline`],
1025/// [`LayoutAlgorithm::Layered`].
1026/// Individual [`EdgeNode`]s may override [`Self::edge_routing`].
1027///
1028/// Spacing (px, document space) controls packing tightness:
1029/// - [`Self::node_spacing`] — gap between nodes in the same layer (default ~20)
1030/// - [`Self::layer_spacing`] — gap between reactant/product layers (default ~0)
1031#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1032#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
1033#[cfg_attr(feature = "codegen", ts(export))]
1034pub struct LayoutOpts {
1035    /// Placement algorithm (`layered` / `radial` / `force` / `stress`).
1036    #[serde(default, skip_serializing_if = "Option::is_none")]
1037    #[cfg_attr(feature = "codegen", ts(optional))]
1038    pub algorithm: Option<LayoutAlgorithm>,
1039    /// Flow axis (`right` / `left` / `up` / `down`).
1040    #[serde(default, skip_serializing_if = "Option::is_none")]
1041    #[cfg_attr(feature = "codegen", ts(optional))]
1042    pub direction: Option<LayoutDirection>,
1043    /// Shaft style (`polyline` / `orthogonal` / `splines`).
1044    #[serde(default, skip_serializing_if = "Option::is_none")]
1045    #[cfg_attr(feature = "codegen", ts(optional))]
1046    pub edge_routing: Option<EdgeRouting>,
1047    /// Within-layer node gap (px). Smaller → tighter pack.
1048    #[serde(default, skip_serializing_if = "Option::is_none")]
1049    #[cfg_attr(feature = "codegen", ts(optional))]
1050    pub node_spacing: Option<f64>,
1051    /// Between-layer gap along the flow axis (px). Smaller → tighter pack.
1052    #[serde(default, skip_serializing_if = "Option::is_none")]
1053    #[cfg_attr(feature = "codegen", ts(optional))]
1054    pub layer_spacing: Option<f64>,
1055    /// After ELK, refine edge routes and labels with the constraint solver.
1056    /// Omit or `true` → refine on; `false` → stock ELK placement.
1057    #[serde(default, skip_serializing_if = "Option::is_none")]
1058    #[cfg_attr(feature = "codegen", ts(optional))]
1059    pub refine: Option<bool>,
1060}
1061
1062impl LayoutOpts {
1063    /// Default within-layer gap for reaction schemes (px).
1064    pub const DEFAULT_NODE_SPACING: f64 = 20.0;
1065    /// Default between-layer gap for reaction schemes (px).
1066    pub const DEFAULT_LAYER_SPACING: f64 = 0.0;
1067
1068    pub fn algorithm_or_default(&self) -> LayoutAlgorithm {
1069        self.algorithm.unwrap_or_default()
1070    }
1071
1072    pub fn direction_or_default(&self) -> LayoutDirection {
1073        self.direction.unwrap_or_default()
1074    }
1075
1076    pub fn edge_routing_or_default(&self) -> EdgeRouting {
1077        self.edge_routing.unwrap_or_default()
1078    }
1079
1080    pub fn node_spacing_or_default(&self) -> f64 {
1081        self.node_spacing.unwrap_or(Self::DEFAULT_NODE_SPACING)
1082    }
1083
1084    pub fn layer_spacing_or_default(&self) -> f64 {
1085        self.layer_spacing.unwrap_or(Self::DEFAULT_LAYER_SPACING)
1086    }
1087
1088    /// Energy-refine edges after ELK unless the host opted out.
1089    pub fn refine_enabled(&self) -> bool {
1090        self.refine != Some(false)
1091    }
1092}
1093
1094/// One ancestor container’s contribution to the opts cascade (outer → inner).
1095#[derive(Debug, Clone)]
1096struct CascadeLayer {
1097    opts: Option<Opts>,
1098    common: CommonOpts,
1099}
1100
1101/// Declarative document (`mol`, `group`, `reaction_scheme`, or `grid` root).
1102///
1103/// A root mol **is** [`MolNode`] — the same type as scheme / group children, so
1104/// annotations (`region`, `circle`, `callout`, `atom_label`, `atom_number`,
1105/// `name`, `shade`, …) are one schema everywhere.
1106#[derive(Debug, Clone, Serialize, Deserialize)]
1107#[serde(tag = "type", rename_all = "snake_case")]
1108#[cfg_attr(feature = "codegen", derive(JsonSchema, TS))]
1109#[cfg_attr(feature = "codegen", ts(export))]
1110pub enum DepictSpec {
1111    Mol(MolNode),
1112    Group {
1113        #[serde(default, skip_serializing_if = "Option::is_none")]
1114        #[cfg_attr(feature = "codegen", ts(optional))]
1115        id: Option<String>,
1116        /// When true, later children align onto the first (or each `align_to`).
1117        #[serde(default)]
1118        align: bool,
1119        /// Child **nodes** — mol | text (no edges).
1120        #[serde(default)]
1121        children: Vec<Node>,
1122        /// Group-level cascade bag (list container for child inheritance).
1123        #[serde(default, skip_serializing_if = "Option::is_none")]
1124        #[cfg_attr(feature = "codegen", ts(optional))]
1125        opts: Option<Opts>,
1126        #[serde(default, skip_serializing_if = "Option::is_none")]
1127        #[cfg_attr(feature = "codegen", ts(optional))]
1128        color: Option<String>,
1129        #[serde(default, skip_serializing_if = "Option::is_none")]
1130        #[cfg_attr(feature = "codegen", ts(optional))]
1131        scale: Option<f64>,
1132        #[serde(default, skip_serializing_if = "Option::is_none")]
1133        #[cfg_attr(feature = "codegen", ts(optional))]
1134        aromatic: Option<AromaticStyle>,
1135        #[serde(default, skip_serializing_if = "Option::is_none")]
1136        #[cfg_attr(feature = "codegen", ts(optional))]
1137        debug_box: Option<bool>,
1138        /// Paint alignment correspondence (matched atom tags + mol role badge).
1139        #[serde(default, skip_serializing_if = "Option::is_none")]
1140        #[cfg_attr(feature = "codegen", ts(optional))]
1141        debug_align: Option<bool>,
1142        /// Post-layout SVG viewBox pad (px). Omit → small house default.
1143        #[serde(default, skip_serializing_if = "Option::is_none")]
1144        #[cfg_attr(feature = "codegen", ts(optional))]
1145        pad: Option<f64>,
1146    },
1147    /// Reaction / pathway scheme: mixed **node** children (`mol` | `edge` | `text`).
1148    ReactionScheme {
1149        #[serde(default, skip_serializing_if = "Option::is_none")]
1150        #[cfg_attr(feature = "codegen", ts(optional))]
1151        id: Option<String>,
1152        /// Child **nodes** — mols, edges, and text (any order).
1153        #[serde(default)]
1154        children: Vec<Node>,
1155        /// Scheme layout (direction, edge routing); backend maps these.
1156        #[serde(default, skip_serializing_if = "Option::is_none")]
1157        #[cfg_attr(feature = "codegen", ts(optional))]
1158        layout: Option<LayoutOpts>,
1159        /// Scheme-level cascade bag for child mol inheritance.
1160        #[serde(default, skip_serializing_if = "Option::is_none")]
1161        #[cfg_attr(feature = "codegen", ts(optional))]
1162        opts: Option<Opts>,
1163        #[serde(default, skip_serializing_if = "Option::is_none")]
1164        #[cfg_attr(feature = "codegen", ts(optional))]
1165        color: Option<String>,
1166        #[serde(default, skip_serializing_if = "Option::is_none")]
1167        #[cfg_attr(feature = "codegen", ts(optional))]
1168        scale: Option<f64>,
1169        #[serde(default, skip_serializing_if = "Option::is_none")]
1170        #[cfg_attr(feature = "codegen", ts(optional))]
1171        aromatic: Option<AromaticStyle>,
1172        #[serde(default, skip_serializing_if = "Option::is_none")]
1173        #[cfg_attr(feature = "codegen", ts(optional))]
1174        debug_box: Option<bool>,
1175        /// Paint alignment correspondence (matched atom tags + mol role badge).
1176        #[serde(default, skip_serializing_if = "Option::is_none")]
1177        #[cfg_attr(feature = "codegen", ts(optional))]
1178        debug_align: Option<bool>,
1179        /// Post-layout SVG viewBox pad (px). Omit → small house default.
1180        #[serde(default, skip_serializing_if = "Option::is_none")]
1181        #[cfg_attr(feature = "codegen", ts(optional))]
1182        pad: Option<f64>,
1183    },
1184    /// Grid root — each child is one row (`mol` / `group` / `reaction_scheme` / nested `grid`).
1185    Grid {
1186        #[serde(default, skip_serializing_if = "Option::is_none")]
1187        #[cfg_attr(feature = "codegen", ts(optional))]
1188        id: Option<String>,
1189        /// Row roots (nested grids flatten in document order when walking mols).
1190        #[serde(default)]
1191        children: Vec<DepictSpec>,
1192        /// Grid-level cascade bag (inherits onto every row / mol).
1193        #[serde(default, skip_serializing_if = "Option::is_none")]
1194        #[cfg_attr(feature = "codegen", ts(optional))]
1195        opts: Option<Opts>,
1196        #[serde(default, skip_serializing_if = "Option::is_none")]
1197        #[cfg_attr(feature = "codegen", ts(optional))]
1198        color: Option<String>,
1199        #[serde(default, skip_serializing_if = "Option::is_none")]
1200        #[cfg_attr(feature = "codegen", ts(optional))]
1201        scale: Option<f64>,
1202        #[serde(default, skip_serializing_if = "Option::is_none")]
1203        #[cfg_attr(feature = "codegen", ts(optional))]
1204        aromatic: Option<AromaticStyle>,
1205        #[serde(default, skip_serializing_if = "Option::is_none")]
1206        #[cfg_attr(feature = "codegen", ts(optional))]
1207        debug_box: Option<bool>,
1208        /// Paint alignment correspondence (matched atom tags + mol role badge).
1209        #[serde(default, skip_serializing_if = "Option::is_none")]
1210        #[cfg_attr(feature = "codegen", ts(optional))]
1211        debug_align: Option<bool>,
1212        /// Post-layout SVG viewBox pad (px). Omit → small house default.
1213        #[serde(default, skip_serializing_if = "Option::is_none")]
1214        #[cfg_attr(feature = "codegen", ts(optional))]
1215        pad: Option<f64>,
1216    },
1217}
1218
1219impl DepictSpec {
1220    fn cascade_layer(&self) -> Option<CascadeLayer> {
1221        match self {
1222            DepictSpec::Mol(_) => None,
1223            DepictSpec::Group {
1224                opts,
1225                color,
1226                scale,
1227                aromatic,
1228                debug_box,
1229                debug_align,
1230                pad,
1231                ..
1232            }
1233            | DepictSpec::ReactionScheme {
1234                opts,
1235                color,
1236                scale,
1237                aromatic,
1238                debug_box,
1239                debug_align,
1240                pad,
1241                ..
1242            }
1243            | DepictSpec::Grid {
1244                opts,
1245                color,
1246                scale,
1247                aromatic,
1248                debug_box,
1249                debug_align,
1250                pad,
1251                ..
1252            } => Some(CascadeLayer {
1253                opts: opts.clone(),
1254                common: CommonOpts {
1255                    color: color.clone(),
1256                    scale: *scale,
1257                    aromatic: *aromatic,
1258                    debug_box: *debug_box,
1259                    debug_align: *debug_align,
1260                    pad: *pad,
1261                },
1262            }),
1263        }
1264    }
1265
1266    /// Walk mols in document order with ancestor cascade layers (outer → inner).
1267    fn collect_mols_with_layers(
1268        &self,
1269        stack: &mut Vec<CascadeLayer>,
1270        out: &mut Vec<(MolNode, Vec<CascadeLayer>)>,
1271    ) {
1272        match self {
1273            DepictSpec::Mol(m) => {
1274                out.push((m.clone(), stack.clone()));
1275            }
1276            DepictSpec::Group { children, .. } | DepictSpec::ReactionScheme { children, .. } => {
1277                let layer = self.cascade_layer();
1278                if let Some(layer) = layer.clone() {
1279                    stack.push(layer);
1280                }
1281                for n in children {
1282                    if let Some(m) = n.as_mol() {
1283                        out.push((m.clone(), stack.clone()));
1284                    }
1285                }
1286                if layer.is_some() {
1287                    stack.pop();
1288                }
1289            }
1290            DepictSpec::Grid { children, .. } => {
1291                let layer = self.cascade_layer();
1292                if let Some(layer) = layer.clone() {
1293                    stack.push(layer);
1294                }
1295                for row in children {
1296                    row.collect_mols_with_layers(stack, out);
1297                }
1298                if layer.is_some() {
1299                    stack.pop();
1300                }
1301            }
1302        }
1303    }
1304
1305    fn mols_with_layers(&self) -> Vec<(MolNode, Vec<CascadeLayer>)> {
1306        let mut stack = Vec::new();
1307        let mut out = Vec::new();
1308        self.collect_mols_with_layers(&mut stack, &mut out);
1309        out
1310    }
1311
1312    /// Flatten to mol nodes in document order (skips edge / text; walks grid rows).
1313    pub fn mols(&self) -> Vec<MolNode> {
1314        self.mols_with_layers()
1315            .into_iter()
1316            .map(|(m, _)| m)
1317            .collect()
1318    }
1319
1320    /// Grid row roots (empty when not a grid).
1321    pub fn grid_rows(&self) -> &[DepictSpec] {
1322        match self {
1323            DepictSpec::Grid { children, .. } => children.as_slice(),
1324            _ => &[],
1325        }
1326    }
1327
1328    /// Child nodes of a flat container (empty for mol / grid roots).
1329    pub fn nodes(&self) -> &[Node] {
1330        match self {
1331            DepictSpec::Group { children, .. } | DepictSpec::ReactionScheme { children, .. } => {
1332                children.as_slice()
1333            }
1334            DepictSpec::Mol(_) | DepictSpec::Grid { .. } => &[],
1335        }
1336    }
1337
1338    /// Edge nodes in document order (includes edges inside grid rows).
1339    pub fn edges(&self) -> Vec<&EdgeNode> {
1340        match self {
1341            DepictSpec::Grid { children, .. } => {
1342                children.iter().flat_map(|row| row.edges()).collect()
1343            }
1344            _ => self.nodes().iter().filter_map(Node::as_edge).collect(),
1345        }
1346    }
1347
1348    /// Text nodes in document order (includes texts inside grid rows).
1349    pub fn texts(&self) -> Vec<&TextNode> {
1350        match self {
1351            DepictSpec::Grid { children, .. } => {
1352                children.iter().flat_map(|row| row.texts()).collect()
1353            }
1354            _ => self.nodes().iter().filter_map(Node::as_text).collect(),
1355        }
1356    }
1357
1358    /// Look up a mol or text node by id (for label / lane refs).
1359    pub fn node_by_id(&self, id: &str) -> Option<&Node> {
1360        match self {
1361            DepictSpec::Grid { children, .. } => children.iter().find_map(|row| row.node_by_id(id)),
1362            _ => self.nodes().iter().find(|n| n.id() == Some(id)),
1363        }
1364    }
1365
1366    pub fn align_enabled(&self) -> bool {
1367        matches!(self, DepictSpec::Group { align: true, .. })
1368    }
1369
1370    /// Container-level opts bag (`group`, `reaction_scheme`, or `grid`).
1371    pub fn container_opts(&self) -> Option<&Opts> {
1372        match self {
1373            DepictSpec::Group { opts, .. }
1374            | DepictSpec::ReactionScheme { opts, .. }
1375            | DepictSpec::Grid { opts, .. } => opts.as_ref(),
1376            DepictSpec::Mol(_) => None,
1377        }
1378    }
1379
1380    /// Group-level opts bag (if this is a group).
1381    #[inline]
1382    pub fn group_opts(&self) -> Option<&Opts> {
1383        match self {
1384            DepictSpec::Group { opts, .. } => opts.as_ref(),
1385            _ => None,
1386        }
1387    }
1388
1389    /// Resolve cascading mol opts for child index `i` (0 for a mol root).
1390    ///
1391    /// Order: each ancestor (opts bag → flat common), outer → inner, then node
1392    /// `opts` → node local flat fields. Grid rows contribute their own layers.
1393    pub fn resolve_mol_chrome(&self, i: usize) -> MolOpts {
1394        let entries = self.mols_with_layers();
1395        let (node, layers) = entries.get(i).expect("mol index");
1396        let mut o = MolOpts::default();
1397        for layer in layers {
1398            if let Some(ref bag) = layer.opts {
1399                bag.apply_to_mol(&mut o);
1400            }
1401            o.merge_common(&layer.common);
1402        }
1403        if let Some(ref bag) = node.opts {
1404            bag.apply_to_mol(&mut o);
1405        }
1406        o.merge_from(&node.local_opts());
1407        o
1408    }
1409
1410    /// Resolved chrome for every mol in document order (host paint / tests).
1411    pub fn resolve_all_mol_chrome(&self) -> Vec<MolOpts> {
1412        let n = self.mols_with_layers().len();
1413        (0..n).map(|i| self.resolve_mol_chrome(i)).collect()
1414    }
1415}
1416
1417impl From<MolNode> for DepictSpec {
1418    fn from(m: MolNode) -> Self {
1419        DepictSpec::Mol(m)
1420    }
1421}
1422
1423impl From<MolNode> for Node {
1424    fn from(m: MolNode) -> Self {
1425        Node::Mol(m)
1426    }
1427}