crcbl-ui 0.20.0

Crucible immediate-mode GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! The property inspector: UI rung 8's
//! reflection-driven panel with per-type overrides.
//!
//! # What it draws
//!
//! An `inspector` block holding one `.inspector-row` per
//! [`Reflect::fields`] entry — a
//! `.inspector-label` span for the field's
//! [`label`](crcbl_reflect::Field::label), then the widget that edits it,
//! classed `.inspector-field`:
//!
//! | the leaf's [`ValueKind`] | the widget |
//! |---|---|
//! | [`ValueKind::Bool`] | [`Ui::checkbox`] |
//! | [`ValueKind::Int`], [`ValueKind::UInt`], [`ValueKind::Float`] | [`Ui::drag_value`] |
//! | [`ValueKind::Text`] | [`Ui::text_input`] |
//!
//! A field that is not a leaf — a [`Kind::Struct`], a [`Kind::Enum`] or a
//! [`Kind::List`] — is a [`Ui::collapsing_keyed`] classed `.inspector-group` whose
//! body holds that value's own rows, reached through
//! [`Reflect::field_mut`]. A struct's and an
//! enum's groups are keyed by their fields and a list's by their indices, and an
//! enum's header carries its active variant after its label, because
//! [`Reflect::fields`] describes that variant
//! alone. **Depth is styling, not machinery**: the nesting a reader sees is
//! `.collapsing-body`'s padding, and a closed header builds no body at all, so
//! a deep component costs only what is open.
//!
//! # A number's range and step
//!
//! [`Field::range`](crcbl_reflect::Field::range) bounds the drag-value and
//! [`Field::step`](crcbl_reflect::Field::step) is both the step one navigation
//! notch takes and the distance one pixel of a drag moves — one step per pixel,
//! which is the only rule that needs no constant per range. A field with no
//! `#[reflect(step)]` takes [`InspectorOptions::step`] if it is a float and
//! [`WHOLE_STEP`] if it is a whole number, and a field with no
//! `#[reflect(min, max)]` is bounded by the widget's own type rather than by a
//! bound this module invented.
//!
//! **A [`Kind::List`]'s elements inherit the list's own range and step**, and
//! nothing else does. `#[reflect(min = 0.0, max = 1.0)]` on a `[f32; 3]` tint
//! is a statement about each channel — the list itself is not a leaf and has no
//! value of its own to bound — and an element carries no
//! [`Field`](crcbl_reflect::Field) to say otherwise. A [`Kind::Struct`]'s
//! fields do carry their own, so a parent never overwrites them.
//!
//! **The widget edits the leaf's own kind.** A [`Value::Int`] row drags an
//! `i64`, a [`Value::UInt`] row a `u64` and a [`Value::Float`] row an `f64`
//! ([`DragNumber`](super::DragNumber)), so a dragged field keeps every digit
//! its kind holds and a whole number past an `f32`'s 24 bits still moves one
//! at a time. A whole number's notch is the field's step rounded to the
//! nearest whole, and a drag crosses to the next value halfway. The row
//! writes back **only in the frame the widget reports
//! [`Response::changed`]**, so a field nobody touched is never written — a
//! narrower leaf, an `f32` or a `u8`, is never put through its own `set` for
//! nothing.
//!
//! # An edit is a command, not a write
//!
//! Every write the panel makes is reported as a [`FieldEdit`]: the dotted
//! [`crcbl_reflect::set_path`] path from the value the inspector was handed,
//! the [`Value`] the field held, and the one it holds now.
//! [`Inspection::edits`] is the frame's list, in the order the rows made them.
//!
//! **Undoing one is the same call with the other value**:
//! `set_path(value, &edit.path, &edit.before)`, against the value the
//! inspector was handed. This module builds no undo stack, no editor-wide
//! command enum and no transport — `docs/plan/08-editor.md` owns those, and the
//! user's decision of 2026-09-16 is that they exist from the editor's first
//! slice. What is here is the half an inspector can honestly produce: the value
//! a caller records.
//!
//! A write the leaf refuses — a number that does not fit, a non-finite float —
//! leaves the field alone and reports nothing, and so does a write that landed
//! on the value already there.
//!
//! # Switching an enum's variant
//!
//! With [`InspectorOptions::variants`], an enum's group opens on a
//! `.inspector-row` labelled [`VARIANT_LABEL`] holding a [`Ui::select`]
//! classed `.inspector-field` over the [`Reflect::variants`] entries, showing
//! the active one: a click or accept opens the list in a pop-up over the
//! rows, and a click or accept on a variant there picks it. A drop-down
//! rather than a strip of every variant, because a pop-up costs a row nothing
//! however many variants an enum has.
//!
//! Picking another variant switches it ([`Reflect::set_variant`]: the new
//! variant's fields at their defaults) and reports a [`VariantEdit`] in
//! [`Inspection::switches`]: the enum's path and a [`Snapshot`] of the whole
//! enum before and after, since a switch replaces every field the variant
//! held and the leaf form of an edit cannot put them back. **Every switch is
//! made after every field edit of the frame** — the rows draw over the value
//! as the frame found it, and the switches are applied as the call returns —
//! so a caller undoes a frame by putting back its switches newest first and
//! then its edits newest first, and redoes it in the other order.
//!
//! Off by default, because a caller that records only
//! [`Inspection::edits`] would be handed switches it cannot undo.
//!
//! # Which field a person means
//!
//! [`Inspection::hovered`] and [`Inspection::focused`] name the leaf whose
//! widget the pointer is over and the one that holds the tree's focus, by the
//! same path an edit carries — so a caller can act on "this field" without
//! knowing how the rows are laid out: copy its value, paste one over it. Each
//! is the leaf's widget alone; a label, a header and the gaps between rows name
//! nothing, because nothing there is a value.
//!
//! # Per-type overrides
//!
//! [`Overrides`] is the caller's, built once and handed to
//! [`Ui::inspector_with`]: [`Overrides::register`] takes a type and a builder,
//! and a value of that type is drawn by the builder instead of by its [`Kind`].
//! This is Unreal's Details-panel customisation and Fyrox's
//! `PropertyEditorDefinition` in the smallest form that works, and it is what
//! [`Reflect::as_any`] exists for — a
//! `&dyn Reflect` alone cannot say which type it is.
//!
//! [`Overrides::vectors`] is the one this crate ships: a three-component vector
//! on one row of three drag-values, which is how every editor of this shape
//! draws a position. It is registered for the four three-component vectors
//! `crcbl-reflect` covers, and a caller registers its own beside it.

