Skip to main content

brep_render/engine_state/
sketch_panel.rs

1use super::*;
2
3/// One row in a sketch entity-LIST panel (Points / Curves / Constraints) — the
4/// display label plus the `(kind, id)` needed to select / hover / delete it, and
5/// its current selected/construction state for row styling. Built by
6/// [`EngineState::sketch_point_rows`] / `sketch_geometry_rows` /
7/// `sketch_constraint_rows`; the panel renders them and routes clicks back through
8/// [`EngineState::sketch_select_entity`] / `sketch_hover_entity`.
9#[derive(Clone, Debug, PartialEq)]
10pub struct SketchEntityRow {
11    /// Entity ref kind: `"point"` | `"geometry"` | `"constraint"`.
12    pub kind: &'static str,
13    /// The entity id (opaque `Value`, passed straight back to select/hover).
14    pub id: serde_json::Value,
15    /// Human display label (mirrors the previous list rows).
16    pub label: String,
17    /// Whether this entity is in the current sketch selection (row highlight).
18    pub selected: bool,
19    /// Construction-only entity (dashed / de-emphasized styling).
20    pub construction: bool,
21    /// The solver names this entity in a CONSTRAINT CONFLICT (constraint rows
22    /// only) — the panel paints the row red to match its canvas annotation.
23    pub conflicting: bool,
24}
25
26/// How a notice is drawn: an [`Error`](Self::Error) (a refusal, a failure —
27/// what [`EngineState::push_notice`] queues), a [`Warning`](Self::Warning)
28/// (it worked, and something needs a look) or [`Info`](Self::Info) (it worked:
29/// "Updated 2 part(s)", "Saved 'widget'").
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub enum NoticeSeverity {
32    #[default]
33    Error,
34    Warning,
35    Info,
36}
37
38impl EngineState {
39    /// Queue a notice of `severity`. [`Self::push_notice`] is this with
40    /// [`NoticeSeverity::Error`]; bounded the same way.
41    pub fn push_notice_as(&mut self, severity: NoticeSeverity, message: impl Into<String>) {
42        if severity == NoticeSeverity::Error {
43            return self.push_notice(message);
44        }
45        let message = message.into();
46        #[cfg(not(target_arch = "wasm32"))]
47        eprintln!("{message}");
48        self.graded_notices.push((severity, message));
49        if self.graded_notices.len() > 8 {
50            let overflow = self.graded_notices.len() - 8;
51            self.graded_notices.drain(0..overflow);
52        }
53    }
54
55    /// Drain every queued notice with its severity: the errors, then the
56    /// warnings and successes. The shell's toast overlay reads this.
57    pub fn take_graded_notices(&mut self) -> Vec<(NoticeSeverity, String)> {
58        let errors = std::mem::take(&mut self.notices).into_iter().map(|text| (NoticeSeverity::Error, text));
59        errors.chain(std::mem::take(&mut self.graded_notices)).collect()
60    }
61
62    /// Queue a transient user-facing notice (shown as a toast by the shell) and,
63    /// on native, also log it. Bounded so a pathological loop can't grow it.
64    pub fn push_notice(&mut self, message: impl Into<String>) {
65        let message = message.into();
66        #[cfg(not(target_arch = "wasm32"))]
67        eprintln!("{message}");
68        self.notices.push(message);
69        if self.notices.len() > 8 {
70            let overflow = self.notices.len() - 8;
71            self.notices.drain(0..overflow);
72        }
73    }
74
75    /// Drain the queued notices (the shell calls this once per frame and shows
76    /// each as a toast).
77    pub fn take_notices(&mut self) -> Vec<String> {
78        self.take_graded_notices().into_iter().map(|(_, text)| text).collect()
79    }
80
81    /// Re-solve the ACTIVE sketch session and, on failure, queue a user notice
82    /// naming `context`. Replaces the scattered swallowed `eprintln!` on the
83    /// interactive re-solve paths — the solver rarely fails, but when an edit
84    /// leaves the sketch unsolvable the user should see why.
85    pub(super) fn resolve_active_sketch(&mut self, context: &str) {
86        let error = self
87            .sketch_edit
88            .as_mut()
89            .and_then(|edit| edit.session.resolve().err());
90        if let Some(error) = error {
91            self.push_notice(format!("Sketch solve failed ({context}): {error}"));
92        }
93    }
94
95    /// Whether `(kind, id)` is in the current sketch selection.
96    fn sketch_ref_selected(session: &crate::sketch::SketchSession, kind: &str, id: &serde_json::Value) -> bool {
97        use crate::sketch::doc::id_key;
98        let key = id_key(id);
99        session.selection.iter().any(|r| {
100            r.get("kind").and_then(serde_json::Value::as_str) == Some(kind)
101                && r.get("id").map(id_key).as_deref() == Some(key.as_str())
102        })
103    }
104
105    /// The Points list: `P{id} (x, y)` plus ⛓ external / ◐ construction / ⏚ ground
106    /// markers, mirroring the previous Points rows.
107    pub fn sketch_point_rows(&self) -> Vec<SketchEntityRow> {
108        use crate::sketch::doc::id_key;
109        let Some(edit) = self.sketch_edit.as_ref() else {
110            return Vec::new();
111        };
112        let session = &edit.session;
113        session
114            .doc
115            .points
116            .iter()
117            .map(|p| {
118                let grounded = session.doc.constraints.iter().any(|c| {
119                    c.ctype() == Some("⏚")
120                        && c.points().first().map(id_key).as_deref() == Some(id_key(&p.id).as_str())
121                });
122                let mut marks = String::new();
123                if p.external_reference {
124                    marks.push_str(" \u{26D3}"); // ⛓ chain-links (bundled font; 🔗 is not)
125                }
126                if p.construction {
127                    marks.push_str(" ◐");
128                }
129                if grounded {
130                    marks.push_str(" ⏚");
131                }
132                SketchEntityRow {
133                    kind: "point",
134                    id: p.id.clone(),
135                    label: if crate::sketch::external_ref::is_origin_id(&p.id) {
136                        format!("Origin ({:.1}, {:.1}){marks}", p.x, p.y)
137                    } else {
138                        format!("P{} ({:.1}, {:.1}){marks}", id_key(&p.id), p.x, p.y)
139                    },
140                    selected: Self::sketch_ref_selected(session, "point", &p.id),
141                    construction: p.construction,
142                    conflicting: false,
143                }
144            })
145            .collect()
146    }
147
148    /// The Curves list: `{type}:{id} [p0,p1,…]` (◐ for construction), mirroring the
149    /// previous Curves rows.
150    pub fn sketch_geometry_rows(&self) -> Vec<SketchEntityRow> {
151        use crate::sketch::doc::id_key;
152        let Some(edit) = self.sketch_edit.as_ref() else {
153            return Vec::new();
154        };
155        let session = &edit.session;
156        session
157            .doc
158            .geometries
159            .iter()
160            .map(|g| {
161                let pts = g
162                    .points
163                    .iter()
164                    .map(id_key)
165                    .collect::<Vec<_>>()
166                    .join(",");
167                let construction = g.construction();
168                let mark = if construction { " ◐" } else { "" };
169                SketchEntityRow {
170                    kind: "geometry",
171                    id: g.id.clone(),
172                    label: format!("{}:{}{mark} [{pts}]", g.geom_type, id_key(&g.id)),
173                    selected: Self::sketch_ref_selected(session, "geometry", &g.id),
174                    construction,
175                    conflicting: false,
176                }
177            })
178            .collect()
179    }
180
181    /// The Constraints list: `{id} {type} {value} [points]`, mirroring the previous
182    /// Constraints rows.
183    pub fn sketch_constraint_rows(&self) -> Vec<SketchEntityRow> {
184        use crate::sketch::doc::id_key;
185        let Some(edit) = self.sketch_edit.as_ref() else {
186            return Vec::new();
187        };
188        let session = &edit.session;
189        session
190            .doc
191            .constraints
192            .iter()
193            .filter_map(|c| {
194                let id = c.raw.get("id")?.clone();
195                let ctype = c.ctype().unwrap_or("?");
196                let value = c
197                    .raw
198                    .get("value")
199                    .and_then(serde_json::Value::as_f64)
200                    .map(|v| format!(" {v:.3}"))
201                    .unwrap_or_default();
202                let pts = c
203                    .points()
204                    .iter()
205                    .map(id_key)
206                    .collect::<Vec<_>>()
207                    .join(",");
208                Some(SketchEntityRow {
209                    kind: "constraint",
210                    id: id.clone(),
211                    label: format!("{} {ctype}{value} [{pts}]", id_key(&id)),
212                    selected: Self::sketch_ref_selected(session, "constraint", &id),
213                    construction: false,
214                    conflicting: session.diagnostics.constraint_conflicting(&id),
215                })
216            })
217            .collect()
218    }
219
220    /// Select an entity BY ref from a list row (mirrors [`sketch_click_at`]): honors the
221    /// SAME "Multi-select" setting — under `ClickToggles` a plain click toggles the row
222    /// (no modifier needed); under `CtrlClick` a plain click replaces the
223    /// selection and an additive (Ctrl/Cmd) click toggles.
224    pub fn sketch_select_entity(&mut self, kind: &str, id: serde_json::Value, additive: bool) {
225        let toggles = self.settings.multi_select == crate::style::MultiSelectMode::ClickToggles;
226        let entity_ref = serde_json::json!({ "kind": kind, "id": id });
227        let Some(edit) = self.sketch_edit.as_mut() else {
228            return;
229        };
230        if !additive && !toggles {
231            edit.session.clear_selection();
232        }
233        edit.session.toggle_selection(entity_ref);
234        self.refresh_sketch_overlay();
235        self.dirty = true;
236    }
237
238    /// Hover an entity BY ref from a list row (list→canvas highlight). Sets the
239    /// one-frame guard so the viewport — which draws after the panel and would
240    /// otherwise clear the hover because the pointer is off the viewport — keeps it.
241    pub fn sketch_hover_entity(&mut self, kind: &str, id: serde_json::Value) {
242        if self.sketch_edit.is_none() {
243            return;
244        }
245        // `set_sketch_hover` re-tessellates only when the hovered ref actually
246        // changes, so holding the pointer on one row does not churn the overlay.
247        let entity_ref = serde_json::json!({ "kind": kind, "id": id });
248        self.set_sketch_hover(Some(entity_ref));
249        self.sketch_list_hover_active = true;
250    }
251
252    /// Consume the "list panel set the hover this frame" guard (read + reset). The
253    /// viewport calls this before its off-viewport `sketch_clear_hover` so a
254    /// panel-set hover survives the frame.
255    pub fn take_sketch_list_hover(&mut self) -> bool {
256        std::mem::take(&mut self.sketch_list_hover_active)
257    }
258
259    /// The active sketch's solver settings (the Solver Settings panel reads this).
260    /// `None` when not editing a sketch.
261    pub fn sketch_solver_settings(&self) -> Option<crate::sketch::SketchSolverSettings> {
262        self.sketch_edit
263            .as_ref()
264            .map(|edit| edit.session.solver_settings.clone())
265    }
266
267    /// Replace the active sketch's solver settings and re-solve so the change
268    /// takes effect immediately. No-op when not editing a sketch.
269    pub fn sketch_set_solver_settings(&mut self, settings: crate::sketch::SketchSolverSettings) {
270        if let Some(edit) = self.sketch_edit.as_mut() {
271            edit.session.solver_settings = settings;
272        } else {
273            return;
274        }
275        self.resolve_active_sketch("solver settings");
276        self.refresh_sketch_overlay();
277        self.dirty = true;
278    }
279}
280
281/// One applicable-constraint palette entry: the glyph passed back to
282/// [`EngineState::sketch_add_constraint`] plus a human tooltip and a dimensional
283/// tag (whether it opens a value the solver seeds from the current measurement).
284#[derive(Clone, Debug, PartialEq)]
285pub struct SketchConstraintAction {
286    /// The constraint glyph (e.g. `"━"`, `"⟂"`, `"R"`) — the argument to
287    /// [`EngineState::sketch_add_constraint`].
288    pub symbol: String,
289    /// A human tooltip label (e.g. `"Horizontal"`, `"Radius"`).
290    pub label: String,
291    /// Whether this is a dimensional constraint (its value is seeded from the
292    /// current measurement; S5 makes it editable).
293    pub dimensional: bool,
294}
295
296impl EngineState {
297    /// The ordered palette of constraints applicable to the active sketch selection
298    /// (a faithful port of `#refreshContextBar`). Empty when not in sketch mode or
299    /// the selection surfaces no constraint. The Fix/Unfix + construction + cleanup
300    /// affordances are exposed separately (see [`sketch_selection_all_grounded`] /
301    /// [`sketch_selection_all_construction`] / [`sketch_cleanup_unused_points`]).
302    ///
303    /// [`sketch_selection_all_grounded`]: Self::sketch_selection_all_grounded
304    /// [`sketch_selection_all_construction`]: Self::sketch_selection_all_construction
305    /// [`sketch_cleanup_unused_points`]: Self::sketch_cleanup_unused_points
306    pub fn sketch_applicable_constraints(&self) -> Vec<SketchConstraintAction> {
307        match self.sketch_edit.as_ref() {
308            Some(edit) => sketch_palette_for(&edit.session),
309            None => Vec::new(),
310        }
311    }
312
313    /// Add the constraint named by `symbol` from the current selection (a port of
314    /// `createConstraint`): build the ordered point-id list, dedup on
315    /// `type + sorted-points`, append (dimensional → `value:null`), then re-solve +
316    /// refresh (keeping the selection). Returns whether a constraint was added.
317    pub fn sketch_add_constraint(&mut self, symbol: &str) -> bool {
318        // Snapshot BEFORE the (in-place) add; discard it below when the add is a
319        // dedup no-op so a dead click neither pollutes undo nor clobbers redo (S6a).
320        let added = match self.sketch_edit.as_mut() {
321            Some(edit) => {
322                edit.record_undo();
323                sketch_build_and_add_constraint(&mut edit.session, symbol)
324            }
325            None => return false,
326        };
327        if added {
328            self.resolve_active_sketch("add-constraint");
329            self.refresh_sketch_overlay();
330            self.dirty = true;
331        } else if let Some(edit) = self.sketch_edit.as_mut() {
332            edit.undo_stack.pop();
333        }
334        added
335    }
336
337    /// Toggle the ground (`⏚`) constraint on the selected points: if ALL selected
338    /// points are already grounded → remove those grounds (and clear their `fixed`
339    /// flag); else add a `⏚` for each ungrounded selected point (and set `fixed`).
340    /// Re-solves + refreshes. Returns whether anything changed. No-op with no point
341    /// selected / not in sketch mode.
342    pub fn sketch_toggle_ground(&mut self) -> bool {
343        use crate::sketch::doc::id_key;
344        use std::collections::HashSet;
345
346        let Some(edit) = self.sketch_edit.as_mut() else {
347            return false;
348        };
349        let sel_ids: Vec<serde_json::Value> = edit
350            .session
351            .selection
352            .iter()
353            .filter(|r| r.get("kind").and_then(|v| v.as_str()) == Some("point"))
354            .filter_map(|r| r.get("id").cloned())
355            // The part-origin reference stays grounded.
356            .filter(|id| !crate::sketch::external_ref::is_origin_id(id))
357            .collect();
358        if sel_ids.is_empty() {
359            return false;
360        }
361        // Selected points → the toggle always adds or removes grounds; snapshot (S6a).
362        edit.record_undo();
363        let doc = &mut edit.session.doc;
364        let has_ground = |doc: &crate::sketch::SketchDoc, id: &serde_json::Value| -> bool {
365            doc.constraints.iter().any(|c| {
366                c.ctype() == Some("⏚")
367                    && c.points().first().map(id_key) == Some(id_key(id))
368            })
369        };
370        let all_grounded = sel_ids.iter().all(|id| has_ground(doc, id));
371        if all_grounded {
372            let sel_keys: HashSet<String> = sel_ids.iter().map(id_key).collect();
373            doc.constraints.retain(|c| {
374                if c.ctype() != Some("⏚") {
375                    return true;
376                }
377                match c.points().first() {
378                    Some(p) => !sel_keys.contains(&id_key(p)),
379                    None => true,
380                }
381            });
382            for id in &sel_ids {
383                if let Some(p) = doc.point_mut(id) {
384                    p.fixed = false;
385                }
386            }
387        } else {
388            for id in &sel_ids {
389                if has_ground(doc, id) {
390                    continue;
391                }
392                let cid = doc.next_constraint_id();
393                let mut raw = serde_json::Map::new();
394                raw.insert("id".to_string(), cid);
395                raw.insert("type".to_string(), serde_json::Value::String("⏚".to_string()));
396                raw.insert(
397                    "points".to_string(),
398                    serde_json::Value::Array(vec![id.clone()]),
399                );
400                doc.constraints.push(crate::sketch::SketchConstraint { raw });
401                if let Some(p) = doc.point_mut(id) {
402                    p.fixed = true;
403                }
404            }
405        }
406        self.resolve_active_sketch("toggle-ground");
407        self.refresh_sketch_overlay();
408        self.dirty = true;
409        true
410    }
411
412    /// Flip the `construction` flag on ALL selected points AND geometries: if every
413    /// selected entity is already construction → make them regular, else make them
414    /// all construction. Re-solves + refreshes. Returns whether anything was
415    /// selected. No-op with nothing selected / not in sketch mode.
416    pub fn sketch_toggle_construction(&mut self) -> bool {
417        let Some(edit) = self.sketch_edit.as_mut() else {
418            return false;
419        };
420        let mut pt_ids: Vec<serde_json::Value> = Vec::new();
421        let mut geo_ids: Vec<serde_json::Value> = Vec::new();
422        for r in &edit.session.selection {
423            match r.get("kind").and_then(|v| v.as_str()) {
424                Some("point") => {
425                    // The part-origin reference stays construction.
426                    if let Some(id) = r.get("id").filter(|id| !crate::sketch::external_ref::is_origin_id(id)) {
427                        pt_ids.push(id.clone());
428                    }
429                }
430                Some("geometry") => {
431                    if let Some(id) = r.get("id") {
432                        geo_ids.push(id.clone());
433                    }
434                }
435                _ => {}
436            }
437        }
438        if pt_ids.is_empty() && geo_ids.is_empty() {
439            return false;
440        }
441        // Selected entities → the flip always changes something; snapshot (S6a).
442        edit.record_undo();
443        let doc = &mut edit.session.doc;
444        let all_construction = pt_ids
445            .iter()
446            .all(|id| doc.point(id).map_or(false, |p| p.construction))
447            && geo_ids
448                .iter()
449                .all(|id| doc.geometry(id).map_or(false, |g| g.construction()));
450        let next = !all_construction;
451        for id in &pt_ids {
452            if let Some(p) = doc.point_mut(id) {
453                p.construction = next;
454            }
455        }
456        for id in &geo_ids {
457            if let Some(g) = doc.geometry_mut(id) {
458                g.extra
459                    .insert("construction".to_string(), serde_json::Value::Bool(next));
460            }
461        }
462        self.resolve_active_sketch("toggle-construction");
463        self.refresh_sketch_overlay();
464        self.dirty = true;
465        true
466    }
467
468    /// Remove points referenced by NO geometry AND no constraint (the 🧹 action).
469    /// Re-solves + refreshes only when something was dropped. Returns whether a
470    /// point was removed. No-op when not in sketch mode.
471    pub fn sketch_cleanup_unused_points(&mut self) -> bool {
472        use crate::sketch::doc::id_key;
473        use std::collections::HashSet;
474
475        let Some(edit) = self.sketch_edit.as_mut() else {
476            return false;
477        };
478        // Snapshot before the cleanup; discarded below when nothing is removed (S6a).
479        edit.record_undo();
480        let doc = &mut edit.session.doc;
481        let mut used: HashSet<String> = HashSet::new();
482        for g in &doc.geometries {
483            for pid in &g.points {
484                used.insert(id_key(pid));
485            }
486        }
487        for c in &doc.constraints {
488            for pid in c.points() {
489                used.insert(id_key(pid));
490            }
491        }
492        let before = doc.points.len();
493        doc.points.retain(|p| used.contains(&id_key(&p.id)));
494        let removed = doc.points.len() != before;
495        if !removed {
496            edit.undo_stack.pop();
497            return false;
498        }
499        self.resolve_active_sketch("cleanup");
500        self.refresh_sketch_overlay();
501        self.dirty = true;
502        true
503    }
504
505    /// The number of constraints in the active sketch (0 when not in sketch mode) —
506    /// the verifier / palette readout.
507    pub fn sketch_constraint_count(&self) -> usize {
508        self.sketch_edit
509            .as_ref()
510            .map_or(0, |edit| edit.session.doc.constraints.len())
511    }
512
513    /// Whether the selected points are ALL grounded (`Some(true)`), NOT all grounded
514    /// (`Some(false)`), or no point is selected (`None`) — labels the Fix vs Unfix
515    /// button.
516    pub fn sketch_selection_all_grounded(&self) -> Option<bool> {
517        use crate::sketch::doc::id_key;
518        let edit = self.sketch_edit.as_ref()?;
519        let doc = &edit.session.doc;
520        let sel: Vec<&serde_json::Value> = edit
521            .session
522            .selection
523            .iter()
524            .filter(|r| r.get("kind").and_then(|v| v.as_str()) == Some("point"))
525            .filter_map(|r| r.get("id"))
526            .collect();
527        if sel.is_empty() {
528            return None;
529        }
530        let all = sel.iter().all(|id| {
531            doc.constraints.iter().any(|c| {
532                c.ctype() == Some("⏚")
533                    && c.points().first().map(id_key) == Some(id_key(id))
534            })
535        });
536        Some(all)
537    }
538
539    /// Whether the selected points + geometries are ALL construction (`Some(true)`),
540    /// NOT all construction (`Some(false)`), or nothing is selected (`None`) — labels
541    /// the ◐ construction-toggle button's direction.
542    pub fn sketch_selection_all_construction(&self) -> Option<bool> {
543        let edit = self.sketch_edit.as_ref()?;
544        let doc = &edit.session.doc;
545        let mut any = false;
546        let mut all = true;
547        for r in &edit.session.selection {
548            match r.get("kind").and_then(|v| v.as_str()) {
549                Some("point") => {
550                    any = true;
551                    if let Some(id) = r.get("id") {
552                        if !doc.point(id).map_or(false, |p| p.construction) {
553                            all = false;
554                        }
555                    }
556                }
557                Some("geometry") => {
558                    any = true;
559                    if let Some(id) = r.get("id") {
560                        if !doc.geometry(id).map_or(false, |g| g.construction()) {
561                            all = false;
562                        }
563                    }
564                }
565                _ => {}
566            }
567        }
568        if !any {
569            return None;
570        }
571        Some(all)
572    }
573}
574
575/// Build the applicable-constraint palette for a session's selection — the port of
576/// `SketchMode3D.#refreshContextBar`'s branch logic (constraint buttons only; the
577/// state toggles + cleanup + delete are returned via companion accessors).
578fn sketch_palette_for(session: &crate::sketch::SketchSession) -> Vec<SketchConstraintAction> {
579    use crate::sketch::doc::id_key;
580    use std::collections::HashSet;
581
582    let doc = &session.doc;
583    let mut sel_points: Vec<serde_json::Value> = Vec::new();
584    let mut geos: Vec<&crate::sketch::SketchGeometry> = Vec::new();
585    for r in &session.selection {
586        match r.get("kind").and_then(|v| v.as_str()) {
587            Some("point") => {
588                if let Some(id) = r.get("id") {
589                    sel_points.push(id.clone());
590                }
591            }
592            Some("geometry") => {
593                if let Some(id) = r.get("id") {
594                    if let Some(g) = doc.geometry(id) {
595                        geos.push(g);
596                    }
597                }
598            }
599            _ => {}
600        }
601    }
602
603    // point-coverage = selected point ids ∪ endpoints of selected geometries
604    // (arc: only points[0..2] — center + start).
605    let mut point_set: HashSet<String> = HashSet::new();
606    for id in &sel_points {
607        point_set.insert(id_key(id));
608    }
609    for g in &geos {
610        let pts: &[serde_json::Value] = if g.geom_type == "arc" {
611            &g.points[..g.points.len().min(2)]
612        } else {
613            &g.points
614        };
615        for pid in pts {
616            point_set.insert(id_key(pid));
617        }
618    }
619    let point_count = point_set.len();
620    let selected_point_ids_len = sel_points.len();
621    let is_radial =
622        |g: &crate::sketch::SketchGeometry| g.geom_type == "arc" || g.geom_type == "circle";
623
624    let mut out: Vec<SketchConstraintAction> = Vec::new();
625    let mut push = |symbol: &str, label: &str, dimensional: bool| {
626        out.push(SketchConstraintAction {
627            symbol: symbol.to_string(),
628            label: label.to_string(),
629            dimensional,
630        });
631    };
632
633    // 1 arc/circle → radial dims (defer the leader to S5).
634    if geos.len() == 1 && is_radial(geos[0]) {
635        push("R", "Radius", true);
636        push("⌀", "Diameter", true);
637        return out;
638    }
639    // 2 lines → parallel / perp / angle / equal-length / collinear / point-on-line,
640    // plus tangent when either line is a spline HANDLE GUIDE. A guide IS a line, so
641    // every offer above stays legitimate on one (its two ends are still two points
642    // whose direction can be made parallel to another line's); tangency is the extra
643    // question only a guide can be asked, and it is the reason a guide gets selected
644    // at all. Both new pairs — guide + line and guide + guide — are pairs the
645    // solver's `c_tangent` already reads as a spline tangent, at a drawn end and at
646    // an inserted interior anchor alike.
647    if geos.len() == 2 && geos.iter().all(|g| g.geom_type == "line") {
648        push("∥", "Parallel", false);
649        push("⟂", "Perpendicular", false);
650        push("∠", "Angle", true);
651        push("⇌", "Equal distance", false);
652        push("⋰", "Collinear", false);
653        push("⏛", "Point on line", false);
654        if geos
655            .iter()
656            .any(|g| crate::sketch::spline::is_handle_guide(doc, g))
657        {
658            push("⌒", "Tangent", false);
659        }
660        // Curvature (G2) is the narrower question: the two guides have to be the
661        // two sides of ONE joint — either side of one interior anchor, or two
662        // ends the document already holds together. A guide paired with a plain
663        // line is never one (a line has no curvature to match), and neither are
664        // two guides at unrelated anchors.
665        if crate::sketch::spline::is_curvature_joint(doc, geos[0], geos[1]) {
666            push("ϰ", "Curvature (G2)", false);
667        }
668        return out;
669    }
670    // 2 arcs/circles → equal-radius / concentric / tangent.
671    if geos.len() == 2 && geos.iter().all(|g| is_radial(g)) {
672        push("⊜", "Equal radius", false);
673        push("◎", "Concentric", false);
674        push("⌒", "Tangent", false);
675        return out;
676    }
677    // line + arc/circle → tangent, plus curvature when the line is a spline
678    // handle guide at an END anchor: the spline's curvature there becomes the
679    // circle's 1/ρ, which is how a curve is continued into an arc.
680    if geos.len() == 2
681        && ((geos[0].geom_type == "line" && is_radial(geos[1]))
682            || (geos[1].geom_type == "line" && is_radial(geos[0])))
683    {
684        push("⌒", "Tangent", false);
685        if geos
686            .iter()
687            .any(|g| crate::sketch::spline::is_end_handle_guide(doc, g))
688        {
689            push("ϰ", "Curvature (G2)", false);
690        }
691        return out;
692    }
693    // A spline BODY + a line, or a spline body + an arc/circle → tangency at a
694    // point INTERIOR to one of the spline's spans (`∿`).
695    //
696    // The PICK is the whole difference from `⌒`. Selecting an anchor's handle
697    // guide asks for tangency AT that anchor, where the spline's tangent has a
698    // name (anchor→handle) and no touch parameter is needed — that stays `⌒`.
699    // Selecting the curve ITSELF asks for tangency wherever the two geometries
700    // actually touch, which is the foot-parameter lane and a different
701    // constraint type. So a guide is refused here, and a body is refused there.
702    if sketch_foot_tangent_pair(doc, &geos).is_some() {
703        push("∿", "Tangent (span point)", false);
704        return out;
705    }
706    // 1 line + 2 selected points → perpendicular / symmetric-about-line (no return).
707    if geos.len() == 1 && geos[0].geom_type == "line" && selected_point_ids_len == 2 {
708        push("⟂", "Perpendicular", false);
709        push("⋈", "Symmetric about line", false);
710    }
711
712    if point_count == 1 {
713        push("⏚", "Ground (fix point)", false);
714    }
715    if point_count == 2 {
716        push("━", "Horizontal", false);
717        push("│", "Vertical", false);
718        push("≡", "Coincident", false);
719        push("⟺", "Distance", true);
720    }
721    if point_count == 3 {
722        push("⋯", "Midpoint", false);
723        push("⏛", "Point on line", false);
724        push("↥", "Line to point distance", true);
725        push("∠", "Angle", true);
726        // Collinear needs 3+ ACTUAL selected points (not derived from geometry).
727        if selected_point_ids_len >= 3 {
728            push("⋰", "Collinear", false);
729        }
730    }
731    // 4+ free-standing points → still offer Collinear.
732    if point_count > 3 && geos.is_empty() && selected_point_ids_len >= 3 {
733        push("⋰", "Collinear", false);
734    }
735
736    out
737}
738
739/// The point-id list for a tangent (`⌒`) constraint
740/// from two selected geometries — `[lineA, lineB, center, boundary]` for line+circle,
741/// `[c1, boundary1, c2, boundary2]` for circle+circle, and `[a0, a1, b0, b1]` for two
742/// lines of which at least one is a spline handle guide. `None` for any other pair.
743///
744/// The guide gate on the two-line case is not decoration: the solver's `c_tangent`
745/// falls through to `c_tangent_line_circle` for a pair it cannot read as a spline,
746/// which would take the second line's two ends for a circle's centre and rim. A pair
747/// of plain lines has no tangency to state, so it is refused here rather than
748/// silently stored as a nonsense circle.
749fn sketch_build_tangent_points(
750    doc: &crate::sketch::SketchDoc,
751    geos: &[&crate::sketch::SketchGeometry],
752) -> Option<Vec<serde_json::Value>> {
753    if geos.len() != 2 {
754        return None;
755    }
756    let is_radial = |g: &crate::sketch::SketchGeometry| g.geom_type == "arc" || g.geom_type == "circle";
757    if geos.iter().all(|g| g.geom_type == "line") {
758        let (a, b) = (geos[0], geos[1]);
759        if a.points.len() < 2 || b.points.len() < 2 {
760            return None;
761        }
762        if !crate::sketch::spline::is_handle_guide(doc, a)
763            && !crate::sketch::spline::is_handle_guide(doc, b)
764        {
765            return None;
766        }
767        return Some(vec![
768            a.points[0].clone(),
769            a.points[1].clone(),
770            b.points[0].clone(),
771            b.points[1].clone(),
772        ]);
773    }
774    let line = geos.iter().find(|g| g.geom_type == "line");
775    let circ = geos.iter().find(|g| is_radial(g));
776    if let (Some(line), Some(circ)) = (line, circ) {
777        if line.points.len() < 2 || circ.points.len() < 2 {
778            return None;
779        }
780        return Some(vec![
781            line.points[0].clone(),
782            line.points[1].clone(),
783            circ.points[0].clone(),
784            circ.points[1].clone(),
785        ]);
786    }
787    if geos.iter().all(|g| is_radial(g)) {
788        let (a, b) = (geos[0], geos[1]);
789        if a.points.len() < 2 || b.points.len() < 2 {
790            return None;
791        }
792        return Some(vec![
793            a.points[0].clone(),
794            a.points[1].clone(),
795            b.points[0].clone(),
796            b.points[1].clone(),
797        ]);
798    }
799    None
800}
801
802/// The `(spline body, line-or-circle)` pair a foot-parameter tangency (`∿`) is
803/// offered for, or `None` for any other selection.
804///
805/// ONE gate, read by both the palette offer and the point-list builder, so an
806/// offered `∿` is an `∿` that builds and solves — the same contract the tangent's
807/// guide gate carries. What it admits:
808///
809/// * exactly two geometries, one of them a spline (a `3n + 1` control polygon),
810/// * the other a plain line or an arc/circle,
811/// * and NOT a spline handle guide: a guide is a line whose two ends are the
812///   spline's own control points, so tangency to it would be tangency of the
813///   curve to its own construction artifact. Tangency at the anchor a guide
814///   stands for is `⌒`'s lane, which is where that selection belongs.
815fn sketch_foot_tangent_pair<'a>(
816    doc: &crate::sketch::SketchDoc,
817    geos: &[&'a crate::sketch::SketchGeometry],
818) -> Option<(&'a crate::sketch::SketchGeometry, &'a crate::sketch::SketchGeometry)> {
819    if geos.len() != 2 {
820        return None;
821    }
822    let is_spline = |g: &crate::sketch::SketchGeometry| {
823        crate::sketch::spline::is_spline_type(&g.geom_type)
824    };
825    let is_radial =
826        |g: &crate::sketch::SketchGeometry| g.geom_type == "arc" || g.geom_type == "circle";
827    let spline = *geos.iter().find(|g| is_spline(g))?;
828    let target = *geos.iter().find(|g| !is_spline(g))?;
829    if spline.points.len() < 4 || target.points.len() < 2 {
830        return None;
831    }
832    let target_is_usable = if target.geom_type == "line" {
833        !crate::sketch::spline::is_handle_guide(doc, target)
834    } else {
835        is_radial(target)
836    };
837    target_is_usable.then_some((spline, target))
838}
839
840/// The point-id list for a foot-parameter tangency (`∿`) —
841/// `[lineA, lineB, s0, s1]` against a line, `[center, boundary, s0, s1]` against
842/// an arc/circle, where `(s0, s1)` are the SPLINE's first two control ids acting
843/// as a geometry handle.
844///
845/// The spline is named by a pair rather than by its geometry id because a
846/// constraint record's only geometric field is `points` — the same reason the
847/// tangent names a circle by `(centre, rim)`. Two leading controls identify one
848/// spline: a document cannot hold two curves that start from the same two points
849/// without them being the same curve.
850fn sketch_build_foot_tangent_points(
851    doc: &crate::sketch::SketchDoc,
852    geos: &[&crate::sketch::SketchGeometry],
853) -> Option<Vec<serde_json::Value>> {
854    let (spline, target) = sketch_foot_tangent_pair(doc, geos)?;
855    Some(vec![
856        target.points[0].clone(),
857        target.points[1].clone(),
858        spline.points[0].clone(),
859        spline.points[1].clone(),
860    ])
861}
862
863/// The point-id list for a curvature (`ϰ`) constraint from two selected
864/// geometries — the SAME two-pair shape the tangent uses, so the solver's
865/// dispatch reads it the same way: `[anchorA, handleA, anchorB, handleB]` for a
866/// joint, `[anchor, handle, center, boundary]` against a circle/arc.
867///
868/// Gated on exactly what the palette offers, for the same reason the tangent's
869/// guide gate exists: an offered curvature continuity is one that solves. A
870/// spline end against a circle is a join; two guides are a join only when they
871/// are the two sides of one joint; anything else — two plain lines, a guide and
872/// an unrelated line, two ends with nothing holding them together — has no
873/// curvature continuity to state and is refused here rather than stored as a
874/// constraint the solver would have to name an error on.
875fn sketch_build_curvature_points(
876    doc: &crate::sketch::SketchDoc,
877    geos: &[&crate::sketch::SketchGeometry],
878) -> Option<Vec<serde_json::Value>> {
879    if geos.len() != 2 {
880        return None;
881    }
882    let is_radial =
883        |g: &crate::sketch::SketchGeometry| g.geom_type == "arc" || g.geom_type == "circle";
884    if geos.iter().all(|g| g.geom_type == "line") {
885        if !crate::sketch::spline::is_curvature_joint(doc, geos[0], geos[1]) {
886            return None;
887        }
888        let (a, b) = (geos[0], geos[1]);
889        return Some(vec![
890            a.points[0].clone(),
891            a.points[1].clone(),
892            b.points[0].clone(),
893            b.points[1].clone(),
894        ]);
895    }
896    let guide = geos
897        .iter()
898        .find(|g| crate::sketch::spline::is_end_handle_guide(doc, g))?;
899    let circ = geos.iter().find(|g| is_radial(g))?;
900    if circ.points.len() < 2 {
901        return None;
902    }
903    Some(vec![
904        guide.points[0].clone(),
905        guide.points[1].clone(),
906        circ.points[0].clone(),
907        circ.points[1].clone(),
908    ])
909}
910
911/// Whether the perpendicular (`⟂`) 4-point list should SWAP its first two points to
912/// orient line 1 closer to 90° against line 2 — a faithful port of the previous
913/// angle-calculation block. `pts = [l1a, l1b, l2a, l2b]`.
914pub(super) fn sketch_perpendicular_should_swap(
915    doc: &crate::sketch::SketchDoc,
916    pts: &[serde_json::Value],
917) -> bool {
918    let coord = |v: &serde_json::Value| doc.point(v).map(|p| (p.x, p.y));
919    let (Some(p0), Some(p1), Some(p2), Some(p3)) =
920        (coord(&pts[0]), coord(&pts[1]), coord(&pts[2]), coord(&pts[3]))
921    else {
922        return false;
923    };
924    // calculateAngle(a, b) = atan2(b.y-a.y, b.x-a.x) in [0, 360).
925    let angle = |a: (f64, f64), b: (f64, f64)| -> f64 {
926        let deg = (b.1 - a.1).atan2(b.0 - a.0) * 180.0 / std::f64::consts::PI;
927        (deg + 360.0) % 360.0
928    };
929    // Fold into (-180, 180]: (a + 180) % 360 - 180.
930    let fold = |a: f64| (a + 180.0) % 360.0 - 180.0;
931    let line1_a = fold(angle(p0, p1));
932    let line1_b = fold(angle(p1, p0));
933    let line2 = fold(angle(p2, p3));
934    let diff_a = line1_a - line2;
935    let diff_b = line1_b - line2;
936    (90.0 - diff_a).abs() > (90.0 - diff_b).abs()
937}
938
939/// The `type + sorted-point-ids` dedup signature (the solver runs with
940/// `remove_implied_duplicates:false`, so this is the only dedup on adds).
941pub(super) fn sketch_constraint_signature(ctype: &str, points: &[serde_json::Value]) -> String {
942    use crate::sketch::doc::id_key;
943    let mut keys: Vec<String> = points.iter().map(id_key).collect();
944    keys.sort();
945    format!("{ctype}|{}", keys.join(","))
946}
947
948/// The port of `ConstraintEngine.createConstraint`: from the session's selection build
949/// the ordered point-id list(s) for `symbol`, dedup on `type + sorted-points`, and
950/// append the constraint(s) (dimensional → `value:null` + `valueNeedsSetup:true`).
951/// Returns whether at least one constraint was added. The caller re-solves.
952fn sketch_build_and_add_constraint(
953    session: &mut crate::sketch::SketchSession,
954    symbol: &str,
955) -> bool {
956    /// The constraint(s) to append for a symbol: the stored solver `type`, its
957    /// display style, and one or more ordered point-id lists (`⏛`-from-2-lines and
958    /// the like push several).
959    struct Built {
960        store_type: String,
961        display_style: &'static str,
962        lists: Vec<Vec<serde_json::Value>>,
963    }
964
965    // --- Phase 1: read-only — assemble the constraint(s) from the selection. ---
966    let built: Option<Built> = {
967        let doc = &session.doc;
968        // `selected` mirrors the previous behavior: point → push it; geometry → push all its
969        // points, arc pops the last (center + start). `geo_items`/`point_items` are
970        // the role-based lists the specials use; `geometry_type` is the LAST
971        // geometry's type; `first_kind` drives the `⋯` reverse.
972        let mut selected: Vec<serde_json::Value> = Vec::new();
973        let mut geo_items: Vec<&crate::sketch::SketchGeometry> = Vec::new();
974        let mut point_items: Vec<serde_json::Value> = Vec::new();
975        let mut geometry_type: Option<String> = None;
976        let mut first_kind: Option<String> = None;
977        let mut has_geometry = false;
978        for (i, r) in session.selection.iter().enumerate() {
979            let kind = r.get("kind").and_then(|v| v.as_str());
980            let Some(id) = r.get("id") else { continue };
981            if i == 0 {
982                first_kind = kind.map(|k| k.to_string());
983            }
984            match kind {
985                Some("point") => {
986                    if let Some(p) = doc.point(id) {
987                        selected.push(p.id.clone());
988                        point_items.push(p.id.clone());
989                    }
990                }
991                Some("geometry") => {
992                    if let Some(g) = doc.geometry(id) {
993                        for pid in &g.points {
994                            if doc.point(pid).is_some() {
995                                selected.push(pid.clone());
996                            }
997                        }
998                        if g.geom_type == "arc" {
999                            selected.pop();
1000                        }
1001                        geometry_type = Some(g.geom_type.clone());
1002                        geo_items.push(g);
1003                        has_geometry = true;
1004                    }
1005                }
1006                _ => {}
1007            }
1008        }
1009        if selected.is_empty() {
1010            None
1011        } else {
1012            let radial = |g: &crate::sketch::SketchGeometry| {
1013                g.geom_type == "arc" || g.geom_type == "circle"
1014            };
1015            let simple = |t: &str, list: Vec<serde_json::Value>, ds: &'static str| Built {
1016                store_type: t.to_string(),
1017                display_style: ds,
1018                lists: vec![list],
1019            };
1020
1021            // ---- Geometry-role specials (dispatched by role, not point count). ----
1022            match symbol {
1023                "◎" => {
1024                    if geo_items.len() == 2 && geo_items.iter().all(|g| radial(g)) {
1025                        Some(simple(
1026                            "◎",
1027                            vec![geo_items[0].points[0].clone(), geo_items[1].points[0].clone()],
1028                            "",
1029                        ))
1030                    } else {
1031                        None
1032                    }
1033                }
1034                "⊜" => {
1035                    if geo_items.len() == 2 && geo_items.iter().all(|g| radial(g)) {
1036                        let (g0, g1) = (geo_items[0], geo_items[1]);
1037                        Some(simple(
1038                            "⊜",
1039                            vec![
1040                                g0.points[0].clone(),
1041                                g0.points[1].clone(),
1042                                g1.points[0].clone(),
1043                                g1.points[1].clone(),
1044                            ],
1045                            "",
1046                        ))
1047                    } else {
1048                        None
1049                    }
1050                }
1051                "⌒" => sketch_build_tangent_points(doc, &geo_items).map(|pts| simple("⌒", pts, "")),
1052                "ϰ" => {
1053                    sketch_build_curvature_points(doc, &geo_items).map(|pts| simple("ϰ", pts, ""))
1054                }
1055                "∿" => sketch_build_foot_tangent_points(doc, &geo_items)
1056                    .map(|pts| simple("∿", pts, "")),
1057                "⋰" => {
1058                    let ids = if geo_items.len() >= 2
1059                        && geo_items.iter().all(|g| g.geom_type == "line")
1060                    {
1061                        let mut v = Vec::new();
1062                        for g in &geo_items {
1063                            v.push(g.points[0].clone());
1064                            v.push(g.points[1].clone());
1065                        }
1066                        Some(v)
1067                    } else if point_items.len() >= 3 {
1068                        Some(point_items.clone())
1069                    } else {
1070                        None
1071                    };
1072                    ids.filter(|v| v.len() >= 3).map(|v| simple("⋰", v, ""))
1073                }
1074                "⋈" => geo_items
1075                    .iter()
1076                    .find(|g| g.geom_type == "line")
1077                    .filter(|line| line.points.len() >= 2 && point_items.len() == 2)
1078                    .map(|line| {
1079                        simple(
1080                            "⋈",
1081                            vec![
1082                                line.points[0].clone(),
1083                                line.points[1].clone(),
1084                                point_items[0].clone(),
1085                                point_items[1].clone(),
1086                            ],
1087                            "",
1088                        )
1089                    }),
1090                // Radial dims: a `⟺` on [center, boundary] with a radius/diameter
1091                // display style (single arc/circle; `selected` is arc-popped to 2).
1092                "R" | "⌀" => {
1093                    if selected.len() == 2 {
1094                        let ds = if symbol == "⌀" { "diameter" } else { "radius" };
1095                        Some(Built {
1096                            store_type: "⟺".to_string(),
1097                            display_style: ds,
1098                            lists: vec![selected.clone()],
1099                        })
1100                    } else {
1101                        None
1102                    }
1103                }
1104                _ => {
1105                    // ---- Count-based (mirrors the previous `selected.length` blocks). ----
1106                    match selected.len() {
1107                        1 => match symbol {
1108                            "⏚" => Some(simple("⏚", selected.clone(), "")),
1109                            _ => None,
1110                        },
1111                        2 => match symbol {
1112                            "━" | "│" | "≡" => Some(simple(symbol, selected.clone(), "")),
1113                            "⟺" => {
1114                                let ds = if matches!(
1115                                    geometry_type.as_deref(),
1116                                    Some("arc") | Some("circle")
1117                                ) {
1118                                    "radius"
1119                                } else {
1120                                    ""
1121                                };
1122                                Some(Built {
1123                                    store_type: "⟺".to_string(),
1124                                    display_style: ds,
1125                                    lists: vec![selected.clone()],
1126                                })
1127                            }
1128                            _ => None,
1129                        },
1130                        3 => match symbol {
1131                            "⏛" => Some(simple("⏛", selected.clone(), "")),
1132                            "⋯" => {
1133                                let mut pts = selected.clone();
1134                                if has_geometry && first_kind.as_deref() == Some("point") {
1135                                    pts.reverse();
1136                                }
1137                                Some(simple("⋯", pts, ""))
1138                            }
1139                            "↥" => {
1140                                if geo_items.len() == 1 && point_items.len() == 1 {
1141                                    let line = geo_items[0];
1142                                    if line.geom_type == "line" && line.points.len() >= 2 {
1143                                        Some(simple(
1144                                            "↥",
1145                                            vec![
1146                                                line.points[0].clone(),
1147                                                line.points[1].clone(),
1148                                                point_items[0].clone(),
1149                                            ],
1150                                            "",
1151                                        ))
1152                                    } else {
1153                                        None
1154                                    }
1155                                } else {
1156                                    // 3 raw points (no geometry) → point-line-distance
1157                                    // over the selection as-is.
1158                                    Some(simple("↥", selected.clone(), ""))
1159                                }
1160                            }
1161                            "⇌" => Some(simple("⇌", selected.clone(), "")),
1162                            _ => None,
1163                        },
1164                        4 | 5 => match symbol {
1165                            "⏛" => {
1166                                // Two lines → constrain BOTH endpoints of line 2 onto
1167                                // line 1 (two point-on-line constraints).
1168                                if geo_items.len() == 2
1169                                    && geo_items.iter().all(|g| g.geom_type == "line")
1170                                    && geo_items[0].points.len() >= 2
1171                                    && geo_items[1].points.len() >= 2
1172                                {
1173                                    let (g0, g1) = (geo_items[0], geo_items[1]);
1174                                    Some(Built {
1175                                        store_type: "⏛".to_string(),
1176                                        display_style: "",
1177                                        lists: vec![
1178                                            vec![
1179                                                g0.points[0].clone(),
1180                                                g0.points[1].clone(),
1181                                                g1.points[0].clone(),
1182                                            ],
1183                                            vec![
1184                                                g0.points[0].clone(),
1185                                                g0.points[1].clone(),
1186                                                g1.points[1].clone(),
1187                                            ],
1188                                        ],
1189                                    })
1190                                } else {
1191                                    None
1192                                }
1193                            }
1194                            "⟂" => {
1195                                if selected.len() != 4 {
1196                                    None
1197                                } else {
1198                                    let mut pts = selected.clone();
1199                                    if sketch_perpendicular_should_swap(doc, &pts) {
1200                                        pts.swap(0, 1);
1201                                    }
1202                                    Some(simple("⟂", pts, ""))
1203                                }
1204                            }
1205                            "∥" => Some(simple("∥", selected.clone(), "")),
1206                            "∠" => Some(simple("∠", selected.clone(), "")),
1207                            "⇌" => Some(simple("⇌", selected.clone(), "")),
1208                            _ => None,
1209                        },
1210                        _ => None,
1211                    }
1212                }
1213            }
1214        }
1215    };
1216
1217    let Some(built) = built else {
1218        return false;
1219    };
1220
1221    // --- Phase 2: mutate — dedup + append (every constraint carries the base
1222    //     fields; the solver seeds a null value from the current measurement). ---
1223    let doc = &mut session.doc;
1224    let mut added_any = false;
1225    for pts in &built.lists {
1226        let sig = sketch_constraint_signature(&built.store_type, pts);
1227        let duplicate = doc.constraints.iter().any(|c| match c.ctype() {
1228            Some(t) => sketch_constraint_signature(t, c.points()) == sig,
1229            None => false,
1230        });
1231        if duplicate {
1232            continue;
1233        }
1234        let id = doc.next_constraint_id();
1235        let mut raw = serde_json::Map::new();
1236        raw.insert("id".to_string(), id);
1237        raw.insert(
1238            "type".to_string(),
1239            serde_json::Value::String(built.store_type.clone()),
1240        );
1241        raw.insert("points".to_string(), serde_json::Value::Array(pts.clone()));
1242        raw.insert("labelX".to_string(), serde_json::Value::from(0));
1243        raw.insert("labelY".to_string(), serde_json::Value::from(0));
1244        raw.insert(
1245            "displayStyle".to_string(),
1246            serde_json::Value::String(built.display_style.to_string()),
1247        );
1248        raw.insert("value".to_string(), serde_json::Value::Null);
1249        raw.insert("valueNeedsSetup".to_string(), serde_json::Value::Bool(true));
1250        doc.constraints.push(crate::sketch::SketchConstraint { raw });
1251        added_any = true;
1252    }
1253    added_any
1254}
1255