Skip to main content

brep_render/sketch/
session.rs

1//! A sketch's solved document, plane, diagnostics, and interaction state.
2
3use crate::geometry2d::point_segment_distance;
4
5use serde_json::{json, Value};
6
7use super::doc::{id_key, SketchDiagnostics, SketchDoc};
8use super::tessellate::{self, SketchTessellation};
9use super::{solve, PlaneFrame};
10use crate::style::SketchColors;
11
12/// State for one active sketch.
13pub struct SketchSession {
14    /// The solved sketch (points carry solved coordinates).
15    pub doc: SketchDoc,
16    /// The plane the sketch's `(u, v)` coordinates are embedded in.
17    pub plane: PlaneFrame,
18    /// The last solve's read-only diagnostics (DOF, over/under status, mobility).
19    pub diagnostics: SketchDiagnostics,
20
21    // --- interaction state ---------------------------------------------------
22    /// Selected entities — a set of entity refs
23    /// (`{"kind":"point"|"geometry","id":<id>}`; see [`point_ref`]/[`geometry_ref`])
24    /// — and the one under the cursor.
25    pub selection: RefSelection,
26    /// The active drawing tool.
27    pub tool: Option<String>,
28    /// Persisted dimension label offsets.
29    pub dim_offsets: serde_json::Map<String, Value>,
30    /// The overlay color palette — a live [`SketchColors`] view of the display
31    /// settings (`RenderSettings::sketch_colors`). The engine sets this on entry and
32    /// re-syncs it when the settings change; every overlay builder reads from here so
33    /// the sketch colors are managed in the settings like the rest of the display.
34    /// Defaults to [`SketchColors::default`] so a session built in a test (or before
35    /// the engine syncs) renders the standard theme.
36    pub colors: SketchColors,
37    /// User-tunable solver knobs (the Solver Settings panel). Read by every
38    /// [`resolve`](Self::resolve); default reproduces the historical solve.
39    pub solver_settings: solve::SketchSolverSettings,
40    /// The fillet and chamfer tools' options.
41    pub corner_options: super::corner::CornerOptions,
42    /// Why the last fillet or chamfer click changed nothing (a refusal), shown
43    /// in the tool's options panel; cleared by the next edit that succeeds.
44    pub corner_message: Option<String>,
45}
46
47/// A sketch session's selection set and hover — ONE implementation for the
48/// planar session and the 3D one ([`crate::sketch3d::Sketch3dSession`]):
49/// entity refs, matched through [`refs_equal`].
50#[derive(Debug, Clone, Default, PartialEq)]
51pub struct RefSelection {
52    /// The selected entity refs, in selection order.
53    pub items: Vec<Value>,
54    /// The entity ref under the cursor, or `None`.
55    pub hovered: Option<Value>,
56}
57
58impl RefSelection {
59    /// Whether `entity_ref` is selected (matched via [`refs_equal`]).
60    pub fn is_selected(&self, entity_ref: &Value) -> bool {
61        self.items.iter().any(|r| refs_equal(r, entity_ref))
62    }
63
64    /// Remove `entity_ref` if selected, else add it.
65    pub fn toggle(&mut self, entity_ref: Value) {
66        if let Some(pos) = self.items.iter().position(|r| refs_equal(r, &entity_ref)) {
67            self.items.remove(pos);
68        } else {
69            self.items.push(entity_ref);
70        }
71    }
72
73    /// Select nothing (the hover is left alone).
74    pub fn clear(&mut self) {
75        self.items.clear();
76    }
77}
78
79impl SketchSession {
80    /// Build a session from a (possibly unsolved) doc + plane, solving it once.
81    pub fn new(doc: SketchDoc, plane: PlaneFrame) -> Result<Self, String> {
82        let (solved, diagnostics) = solve::solve(&doc)?;
83        Ok(Self {
84            doc: solved,
85            plane,
86            diagnostics,
87            selection: RefSelection::default(),
88            tool: None,
89            dim_offsets: serde_json::Map::new(),
90            colors: SketchColors::default(),
91            solver_settings: solve::SketchSolverSettings::default(),
92            corner_options: super::corner::CornerOptions::default(),
93            corner_message: None,
94        })
95    }
96
97    /// Re-solve the current doc, refreshing coordinates + diagnostics in place,
98    /// honoring the session's [`solver_settings`](Self::solver_settings).
99    pub fn resolve(&mut self) -> Result<(), String> {
100        let (solved, diagnostics) = solve::solve_with(&self.doc, &self.solver_settings)?;
101        self.doc = solved;
102        self.diagnostics = diagnostics;
103        Ok(())
104    }
105
106    /// Re-solve one interactive drag frame: with `BREP_SKETCH_DRAG_MIN_CHANGE` on,
107    /// the smallest change from the current coordinates
108    /// ([`resolve_min_change`](Self::resolve_min_change)); otherwise a plain
109    /// [`resolve`](Self::resolve).
110    pub fn resolve_drag(&mut self) -> Result<(), String> {
111        if solve::drag_min_change() {
112            self.resolve_min_change()
113        } else {
114            self.resolve()
115        }
116    }
117
118    /// Re-solve by the smallest change of the free coordinates that meets every
119    /// constraint ([`solve::solve_drag_with`]), relaxing only when that fails.
120    pub fn resolve_min_change(&mut self) -> Result<(), String> {
121        let (solved, diagnostics) = solve::solve_drag_with(&self.doc, &self.solver_settings)?;
122        self.doc = solved;
123        self.diagnostics = diagnostics;
124        Ok(())
125    }
126
127    /// The `set_overlay` JSON for this solved sketch (see
128    /// [`tessellate::overlay_json`]). `world_per_pixel` sizes construction dashes.
129    pub fn overlay_json(&self, world_per_pixel: f64) -> String {
130        tessellate::overlay_json(
131            &self.doc,
132            &self.diagnostics,
133            &self.plane,
134            world_per_pixel,
135            &self.colors,
136        )
137    }
138
139    /// The flat overlay buffers (for tests / verification stats).
140    pub fn tessellation(&self, world_per_pixel: f64) -> SketchTessellation {
141        tessellate::tessellate(
142            &self.doc,
143            &self.diagnostics,
144            &self.plane,
145            world_per_pixel,
146            &self.colors,
147        )
148    }
149
150    /// The `set_overlay` JSON with the live hover + selection colored in (S2). Empty
151    /// hover + selection reproduce [`overlay_json`](Self::overlay_json) exactly.
152    pub fn overlay_json_with_state(&self, world_per_pixel: f64) -> String {
153        tessellate::overlay_json_with_state(
154            &self.doc,
155            &self.diagnostics,
156            &self.plane,
157            world_per_pixel,
158            &self.colors,
159            self.selection.hovered.as_ref(),
160            &self.selection.items,
161        )
162    }
163
164    /// The `set_overlay` JSON for the `sketch-dim-leaders` group (S5): the per-type
165    /// leader/arrow segments for every dimensional constraint, offset by its stored
166    /// `{du, dv}` (see [`dimensions`](super::dimensions)). Always emitted (empty when
167    /// the sketch has no dimensions) so a stale group clears on the next refresh.
168    pub fn dim_leaders_overlay_json(&self, world_per_pixel: f64) -> String {
169        super::dimensions::dimension_leaders_overlay_json(
170            &self.doc,
171            &self.diagnostics,
172            &self.plane,
173            &self.dim_offsets,
174            world_per_pixel,
175            &self.colors,
176        )
177    }
178
179    /// Like [`dim_leaders_overlay_json`](Self::dim_leaders_overlay_json) but emphasizes
180    /// the live hovered / selected dimensional constraint (amber selected, light-blue
181    /// hovered — matching points/geometry). Used by the interactive overlay refresh.
182    pub fn dim_leaders_overlay_json_with_state(&self, world_per_pixel: f64) -> String {
183        super::dimensions::dimension_leaders_overlay_json_with_state(
184            &self.doc,
185            &self.diagnostics,
186            &self.plane,
187            &self.dim_offsets,
188            world_per_pixel,
189            &self.colors,
190            self.selection.hovered.as_ref(),
191            &self.selection.items,
192        )
193    }
194
195    /// The `set_overlay` JSON for the `sketch-dof-arrows` group: the free directions
196    /// of the hovered point (or of each point of the hovered geometry), drawn as
197    /// double-headed arrows. Empty when nothing movable is hovered.
198    pub fn freedom_arrows_overlay_json(&self, world_per_pixel: f64) -> String {
199        super::freedom::freedom_arrows_overlay_json(
200            &self.doc,
201            &self.diagnostics,
202            &self.plane,
203            world_per_pixel,
204            &self.colors,
205            self.selection.hovered.as_ref(),
206        )
207    }
208
209    /// The `set_overlay` JSON for the `sketch-constraint-glyphs` group (S6c): the small
210    /// screen-constant line-art marks for every GEOMETRIC (non-dimensional) constraint
211    /// — perpendicular, parallel, horizontal/vertical, coincident, equal, … (see
212    /// [`constraint_glyphs`](super::constraint_glyphs)). Painted in the shared
213    /// constraint green. Always emitted (empty when the sketch has no geometric
214    /// constraints) so a stale group clears on the next refresh.
215    pub fn constraint_glyphs_overlay_json(&self, world_per_pixel: f64) -> String {
216        super::constraint_glyphs::constraint_glyphs_overlay_json(
217            &self.doc,
218            &self.diagnostics,
219            &self.plane,
220            &self.dim_offsets,
221            world_per_pixel,
222            &self.colors,
223        )
224    }
225
226    /// Like [`constraint_glyphs_overlay_json`](Self::constraint_glyphs_overlay_json) but
227    /// emphasizes the live hovered / selected geometric constraint (amber selected,
228    /// light-blue hovered — matching points/geometry). Used by the interactive refresh.
229    pub fn constraint_glyphs_overlay_json_with_state(&self, world_per_pixel: f64) -> String {
230        super::constraint_glyphs::constraint_glyphs_overlay_json_with_state(
231            &self.doc,
232            &self.diagnostics,
233            &self.plane,
234            &self.dim_offsets,
235            world_per_pixel,
236            &self.colors,
237            self.selection.hovered.as_ref(),
238            &self.selection.items,
239        )
240    }
241
242    /// The per-constraint dimension labels (S5): one [`DimLabel`](super::dimensions::DimLabel)
243    /// per dimensional constraint, each anchored in world space (`plane.to_world` of
244    /// the label uv + its stored offset). brep-app projects `world` → screen and
245    /// draws the editable value text there.
246    pub fn dimension_labels(&self, world_per_pixel: f64) -> Vec<super::dimensions::DimLabel> {
247        super::dimensions::dimension_labels(
248            &self.doc,
249            &self.diagnostics,
250            &self.plane,
251            &self.dim_offsets,
252            world_per_pixel,
253        )
254    }
255
256    /// The `set_overlay` JSON for the active draw tool's in-progress rubber-band
257    /// preview (S3a): the dim dashed geometry from the `pending` anchor points (their
258    /// ids, resolved to uv against the live doc) toward `hover_uv`, plus the raw
259    /// freehand `stroke` (S6b-3) as a dim solid polyline while a handdraw drag is live.
260    /// Always a `sketch-preview` group (empty when there is nothing to preview yet).
261    pub fn preview_overlay_json(
262        &self,
263        world_per_pixel: f64,
264        pending: &[Value],
265        hover_uv: Option<(f64, f64)>,
266        stroke: &[(f64, f64)],
267    ) -> String {
268        let pending_uv: Vec<[f64; 2]> = pending
269            .iter()
270            .filter_map(|id| self.doc.point(id).map(|p| [p.x, p.y]))
271            .collect();
272        let stroke_uv: Vec<[f64; 2]> = stroke.iter().map(|&(u, v)| [u, v]).collect();
273        tessellate::preview_overlay_json(
274            self.tool.as_deref(),
275            &pending_uv,
276            hover_uv,
277            &stroke_uv,
278            &self.plane,
279            world_per_pixel,
280            &self.colors,
281        )
282    }
283
284    // --- S2 hover / selection state ------------------------------------------
285
286    /// Whether `entity_ref` is in the selection set (matched via [`refs_equal`]).
287    pub fn is_selected(&self, entity_ref: &Value) -> bool {
288        self.selection.is_selected(entity_ref)
289    }
290
291    /// Toggle `entity_ref` in the selection set: remove it if present, else add it.
292    pub fn toggle_selection(&mut self, entity_ref: Value) {
293        self.selection.toggle(entity_ref)
294    }
295
296    /// Clear the selection set.
297    pub fn clear_selection(&mut self) {
298        self.selection.clear()
299    }
300
301    /// Set (or clear) the hovered entity ref.
302    pub fn set_hover(&mut self, entity_ref: Option<Value>) {
303        self.selection.hovered = entity_ref;
304    }
305
306    // --- S2 hit-testing ------------------------------------------------------
307
308    /// The entity ref nearest to plane coordinate `(u, v)` within `radius` — a
309    /// POINT wins over geometry when one is in range (points take priority), else
310    /// the nearest geometry whose polyline passes within `radius`. Construction
311    /// geometry is included (it is pickable). `None` when nothing is in range.
312    pub fn pick_entity(&self, u: f64, v: f64, radius: f64) -> Option<Value> {
313        // Points first (priority over geometry under the cursor).
314        let mut best_pt: Option<(f64, &Value)> = None;
315        for p in &self.doc.points {
316            let d = ((p.x - u).powi(2) + (p.y - v).powi(2)).sqrt();
317            if d <= radius && best_pt.map_or(true, |(bd, _)| d < bd) {
318                best_pt = Some((d, &p.id));
319            }
320        }
321        if let Some((_, id)) = best_pt {
322            return Some(point_ref(id));
323        }
324
325        // Else the nearest geometry polyline within radius.
326        let mut best_geo: Option<(f64, &Value)> = None;
327        for g in &self.doc.geometries {
328            let poly = tessellate::geometry_polyline_uv(g, &self.doc);
329            if poly.len() < 2 {
330                continue;
331            }
332            let mut dmin = f64::INFINITY;
333            for seg in poly.windows(2) {
334                let d = point_segment_distance((u, v), seg[0].into(), seg[1].into()).0;
335                if d < dmin {
336                    dmin = d;
337                }
338            }
339            if dmin <= radius && best_geo.map_or(true, |(bd, _)| dmin < bd) {
340                best_geo = Some((dmin, &g.id));
341            }
342        }
343        if let Some((_, id)) = best_geo { return Some(geometry_ref(id)); }
344        // Glyph outlines pick their owning object, never a glyph handle/segment.
345        if !self.doc.geometries.iter().any(|g| g.geom_type == "text") { return None; }
346        let expanded = super::text::expanded(&self.doc).ok()?;
347        let mut best: Option<(f64, Value)> = None;
348        for g in expanded.geometries.iter().filter(|g| g.extra.contains_key("textOwner")) {
349            let poly = tessellate::geometry_polyline_uv(g, &expanded);
350            for seg in poly.windows(2) {
351                let distance = point_segment_distance((u,v),seg[0].into(),seg[1].into()).0;
352                if distance <= radius && best.as_ref().is_none_or(|(d,_)| distance < *d) {
353                    best = Some((distance, geometry_ref(&g.extra["textOwner"])));
354                }
355            }
356        }
357        best.map(|(_, id)|id)
358    }
359
360    /// The CONSTRAINT nearest to `(u, v)` within `radius` — a `constraint` entity ref
361    /// (`{"kind":"constraint","id":<id>}`), or `None`. A GEOMETRIC constraint is picked
362    /// near its glyph line-art (the exact segments [`constraint_glyphs`] draws); a
363    /// DIMENSIONAL one near its leader/arrow lines (NOT its value label — the label is
364    /// the egui value-editor affordance). Solver-internal `temporary` helpers are never
365    /// pickable. `world_per_pixel` sizes the screen-constant glyph/leader placement (so
366    /// picking tracks what is drawn). The CALLER enforces priority: points > geometry >
367    /// constraint (see `EngineState::sketch_entity_at`), so a glyph over a point never
368    /// shadows the point.
369    ///
370    /// [`constraint_glyphs`]: super::constraint_glyphs
371    pub fn pick_constraint(&self, u: f64, v: f64, radius: f64, world_per_pixel: f64) -> Option<Value> {
372        let mut best: Option<(f64, &Value)> = None;
373        let mut glyphs: std::collections::HashMap<usize, Vec<([f64; 2], [f64; 2])>> =
374            super::constraint_glyphs::glyph_layout_segments(&self.doc, &self.dim_offsets, world_per_pixel)
375                .into_iter()
376                .collect();
377        for (index, c) in self.doc.constraints.iter().enumerate() {
378            if c.temporary() {
379                continue;
380            }
381            let Some(id) = c.raw.get("id") else { continue };
382            // A constraint contributes glyph segments (geometric) XOR leader segments
383            // (dimensional); measure the cursor against whichever it draws.
384            let mut dmin = f64::INFINITY;
385            for (a, b) in glyphs.remove(&index).unwrap_or_default() {
386                let d = point_segment_distance((u, v), a.into(), b.into()).0;
387                if d < dmin {
388                    dmin = d;
389                }
390            }
391            if let Some(segments) = super::dimensions::constraint_dim_segments(
392                c,
393                &self.doc,
394                &self.dim_offsets,
395                world_per_pixel,
396            ) {
397                for (a, b) in segments {
398                    let d = point_segment_distance((u, v), a.into(), b.into()).0;
399                    if d < dmin {
400                        dmin = d;
401                    }
402                }
403            }
404            if dmin <= radius && best.map_or(true, |(bd, _)| dmin < bd) {
405                best = Some((dmin, id));
406            }
407        }
408        best.map(|(_, id)| constraint_ref(id))
409    }
410
411    /// The nearest DRAGGABLE point to `(u, v)` within `radius` (its id + authored
412    /// `fixed` flag), or `None`. A point is draggable only if the solver reports it
413    /// movable (a locked / grounded point has no free coordinates to drag), so a
414    /// drag on a fully-constrained point falls through to a camera orbit.
415    pub fn pick_draggable_point(&self, u: f64, v: f64, radius: f64) -> Option<(Value, bool)> {
416        let mut best: Option<(f64, &super::doc::SketchPoint)> = None;
417        for p in &self.doc.points {
418            let movable = self.diagnostics.point_movable(&p.id).unwrap_or(!p.fixed);
419            if !movable {
420                continue;
421            }
422            let d = ((p.x - u).powi(2) + (p.y - v).powi(2)).sqrt();
423            if d <= radius && best.map_or(true, |(bd, _)| d < bd) {
424                best = Some((d, p));
425            }
426        }
427        best.map(|(_, p)| (p.id.clone(), p.fixed))
428    }
429
430    /// The point-set to DRAG for a hovered entity ref (`{"kind","id"}`) — the grab
431    /// path grabs exactly what's highlighted rather than re-picking at egui's
432    /// offset drag-start position. A `"point"` ref → that point iff it is MOVABLE;
433    /// a `"geometry"` ref → its movable (deduped) points. Free geometry
434    /// translates rigidly; locked endpoints stay anchored during the solve.
435    /// Each entry is `(id, orig_x, orig_y, orig_fixed)`. `None`
436    /// for a locked point, a fully-locked geometry, or a stale/unknown ref (the
437    /// caller then falls through to a camera gesture — it never drags something the
438    /// user is not pointing at).
439    pub fn drag_points_from_ref(&self, entity_ref: &Value) -> Option<Vec<(Value, f64, f64, bool)>> {
440        let kind = entity_ref.get("kind").and_then(Value::as_str)?;
441        let id = entity_ref.get("id")?;
442        match kind {
443            "point" => {
444                let p = self.doc.point(id)?;
445                let movable = self.diagnostics.point_movable(&p.id).unwrap_or(!p.fixed);
446                movable.then(|| vec![(p.id.clone(), p.x, p.y, p.fixed)])
447            }
448            "geometry" => {
449                // Raw doc ids compare via `id_key` (numeric identity) — NOT
450                // `refs_equal`, which is for `{"kind","id"}` entity refs and treats
451                // every bare id as equal.
452                let g = self
453                    .doc
454                    .geometries
455                    .iter()
456                    .find(|g| id_key(&g.id) == id_key(id))?;
457                let mut out: Vec<(Value, f64, f64, bool)> = Vec::new();
458                for pid in &g.points {
459                    // A closed polyline repeats its start id — dedupe so a point is
460                    // pinned once.
461                    if out.iter().any(|(pt_id, ..)| id_key(pt_id) == id_key(pid)) {
462                        continue;
463                    }
464                    if let Some(p) = self.doc.point(pid) {
465                        // Ground constraints anchor the coordinates supplied to the
466                        // solver. Moving a locked endpoint here would re-ground it
467                        // at the drag target (including the sketch origin).
468                        if self.diagnostics.point_movable(&p.id).unwrap_or(!p.fixed) {
469                            out.push((p.id.clone(), p.x, p.y, p.fixed));
470                        }
471                    }
472                }
473                (!out.is_empty()).then_some(out)
474            }
475            _ => None,
476        }
477    }
478
479    /// Seed a standalone demo sketch (S0 milestone): a fully-constrained 20×12
480    /// rectangle grounded at the origin PLUS a free (unconstrained) circle beside
481    /// it, both on the XY plane. The mix proves the pipeline end to end — the
482    /// rectangle solves to `locked` (white), the circle stays `movable` (blue),
483    /// and the sketch reports `dof = 4` (the circle's four free coordinates).
484    pub fn seed_rectangle_circle() -> Result<Self, String> {
485        Self::new(seed_doc(), PlaneFrame::xy())
486    }
487}
488
489/// The seed document consumed by [`SketchSession::seed_rectangle_circle`].
490fn seed_doc() -> SketchDoc {
491    let value = json!({
492        "points": [
493            // rectangle corners (p0 grounded at the origin)
494            { "id": 0, "x": 0.0,  "y": 0.0,  "fixed": false, "construction": false, "externalReference": false },
495            { "id": 1, "x": 20.0, "y": 0.0,  "fixed": false, "construction": false, "externalReference": false },
496            { "id": 2, "x": 20.0, "y": 12.0, "fixed": false, "construction": false, "externalReference": false },
497            { "id": 3, "x": 0.0,  "y": 12.0, "fixed": false, "construction": false, "externalReference": false },
498            // free circle (center + radius point), unconstrained -> 4 DOF, movable
499            { "id": 4, "x": 34.0, "y": 6.0,  "fixed": false, "construction": false, "externalReference": false },
500            { "id": 5, "x": 40.0, "y": 6.0,  "fixed": false, "construction": false, "externalReference": false }
501        ],
502        "geometries": [
503            { "id": 10, "type": "line",   "points": [0, 1], "construction": false },
504            { "id": 11, "type": "line",   "points": [1, 2], "construction": false },
505            { "id": 12, "type": "line",   "points": [2, 3], "construction": false },
506            { "id": 13, "type": "line",   "points": [3, 0], "construction": false },
507            { "id": 20, "type": "circle", "points": [4, 5], "construction": false }
508        ],
509        "constraints": [
510            { "id": 0, "type": "⏚", "points": [0] },
511            { "id": 1, "type": "━", "points": [0, 1] },
512            { "id": 2, "type": "⟺", "points": [0, 1], "value": 20.0 },
513            { "id": 3, "type": "│", "points": [1, 2] },
514            { "id": 4, "type": "⟺", "points": [1, 2], "value": 12.0 },
515            { "id": 5, "type": "━", "points": [2, 3] },
516            { "id": 6, "type": "│", "points": [3, 0] }
517        ]
518    });
519    serde_json::from_value(value).expect("seed sketch doc is valid")
520}
521
522// --- S2 entity-ref convention --------------------------------------------------
523//
524// Hover + selection both use ONE ref shape: `{"kind":"point"|"geometry","id":<id>}`
525// where `<id>` is the raw doc id `Value` (a number in practice). Two refs are equal
526// when their kinds match and their ids agree under the solver's [`id_key`] identity
527// (so numeric `4` and string `"4"` are the same entity).
528
529/// Build a `{"kind":"point","id":<id>}` entity ref.
530pub fn point_ref(id: &Value) -> Value {
531    json!({ "kind": "point", "id": id.clone() })
532}
533
534/// Build a `{"kind":"geometry","id":<id>}` entity ref.
535pub fn geometry_ref(id: &Value) -> Value {
536    json!({ "kind": "geometry", "id": id.clone() })
537}
538
539/// Build a `{"kind":"constraint","id":<id>}` entity ref — a CONSTRAINT is selectable
540/// like a point/geometry (picked near its glyph or dimension leader) so it can be
541/// emphasized + deleted; deleting it drops only the constraint, never its geometry.
542pub fn constraint_ref(id: &Value) -> Value {
543    json!({ "kind": "constraint", "id": id.clone() })
544}
545
546/// Whether two entity refs name the same entity (same `kind`, same `id` under
547/// [`id_key`]).
548pub fn refs_equal(a: &Value, b: &Value) -> bool {
549    a.get("kind") == b.get("kind") && a.get("id").map(id_key) == b.get("id").map(id_key)
550}
551
552/// Whether two optional entity refs are equal (both absent, or both present and
553/// [`refs_equal`]) — the hover-changed test.
554pub fn entity_ref_eq(a: Option<&Value>, b: Option<&Value>) -> bool {
555    match (a, b) {
556        (None, None) => true,
557        (Some(x), Some(y)) => refs_equal(x, y),
558        _ => false,
559    }
560}
561