use std::any::TypeId;
use std::fmt;

use crcbl_reflect::{
    Kind, Range, Reflect, Snapshot, Value, ValueKind, get_path, set_path, set_variant_path,
    snapshot_path,
};

use super::{Ui, WidgetKind, typed};
use crate::tree::Response;

/// The step a [`ValueKind::Float`] field with no `#[reflect(step)]` is dragged
/// and stepped by: [`InspectorOptions::step`]'s default.
pub const INSPECTOR_STEP: f64 = 0.01;

/// The step a whole number with no `#[reflect(step)]` is dragged and stepped
/// by.
///
/// Not configurable, because it is the type's rather than a policy: the values
/// between two neighbouring integers are not values the leaf can hold.
pub const WHOLE_STEP: f64 = 1.0;

/// What [`Overrides::vectors`] labels a three-component vector's drag-values
/// with, and the path segments it writes a [`Kind::Struct`] one through.
pub const AXES: [&str; 3] = ["x", "y", "z"];

/// One write an inspector made, as a caller records it.
///
/// Undoing it is `set_path(value, &edit.path, &edit.before)`; redoing it is the
/// same call with [`after`](Self::after).
#[derive(Clone, Debug, PartialEq)]
pub struct FieldEdit {
    /// The dotted [`crcbl_reflect::set_path`] path, from the value the
    /// inspector was handed. Empty when that value is itself the leaf.
    pub path: String,
    /// What the field held before the edit.
    pub before: Value,
    /// What it holds now, read back from the leaf — so a field that narrowed
    /// the write reports what it actually kept.
    pub after: Value,
}

