Skip to main content

brep_app/panels/
component_actions.rs

1//! The shared COMPONENT action set (assemblies build-spec §8.5) — the ONE
2//! entry point for per-component interactions, consumed by the selection
3//! context bar (this lane) and, through the same enum, by the assembly
4//! structure tree's per-node action hooks (lane F seam: the tree calls
5//! [`run_component_action`] with the node's owning ACOMP feature id — actions
6//! always ROUTE TO the owning feature, one truth, one undo lane).
7//!
8//! Engine-mutating actions (Move / Fix-Unfix / Delete) run HERE against
9//! [`EngineState`]; the document-level flow (Edit Part) returns a
10//! [`ComponentActionRequest`] for the SHELL, which owns the open documents and
11//! the file dialog.
12
13use brep_render::engine_state::EngineState;
14
15/// One per-component action (spec §8.5 / §8.2 tree actions).
16#[derive(Clone, Copy, PartialEq, Eq, Debug)]
17pub enum ComponentAction {
18    /// Toggle the Move gizmo on/off — arrows + rotation arcs together (fixed refuses
19    /// with a toast). Engine-side.
20    Move,
21    /// Open the part's SOURCE document in its own document tab (shell-side).
22    /// Editing a component IS opening its part: there is no separate
23    /// edit-in-place session any more — the part is a document like any other,
24    /// and the assembly picks the change up through the outdated badge /
25    /// `panels::update_components` once the part is saved.
26    OpenPart,
27    /// Fix ⇄ Unfix (writes `isFixed` on the owning ACOMP; re-runs + re-solves).
28    ToggleFixed,
29    /// Delete the owning ACOMP feature (the library entry GC's kernel-side when
30    /// its last instance goes).
31    Delete,
32}
33
34impl ComponentAction {
35    /// Every action, in bar order.
36    pub const ALL: [ComponentAction; 4] = [
37        ComponentAction::Move,
38        ComponentAction::OpenPart,
39        ComponentAction::ToggleFixed,
40        ComponentAction::Delete,
41    ];
42
43    /// Stable id (widget keys / verifier state).
44    pub fn id(self) -> &'static str {
45        match self {
46            ComponentAction::Move => "move",
47            ComponentAction::OpenPart => "open-part",
48            ComponentAction::ToggleFixed => "toggle-fixed",
49            ComponentAction::Delete => "delete",
50        }
51    }
52
53    /// The id in reverse (`None` for an unknown id).
54    pub fn from_id(id: &str) -> Option<Self> {
55        Self::ALL.into_iter().find(|action| action.id() == id)
56    }
57
58    /// The button label. `fixed` flips the Fix/Unfix wording.
59    pub fn label(self, fixed: bool) -> &'static str {
60        match self {
61            ComponentAction::Move => "\u{2725} Move",
62            ComponentAction::OpenPart => "\u{270E} Edit Part",
63            ComponentAction::ToggleFixed => {
64                if fixed {
65                    "\u{1F513} Unfix"
66                } else {
67                    "\u{1F512} Fix"
68                }
69            }
70            ComponentAction::Delete => "\u{2716} Delete",
71        }
72    }
73
74    /// Hover tooltip.
75    pub fn tooltip(self) -> &'static str {
76        match self {
77            ComponentAction::Move => "Move/rotate gizmo on-off (arrows + arcs together)",
78            ComponentAction::OpenPart => "Open the part's source document in its own tab",
79            ComponentAction::ToggleFixed => "Ground / free this instance for the solver",
80            ComponentAction::Delete => "Delete this component instance",
81        }
82    }
83}
84
85/// A document-level flow the SHELL must run (it owns the open documents + the
86/// file dialog); engine-mutating actions never produce one.
87#[derive(Clone, PartialEq, Eq, Debug)]
88pub enum ComponentActionRequest {
89    OpenPart { component_id: String },
90}
91
92/// Run `action` on the component owned by ACOMP feature `component_id`.
93/// Engine-mutating actions apply immediately; Edit Part returns the request the
94/// shell dispatches. Unknown component ids toast.
95pub fn run_component_action(
96    state: &mut EngineState,
97    action: ComponentAction,
98    component_id: &str,
99) -> Option<ComponentActionRequest> {
100    match action {
101        ComponentAction::Move => {
102            // Toggle the full gizmo (arrows + arcs together); a FIXED component
103            // refuses with a toast inside the engine (spec §8.5).
104            state.component_move_toggle(component_id);
105            None
106        }
107        ComponentAction::ToggleFixed => {
108            let Some(info) = state.component_info(component_id) else {
109                state.push_notice(format!("'{component_id}' is not an assembly component"));
110                return None;
111            };
112            let mut params = serde_json::from_str::<serde_json::Value>(
113                &state.feature_params_json(feature_index(state, component_id)?),
114            )
115            .unwrap_or_else(|_| serde_json::json!({}));
116            if let Some(object) = params.as_object_mut() {
117                // An EXPLICIT boolean either way — the kernel honors explicit
118                // `false` (un-fixing the sole component stays possible; the
119                // absent-auto-grounds rule keys on absence only).
120                object.insert("isFixed".into(), serde_json::Value::Bool(!info.fixed));
121            }
122            let _ = state.update_feature_params(component_id, &params.to_string());
123            None
124        }
125        ComponentAction::Delete => {
126            // Deleting the feature is the ONE truth (tree/bar both route here);
127            // the parts-library entry GC's at the kernel's next rebuild when its
128            // last instance goes.
129            let _ = state.delete_feature(component_id);
130            None
131        }
132        ComponentAction::OpenPart => Some(ComponentActionRequest::OpenPart {
133            component_id: component_id.to_string(),
134        }),
135    }
136}
137
138/// The feature index carrying id `id` (the engine exposes index→id, so scan).
139fn feature_index(state: &EngineState, id: &str) -> Option<usize> {
140    (0..state.history_len()).find(|&i| state.feature_id_at(i).as_deref() == Some(id))
141}
142
143/// The component's parts-library `sourceKey` (the ModelStore document name the
144/// part was inserted from), read off the document's `partsLibrary` block —
145/// `None` when the component / entry / key is absent (an imported or
146/// embedded-only part, which therefore has no file to open). The Edit-Part flow
147/// keys its store lookup on this.
148pub fn part_source_key(state: &EngineState, component_id: &str) -> Option<String> {
149    let info = state.component_info(component_id)?;
150    let document: serde_json::Value =
151        serde_json::from_str(&state.history_request_json()).ok()?;
152    document["partsLibrary"][&info.part_name]["sourceKey"]
153        .as_str()
154        .filter(|key| !key.is_empty())
155        .map(str::to_string)
156}
157
158// BREP private tests: 6e2e5385bc2bda24