Skip to main content

brep_instructions/
model.rs

1//! The `instructions` block: everything an instructions document authors.
2//!
3//! An instructions document places its target assembly as one grounded
4//! component and keeps the authored instructions in this top-level block. The
5//! block is plain data: a tree of steps. A step adds parts and may hold child
6//! steps, the group it installs: the children build the group (and see only
7//! it), then the step places it over what its earlier siblings built. Reading
8//! order is children first, then their parent, depth first. A sub-assembly is
9//! such a step: its parts' steps are its children. Views are PMI views of the
10//! document, named by id; everything else a step shows is here.
11//!
12//! Schema 1 kept chapters (one per assembly level) of flat steps; it reads as
13//! the same tree ([`Instructions::from_value`]).
14
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17use std::collections::HashSet;
18
19/// The document key the block is stored under.
20pub const BLOCK_KEY: &str = "instructions";
21
22/// The block's schema version.
23pub const SCHEMA: u32 = 2;
24
25/// The `documentClass` value of an instructions document.
26pub const DOCUMENT_CLASS: &str = "instructions";
27
28/// The file extension of an instructions document, dot included.
29pub const EXTENSION: &str = ".ibrep";
30
31/// The part attribute that marks a fastener (bool).
32pub const FASTENER_ATTRIBUTE: &str = "Fastener";
33/// The part attribute holding a fastener's torque, as text with its unit.
34pub const TORQUE_ATTRIBUTE: &str = "Torque";
35/// The part attribute that marks a serial-tracked part (bool).
36pub const SERIAL_TRACKED_ATTRIBUTE: &str = "Serial_Tracked";
37
38/// The steps-per-page counts a template offers.
39pub const STEPS_PER_PAGE: [u8; 3] = [1, 2, 4];
40
41#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub struct Instructions {
45    pub schema: u32,
46    /// The assembly revision these instructions describe. Authoritative: the
47    /// server derives what the instructions reference from this field alone.
48    pub target: Target,
49    #[serde(default)]
50    pub template: Template,
51    #[serde(default)]
52    pub front: FrontMatter,
53    /// The top-level steps, in order; each may hold children ([`Step::steps`]).
54    #[serde(default)]
55    pub steps: Vec<Step>,
56    #[serde(default)]
57    pub id_counter: u64,
58    /// A re-target waiting for the author's approval. Release is refused while
59    /// it is set.
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub retarget: Option<Retarget>,
62}
63
64/// One revision of the target assembly.
65#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
66#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
67#[serde(rename_all = "camelCase")]
68pub struct Target {
69    /// The store key the assembly was placed from: `part/<id>/rev/<rev>` in a
70    /// PLM session, the file's key otherwise.
71    pub source_key: String,
72    #[serde(default)]
73    pub part_number: String,
74    /// The revision label, for display.
75    #[serde(default)]
76    pub revision: String,
77    /// The placed document's content signature.
78    #[serde(default)]
79    pub signature: String,
80    /// The assembly's name, for titles.
81    #[serde(default)]
82    pub name: String,
83}
84
85#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
87#[serde(rename_all = "lowercase")]
88pub enum Orientation {
89    #[default]
90    Portrait,
91    Landscape,
92}
93
94/// How a document's steps are drawn: in the PDF, the step images, the HTML
95/// player and the in-app player alike.
96#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99pub enum Style {
100    /// A flat technical illustration on light grey: the parts earlier steps
101    /// placed white with thin grey visible edges, the parts the step adds
102    /// flat blue under a heavy black outline, each sliding in along a black
103    /// arrow. The default for a new document.
104    LineArt,
105    /// The shaded look documents had before Line art: lit faces, the parts
106    /// the step adds in their own colours, the placed parts ghosted. What a
107    /// document saved without a style reads as.
108    Shaded,
109}
110
111impl Style {
112    /// Every style, for a dropdown: the value, its key and its label.
113    pub const CHOICES: [(Style, &'static str, &'static str); 2] =
114        [(Style::LineArt, "lineArt", "Line art"), (Style::Shaded, "shaded", "Shaded")];
115
116    /// What a document saved before styles existed reads as: the look it had.
117    pub fn saved_before_styles() -> Self {
118        Style::Shaded
119    }
120
121    pub fn as_str(self) -> &'static str {
122        match self {
123            Style::LineArt => "lineArt",
124            Style::Shaded => "shaded",
125        }
126    }
127}
128
129/// The printed page template, one per document.
130#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132#[serde(rename_all = "camelCase")]
133pub struct Template {
134    /// 1, 2 or 4.
135    pub steps_per_page: u8,
136    pub orientation: Orientation,
137    /// A paper-size key (`A4`, `Letter`, …).
138    pub paper: String,
139    /// How the steps are drawn. A new document is Line art; one saved
140    /// before styles existed reads as Shaded, the look it was made with
141    /// (reading never dirties a document).
142    #[serde(default = "Style::saved_before_styles")]
143    pub style: Style,
144}
145
146impl Default for Template {
147    fn default() -> Self {
148        Self { steps_per_page: 1, orientation: Orientation::Portrait, paper: "A4".into(), style: Style::LineArt }
149    }
150}
151
152/// The cover and the lists before the steps.
153#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
155#[serde(rename_all = "camelCase")]
156pub struct FrontMatter {
157    #[serde(default)]
158    pub title: String,
159    #[serde(default)]
160    pub subtitle: String,
161    /// The step whose view is the cover picture; the last step when absent.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub cover_step: Option<String>,
164    pub parts_list: bool,
165    pub tools_list: bool,
166}
167
168impl Default for FrontMatter {
169    fn default() -> Self {
170        Self { title: String::new(), subtitle: String::new(), cover_step: None, parts_list: true, tools_list: true }
171    }
172}
173
174/// A schema-1 chapter: the steps of one assembly level, read only to migrate.
175#[derive(Debug, Clone, Deserialize)]
176#[serde(rename_all = "camelCase")]
177struct ChapterV1 {
178    id: String,
179    /// The occurrence path of the assembly the chapter built; `""` for the
180    /// target assembly itself.
181    #[serde(default)]
182    assembly: String,
183    #[serde(default)]
184    title: String,
185    #[serde(default)]
186    steps: Vec<Step>,
187}
188
189#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
190#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
191#[serde(rename_all = "camelCase")]
192pub struct Step {
193    pub id: String,
194    pub title: String,
195    #[serde(default, skip_serializing_if = "String::is_empty")]
196    pub notes: String,
197    #[serde(default)]
198    pub adds: Vec<Add>,
199    /// The PMI view (camera, exploded state, balloons) the step shows.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub view: Option<String>,
202    #[serde(default, skip_serializing_if = "Vec::is_empty")]
203    pub tools: Vec<ToolUse>,
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub torque: Option<Torque>,
206    #[serde(default, skip_serializing_if = "Vec::is_empty")]
207    pub callouts: Vec<Callout>,
208    /// Insertion-motion arrows: each played as a short move home.
209    #[serde(default, skip_serializing_if = "Vec::is_empty")]
210    pub arrows: Vec<Arrow>,
211    /// Reserved for a motion clip attached to the step.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub motion: Option<Value>,
214    #[serde(default)]
215    pub signoff: Signoff,
216    /// The author captured the view's camera from the viewport: it is kept
217    /// through every regeneration until Reset view. Otherwise the engine
218    /// generates the camera from the step's parts and its parent's direction.
219    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
220    pub camera_captured: bool,
221    /// Child steps, in order: the group this step installs. They are read
222    /// before it and see only the group's own parts.
223    #[serde(default, skip_serializing_if = "Vec::is_empty")]
224    pub steps: Vec<Step>,
225}
226
227/// Parts one step adds: one part, at one or more occurrences.
228#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
229#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
230#[serde(rename_all = "camelCase")]
231pub struct Add {
232    /// Occurrence paths, relative to the document (`ACOMP1:ACOMP3`).
233    pub occurrences: Vec<String>,
234    /// The part: its PLM part id when it was placed from a PLM revision
235    /// (what the server and the thumbnails key on), else its name.
236    pub part: String,
237    /// The display name, when it differs from `part` (a PLM part): what the
238    /// pane, the parts list and the player show. See [`Add::display_name`].
239    #[serde(default, skip_serializing_if = "String::is_empty")]
240    pub name: String,
241    #[serde(default)]
242    pub find_number: String,
243    /// A finished sub-assembly placed as one part.
244    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
245    pub subassembly: bool,
246    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
247    pub fastener: bool,
248    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
249    pub serial_tracked: bool,
250}
251
252impl Add {
253    pub fn quantity(&self) -> usize {
254        self.occurrences.len()
255    }
256
257    /// What to show for the part: its name, else `part` (an add written
258    /// before names were carried, or a part that is its own name).
259    pub fn display_name(&self) -> &str {
260        if self.name.is_empty() {
261            &self.part
262        } else {
263            &self.name
264        }
265    }
266
267    /// An add for `part` named `name` (the name is written only when it
268    /// differs).
269    pub fn named(occurrences: Vec<String>, part: &str, name: &str) -> Self {
270        Self {
271            occurrences,
272            part: part.to_string(),
273            name: if name == part { String::new() } else { name.to_string() },
274            ..Self::default()
275        }
276    }
277
278    /// The same BOM row: the same part under the same find number, placed
279    /// the same way (a sub-assembly is not the part of the same name).
280    fn same_row(&self, other: &Add) -> bool {
281        self.part == other.part && self.find_number == other.find_number && self.subassembly == other.subassembly
282    }
283}
284
285impl Step {
286    /// An empty step with `id` and `title`.
287    pub fn new(id: String, title: String) -> Self {
288        Self { id, title, ..Self::default() }
289    }
290
291    /// Whether `step_id` is this step or one of its descendants.
292    pub fn contains(&self, step_id: &str) -> bool {
293        self.id == step_id || self.steps.iter().any(|s| s.contains(step_id))
294    }
295
296    /// Whether this step places a sub-assembly at `occurrence`.
297    fn places(&self, occurrence: &str) -> bool {
298        self.adds.iter().any(|a| a.subassembly && a.occurrences.iter().any(|o| o == occurrence))
299    }
300
301    /// Every occurrence this step and its descendants add.
302    pub fn occurrences_with_descendants<'a>(&'a self, out: &mut Vec<&'a str>) {
303        out.extend(self.adds.iter().flat_map(|a| a.occurrences.iter().map(String::as_str)));
304        for child in &self.steps {
305            child.occurrences_with_descendants(out);
306        }
307    }
308
309    /// One BOM row per part: adds of the same row (see `Add::same_row`)
310    /// become one add holding every occurrence, in first-add order. Merged
311    /// steps, moved parts and documents written one add per occurrence all
312    /// read as `8 × bolt`, never eight rows of `1 × bolt`.
313    pub fn coalesce_adds(&mut self) {
314        let mut rows: Vec<Add> = Vec::with_capacity(self.adds.len());
315        for mut add in std::mem::take(&mut self.adds) {
316            match rows.iter_mut().find(|row| row.same_row(&add)) {
317                Some(row) => {
318                    row.occurrences.append(&mut add.occurrences);
319                    row.fastener |= add.fastener;
320                    row.serial_tracked |= add.serial_tracked;
321                }
322                None => rows.push(add),
323            }
324        }
325        self.adds = rows;
326    }
327}
328
329/// A tool a step uses: a tools-library entry by id, with a snapshot of its
330/// name and spec so printed and offline copies need no server.
331#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
332#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
333#[serde(rename_all = "camelCase")]
334pub struct ToolUse {
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub tool_id: Option<String>,
337    pub name: String,
338    #[serde(default)]
339    pub spec: String,
340    /// Added without the library (no session); listed for linking.
341    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
342    pub unlinked: bool,
343}
344
345#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
346#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
347#[serde(rename_all = "lowercase")]
348pub enum TorqueSource {
349    /// Defaulted from the fastener part's attribute.
350    Part,
351    /// Set on the step by the author.
352    Override,
353}
354
355#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
356#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
357#[serde(rename_all = "camelCase")]
358pub struct Torque {
359    /// As authored (`12`, `10-12`).
360    pub value: String,
361    #[serde(default)]
362    pub unit: String,
363    pub source: TorqueSource,
364}
365
366impl Torque {
367    /// A torque attribute's text (`12 N·m`) split at its first space into
368    /// value and unit; `None` for an empty one.
369    pub fn from_attribute(text: &str) -> Option<Self> {
370        let text = text.trim();
371        if text.is_empty() {
372            return None;
373        }
374        let (value, unit) = match text.split_once(char::is_whitespace) {
375            Some((value, unit)) => (value.trim(), unit.trim()),
376            None => (text, ""),
377        };
378        Some(Self { value: value.into(), unit: unit.into(), source: TorqueSource::Part })
379    }
380
381    /// `12 N·m`.
382    pub fn text(&self) -> String {
383        if self.unit.is_empty() {
384            self.value.clone()
385        } else {
386            format!("{} {}", self.value, self.unit)
387        }
388    }
389}
390
391#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
392#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
393#[serde(rename_all = "lowercase")]
394pub enum CalloutKind {
395    Caution,
396    Note,
397    Check,
398}
399
400impl CalloutKind {
401    pub fn label(self) -> &'static str {
402        match self {
403            Self::Caution => "Caution",
404            Self::Note => "Note",
405            Self::Check => "Check",
406        }
407    }
408}
409
410#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
411#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
412#[serde(rename_all = "camelCase")]
413pub struct Callout {
414    pub id: String,
415    pub kind: CalloutKind,
416    pub text: String,
417    /// The occurrence the callout points at, if any.
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    pub occurrence: Option<String>,
420}
421
422#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
423#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
424#[serde(rename_all = "camelCase")]
425pub struct Arrow {
426    pub occurrence: String,
427    /// The direction the part travels IN from (unit-free; normalised on use).
428    pub direction: [f64; 3],
429    /// How far out the motion starts, in model units.
430    pub distance: f64,
431}
432
433impl Arrow {
434    /// The start offset of the insertion: `-direction` scaled to `distance`,
435    /// so the part travels along `direction` to home. Zero for a zero vector.
436    pub fn start_offset(&self) -> [f64; 3] {
437        let [x, y, z] = self.direction;
438        let length = (x * x + y * y + z * z).sqrt();
439        if !(length > 1e-12) || !self.distance.is_finite() {
440            return [0.0; 3];
441        }
442        let k = -self.distance / length;
443        [x * k, y * k, z * k]
444    }
445}
446
447#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
448#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
449#[serde(rename_all = "camelCase")]
450pub struct Signoff {
451    pub required: bool,
452}
453
454impl Default for Signoff {
455    fn default() -> Self {
456        Self { required: true }
457    }
458}
459
460/// One occurrence in a re-target diff.
461#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
462#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
463#[serde(rename_all = "camelCase")]
464pub struct OccurrenceChange {
465    pub occurrence: String,
466    pub part: String,
467    /// For a replaced occurrence: the part it was.
468    #[serde(default, skip_serializing_if = "Option::is_none")]
469    pub was: Option<String>,
470}
471
472/// A re-target waiting for approval: what changed between the two assembly
473/// revisions and the steps it touches.
474#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
475#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
476#[serde(rename_all = "camelCase")]
477pub struct Retarget {
478    pub from: Target,
479    pub to: Target,
480    #[serde(default)]
481    pub added: Vec<OccurrenceChange>,
482    #[serde(default)]
483    pub removed: Vec<OccurrenceChange>,
484    #[serde(default)]
485    pub replaced: Vec<OccurrenceChange>,
486    /// Steps an add was removed from or changed in, and steps made for the
487    /// added parts.
488    #[serde(default)]
489    pub touched_steps: Vec<String>,
490    /// Steps left with nothing to add.
491    #[serde(default)]
492    pub empty_steps: Vec<String>,
493}
494
495impl Instructions {
496    /// A new, empty block for `target`.
497    pub fn new(target: Target) -> Self {
498        let title = target.name.clone();
499        Self {
500            schema: SCHEMA,
501            target,
502            template: Template::default(),
503            front: FrontMatter { title, ..FrontMatter::default() },
504            steps: Vec::new(),
505            id_counter: 0,
506            retarget: None,
507        }
508    }
509
510    /// Read the block from its JSON, validated. A schema-1 block (chapters of
511    /// steps) reads as the tree: the root chapter's steps at the top, a
512    /// sub-assembly's chapter as the children of the step that places it, and
513    /// is schema 2 from then on (written back on the next edit).
514    pub fn from_value(value: &Value) -> Result<Self, String> {
515        let schema = value.get("schema").and_then(Value::as_u64).unwrap_or(0);
516        let value = if schema == 1 { migrate_chapters(value)? } else { value.clone() };
517        let mut block: Self = serde_json::from_value(value).map_err(|e| format!("instructions block: {e}"))?;
518        block.validate()?;
519        block.coalesce_adds();
520        Ok(block)
521    }
522
523    /// Every step's adds as one row per part ([`Step::coalesce_adds`]).
524    pub fn coalesce_adds(&mut self) {
525        for_each_step_mut(&mut self.steps, &mut |step| step.coalesce_adds());
526    }
527
528    /// Read the block out of a whole document, if it has one.
529    pub fn from_document(document: &Value) -> Result<Option<Self>, String> {
530        match document.get(BLOCK_KEY) {
531            None | Some(Value::Null) => Ok(None),
532            Some(block) => Self::from_value(block).map(Some),
533        }
534    }
535
536    pub fn to_value(&self) -> Value {
537        serde_json::to_value(self).expect("instructions block serializes")
538    }
539
540    /// The structural rules: a known schema, a template the layout can draw,
541    /// unique step ids over the whole tree, and no occurrence added twice.
542    pub fn validate(&self) -> Result<(), String> {
543        if self.schema == 0 || self.schema > SCHEMA {
544            return Err(format!("instructions schema {} is not supported (this build reads up to {SCHEMA})", self.schema));
545        }
546        if !STEPS_PER_PAGE.contains(&self.template.steps_per_page) {
547            return Err(format!("steps per page must be 1, 2 or 4, not {}", self.template.steps_per_page));
548        }
549        let mut ids = HashSet::new();
550        let mut occurrences = HashSet::new();
551        for (_, step) in self.steps() {
552            if !ids.insert(step.id.as_str()) {
553                return Err(format!("duplicate id '{}'", step.id));
554            }
555            for add in &step.adds {
556                for occurrence in &add.occurrences {
557                    if !occurrences.insert(occurrence.as_str()) {
558                        return Err(format!("occurrence '{occurrence}' is added in more than one step"));
559                    }
560                }
561            }
562        }
563        Ok(())
564    }
565
566    /// A fresh id with `prefix` (`MS` step, `MK` callout; `MC` was a chapter).
567    pub fn next_id(&mut self, prefix: &str) -> String {
568        self.id_counter += 1;
569        format!("{prefix}{}", self.id_counter)
570    }
571
572    pub fn step_count(&self) -> usize {
573        self.steps().count()
574    }
575
576    /// Every step in reading order (a step's children, depth first, before the
577    /// step itself) with its depth (0 at the top).
578    pub fn steps(&self) -> impl Iterator<Item = (usize, &Step)> {
579        fn walk<'a>(steps: &'a [Step], depth: usize, out: &mut Vec<(usize, &'a Step)>) {
580            for step in steps {
581                walk(&step.steps, depth + 1, out);
582                out.push((depth, step));
583            }
584        }
585        let mut out = Vec::with_capacity(16);
586        walk(&self.steps, 0, &mut out);
587        out.into_iter()
588    }
589
590    /// The index path of a step: an index per level from the top.
591    fn path_of(&self, step_id: &str) -> Option<Vec<usize>> {
592        fn walk(steps: &[Step], step_id: &str, path: &mut Vec<usize>) -> bool {
593            for (i, step) in steps.iter().enumerate() {
594                path.push(i);
595                if step.id == step_id || walk(&step.steps, step_id, path) {
596                    return true;
597                }
598                path.pop();
599            }
600            false
601        }
602        let mut path = Vec::new();
603        walk(&self.steps, step_id, &mut path).then_some(path)
604    }
605
606    pub fn step(&self, step_id: &str) -> Option<&Step> {
607        self.steps().find(|(_, s)| s.id == step_id).map(|(_, s)| s)
608    }
609
610    pub fn step_mut(&mut self, step_id: &str) -> Option<&mut Step> {
611        let path = self.path_of(step_id)?;
612        let (last, parents) = path.split_last()?;
613        Some(&mut list_at_mut(&mut self.steps, parents)[*last])
614    }
615
616    /// The list the step sits in (its siblings, itself included) and its index
617    /// there.
618    pub fn siblings(&self, step_id: &str) -> Option<(&[Step], usize)> {
619        let path = self.path_of(step_id)?;
620        let (last, parents) = path.split_last()?;
621        let mut list = &self.steps;
622        for &i in parents {
623            list = &list[i].steps;
624        }
625        Some((list.as_slice(), *last))
626    }
627
628    pub fn siblings_mut(&mut self, step_id: &str) -> Option<(&mut Vec<Step>, usize)> {
629        let path = self.path_of(step_id)?;
630        let (last, parents) = path.split_last()?;
631        Some((list_at_mut(&mut self.steps, parents), *last))
632    }
633
634    /// The parent step's id: `Some(None)` at the top level, `None` for an
635    /// unknown step.
636    pub fn parent_id(&self, step_id: &str) -> Option<Option<&str>> {
637        let path = self.path_of(step_id)?;
638        let (_, parents) = path.split_last()?;
639        let mut list = &self.steps;
640        let mut parent = None;
641        for &i in parents {
642            parent = Some(list[i].id.as_str());
643            list = &list[i].steps;
644        }
645        Some(parent)
646    }
647
648    /// How deep a step sits: 0 at the top level.
649    pub fn depth(&self, step_id: &str) -> Option<usize> {
650        self.path_of(step_id).map(|path| path.len() - 1)
651    }
652
653    /// The steps that build one assembly: the top level for `""`, else the
654    /// children of the step that places the sub-assembly at `occurrence`.
655    pub fn group_steps_mut(&mut self, occurrence: &str) -> Option<&mut Vec<Step>> {
656        if occurrence.is_empty() {
657            return Some(&mut self.steps);
658        }
659        let placing = self.steps().find(|(_, s)| s.places(occurrence)).map(|(_, s)| s.id.clone())?;
660        self.step_mut(&placing).map(|step| &mut step.steps)
661    }
662
663    /// The step number a reader sees (1-based, in reading order).
664    pub fn step_number(&self, step_id: &str) -> Option<usize> {
665        self.steps().position(|(_, s)| s.id == step_id).map(|n| n + 1)
666    }
667
668    /// Distinct tools in first-use order, with the step ids that use each.
669    pub fn tools_list(&self) -> Vec<(ToolUse, Vec<String>)> {
670        let mut list: Vec<(ToolUse, Vec<String>)> = Vec::new();
671        for (_, step) in self.steps() {
672            for tool in &step.tools {
673                let same = |t: &ToolUse| match (&t.tool_id, &tool.tool_id) {
674                    (Some(a), Some(b)) => a == b,
675                    (None, None) => t.name == tool.name && t.spec == tool.spec,
676                    _ => false,
677                };
678                match list.iter_mut().find(|(t, _)| same(t)) {
679                    Some((_, steps)) => {
680                        if !steps.contains(&step.id) {
681                            steps.push(step.id.clone());
682                        }
683                    }
684                    None => list.push((tool.clone(), vec![step.id.clone()])),
685                }
686            }
687        }
688        list
689    }
690
691    /// The parts list: one row per part (and per sub-assembly), with its
692    /// find number and the quantity added over every step, in first-add order.
693    pub fn parts_list(&self) -> Vec<PartsRow> {
694        let mut rows: Vec<PartsRow> = Vec::new();
695        for (_, step) in self.steps() {
696            for add in &step.adds {
697                match rows.iter_mut().find(|r| r.part == add.part && r.find_number == add.find_number) {
698                    Some(row) => row.quantity += add.quantity(),
699                    None => rows.push(PartsRow {
700                        part: add.part.clone(),
701                        name: add.display_name().to_string(),
702                        find_number: add.find_number.clone(),
703                        quantity: add.quantity(),
704                        subassembly: add.subassembly,
705                        first_step: step.id.clone(),
706                    }),
707                }
708            }
709        }
710        rows
711    }
712}
713
714/// The list at an index path (every index but the step's own).
715fn list_at_mut<'a>(mut list: &'a mut Vec<Step>, parents: &[usize]) -> &'a mut Vec<Step> {
716    for &i in parents {
717        list = &mut list[i].steps;
718    }
719    list
720}
721
722/// `f` on every step of the tree, parents before children.
723pub fn for_each_step_mut(steps: &mut [Step], f: &mut dyn FnMut(&mut Step)) {
724    for step in steps {
725        f(step);
726        for_each_step_mut(&mut step.steps, f);
727    }
728}
729
730/// Keep the steps `keep` accepts, at every level.
731pub fn retain_steps(steps: &mut Vec<Step>, keep: &dyn Fn(&Step) -> bool) {
732    steps.retain(keep);
733    for step in steps {
734        retain_steps(&mut step.steps, keep);
735    }
736}
737
738/// A schema-1 block as schema 2: the root chapter's steps are the top level;
739/// a sub-assembly's chapter becomes the children of the step that places that
740/// sub-assembly (so an old document reads as the tree the wizard proposes); a
741/// chapter no step places becomes a top-level step of its own, ahead of the
742/// root's steps as it printed, titled after the chapter and keeping its id.
743fn migrate_chapters(value: &Value) -> Result<Value, String> {
744    let mut object = value.as_object().cloned().ok_or("instructions block: not an object")?;
745    let chapters: Vec<ChapterV1> = match object.remove("chapters") {
746        Some(chapters) => serde_json::from_value(chapters).map_err(|e| format!("instructions block: chapters: {e}"))?,
747        None => Vec::new(),
748    };
749    // Writers of that era put an empty `steps` object beside the chapters.
750    object.remove("steps");
751    let (root, others): (Vec<ChapterV1>, Vec<ChapterV1>) = chapters.into_iter().partition(|c| c.assembly.is_empty());
752    let mut steps: Vec<Step> = root.into_iter().flat_map(|c| c.steps).collect();
753    // Deepest chapters come first in a schema-1 block, so walk them from the
754    // last: a sub-assembly's placing step is in place before its own chapter
755    // looks for it.
756    for chapter in others.into_iter().rev() {
757        let mut placing = None;
758        for_each_step_mut(&mut steps, &mut |step| {
759            if placing.is_none() && step.places(&chapter.assembly) {
760                placing = Some(step.id.clone());
761            }
762        });
763        let chapter_steps = chapter.steps;
764        match placing {
765            Some(id) => {
766                for_each_step_mut(&mut steps, &mut |step| {
767                    if step.id == id {
768                        step.steps = chapter_steps.clone();
769                    }
770                });
771            }
772            None => steps.insert(0, Step { id: chapter.id, title: chapter.title, steps: chapter_steps, ..Step::default() }),
773        }
774    }
775    object.insert("schema".into(), Value::from(SCHEMA));
776    object.insert("steps".into(), serde_json::to_value(steps).map_err(|e| format!("instructions block: {e}"))?);
777    Ok(Value::Object(object))
778}
779
780/// One row of the parts list.
781#[derive(Debug, Clone, PartialEq, Serialize)]
782#[serde(rename_all = "camelCase")]
783pub struct PartsRow {
784    pub part: String,
785    /// The display name ([`Add::display_name`]).
786    pub name: String,
787    pub find_number: String,
788    pub quantity: usize,
789    pub subassembly: bool,
790    pub first_step: String,
791}
792