/// What the variant drop-down labels its row with; see the module docs.
pub const VARIANT_LABEL: &str = "Variant";

/// One enum switched to another variant, as a caller records it.
///
/// Undoing it is `restore_path(value, &edit.path, &edit.before)`; redoing it
/// is the same call with [`after`](Self::after) — see
/// [`crcbl_reflect::restore_path`].
#[derive(Clone, Debug, PartialEq)]
pub struct VariantEdit {
    /// The dotted path to the enum, from the value the inspector was handed.
    /// Never empty: an enum handed in itself is drawn as its rows, with no
    /// group to hold a drop-down.
    pub path: String,
    /// The whole enum before the switch: the variant it was in and every
    /// field under it.
    pub before: Snapshot,
    /// The whole enum after it: the new variant, its fields at their
    /// defaults.
    pub after: Snapshot,
}

/// What one [`Ui::inspector`] call built, and what it changed.
#[derive(Clone, Debug, PartialEq)]
pub struct Inspection {
    /// The `inspector` block's own [`Response`].
    pub response: Response,
    /// The edits this frame's rows made, in the order they made them; empty
    /// when nothing moved.
    pub edits: Vec<FieldEdit>,
    /// The variants switched this frame, in the order they were picked, each
    /// made after every one of [`edits`](Self::edits); empty unless
    /// [`InspectorOptions::variants`] is set.
    pub switches: Vec<VariantEdit>,
    /// The path of the leaf whose widget the pointer is over this frame, if
    /// it is over one; see the module docs.
    pub hovered: Option<String>,
    /// The path of the leaf whose widget holds the tree's focus this frame, if
    /// one does.
    pub focused: Option<String>,
}

/// What a frame's rows report as they are built: the edits they made, and
/// which leaf's widget is under the pointer and which holds focus.
#[derive(Debug, Default)]
struct Report {
    edits: Vec<FieldEdit>,
    /// Each enum a drop-down picked another variant of, by path, and the variant:
    /// switched once every row is built.
    picked: Vec<(String, &'static str)>,
    hovered: Option<String>,
    focused: Option<String>,
}

impl Report {
    /// Records that the widget editing the leaf at `path` answered `response`.
    fn locate(&mut self, path: &str, response: &Response) {
        if response.hovered {
            self.hovered = Some(path.to_owned());
        }
        if response.focused {
            self.focused = Some(path.to_owned());
        }
    }
}

/// A row builder registered for one type; see [`Overrides`].
pub type RowBuilder = Box<dyn Fn(&mut Ui, &mut FieldRow<'_>)>;

/// The per-type row builders an inspector draws with instead of its own rows.
///
/// The caller owns this and builds it once — a builder is a boxed closure, so
/// rebuilding the set every frame would allocate every frame. It reaches the
/// widget through [`InspectorOptions::overrides`].
///
/// ```
/// use crcbl_reflect::Value;
/// use crcbl_ui::tree::{Overrides, TextInputOptions, Ui};
///
/// // The vector row this crate ships, plus one of the caller's own: every
/// // `String` field drawn with a placeholder, as Unreal customises an FString.
/// let mut overrides = Overrides::vectors();
/// overrides.register::<String>(|ui, field| {
///     let label = field.label;
///     ui.block(".inspector-row", &[], |ui| {
///         ui.span(".inspector-label", label, &[]);
///         let mut text = match field.get("") {
///             Some(Value::Text(text)) => text,
///             _ => String::new(),
///         };
///         let options = TextInputOptions {
///             placeholder: "unnamed",
///             ..TextInputOptions::default()
///         };
///         if ui
///             .text_input_with(".inspector-field", &mut text, options)
///             .changed
///         {
///             field.set("", Value::Text(text));
///         }
///     });
/// });
/// assert_eq!(overrides.len(), 5);
/// ```
#[derive(Default)]
pub struct Overrides {
    /// One builder per type, in registration order. The lookup is linear
    /// because an editor registers a handful of these, not a map's worth.
    builders: Vec<(TypeId, RowBuilder)>,
}

impl fmt::Debug for Overrides {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // A closure has nothing to print, so what a reader can use is how many
        // types are covered.
        f.debug_struct("Overrides")
            .field("types", &self.builders.len())
            .finish()
    }
}

impl Overrides {
    /// No overrides: every value is drawn by its own [`Kind`].
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// The one override this crate ships: a three-component vector drawn as
    /// three drag-values on one row, registered for `[f64; 3]`, `[f32; 3]`,
    /// [`glam::DVec3`] and [`glam::Vec3`] — the four spellings a position, a
    /// half extent and a linear-RGB tint take in this workspace.
    #[must_use]
    pub fn vectors() -> Self {
        let mut overrides = Self::new();
        overrides.register::<[f64; 3]>(|ui, field| vector_row(ui, field, false));
        overrides.register::<[f32; 3]>(|ui, field| vector_row(ui, field, false));
        overrides.register::<glam::DVec3>(|ui, field| vector_row(ui, field, true));
        overrides.register::<glam::Vec3>(|ui, field| vector_row(ui, field, true));
        overrides
    }

