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