Skip to main content

brep_instructions/
edit.rs

1//! Step editing: merge, split, insert, reorder, nest, move a part between
2//! steps, update a step's fields, and each step's presentation.
3//!
4//! Merge, split, reorder and a part's move stay among siblings (the steps
5//! under one parent): a group builds one thing. [`nest_step`] moves a step to
6//! another parent, children and all. Each refusal says why.
7
8use crate::model::{Add, Arrow, Callout, Instructions, Signoff, Step, Torque, ToolUse};
9use crate::wizard::{Component, Level};
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12use std::collections::HashSet;
13
14/// Merge `step_ids` (two or more siblings) into the first of them in their
15/// order, which keeps its place: adds, tools, callouts, arrows and child
16/// steps are appended in order, notes joined, and the first torque and view
17/// kept.
18pub fn merge(block: &mut Instructions, step_ids: &[&str]) -> Result<String, String> {
19    if step_ids.len() < 2 {
20        return Err("pick two or more steps to merge".into());
21    }
22    let mut located = Vec::new();
23    for id in step_ids {
24        let parent = block.parent_id(id).ok_or_else(|| format!("no step '{id}'"))?.map(str::to_string);
25        let (_, index) = block.siblings(id).ok_or_else(|| format!("no step '{id}'"))?;
26        if located.contains(&(parent.clone(), index)) {
27            return Err(format!("step '{id}' is named twice"));
28        }
29        located.push((parent, index));
30    }
31    if located.iter().any(|(parent, _)| *parent != located[0].0) {
32        return Err("only sibling steps can be merged (steps under the same parent): these are not siblings".into());
33    }
34    let mut indices: Vec<usize> = located.iter().map(|(_, i)| *i).collect();
35    indices.sort_unstable();
36    let (steps, _) = block.siblings_mut(step_ids[0]).ok_or_else(|| format!("no step '{}'", step_ids[0]))?;
37    let mut absorbed: Vec<Step> = Vec::new();
38    for &i in indices[1..].iter().rev() {
39        absorbed.push(steps.remove(i));
40    }
41    absorbed.reverse();
42    let keeper = &mut steps[indices[0]];
43    for step in absorbed {
44        keeper.adds.extend(step.adds);
45        for tool in step.tools {
46            if !keeper.tools.contains(&tool) {
47                keeper.tools.push(tool);
48            }
49        }
50        keeper.callouts.extend(step.callouts);
51        keeper.arrows.extend(step.arrows);
52        if !step.notes.is_empty() {
53            if !keeper.notes.is_empty() {
54                keeper.notes.push('\n');
55            }
56            keeper.notes.push_str(&step.notes);
57        }
58        if keeper.torque.is_none() {
59            keeper.torque = step.torque;
60        }
61        if keeper.view.is_none() {
62            keeper.view = step.view;
63        }
64        if keeper.motion.is_none() {
65            keeper.motion = step.motion;
66        }
67        keeper.signoff.required |= step.signoff.required;
68        keeper.steps.extend(step.steps);
69    }
70    keeper.coalesce_adds();
71    Ok(keeper.id.clone())
72}
73
74/// Split the adds at `add_indices` out of `step_id` into a new step right
75/// after it, with the arrows and callouts that point at their occurrences.
76/// Returns the new step's id.
77pub fn split(block: &mut Instructions, step_id: &str, add_indices: &[usize]) -> Result<String, String> {
78    let count = block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?.adds.len();
79    let picked: HashSet<usize> = add_indices.iter().copied().collect();
80    if picked.is_empty() {
81        return Err("pick the parts to split into a new step".into());
82    }
83    if let Some(bad) = picked.iter().find(|&&i| i >= count) {
84        return Err(format!("step '{step_id}' has no part {bad}"));
85    }
86    if picked.len() == count {
87        return Err("a split must leave at least one part in the step".into());
88    }
89    let id = block.next_id("MS");
90    let (steps, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
91    let step = &mut steps[s];
92    let (moved, kept): (Vec<_>, Vec<_>) =
93        std::mem::take(&mut step.adds).into_iter().enumerate().partition(|(i, _)| picked.contains(i));
94    step.adds = kept.into_iter().map(|(_, a)| a).collect();
95    let moved: Vec<_> = moved.into_iter().map(|(_, a)| a).collect();
96    let moved_occurrences: HashSet<&str> = moved.iter().flat_map(|a| a.occurrences.iter().map(String::as_str)).collect();
97    let (arrows, kept_arrows): (Vec<Arrow>, Vec<Arrow>) =
98        std::mem::take(&mut step.arrows).into_iter().partition(|a| moved_occurrences.contains(a.occurrence.as_str()));
99    step.arrows = kept_arrows;
100    let (callouts, kept_callouts): (Vec<Callout>, Vec<Callout>) = std::mem::take(&mut step.callouts)
101        .into_iter()
102        .partition(|k| k.occurrence.as_deref().is_some_and(|o| moved_occurrences.contains(o)));
103    step.callouts = kept_callouts;
104    let torque = if moved.iter().any(|a| a.fastener) { step.torque.clone() } else { None };
105    if torque.is_some() && !step.adds.iter().any(|a| a.fastener) {
106        step.torque = None;
107    }
108    let title = match moved.as_slice() {
109        [one] if one.quantity() == 1 => format!("Install {}", one.part),
110        [one] => format!("Install {} × {}", one.quantity(), one.part),
111        _ => format!("{} (continued)", step.title),
112    };
113    let tools = step.tools.clone();
114    let new = Step { id: id.clone(), title, adds: moved, tools, torque, callouts, arrows, ..Step::default() };
115    steps.insert(s + 1, new);
116    Ok(id)
117}
118
119/// Move `step_id` to `index` among its siblings (clamped to the end).
120pub fn move_step(block: &mut Instructions, step_id: &str, index: usize) -> Result<(), String> {
121    let (steps, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
122    let step = steps.remove(s);
123    let index = index.min(steps.len());
124    steps.insert(index, step);
125    Ok(())
126}
127
128/// Move `step_id`, children and all, under `parent` (`None`: the top level)
129/// at `index` among its new siblings (clamped to the end). Its id, and its
130/// children's, never change. A step cannot go inside itself.
131pub fn nest_step(block: &mut Instructions, step_id: &str, parent: Option<&str>, index: usize) -> Result<(), String> {
132    let step = block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
133    if let Some(parent) = parent {
134        if step.contains(parent) {
135            return Err(format!("step '{step_id}' cannot be nested inside itself"));
136        }
137        block.step(parent).ok_or_else(|| format!("no step '{parent}'"))?;
138    }
139    let (siblings, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
140    let step = siblings.remove(s);
141    let list = match parent {
142        None => &mut block.steps,
143        Some(parent) => &mut block.step_mut(parent).ok_or_else(|| format!("no step '{parent}'"))?.steps,
144    };
145    let index = index.min(list.len());
146    list.insert(index, step);
147    Ok(())
148}
149
150/// Move one add (by index) from `from` to `to`, a sibling step. The source
151/// step may be left empty; it is then listed by [`empty_steps`].
152pub fn move_add(block: &mut Instructions, from: &str, add_index: usize, to: &str) -> Result<(), String> {
153    let from_parent = block.parent_id(from).ok_or_else(|| format!("no step '{from}'"))?.map(str::to_string);
154    let to_parent = block.parent_id(to).ok_or_else(|| format!("no step '{to}'"))?.map(str::to_string);
155    if from_parent != to_parent {
156        return Err("a part can only move to a sibling step (one under the same parent)".into());
157    }
158    if from == to {
159        return Ok(());
160    }
161    let source = block.step_mut(from).ok_or_else(|| format!("no step '{from}'"))?;
162    if add_index >= source.adds.len() {
163        return Err(format!("step '{from}' has no part {add_index}"));
164    }
165    let add = source.adds.remove(add_index);
166    let occurrences: HashSet<String> = add.occurrences.iter().cloned().collect();
167    let (arrows, kept): (Vec<Arrow>, Vec<Arrow>) =
168        std::mem::take(&mut source.arrows).into_iter().partition(|a| occurrences.contains(&a.occurrence));
169    source.arrows = kept;
170    let target = block.step_mut(to).ok_or_else(|| format!("no step '{to}'"))?;
171    target.adds.push(add);
172    target.coalesce_adds();
173    target.arrows.extend(arrows);
174    Ok(())
175}
176
177/// A new empty step right after `after` among its siblings, or at the end of
178/// the top level. Parts come to it by [`move_add`]. Returns its id.
179pub fn insert_step(block: &mut Instructions, after: Option<&str>) -> Result<String, String> {
180    if let Some(step_id) = after {
181        block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
182    }
183    let id = block.next_id("MS");
184    let step = Step::new(id.clone(), "New step".into());
185    match after {
186        Some(step_id) => {
187            let (steps, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
188            steps.insert(s + 1, step);
189        }
190        None => block.steps.push(step),
191    }
192    Ok(id)
193}
194
195/// What [`add_parts`] did: how many occurrences joined the step, and the
196/// ones left where they were, each with the step that holds it (or the
197/// sub-assembly it is inside).
198#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
199#[serde(rename_all = "camelCase")]
200pub struct AddReport {
201    pub added: usize,
202    #[serde(default)]
203    pub left: Vec<LeftOccurrence>,
204}
205
206#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
207#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase")]
209pub struct LeftOccurrence {
210    pub occurrence: String,
211    /// The step that adds it, or the step that places the sub-assembly it
212    /// is inside.
213    pub step: String,
214}
215
216/// The step that holds `occurrence`: the one adding it (`exact`), else the
217/// one adding its nearest ancestor (a sub-assembly placed whole).
218fn holder<'a>(block: &'a Instructions, occurrence: &str) -> Option<(&'a Step, bool)> {
219    let mut best: Option<(&Step, usize)> = None;
220    for (_, step) in block.steps() {
221        for added in step.adds.iter().flat_map(|a| a.occurrences.iter()) {
222            if added == occurrence {
223                return Some((step, true));
224            }
225            if occurrence.starts_with(added.as_str()) && occurrence[added.len()..].starts_with(':') && best.is_none_or(|(_, len)| added.len() > len) {
226                best = Some((step, added.len()));
227            }
228        }
229    }
230    best.map(|(step, _)| (step, false))
231}
232
233/// Add `components` (parts of the assembly, by occurrence) to `step_id`: a
234/// BOM row dragged into a step. An occurrence already in a step, or inside
235/// a sub-assembly another step places whole, is left where it is and
236/// reported, unless the target step is inside that sub-assembly's group
237/// (a descendant of the step placing it, not that step itself: the step
238/// placing the whole never also adds one of its parts). A fastener brings
239/// its torque when
240/// the step has none. Rows coalesce as everywhere ([`Step::coalesce_adds`]).
241pub fn add_parts(block: &mut Instructions, step_id: &str, components: &[&Component]) -> Result<AddReport, String> {
242    block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
243    let mut report = AddReport::default();
244    let mut adds: Vec<Add> = Vec::new();
245    let mut torque = None;
246    for component in components {
247        match holder(block, &component.path) {
248            Some((step, true)) => report.left.push(LeftOccurrence { occurrence: component.path.clone(), step: step.id.clone() }),
249            Some((step, false)) if step.id == step_id || !step.contains(step_id) => {
250                report.left.push(LeftOccurrence { occurrence: component.path.clone(), step: step.id.clone() })
251            }
252            _ => {
253                if adds.iter().any(|a| a.occurrences.contains(&component.path)) {
254                    continue;
255                }
256                adds.push(Add {
257                    find_number: component.find_number.clone(),
258                    subassembly: component.children.is_some(),
259                    fastener: component.fastener,
260                    serial_tracked: component.serial_tracked,
261                    ..Add::named(vec![component.path.clone()], component.part_key(), &component.part)
262                });
263                if component.fastener && torque.is_none() {
264                    torque = component.torque.as_deref().and_then(Torque::from_attribute);
265                }
266                report.added += 1;
267            }
268        }
269    }
270    let step = block.step_mut(step_id).expect("checked above");
271    step.adds.extend(adds);
272    if step.torque.is_none() {
273        step.torque = torque;
274    }
275    step.coalesce_adds();
276    Ok(report)
277}
278
279/// Take one add (by index) out of `step_id`: the part is in no step any
280/// more ("not yet planned", [`unplanned`]); its insertion arrows and the
281/// callouts pointing at its occurrences go with it. Returns the add.
282pub fn remove_add(block: &mut Instructions, step_id: &str, add_index: usize) -> Result<Add, String> {
283    let step = block.step_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
284    if add_index >= step.adds.len() {
285        return Err(format!("step '{step_id}' has no part {add_index}"));
286    }
287    let add = step.adds.remove(add_index);
288    let gone: HashSet<&str> = add.occurrences.iter().map(String::as_str).collect();
289    step.arrows.retain(|a| !gone.contains(a.occurrence.as_str()));
290    step.callouts.retain(|c| !c.occurrence.as_deref().is_some_and(|o| gone.contains(o)));
291    if !step.adds.iter().any(|a| a.fastener) && step.torque.as_ref().is_some_and(|t| t.source == crate::model::TorqueSource::Part) {
292        step.torque = None;
293    }
294    Ok(add)
295}
296
297/// The parts of `level` not yet in any step, top-most first: a component no
298/// step adds, itself or through an ancestor; and, inside a sub-assembly
299/// built step by step (the step placing it has child steps), a part no step
300/// adds itself (its own step lost it). A sub-assembly's parts are not listed
301/// while the sub-assembly itself is unplanned (they come with it) nor while a
302/// step places it whole with no child steps (the whole covers them).
303pub fn unplanned<'a>(block: &Instructions, level: &'a Level) -> Vec<&'a Component> {
304    fn walk<'a>(block: &Instructions, level: &'a Level, out: &mut Vec<&'a Component>) {
305        for component in &level.components {
306            match holder(block, &component.path) {
307                None => out.push(component),
308                Some((placing, false)) => {
309                    if !placing.steps.is_empty() {
310                        out.push(component);
311                    }
312                }
313                Some((_, true)) => {
314                    if let Some(children) = &component.children {
315                        walk(block, children, out);
316                    }
317                }
318            }
319        }
320    }
321    let mut out = Vec::new();
322    walk(block, level, &mut out);
323    out
324}
325
326/// Steps with nothing to add and no steps under them (a group with parts
327/// only in its children is not empty).
328pub fn empty_steps(block: &Instructions) -> Vec<String> {
329    block.steps().filter(|(_, s)| s.adds.is_empty() && s.steps.is_empty()).map(|(_, s)| s.id.clone()).collect()
330}
331
332/// Delete a step. Its parts must have moved elsewhere first, so no part is
333/// silently dropped from the instructions, and its child steps too.
334pub fn delete_step(block: &mut Instructions, step_id: &str) -> Result<(), String> {
335    let step = block.step(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
336    if !step.adds.is_empty() {
337        return Err("move this step's parts to another step before deleting it".into());
338    }
339    if !step.steps.is_empty() {
340        return Err("move or delete the steps under this step before deleting it".into());
341    }
342    let (steps, s) = block.siblings_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
343    steps.remove(s);
344    Ok(())
345}
346
347/// Update a step's authored fields from a JSON patch. Keys: `title`, `notes`,
348/// `view` (string or null), `tools` (array), `torque` (object or null; a set
349/// torque becomes an override), `callouts`, `arrows`, `signoff`, `motion`.
350/// Unknown keys are refused. `adds` change only through the edits above.
351pub fn update_step(block: &mut Instructions, step_id: &str, patch: &Value) -> Result<(), String> {
352    let object = patch.as_object().ok_or("a step update is a JSON object")?;
353    let mut ids_needed = 0;
354    if let Some(Value::Array(callouts)) = object.get("callouts") {
355        ids_needed = callouts.iter().filter(|c| c.get("id").and_then(Value::as_str).is_none_or(str::is_empty)).count();
356    }
357    let mut fresh: Vec<String> = (0..ids_needed).map(|_| block.next_id("MK")).collect();
358    let step = block.step_mut(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
359    let mut next = step.clone();
360    for (key, value) in object {
361        let parse = |what: &str| format!("step {key}: not a valid {what}");
362        match key.as_str() {
363            "title" => next.title = value.as_str().ok_or_else(|| parse("text"))?.to_string(),
364            "notes" => next.notes = value.as_str().ok_or_else(|| parse("text"))?.to_string(),
365            "view" => next.view = value.as_str().filter(|v| !v.is_empty()).map(str::to_string),
366            "tools" => next.tools = serde_json::from_value::<Vec<ToolUse>>(value.clone()).map_err(|_| parse("tools list"))?,
367            "torque" => {
368                next.torque = if value.is_null() {
369                    None
370                } else {
371                    let mut torque: Torque = serde_json::from_value(with_source(value)).map_err(|_| parse("torque"))?;
372                    torque.source = crate::model::TorqueSource::Override;
373                    Some(torque)
374                }
375            }
376            "callouts" => {
377                let mut list = Vec::new();
378                for item in value.as_array().ok_or_else(|| parse("callouts list"))? {
379                    let mut item = item.clone();
380                    if item.get("id").and_then(Value::as_str).is_none_or(str::is_empty) {
381                        item["id"] = Value::String(fresh.remove(0));
382                    }
383                    list.push(serde_json::from_value::<Callout>(item).map_err(|_| parse("callout"))?);
384                }
385                next.callouts = list;
386            }
387            "arrows" => next.arrows = serde_json::from_value::<Vec<Arrow>>(value.clone()).map_err(|_| parse("arrows list"))?,
388            "signoff" => next.signoff = serde_json::from_value::<Signoff>(value.clone()).map_err(|_| parse("signoff"))?,
389            "motion" => next.motion = (!value.is_null()).then(|| value.clone()),
390            other => return Err(format!("a step has no field '{other}'")),
391        }
392    }
393    *step = next;
394    Ok(())
395}
396
397fn with_source(value: &Value) -> Value {
398    let mut value = value.clone();
399    if let Some(object) = value.as_object_mut() {
400        object.entry("source").or_insert(Value::String("override".into()));
401    }
402    value
403}
404
405/// What a step shows: occurrences placed in earlier steps (drawn ghosted),
406/// those this step adds (highlighted), and those not placed yet (hidden).
407#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
408#[serde(rename_all = "camelCase")]
409pub struct Presentation {
410    pub placed: Vec<String>,
411    pub adding: Vec<String>,
412    pub hidden: Vec<String>,
413}
414
415/// The presentation of `step_id` over `occurrences`, the occurrence paths of
416/// the drawn solids (a sub-assembly occurrence stands for every path under
417/// it). The step adds what it and its descendants add (a parent installs the
418/// group its children built); placed is what its earlier siblings, and their
419/// descendants, added; a step inside a group sees nothing of the assembly
420/// around the group. Everything else is hidden.
421pub fn presentation(block: &Instructions, step_id: &str, occurrences: &[String]) -> Result<Presentation, String> {
422    let (siblings, s) = block.siblings(step_id).ok_or_else(|| format!("no step '{step_id}'"))?;
423    let mut earlier_list = Vec::new();
424    for sibling in &siblings[..s] {
425        sibling.occurrences_with_descendants(&mut earlier_list);
426    }
427    let earlier: HashSet<&str> = earlier_list.into_iter().collect();
428    let mut now_list = Vec::new();
429    siblings[s].occurrences_with_descendants(&mut now_list);
430    let now: HashSet<&str> = now_list.into_iter().collect();
431    let mut out = Presentation::default();
432    for path in occurrences {
433        let covered = |set: &HashSet<&str>| {
434            set.contains(path.as_str()) || set.iter().any(|p| path.starts_with(p) && path[p.len()..].starts_with(':'))
435        };
436        if covered(&now) {
437            out.adding.push(path.clone());
438        } else if covered(&earlier) {
439            out.placed.push(path.clone());
440        } else {
441            out.hidden.push(path.clone());
442        }
443    }
444    Ok(out)
445}
446