    /// Draws every value of type `T` with `build` rather than with the rows its
    /// [`Kind`] would give. A second registration for one type replaces the
    /// first.
    pub fn register<T: Reflect>(&mut self, build: impl Fn(&mut Ui, &mut FieldRow<'_>) + 'static) {
        let id = TypeId::of::<T>();
        let builder: RowBuilder = Box::new(build);
        match self.builders.iter_mut().find(|(at, _)| *at == id) {
            Some(slot) => slot.1 = builder,
            None => self.builders.push((id, builder)),
        }
    }

    /// How many types are covered.
    #[must_use]
    pub fn len(&self) -> usize {
        self.builders.len()
    }

    /// Whether nothing is registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.builders.is_empty()
    }

    /// The builder registered for `value`'s own type, if any.
    fn of(&self, value: &dyn Reflect) -> Option<&RowBuilder> {
        let id = value.as_any().type_id();
        self.builders
            .iter()
            .find(|(at, _)| *at == id)
            .map(|(_, builder)| builder)
    }
}

/// What [`Ui::inspector_with`] takes beside the value.
#[derive(Clone, Copy, Debug, Default)]
pub struct InspectorOptions<'a> {
    /// The step a [`ValueKind::Float`] field with no `#[reflect(step)]` is
    /// dragged and stepped by; [`INSPECTOR_STEP`] when this is not finite or
    /// not positive, which is what [`Default`] leaves it as.
    pub step: f64,
    /// The per-type row builders, or `None` to draw every value by its own
    /// [`Kind`].
    ///
    /// `Option` rather than a borrow of an empty set, because a [`Vec`] has a
    /// destructor and so cannot be promoted to the `'static` an empty default
    /// would have to borrow.
    pub overrides: Option<&'a Overrides>,
    /// Whether an enum's group offers its variants to switch to, reporting
    /// each switch in [`Inspection::switches`]; see the module docs. Off by
    /// default.
    pub variants: bool,
}

impl InspectorOptions<'_> {
    /// [`Self::step`], or [`INSPECTOR_STEP`] when it is not a step a drag can
    /// use.
    fn float_step(&self) -> f64 {
        if self.step.is_finite() && self.step > 0.0 {
            self.step
        } else {
            INSPECTOR_STEP
        }
    }
}

