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