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    /// What the person doing the work records at the step, in order: boxes
217    /// to tick, choices, written text, measurements, serial numbers.
218    #[serde(default, skip_serializing_if = "Vec::is_empty")]
219    pub fields: Vec<crate::fields::StepField>,
220    /// The author captured the view's camera from the viewport: it is kept
221    /// through every regeneration until Reset view. Otherwise the engine
222    /// generates the camera from the step's parts and its parent's direction.
223    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
224    pub camera_captured: bool,
225    /// Child steps, in order: the group this step installs. They are read
226    /// before it and see only the group's own parts.
227    #[serde(default, skip_serializing_if = "Vec::is_empty")]
228    pub steps: Vec<Step>,
229}
230
231/// Parts one step adds: one part, at one or more occurrences.
232#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
233#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
234#[serde(rename_all = "camelCase")]
235pub struct Add {
236    /// Occurrence paths, relative to the document (`ACOMP1:ACOMP3`).
237    pub occurrences: Vec<String>,
238    /// The part: its PLM part id when it was placed from a PLM revision
239    /// (what the server and the thumbnails key on), else its name.
240    pub part: String,
241    /// The display name, when it differs from `part` (a PLM part): what the
242    /// pane, the parts list and the player show. See [`Add::display_name`].
243    #[serde(default, skip_serializing_if = "String::is_empty")]
244    pub name: String,
245    #[serde(default)]
246    pub find_number: String,
247    /// A finished sub-assembly placed as one part.
248    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
249    pub subassembly: bool,
250    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
251    pub fastener: bool,
252    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
253    pub serial_tracked: bool,
254}
255
256impl Add {
257    pub fn quantity(&self) -> usize {
258        self.occurrences.len()
259    }
260
261    /// What to show for the part: its name, else `part` (an add written
262    /// before names were carried, or a part that is its own name).
263    pub fn display_name(&self) -> &str {
264        if self.name.is_empty() {
265            &self.part
266        } else {
267            &self.name
268        }
269    }
270
271    /// An add for `part` named `name` (the name is written only when it
272    /// differs).
273    pub fn named(occurrences: Vec<String>, part: &str, name: &str) -> Self {
274        Self {
275            occurrences,
276            part: part.to_string(),
277            name: if name == part { String::new() } else { name.to_string() },
278            ..Self::default()
279        }
280    }
281
282    /// The same BOM row: the same part under the same find number, placed
283    /// the same way (a sub-assembly is not the part of the same name).
284    fn same_row(&self, other: &Add) -> bool {
285        self.part == other.part && self.find_number == other.find_number && self.subassembly == other.subassembly
286    }
287}
288
289impl Step {
290    /// An empty step with `id` and `title`.
291    pub fn new(id: String, title: String) -> Self {
292        Self { id, title, ..Self::default() }
293    }
294
295    /// Whether `step_id` is this step or one of its descendants.
296    pub fn contains(&self, step_id: &str) -> bool {
297        self.id == step_id || self.steps.iter().any(|s| s.contains(step_id))
298    }
299
300    /// Whether the step is on a build's checklist: it needs a sign-off, or
301    /// it carries fields to record (a field is captured with its step's
302    /// completion, so a step with fields is completed like a signed one).
303    pub fn on_checklist(&self) -> bool {
304        self.signoff.required || !self.fields.is_empty()
305    }
306
307    /// Whether this step places a sub-assembly at `occurrence`.
308    fn places(&self, occurrence: &str) -> bool {
309        self.adds.iter().any(|a| a.subassembly && a.occurrences.iter().any(|o| o == occurrence))
310    }
311
312    /// Every occurrence this step and its descendants add.
313    pub fn occurrences_with_descendants<'a>(&'a self, out: &mut Vec<&'a str>) {
314        out.extend(self.adds.iter().flat_map(|a| a.occurrences.iter().map(String::as_str)));
315        for child in &self.steps {
316            child.occurrences_with_descendants(out);
317        }
318    }
319
320    /// One BOM row per part: adds of the same row (see `Add::same_row`)
321    /// become one add holding every occurrence, in first-add order. Merged
322    /// steps, moved parts and documents written one add per occurrence all
323    /// read as `8 × bolt`, never eight rows of `1 × bolt`.
324    pub fn coalesce_adds(&mut self) {
325        let mut rows: Vec<Add> = Vec::with_capacity(self.adds.len());
326        for mut add in std::mem::take(&mut self.adds) {
327            match rows.iter_mut().find(|row| row.same_row(&add)) {
328                Some(row) => {
329                    row.occurrences.append(&mut add.occurrences);
330                    row.fastener |= add.fastener;
331                    row.serial_tracked |= add.serial_tracked;
332                }
333                None => rows.push(add),
334            }
335        }
336        self.adds = rows;
337    }
338}
339
340/// A tool a step uses: a tools-library entry by id, with a snapshot of its
341/// name and spec so printed and offline copies need no server.
342#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
343#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
344#[serde(rename_all = "camelCase")]
345pub struct ToolUse {
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    pub tool_id: Option<String>,
348    pub name: String,
349    #[serde(default)]
350    pub spec: String,
351    /// Added without the library (no session); listed for linking.
352    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
353    pub unlinked: bool,
354}
355
356#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
357#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
358#[serde(rename_all = "lowercase")]
359pub enum TorqueSource {
360    /// Defaulted from the fastener part's attribute.
361    Part,
362    /// Set on the step by the author.
363    Override,
364}
365
366#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
367#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
368#[serde(rename_all = "camelCase")]
369pub struct Torque {
370    /// As authored (`12`, `10-12`).
371    pub value: String,
372    #[serde(default)]
373    pub unit: String,
374    pub source: TorqueSource,
375}
376
377impl Torque {
378    /// A torque attribute's text (`12 N·m`) split at its first space into
379    /// value and unit; `None` for an empty one.
380    pub fn from_attribute(text: &str) -> Option<Self> {
381        let text = text.trim();
382        if text.is_empty() {
383            return None;
384        }
385        let (value, unit) = match text.split_once(char::is_whitespace) {
386            Some((value, unit)) => (value.trim(), unit.trim()),
387            None => (text, ""),
388        };
389        Some(Self { value: value.into(), unit: unit.into(), source: TorqueSource::Part })
390    }
391
392    /// `12 N·m`.
393    pub fn text(&self) -> String {
394        if self.unit.is_empty() {
395            self.value.clone()
396        } else {
397            format!("{} {}", self.value, self.unit)
398        }
399    }
400}
401
402#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
403#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
404#[serde(rename_all = "lowercase")]
405pub enum CalloutKind {
406    Caution,
407    Note,
408    Check,
409}
410
411impl CalloutKind {
412    pub fn label(self) -> &'static str {
413        match self {
414            Self::Caution => "Caution",
415            Self::Note => "Note",
416            Self::Check => "Check",
417        }
418    }
419}
420
421#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
422#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
423#[serde(rename_all = "camelCase")]
424pub struct Callout {
425    pub id: String,
426    pub kind: CalloutKind,
427    pub text: String,
428    /// The occurrence the callout points at, if any.
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub occurrence: Option<String>,
431}
432
433#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
434#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
435#[serde(rename_all = "camelCase")]
436pub struct Arrow {
437    pub occurrence: String,
438    /// The direction the part travels IN from (unit-free; normalised on use).
439    pub direction: [f64; 3],
440    /// How far out the motion starts, in model units.
441    pub distance: f64,
442}
443
444impl Arrow {
445    /// The start offset of the insertion: `-direction` scaled to `distance`,
446    /// so the part travels along `direction` to home. Zero for a zero vector.
447    pub fn start_offset(&self) -> [f64; 3] {
448        let [x, y, z] = self.direction;
449        let length = (x * x + y * y + z * z).sqrt();
450        if !(length > 1e-12) || !self.distance.is_finite() {
451            return [0.0; 3];
452        }
453        let k = -self.distance / length;
454        [x * k, y * k, z * k]
455    }
456}
457
458#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
459#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
460#[serde(rename_all = "camelCase")]
461pub struct Signoff {
462    pub required: bool,
463}
464
465impl Default for Signoff {
466    fn default() -> Self {
467        Self { required: true }
468    }
469}
470
471/// One occurrence in a re-target diff.
472#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
473#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
474#[serde(rename_all = "camelCase")]
475pub struct OccurrenceChange {
476    pub occurrence: String,
477    pub part: String,
478    /// For a replaced occurrence: the part it was.
479    #[serde(default, skip_serializing_if = "Option::is_none")]
480    pub was: Option<String>,
481}
482
483/// A re-target waiting for approval: what changed between the two assembly
484/// revisions and the steps it touches.
485#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
486#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
487#[serde(rename_all = "camelCase")]
488pub struct Retarget {
489    pub from: Target,
490    pub to: Target,
491    #[serde(default)]
492    pub added: Vec<OccurrenceChange>,
493    #[serde(default)]
494    pub removed: Vec<OccurrenceChange>,
495    #[serde(default)]
496    pub replaced: Vec<OccurrenceChange>,
497    /// Steps an add was removed from or changed in, and steps made for the
498    /// added parts.
499    #[serde(default)]
500    pub touched_steps: Vec<String>,
501    /// Steps left with nothing to add.
502    #[serde(default)]
503    pub empty_steps: Vec<String>,
504}
505
506impl Instructions {
507    /// A new, empty block for `target`.
508    pub fn new(target: Target) -> Self {
509        let title = target.name.clone();
510        Self {
511            schema: SCHEMA,
512            target,
513            template: Template::default(),
514            front: FrontMatter { title, ..FrontMatter::default() },
515            steps: Vec::new(),
516            id_counter: 0,
517            retarget: None,
518        }
519    }
520
521    /// Read the block from its JSON, validated. A schema-1 block (chapters of
522    /// steps) reads as the tree: the root chapter's steps at the top, a
523    /// sub-assembly's chapter as the children of the step that places it, and
524    /// is schema 2 from then on (written back on the next edit).
525    pub fn from_value(value: &Value) -> Result<Self, String> {
526        let schema = value.get("schema").and_then(Value::as_u64).unwrap_or(0);
527        let value = if schema == 1 { migrate_chapters(value)? } else { value.clone() };
528        let mut block: Self = serde_json::from_value(value).map_err(|e| format!("instructions block: {e}"))?;
529        block.validate()?;
530        block.coalesce_adds();
531        Ok(block)
532    }
533
534    /// Every step's adds as one row per part ([`Step::coalesce_adds`]).
535    pub fn coalesce_adds(&mut self) {
536        for_each_step_mut(&mut self.steps, &mut |step| step.coalesce_adds());
537    }
538
539    /// Read the block out of a whole document, if it has one.
540    pub fn from_document(document: &Value) -> Result<Option<Self>, String> {
541        match document.get(BLOCK_KEY) {
542            None | Some(Value::Null) => Ok(None),
543            Some(block) => Self::from_value(block).map(Some),
544        }
545    }
546
547    pub fn to_value(&self) -> Value {
548        serde_json::to_value(self).expect("instructions block serializes")
549    }
550
551    /// The structural rules: a known schema, a template the layout can draw,
552    /// unique step and field ids over the whole tree, well-formed fields, and
553    /// no occurrence added twice.
554    pub fn validate(&self) -> Result<(), String> {
555        if self.schema == 0 || self.schema > SCHEMA {
556            return Err(format!("instructions schema {} is not supported (this build reads up to {SCHEMA})", self.schema));
557        }
558        if !STEPS_PER_PAGE.contains(&self.template.steps_per_page) {
559            return Err(format!("steps per page must be 1, 2 or 4, not {}", self.template.steps_per_page));
560        }
561        let mut ids = HashSet::new();
562        let mut occurrences = HashSet::new();
563        for (_, step) in self.steps() {
564            if !ids.insert(step.id.as_str()) {
565                return Err(format!("duplicate id '{}'", step.id));
566            }
567            for field in &step.fields {
568                if field.id.is_empty() || !ids.insert(field.id.as_str()) {
569                    return Err(format!("duplicate id '{}'", field.id));
570                }
571                field.validate()?;
572            }
573            for add in &step.adds {
574                for occurrence in &add.occurrences {
575                    if !occurrences.insert(occurrence.as_str()) {
576                        return Err(format!("occurrence '{occurrence}' is added in more than one step"));
577                    }
578                }
579            }
580        }
581        Ok(())
582    }
583
584    /// A fresh id with `prefix` (`MS` step, `MK` callout, `MF` field; `MC` was
585    /// a chapter).
586    pub fn next_id(&mut self, prefix: &str) -> String {
587        self.id_counter += 1;
588        format!("{prefix}{}", self.id_counter)
589    }
590
591    pub fn step_count(&self) -> usize {
592        self.steps().count()
593    }
594
595    /// Every step in reading order (a step's children, depth first, before the
596    /// step itself) with its depth (0 at the top).
597    pub fn steps(&self) -> impl Iterator<Item = (usize, &Step)> {
598        fn walk<'a>(steps: &'a [Step], depth: usize, out: &mut Vec<(usize, &'a Step)>) {
599            for step in steps {
600                walk(&step.steps, depth + 1, out);
601                out.push((depth, step));
602            }
603        }
604        let mut out = Vec::with_capacity(16);
605        walk(&self.steps, 0, &mut out);
606        out.into_iter()
607    }
608
609    /// The index path of a step: an index per level from the top.
610    fn path_of(&self, step_id: &str) -> Option<Vec<usize>> {
611        fn walk(steps: &[Step], step_id: &str, path: &mut Vec<usize>) -> bool {
612            for (i, step) in steps.iter().enumerate() {
613                path.push(i);
614                if step.id == step_id || walk(&step.steps, step_id, path) {
615                    return true;
616                }
617                path.pop();
618            }
619            false
620        }
621        let mut path = Vec::new();
622        walk(&self.steps, step_id, &mut path).then_some(path)
623    }
624
625    pub fn step(&self, step_id: &str) -> Option<&Step> {
626        self.steps().find(|(_, s)| s.id == step_id).map(|(_, s)| s)
627    }
628
629    pub fn step_mut(&mut self, step_id: &str) -> Option<&mut Step> {
630        let path = self.path_of(step_id)?;
631        let (last, parents) = path.split_last()?;
632        Some(&mut list_at_mut(&mut self.steps, parents)[*last])
633    }
634
635    /// The list the step sits in (its siblings, itself included) and its index
636    /// there.
637    pub fn siblings(&self, step_id: &str) -> Option<(&[Step], usize)> {
638        let path = self.path_of(step_id)?;
639        let (last, parents) = path.split_last()?;
640        let mut list = &self.steps;
641        for &i in parents {
642            list = &list[i].steps;
643        }
644        Some((list.as_slice(), *last))
645    }
646
647    pub fn siblings_mut(&mut self, step_id: &str) -> Option<(&mut Vec<Step>, usize)> {
648        let path = self.path_of(step_id)?;
649        let (last, parents) = path.split_last()?;
650        Some((list_at_mut(&mut self.steps, parents), *last))
651    }
652
653    /// The parent step's id: `Some(None)` at the top level, `None` for an
654    /// unknown step.
655    pub fn parent_id(&self, step_id: &str) -> Option<Option<&str>> {
656        let path = self.path_of(step_id)?;
657        let (_, parents) = path.split_last()?;
658        let mut list = &self.steps;
659        let mut parent = None;
660        for &i in parents {
661            parent = Some(list[i].id.as_str());
662            list = &list[i].steps;
663        }
664        Some(parent)
665    }
666
667    /// How deep a step sits: 0 at the top level.
668    pub fn depth(&self, step_id: &str) -> Option<usize> {
669        self.path_of(step_id).map(|path| path.len() - 1)
670    }
671
672    /// The steps that build one assembly: the top level for `""`, else the
673    /// children of the step that places the sub-assembly at `occurrence`.
674    pub fn group_steps_mut(&mut self, occurrence: &str) -> Option<&mut Vec<Step>> {
675        if occurrence.is_empty() {
676            return Some(&mut self.steps);
677        }
678        let placing = self.steps().find(|(_, s)| s.places(occurrence)).map(|(_, s)| s.id.clone())?;
679        self.step_mut(&placing).map(|step| &mut step.steps)
680    }
681
682    /// The step number a reader sees (1-based, in reading order).
683    pub fn step_number(&self, step_id: &str) -> Option<usize> {
684        self.steps().position(|(_, s)| s.id == step_id).map(|n| n + 1)
685    }
686
687    /// Distinct tools in first-use order, with the step ids that use each.
688    pub fn tools_list(&self) -> Vec<(ToolUse, Vec<String>)> {
689        let mut list: Vec<(ToolUse, Vec<String>)> = Vec::new();
690        for (_, step) in self.steps() {
691            for tool in &step.tools {
692                let same = |t: &ToolUse| match (&t.tool_id, &tool.tool_id) {
693                    (Some(a), Some(b)) => a == b,
694                    (None, None) => t.name == tool.name && t.spec == tool.spec,
695                    _ => false,
696                };
697                match list.iter_mut().find(|(t, _)| same(t)) {
698                    Some((_, steps)) => {
699                        if !steps.contains(&step.id) {
700                            steps.push(step.id.clone());
701                        }
702                    }
703                    None => list.push((tool.clone(), vec![step.id.clone()])),
704                }
705            }
706        }
707        list
708    }
709
710    /// The parts list: one row per part (and per sub-assembly), with its
711    /// find number and the quantity added over every step, in first-add order.
712    pub fn parts_list(&self) -> Vec<PartsRow> {
713        let mut rows: Vec<PartsRow> = Vec::new();
714        for (_, step) in self.steps() {
715            for add in &step.adds {
716                match rows.iter_mut().find(|r| r.part == add.part && r.find_number == add.find_number) {
717                    Some(row) => row.quantity += add.quantity(),
718                    None => rows.push(PartsRow {
719                        part: add.part.clone(),
720                        name: add.display_name().to_string(),
721                        find_number: add.find_number.clone(),
722                        quantity: add.quantity(),
723                        subassembly: add.subassembly,
724                        first_step: step.id.clone(),
725                    }),
726                }
727            }
728        }
729        rows
730    }
731}
732
733/// The list at an index path (every index but the step's own).
734fn list_at_mut<'a>(mut list: &'a mut Vec<Step>, parents: &[usize]) -> &'a mut Vec<Step> {
735    for &i in parents {
736        list = &mut list[i].steps;
737    }
738    list
739}
740
741/// `f` on every step of the tree, parents before children.
742pub fn for_each_step_mut(steps: &mut [Step], f: &mut dyn FnMut(&mut Step)) {
743    for step in steps {
744        f(step);
745        for_each_step_mut(&mut step.steps, f);
746    }
747}
748
749/// Keep the steps `keep` accepts, at every level.
750pub fn retain_steps(steps: &mut Vec<Step>, keep: &dyn Fn(&Step) -> bool) {
751    steps.retain(keep);
752    for step in steps {
753        retain_steps(&mut step.steps, keep);
754    }
755}
756
757/// A schema-1 block as schema 2: the root chapter's steps are the top level;
758/// a sub-assembly's chapter becomes the children of the step that places that
759/// sub-assembly (so an old document reads as the tree the wizard proposes); a
760/// chapter no step places becomes a top-level step of its own, ahead of the
761/// root's steps as it printed, titled after the chapter and keeping its id.
762fn migrate_chapters(value: &Value) -> Result<Value, String> {
763    let mut object = value.as_object().cloned().ok_or("instructions block: not an object")?;
764    let chapters: Vec<ChapterV1> = match object.remove("chapters") {
765        Some(chapters) => serde_json::from_value(chapters).map_err(|e| format!("instructions block: chapters: {e}"))?,
766        None => Vec::new(),
767    };
768    // Writers of that era put an empty `steps` object beside the chapters.
769    object.remove("steps");
770    let (root, others): (Vec<ChapterV1>, Vec<ChapterV1>) = chapters.into_iter().partition(|c| c.assembly.is_empty());
771    let mut steps: Vec<Step> = root.into_iter().flat_map(|c| c.steps).collect();
772    // Deepest chapters come first in a schema-1 block, so walk them from the
773    // last: a sub-assembly's placing step is in place before its own chapter
774    // looks for it.
775    for chapter in others.into_iter().rev() {
776        let mut placing = None;
777        for_each_step_mut(&mut steps, &mut |step| {
778            if placing.is_none() && step.places(&chapter.assembly) {
779                placing = Some(step.id.clone());
780            }
781        });
782        let chapter_steps = chapter.steps;
783        match placing {
784            Some(id) => {
785                for_each_step_mut(&mut steps, &mut |step| {
786                    if step.id == id {
787                        step.steps = chapter_steps.clone();
788                    }
789                });
790            }
791            None => steps.insert(0, Step { id: chapter.id, title: chapter.title, steps: chapter_steps, ..Step::default() }),
792        }
793    }
794    object.insert("schema".into(), Value::from(SCHEMA));
795    object.insert("steps".into(), serde_json::to_value(steps).map_err(|e| format!("instructions block: {e}"))?);
796    Ok(Value::Object(object))
797}
798
799/// One row of the parts list.
800#[derive(Debug, Clone, PartialEq, Serialize)]
801#[serde(rename_all = "camelCase")]
802pub struct PartsRow {
803    pub part: String,
804    /// The display name ([`Add::display_name`]).
805    pub name: String,
806    pub find_number: String,
807    pub quantity: usize,
808    pub subassembly: bool,
809    pub first_step: String,
810}
811