/// One row of an inspector, as an override sees it: the value the row is for,
/// what it is labelled and bounded by, and the way an edit is reported.
///
/// Read a leaf with [`get`](Self::get) and write one with [`set`](Self::set),
/// both taking a path **relative to this field** — `""` for the field itself,
/// `"x"` or `"1"` for a component of it.
pub struct FieldRow<'a> {
    /// The value this row draws.
    pub value: &'a mut dyn Reflect,
    /// What the row is labelled with: the field's
    /// [`label`](crcbl_reflect::Field::label), or a list element's index.
    pub label: &'a str,
    /// The interval the field is edited within, from `#[reflect(min, max)]`.
    pub range: Option<Range>,
    /// How far one notch moves it, from `#[reflect(step)]`.
    pub step: Option<f64>,
    /// The dotted path from the inspected value to [`value`](Self::value).
    path: &'a str,
    /// Where an edit this row makes is recorded, and which of its widgets is
    /// hovered or focused.
    report: &'a mut Report,
}

impl fmt::Debug for FieldRow<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FieldRow")
            .field("type_name", &self.value.type_name())
            .field("label", &self.label)
            .field("range", &self.range)
            .field("step", &self.step)
            .field("path", &self.path)
            .finish_non_exhaustive()
    }
}

impl FieldRow<'_> {
    /// The dotted path from the inspected value to this row's field.
    #[must_use]
    pub fn path(&self) -> &str {
        self.path
    }

    /// The leaf `at` names inside this field; `""` is the field itself. `None`
    /// when the path names nothing, or stops on something that is not a leaf.
    #[must_use]
    pub fn get(&self, at: &str) -> Option<Value> {
        get_path(self.value, at).ok()
    }

    /// Writes `new` into the leaf `at` names and records the edit under this
    /// row's path joined with `at`.
    ///
    /// Returns whether the field moved. A write the leaf refuses, and one that
    /// landed on the value already there, changes nothing and records nothing.
    pub fn set(&mut self, at: &str, new: Value) -> bool {
        let Ok(before) = get_path(self.value, at) else {
            return false;
        };
        if set_path(self.value, at, &new).is_err() {
            return false;
        }
        let Ok(after) = get_path(self.value, at) else {
            return false;
        };
        // Bit for bit: a write of `-0.0` over `0.0` is an edit to report.
        if after.identical(&before) {
            return false;
        }
        self.report.edits.push(FieldEdit {
            path: joined(self.path, at),
            before,
            after,
        });
        true
    }

    /// Says that `response` is the widget editing the leaf `at` names inside
    /// this field, so [`Inspection::hovered`] and [`Inspection::focused`] can
    /// name it. An override that never calls this leaves its widgets nameless.
    pub fn locate(&mut self, at: &str, response: &Response) {
        self.report.locate(&joined(self.path, at), response);
    }
}

/// What one row is labelled and bounded by: a [`crcbl_reflect::Field`], or a
/// list element's index.
///
/// Not [`crcbl_reflect::Field`] itself, because its `name` and `label` are
/// `&'static str` and an index's are a [`String`] the frame built.
#[derive(Clone, Copy, Debug)]
struct Row<'a> {
    /// The row's path segment; empty for the inspected value itself.
    name: &'a str,
    /// What the row is labelled with.
    label: &'a str,
    /// The field's `#[reflect(min, max)]`.
    range: Option<Range>,
    /// The field's `#[reflect(step)]`.
    step: Option<f64>,
}

/// `path` with `segment` appended, in `crcbl_reflect::set_path`'s grammar.
fn joined(path: &str, segment: &str) -> String {
    match (path.is_empty(), segment.is_empty()) {
        (_, true) => path.to_owned(),
        (true, false) => segment.to_owned(),
        (false, false) => format!("{path}.{segment}"),
    }
}

/// A drag-value over the number `before` holds, in its own kind, inside
/// `range` and moving `step` a pixel and a notch; see the module docs. Returns
/// its [`Response`] and the value to write back in the frame it changed, or
/// nothing — no widget at all — when `before` is not a number.
///
/// A float's interval without a `#[reflect(min, max)]` is the widget's own
/// type's, and a whole number's is its type's: a field with no bound says
/// nothing about what it can hold, so a row must not invent one. A float
/// bound converts to a whole number's with `as`, which saturates.
///
/// `#[track_caller]` so each row's drag-value is keyed by the row builder's
/// call site, as it would be if the builder called [`Ui::drag_value`] itself.
#[track_caller]
fn number_field(
    ui: &mut Ui,
    before: &Value,
    range: Option<Range>,
    step: f64,
) -> Option<(Response, Option<Value>)> {
    const FIELD: &str = ".inspector-field";
    let edited = match *before {
        Value::Int(mut number) => {
            let (min, max) = range.map_or((i64::MIN, i64::MAX), |range| {
                (range.min as i64, range.max as i64)
            });
            let notch = step.round() as i64;
            let response = ui.drag_value(FIELD, &mut number, min..=max, step, notch);
            (response, response.changed.then_some(Value::Int(number)))
        }
        Value::UInt(mut number) => {
            let (min, max) = range.map_or((u64::MIN, u64::MAX), |range| {
                (range.min as u64, range.max as u64)
            });
            let notch = step.round() as u64;
            let response = ui.drag_value(FIELD, &mut number, min..=max, step, notch);
            (response, response.changed.then_some(Value::UInt(number)))
        }
        Value::Float(mut number) => {
            let (min, max) = range.map_or((f64::MIN, f64::MAX), |range| (range.min, range.max));
            let response = ui.drag_value(FIELD, &mut number, min..=max, step, step);
            (response, response.changed.then_some(Value::Float(number)))
        }
        Value::Bool(_) | Value::Text(_) => return None,
    };
    Some(edited)
}

/// Three drag-values on one row: [`Overrides::vectors`]' builder.
///
/// `named` says how the components are reached — by `x`/`y`/`z` for a glam
/// vector, which is a [`Kind::Struct`], and by index for a `[T; 3]`, which is a
/// [`Kind::List`]. Each is labelled by its axis either way, because the axis a
/// person reads is the axis whatever the path spells it as.
fn vector_row(ui: &mut Ui, field: &mut FieldRow<'_>, named: bool) {
    let step = field.step.unwrap_or(INSPECTOR_STEP);
    let range = field.range;
    let label = field.label;
    ui.block(".inspector-row", &[], |ui| {
        ui.span(".inspector-label", label, &[]);
        for (index, axis) in AXES.iter().enumerate() {
            let segment = if named {
                (*axis).to_owned()
            } else {
                index.to_string()
            };
            let Some(before) = field.get(&segment) else {
                continue;
            };
            let mut new = None;
            // Keyed by the axis: three drag-values built at one call site,
            // whose state must follow the component rather than its position.
            ui.block_keyed(*axis, ".inspector-axis", &[], |ui| {
                ui.span(".inspector-axis-label", *axis, &[]);
                if let Some((response, edited)) = number_field(ui, &before, range, step) {
                    new = edited;
                    field.locate(&segment, &response);
                }
            });
            if let Some(new) = new {
                field.set(&segment, new);
            }
        }
    });
}

impl Ui {
    /// A property inspector over `value`: one row per reflected field, as the
    /// module docs describe, with no per-type overrides and [`INSPECTOR_STEP`]
    /// for a float that carries no `#[reflect(step)]`.
    ///
    /// [`Inspection::edits`] is what the frame changed, each as a path and the
    /// value it replaced; the module docs say what undoing one takes.
    #[track_caller]
    pub fn inspector(&mut self, selector: &str, value: &mut dyn Reflect) -> Inspection {
        self.inspector_with(selector, value, &InspectorOptions::default())
    }

    /// [`Ui::inspector`] with `options`: the per-type overrides a caller
    /// registered, and the step an unstepped float takes.
    #[track_caller]
    pub fn inspector_with(
        &mut self,
        selector: &str,
        value: &mut dyn Reflect,
        options: &InspectorOptions<'_>,
    ) -> Inspection {
        let selector = typed("inspector", selector);
        let mut report = Report::default();
        let mut path = String::new();
        let response = self.block(&selector, &[], |ui| {
            // A composite is its rows. A leaf handed in on its own, and any
            // value an override covers, is one row of its own instead.
            let root = Row {
                name: "",
                label: value.type_name(),
                range: None,
                step: None,
            };
            let overridden = options
                .overrides
                .is_some_and(|overrides| overrides.of(value).is_some());
            if overridden || matches!(value.kind(), Kind::Leaf(_)) {
                ui.inspect_row(value, root, &mut path, options, &mut report);
            } else {
                ui.inspect_children(value, root, &mut path, options, &mut report);
            }
        });
        self.mark(response.key, WidgetKind::Inspector);
        let switches = switch_picked(value, &report.picked);
        Inspection {
            response,
            edits: report.edits,
            switches,
            hovered: report.hovered,
            focused: report.focused,
        }
    }

    /// One row per child of `value`: its fields, or its elements by index,
    /// whose bounds are `parent`'s. A leaf has no children and builds nothing.
    fn inspect_children(
        &mut self,
        value: &mut dyn Reflect,
        parent: Row<'_>,
        path: &mut String,
        options: &InspectorOptions<'_>,
        report: &mut Report,
    ) {
        match value.kind() {
            Kind::Struct | Kind::Enum => {
                // `fields` returns `&'static`, so reading it holds no borrow of
                // `value` across `field_mut`.
                let fields = value.fields();
                for (index, field) in fields.iter().enumerate() {
                    let Some(child) = value.field_mut(index) else {
                        continue;
                    };
                    let row = Row {
                        name: field.name,
                        label: field.label,
                        range: field.range,
                        step: field.step,
                    };
                    self.inspect_row(child, row, path, options, report);
                }
            }
            Kind::List { len } => {
                for index in 0..len {
                    let name = index.to_string();
                    let Some(child) = value.field_mut(index) else {
                        continue;
                    };
                    // An element has no `Field` of its own, so the list's
                    // bounds are the only ones it can have; see the module
                    // docs.
                    let row = Row {
                        name: &name,
                        label: &name,
                        range: parent.range,
                        step: parent.step,
                    };
                    self.inspect_row(child, row, path, options, report);
                }
            }
            Kind::Leaf(_) => {}
        }
    }

    /// One row for `child`, under `path` joined with the row's own segment: an
    /// override if one is registered for its type, then a leaf's widget or a
    /// collapsing header holding the value's own rows.
    fn inspect_row(
        &mut self,
        child: &mut dyn Reflect,
        row: Row<'_>,
        path: &mut String,
        options: &InspectorOptions<'_>,
        report: &mut Report,
    ) {
        let base = path.len();
        if !row.name.is_empty() {
            if !path.is_empty() {
                path.push('.');
            }
            path.push_str(row.name);
        }

        if let Some(builder) = options.overrides.and_then(|overrides| overrides.of(child)) {
            let mut field = FieldRow {
                value: child,
                label: row.label,
                range: row.range,
                step: row.step,
                path,
                report,
            };
            builder(self, &mut field);
        } else {
            match child.kind() {
                Kind::Leaf(kind) => self.leaf_row(child, row, kind, path, options, report),
                Kind::Struct | Kind::Enum | Kind::List { .. } => {
                    // An enum describes its active variant's fields and no
                    // others, so the header names the variant the rows are of.
                    let title = match child.variant() {
                        Some(variant) => format!("{}: {variant}", row.label),
                        None => row.label.to_owned(),
                    };
                    self.collapsing_keyed(row.name, ".inspector-group", &title, |ui| {
                        if options.variants
                            && let Some(variant) = ui.variant_select(&*child)
                        {
                            report.picked.push((path.clone(), variant));
                        }
                        ui.inspect_children(child, row, path, options, report);
                    });
                }
            }
        }

        path.truncate(base);
    }

    /// The variant drop-down at the top of an enum's group, as the module docs
    /// describe it: the variant picked this frame, if it is not the active
    /// one. A value with no variants builds nothing.
    fn variant_select(&mut self, value: &dyn Reflect) -> Option<&'static str> {
        let variants = value.variants();
        if variants.is_empty() {
            return None;
        }
        let names: Vec<&'static str> = variants.iter().map(|variant| variant.name).collect();
        let active = value.variant();
        let mut chosen = names
            .iter()
            .position(|&name| Some(name) == active)
            .unwrap_or(names.len());
        let mut picked = None;
        self.block(".inspector-row", &[], |ui| {
            ui.span(".inspector-label", VARIANT_LABEL, &[]);
            if ui.select(".inspector-field", &names, &mut chosen).changed {
                picked = names.get(chosen).copied();
            }
        });
        picked
    }

    /// The row for one leaf: its label, then the widget its [`ValueKind`]
    /// picks. The leaf is written back only in the frame the widget reports a
    /// change; see the module docs.
    fn leaf_row(
        &mut self,
        child: &mut dyn Reflect,
        row: Row<'_>,
        kind: ValueKind,
        path: &str,
        options: &InspectorOptions<'_>,
        report: &mut Report,
    ) {
        let Some(before) = child.get() else {
            return;
        };
        let float_step = options.float_step();
        self.block(".inspector-row", &[], |ui| {
            ui.span(".inspector-label", row.label, &[]);
            let (response, new) = match kind {
                ValueKind::Bool => {
                    let mut on = matches!(before, Value::Bool(true));
                    let response = ui.checkbox(".inspector-field", "", &mut on);
                    let new = response.changed.then_some(Value::Bool(on));
                    (response, new)
                }
                ValueKind::Text => {
                    let mut text = match &before {
                        Value::Text(text) => text.clone(),
                        _ => String::new(),
                    };
                    let response = ui.text_input(".inspector-field", &mut text);
                    let new = response.changed.then_some(Value::Text(text));
                    (response, new)
                }
                ValueKind::Int | ValueKind::UInt | ValueKind::Float => {
                    let step = row.step.unwrap_or(match kind {
                        ValueKind::Float => float_step,
                        _ => WHOLE_STEP,
                    });
                    // A leaf whose value is not of its own kind gets a label
                    // and no widget, which is all a row can honestly draw.
                    let Some(edited) = number_field(ui, &before, row.range, step) else {
                        return;
                    };
                    edited
                }
            };
            report.locate(path, &response);
            if let Some(new) = new {
                write_leaf(child, path, &new, &mut report.edits);
            }
        });
    }
}

/// Switches each enum `picked` names inside `value` to the variant picked
/// for it, in order, and reports each as a [`VariantEdit`].
///
/// A switch the enum refuses, or a path that no longer names it, is no edit
/// and reports nothing — the rule [`write_leaf`] keeps for a leaf.
fn switch_picked(value: &mut dyn Reflect, picked: &[(String, &'static str)]) -> Vec<VariantEdit> {
    let mut switches = Vec::with_capacity(picked.len());
    for (path, variant) in picked {
        let Ok(before) = snapshot_path(value, path) else {
            continue;
        };
        if set_variant_path(value, path, variant).is_err() {
            continue;
        }
        let Ok(after) = snapshot_path(value, path) else {
            continue;
        };
        switches.push(VariantEdit {
            path: path.clone(),
            before,
            after,
        });
    }
    switches
}

/// Writes `new` into `leaf` and records what it replaced.
///
/// Nothing is recorded when the leaf refuses the write, or when the value it
/// kept is the one it already held — a narrowing leaf can turn a changed widget
/// into an unchanged field, and an edit nobody can see is not one a caller
/// should have to undo.
fn write_leaf(leaf: &mut dyn Reflect, path: &str, new: &Value, edits: &mut Vec<FieldEdit>) {
    let Some(before) = leaf.get() else {
        return;
    };
    if leaf.set(new).is_err() {
        return;
    }
    let Some(after) = leaf.get() else {
        return;
    };
    // Bit for bit: a write of `-0.0` over `0.0` is an edit to report.
    if after.identical(&before) {
        return;
    }
    edits.push(FieldEdit {
        path: path.to_owned(),
        before,
        after,
    });
}