bevy_react_core 0.7.0

The core bridge of bevy-react (drive bevy_ui from React over an embedded V8 runtime). Apps depend on the `bevy-react` crate.
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
//! The public Bevy plugin: wires the JS thread, channels, UI root, and hot
//! reload into a consumer's `App`.

use std::path::PathBuf;

use crate::animations::{
    AnimationCommand, AnimationSet, AnimationSettled, ReactUiAnimationsPlugin,
};
use bevy::asset::embedded_asset;
use bevy::prelude::*;
#[cfg(feature = "custom_cursor")]
use bevy::window::CustomCursorImage;

use crate::bridge::{JsBridge, OpReceiver, OutboundResource, OutboundSender};
use crate::elements::editable::{
    apply_pending_selections, on_focus_gained, on_focus_lost, on_text_edit_change,
    sync_editable_a11y,
};
use crate::event::ReactEventRegistry;
use crate::host::{self, HostConfig, HostSenders};
use crate::message::{ReactAppExt, ReactMessage, ReactRegistry};
use crate::protocol::{op::Op, outbound::Outbound};
use crate::reconcile::{
    OpApplyStats, apply_interaction_styles, apply_js_ops, apply_virtual_interaction_styles,
    collect_hover_events, collect_pointer_events, collect_scroll_events, collect_ui_events,
    collect_virtual_clicks, collect_virtual_hover_events, collect_virtual_pointer_events,
};
use crate::request::{RawRequest, ReactRequestRegistry, RequestReceiver, dispatch_react_requests};

/// Whether the React UI currently owns the mouse pointer. Refreshed every frame
/// in [`PointerCaptureSet`]; world-input systems (a 3D camera controller, picking,
/// …) should consult it and ignore the mouse when it reports captured, so a UI
/// drag or click doesn't also drive the scene.
///
/// Order such a system after the set to read the current frame's state:
/// ```no_run
/// # use bevy::prelude::*;
/// # use bevy_react_core::PointerCaptureSet;
/// # fn orbit_camera() {}
/// # let mut app = App::new();
/// app.add_systems(Update, orbit_camera.after(PointerCaptureSet));
/// ```
#[derive(Resource, Default, Debug, Clone, Copy)]
pub struct PointerCapture {
    /// A bevy-react element is being dragged (an `onPointer*` press is in
    /// progress). Stays true for the whole gesture — even after the cursor leaves
    /// the element's bounds — until the button is released.
    pub dragging: bool,
    /// The pointer is over an interactive UI element (its `Interaction` is
    /// `Hovered` or `Pressed`).
    pub over_ui: bool,
    /// The UI consumed this frame's wheel input: a scroll container actually
    /// moved, an `onWheel` listener claimed the delta, or an overlay (devtools
    /// pick mode) owns the pointer. Unlike `over_ui`, merely hovering
    /// interactive UI does not set this — a world wheel-consumer (a zoom
    /// camera) can gate on it alone to keep zooming over pass-through elements.
    pub wheel_captured: bool,
}

impl PointerCapture {
    /// The UI owns the current pointer input; world systems should ignore the
    /// mouse. True while dragging a UI element, while over interactive UI, or
    /// when the UI consumed this frame's wheel. Coarse by design — consumers
    /// wanting finer behavior (e.g. a camera that zooms over pass-through UI)
    /// read the individual fields instead.
    pub fn is_captured(&self) -> bool {
        self.dragging || self.over_ui || self.wheel_captured
    }
}

/// System set in which [`PointerCapture`] is refreshed each frame. Order your
/// world-input systems `.after(PointerCaptureSet)` so they see this frame's state.
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PointerCaptureSet;

/// System set (in `Update`) in which the reconciler's ops for this frame are
/// applied: entities spawned/despawned, the hierarchy synced, `Name`s and the
/// [`ReactNodes`](crate::ReactNodes) index updated. Order app systems that
/// read React-created entities `.after(ReactApplySet)` so they see this
/// frame's mounts (`Added<ReactNode>`) rather than lagging a frame.
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ReactApplySet;

/// Adds a React-driven `bevy_ui` layer to a Bevy `App`.
///
/// Point it at a built JS bundle (see the `bevy-react` npm package). The plugin
/// spawns the dedicated JS thread, applies the reconciler's ops to the ECS,
/// reports interactions back to React, and — unless disabled — hot reloads the
/// app when the bundle changes on disk. In dev builds it also enables the
/// devtools inspector (toggled with `F12`; see [`Self::devtools`]).
///
/// Requires Bevy's `AssetPlugin` (satisfied by `DefaultPlugins`): `build`
/// registers the [`SvgDocument`](crate::svg::SvgDocument) asset + loader, so a
/// headless/minimal app must add `AssetPlugin` (plus its task-pool
/// prerequisites, e.g. via `MinimalPlugins`) before this plugin.
pub struct ReactUiPlugin {
    bundle: PathBuf,
    hot_reload: bool,
    default_font: Option<PathBuf>,
    named_fonts: Vec<(String, PathBuf)>,
    #[cfg(feature = "custom_cursor")]
    custom_cursors: Vec<(String, PathBuf, (u16, u16))>,
    #[cfg(feature = "devtools")]
    devtools: crate::devtools::DevtoolsConfig,
    precompile_filters: PrecompileFilters,
}

/// One partition's selection for [`PrecompileFilters`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum FilterSelection {
    /// Every filter in the partition. The default.
    #[default]
    All,
    /// Only these wire names. A name that is unknown, or belongs to another
    /// partition, warns once at startup (`precompileFilters`) and is skipped.
    Names(Vec<String>),
    /// None of them — they compile lazily on first use, and the composite
    /// gate withholds the layer while they do.
    Off,
}

/// Which shaders [`ReactUiPlugin::precompile_filters`] compiles ahead of first
/// use, per partition of the filter registry. Every field defaults to
/// [`FilterSelection::All`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PrecompileFilters {
    /// Everything the crate ships — the built-in filters AND the built-in
    /// morphs (`crossfade`, `linearWipe`, `pixelize`). "Built-in" is a fact of
    /// who registered the entry, not of its name: an app shadowing a built-in
    /// name with its own type moves it to `filters`/`morphs`.
    pub builtins: FilterSelection,
    /// The app's own regular filters (`add_react_filter`).
    pub filters: FilterSelection,
    /// The app's own morph filters (`add_react_morph_filter`).
    pub morphs: FilterSelection,
}

impl ReactUiPlugin {
    /// Create the plugin for the given built app bundle (`app.js`). The build
    /// emits a `vendor.js` beside it (react + the bevy-react runtime, loaded once);
    /// both must exist. Hot reload (React Fast Refresh — edits preserve component
    /// state) is enabled by default.
    ///
    /// The plugin does **not** spawn a camera — `bevy_ui` needs one to render, so
    /// your app must provide it (a `Camera2d`, or any camera that renders UI).
    pub fn new(bundle: impl Into<PathBuf>) -> Self {
        Self {
            bundle: bundle.into(),
            hot_reload: true,
            default_font: None,
            named_fonts: Vec::new(),
            #[cfg(feature = "custom_cursor")]
            custom_cursors: Vec::new(),
            #[cfg(feature = "devtools")]
            devtools: Default::default(),
            precompile_filters: Default::default(),
        }
    }

    /// The bundle [`Default`] loads: what the `init` template's `ui/`
    /// package builds, relative to the working directory.
    pub const DEFAULT_BUNDLE: &'static str = "ui/dist/app.js";

    /// Configure the devtools inspector, on by default in dev builds (release
    /// builds never run it, even when compiled in). Every
    /// [`DevtoolsConfig`](crate::DevtoolsConfig) field has a default, so
    /// override only what you need:
    ///
    /// ```no_run
    /// # use bevy::prelude::*;
    /// # use bevy_react_core::{DevtoolsConfig, ReactUiPlugin};
    /// # let mut app = App::new();
    /// app.add_plugins(ReactUiPlugin::new("ui/dist/app.js").devtools(DevtoolsConfig {
    ///     toggle_key: KeyCode::F1,
    ///     settings_path: Some(".config/devtools.json".into()),
    ///     ..default()
    /// }));
    /// // or disable devtools entirely
    /// app.add_plugins(ReactUiPlugin::new("ui/dist/app.js").devtools(DevtoolsConfig {
    ///     enabled: false,
    ///     ..default()
    /// }));
    /// ```
    #[cfg(feature = "devtools")]
    pub fn devtools(mut self, config: crate::devtools::DevtoolsConfig) -> Self {
        self.devtools = config;
        self
    }

    /// Choose which filter and morph shaders are compiled ahead of their first
    /// use. Default: all of them.
    ///
    /// A `filter` chain or a `morphFilter` runs as GPU pipelines specialized
    /// per shader and camera target format, compiled on first use — and while
    /// one compiles, the layer's composite is withheld: the subtree draws
    /// nothing for a few frames (a dark blink on the first use of each
    /// morph). With this on, the render world queues every selected shader
    /// (plus the composite, mip-blit and backdrop-blit pipelines every layer
    /// needs) for each camera format the first frame it sees it — effectively
    /// at startup — on the pipeline cache's background workers; no frame
    /// stalls, and each pipeline is tiny. `Names` narrows a partition for an
    /// app with a large filter library; `Off` keeps the lazy path (a morph
    /// declared on an idle node is still warmed before its key changes).
    ///
    /// Partitions: `builtins` is everything the crate ships, both families;
    /// `filters` and `morphs` are the app's own `add_react_filter` /
    /// `add_react_morph_filter` registrations. Multi-pass shaders are found
    /// by resolving the filter with its identity (or empty) params, so a
    /// custom multi-pass filter whose params have no defaults warms its
    /// primary shader only.
    ///
    /// ```no_run
    /// # use bevy::prelude::*;
    /// # use bevy_react_core::{FilterSelection, PrecompileFilters, ReactUiPlugin};
    /// # let mut app = App::new();
    /// // Only two of the app's morphs, everything else as usual.
    /// app.add_plugins(ReactUiPlugin::new("ui/dist/app.js").precompile_filters(
    ///     PrecompileFilters {
    ///         morphs: FilterSelection::Names(vec!["doorway".into(), "bookFlip".into()]),
    ///         ..default()
    ///     },
    /// ));
    /// // or compile everything lazily
    /// app.add_plugins(ReactUiPlugin::new("ui/dist/app.js").precompile_filters(
    ///     PrecompileFilters {
    ///         builtins: FilterSelection::Off,
    ///         filters: FilterSelection::Off,
    ///         morphs: FilterSelection::Off,
    ///     },
    /// ));
    /// ```
    pub fn precompile_filters(mut self, config: PrecompileFilters) -> Self {
        self.precompile_filters = config;
        self
    }

    /// Enable/disable watching the bundle and hot reloading on change.
    pub fn hot_reload(mut self, yes: bool) -> Self {
        self.hot_reload = yes;
        self
    }

    /// Set the app-wide default font, loaded via the `AssetServer` (path relative
    /// to your `AssetPlugin.file_path`, e.g. `"fonts/Roboto.ttf"`). Every `<text>`
    /// run uses it unless its style names another family via [`Self::font`].
    pub fn default_font(mut self, path: impl Into<PathBuf>) -> Self {
        self.default_font = Some(path.into());
        self
    }

    /// Register a named font family. React selects it per element with
    /// `style={{ fontFamily: name }}`; the path is loaded via the `AssetServer`
    /// (relative to your `AssetPlugin.file_path`).
    pub fn font(mut self, name: impl Into<String>, path: impl Into<PathBuf>) -> Self {
        self.named_fonts.push((name.into(), path.into()));
        self
    }

    /// Register a named custom **image** cursor. React selects it per element with
    /// `style={{ cursor: name }}` (any name that isn't a built-in cursor keyword);
    /// the image at `path` is loaded via the `AssetServer` (relative to your
    /// `AssetPlugin.file_path`), and `hotspot` is the click-point pixel (top-left
    /// origin) within it. The cursor analogue of [`Self::font`].
    ///
    /// Needs the `custom_cursor` cargo feature (default; it pulls in
    /// `bevy_winit`). Without it, built-in cursor keywords still work and a
    /// custom name warns like any unknown cursor.
    #[cfg(feature = "custom_cursor")]
    #[cfg_attr(docsrs, doc(cfg(feature = "custom_cursor")))]
    pub fn cursor(
        mut self,
        name: impl Into<String>,
        path: impl Into<PathBuf>,
        hotspot: (u16, u16),
    ) -> Self {
        self.custom_cursors
            .push((name.into(), path.into(), hotspot));
        self
    }
}

/// Register the layer/filter shader assets: the importable filter-pass
/// prelude (`#import bevy_react::filter`, see `layer/filter_prelude.wgsl`)
/// plus the embedded pass shaders. `load_shader_library!` both embeds the
/// prelude and loads it as a `Shader`, which registers its
/// `#define_import_path` with the shader composer.
///
/// Split out of [`Plugin::build`]'s render-gated block so asset-capable tests
/// (see `filters/test_util.rs`) can register the shaders without the render
/// sub-app; callers must have `AssetPlugin` and the `Shader` asset set up.
///
/// Each shader lives next to its loading code — the built-in pass shaders
/// beside `filters/builtin`'s `ReactFilter::shader` impls, the prelude and
/// composite beside `layer/render.rs`'s pipelines — and the embedded paths
/// mirror that layout (this macro roots them at THIS file's directory).
pub(crate) fn register_layer_shader_assets(app: &mut App) {
    bevy::shader::load_shader_library!(app, "layer/filter_prelude.wgsl");
    embedded_asset!(app, "layer/composite.wgsl");
    embedded_asset!(app, "layer/render/mip_blit.wgsl");
    embedded_asset!(app, "layer/render/backdrop_blit.wgsl");
    embedded_asset!(app, "filters/builtin/color_matrix.wgsl");
    embedded_asset!(app, "filters/builtin/blur.wgsl");
    embedded_asset!(app, "filters/builtin/bloom.wgsl");
    embedded_asset!(app, "filters/builtin/chromatic_aberration.wgsl");
    embedded_asset!(app, "filters/builtin/gradient_map.wgsl");
    embedded_asset!(app, "filters/builtin/outline.wgsl");
    embedded_asset!(app, "filters/builtin/pinch.wgsl");
    embedded_asset!(app, "filters/builtin/shadow.wgsl");
    embedded_asset!(app, "filters/builtin/crossfade.wgsl");
    embedded_asset!(app, "filters/builtin/linear_wipe.wgsl");
    embedded_asset!(app, "filters/builtin/pixelize.wgsl");
}

/// Schedule the render-target camera gate — the system that flips a
/// [`PortalCamera`](crate::PortalCamera)'s `Camera::is_active` — from THIS
/// frame's visibility: after bevy_ui layout + clipping (a `display: none` or
/// scrolled-away view is empty/clipped) and after visibility propagation
/// (hidden subtrees), before extraction reads `Camera::is_active` — a view
/// that becomes visible renders the same frame, and a hidden one skips its
/// whole camera pass.
///
/// Bevy prepares a view's per-frame data only for cameras that are
/// `is_active` when the preparing system runs: `CheckVisibility` fills
/// `VisibleEntities`, and `bevy_light`'s `UpdateDirectionalLightCascades`
/// clears every shadow-casting light's `Cascades` map and rebuilds it keyed
/// by **every** active camera with a `Projection` (2D cameras included).
/// `bevy_pbr::render::light::prepare_lights` later `unwrap`s the entry per
/// extracted 3D view, so a camera activated AFTER the build reaches
/// extraction with no entry — a panic. So the activity flip runs BEFORE
/// `CheckVisibility` and `UpdateDirectionalLightCascades` (which order after
/// `CameraUpdateSystems` only; the explicit `before` edges are required).
/// Only `InheritedVisibility` (propagation) and layout feed the gate, so
/// nothing later is needed. (A feature spawning or despawning cameras —
/// `bevy_react_surface` — orders against the same two sets itself.)
pub(crate) fn add_camera_gate_systems(app: &mut App) {
    app.add_systems(
        PostUpdate,
        crate::render_target::drive_target_cameras
            .after(bevy::ui::UiSystems::PostLayout)
            .after(bevy::camera::visibility::VisibilitySystems::VisibilityPropagate)
            .before(bevy::camera::visibility::VisibilitySystems::CheckVisibility)
            .before(bevy::light::SimulationLightSystems::UpdateDirectionalLightCascades),
    );
}

/// The plugin for [`ReactUiPlugin::DEFAULT_BUNDLE`] (`ui/dist/app.js`) with
/// every default — what `ReactPlugins` adds unless `.set(..)` overrides it.
impl Default for ReactUiPlugin {
    fn default() -> Self {
        Self::new(Self::DEFAULT_BUNDLE)
    }
}

/// Register the bindings `ReactUiPlugin` always provides — the built-in
/// messages, requests, events, and filters — as payload types (the plugin
/// attaches their observers and systems itself). The TypeScript exporter
/// seeds its view the same way, since it runs on a bare `App` with no plugin.
pub(crate) fn register_builtin_bindings(app: &mut App) {
    app.add_react_message::<crate::gamepad::GamepadRumble>()
        .add_react_message::<crate::gamepad::GamepadStopRumble>()
        .add_react_request::<crate::window::WindowSizeGet>()
        .add_react_request::<crate::gamepad::GamepadGetAll>()
        .add_react_event::<crate::keyboard::KeyDown>()
        .add_react_event::<crate::keyboard::KeyUp>()
        .add_react_event::<crate::window::Resize>()
        .add_react_event::<crate::gamepad::GamepadConnected>()
        .add_react_event::<crate::gamepad::GamepadDisconnected>()
        .add_react_event::<crate::gamepad::GamepadInputEvent>();
    crate::filters::register_builtin_filters(app);
}

impl Plugin for ReactUiPlugin {
    /// Every plugin has built: snapshot the feature registry for the
    /// decoding host (see [`crate::ext::ExtRegistrySlot`]).
    fn finish(&self, app: &mut App) {
        let registry = app.world().resource::<crate::ext::ExtRegistry>().clone();
        registry.styles().validate();
        app.world()
            .resource::<crate::ext::ExtRegistrySlot>()
            .fill(registry);
    }

    fn build(&self, app: &mut App) {
        // Render-side wiring, gated on a render pipeline being present (the
        // canonical `DefaultPlugins`-first setup), since `embedded_asset!` and the
        // render sub-app need the asset + render infrastructure — a headless `App`
        // with neither (e.g. wiring-only tests) simply skips it.
        if app.is_plugin_added::<bevy::render::RenderPlugin>() {
            // Layer compositing (see `crate::layer::render`): the capture
            // pass + composite quad over stock `bevy_ui_render`, public
            // seams only. Steal window: after Queue, before the stock sort;
            // prepare after the stock prepares' PrepareBindGroups slot is
            // irrelevant (disjoint items).
            register_layer_shader_assets(app);
            if let Some(render_app) = app.get_sub_app_mut(bevy::render::RenderApp) {
                use crate::layer::render as lr;
                use bevy::core_pipeline::schedule::{Core2d, Core2dSystems, Core3d, Core3dSystems};
                use bevy::render::render_phase::{AddRenderCommand, sort_phase_system};
                use bevy::render::render_resource::SpecializedRenderPipelines;
                use bevy::render::{
                    ExtractSchedule, GpuResourceAppExt, Render, RenderStartup, RenderSystems,
                };
                use bevy::ui_render::{
                    RenderUiSystems, TransparentUi, extract_ui_camera_view, ui_pass,
                };

                render_app
                    .init_resource::<lr::ExtractedUiLayers>()
                    .init_resource::<lr::LayerTextureStore>()
                    .init_gpu_resource::<SpecializedRenderPipelines<lr::LayerCompositePipeline>>()
                    .init_gpu_resource::<lr::LayerCompositeMeta>()
                    .init_gpu_resource::<lr::transform3d::CompositeUniformsMeta>()
                    .init_gpu_resource::<SpecializedRenderPipelines<lr::LayerFilterPipeline>>()
                    .init_gpu_resource::<lr::LayerFilterMeta>()
                    .init_gpu_resource::<SpecializedRenderPipelines<lr::mips::LayerBlitPipeline>>()
                    .init_gpu_resource::<lr::mips::LayerMipMeta>()
                    .init_gpu_resource::<SpecializedRenderPipelines<lr::backdrop::BackdropBlitPipeline>>()
                    .init_gpu_resource::<lr::backdrop::BackdropMeta>()
                    .init_gpu_resource::<lr::morph::MorphMeta>()
                    .add_render_command::<TransparentUi, lr::DrawLayerComposite>()
                    .add_systems(
                        RenderStartup,
                        (
                            lr::init_layer_composite_pipeline,
                            lr::init_layer_filter_pipeline,
                            lr::mips::init_layer_blit_pipeline,
                            lr::backdrop::init_backdrop_blit_pipeline,
                        ),
                    )
                    .init_resource::<lr::clip::SwappedClips>()
                    .init_resource::<lr::cached::HiddenMembers>()
                    // `precompile_filters`: the shader list crosses in extract,
                    // the pipelines are queued per newly seen camera format
                    // before any prepare that would specialize them lazily.
                    .init_resource::<lr::warm::WarmShaders>()
                    .add_systems(ExtractSchedule, lr::warm::extract_warm_shaders)
                    .add_systems(
                        Render,
                        lr::warm::warm_layer_pipelines.in_set(RenderSystems::PrepareResources),
                    )
                    .configure_sets(
                        ExtractSchedule,
                        (
                            RenderUiSystems::ExtractBoxShadows,
                            RenderUiSystems::ExtractBackgrounds,
                            RenderUiSystems::ExtractImages,
                            RenderUiSystems::ExtractTextureSlice,
                            RenderUiSystems::ExtractBorders,
                            RenderUiSystems::ExtractViewportNodes,
                            RenderUiSystems::ExtractTextBackgrounds,
                            RenderUiSystems::ExtractTextShadows,
                            RenderUiSystems::ExtractText,
                            RenderUiSystems::ExtractCursor,
                            RenderUiSystems::ExtractDebug,
                            RenderUiSystems::ExtractGradient,
                        )
                            .in_set(lr::ExtractUiItems),
                    )
                    .add_systems(
                        ExtractSchedule,
                        (
                            lr::extract_ui_layers.after(extract_ui_camera_view),
                            // The extract-window clip swap: members'
                            // CalculatedClip carries INTERIOR clips for
                            // exactly the span of the stock UI extraction
                            // sets (the main world is exclusively borrowed
                            // here, so nothing main-world can observe it).
                            // Bracket every RenderUiSystems set (camera views
                            // + the `ExtractUiItems` umbrella).
                            lr::clip::swap_interior_clips_in
                                .before(RenderUiSystems::ExtractCameraViews)
                                .before(lr::ExtractUiItems),
                            lr::clip::swap_interior_clips_out
                                .after(RenderUiSystems::ExtractCameraViews)
                                .after(lr::ExtractUiItems),
                            // The cached-layer extraction skip: members of
                            // layers served from cache are HIDDEN for the
                            // span of the stock item extractors (same
                            // exclusive-borrow contract as the clip swap).
                            // Needs the final `needs_capture`, so it follows
                            // `extract_ui_layers` (itself after the camera
                            // view set) and precedes every item set.
                            lr::cached::hide_cached_layer_members
                                .after(lr::extract_ui_layers)
                                .before(lr::ExtractUiItems),
                            // Restore after every item set — the clip
                            // swap-out already sits after all of them.
                            lr::cached::restore_cached_layer_members
                                .after(lr::clip::swap_interior_clips_out),
                        ),
                    )
                    .add_systems(
                        Render,
                        (
                            lr::redistribute_ui_layers
                                .in_set(RenderSystems::PhaseSort)
                                .before(sort_phase_system::<TransparentUi>),
                            lr::prepare_layer_textures.in_set(RenderSystems::PrepareResources),
                            // Morph staging: the blend pass over the frozen
                            // snapshot + live capture. Before the filter
                            // staging — a regular chain on a morphing layer
                            // sources the blend and its validity prediction
                            // reads the morph slot's `GateState::output_valid`.
                            lr::morph::prepare_layer_morphs
                                .in_set(RenderSystems::PrepareBindGroups)
                                .after(lr::prepare_layer_textures)
                                .before(lr::prepare_layer_filters)
                                .before(lr::prepare_layer_composites),
                            // Filter staging: allocates/specializes everything
                            // a filter pass needs; `ui_layer_capture_pass`
                            // replays the staged runs after each layer's
                            // capture.
                            lr::prepare_layer_filters
                                .in_set(RenderSystems::PrepareBindGroups)
                                .after(lr::prepare_layer_textures)
                                .before(lr::prepare_layer_composites),
                            // Backdrop staging: snapshot blit + a second
                            // filter run per backdrop layer; the composite
                            // gate reads its `output_valid`.
                            lr::backdrop::prepare_layer_backdrops
                                .in_set(RenderSystems::PrepareBindGroups)
                                .after(lr::prepare_layer_textures)
                                .before(lr::prepare_layer_composites),
                            // Mip staging: after filters (`output_valid` /
                            // `output_index` decided — mips build on the
                            // filter output), before composites (its
                            // bind-group choice reads `mips_valid`).
                            lr::mips::prepare_layer_mips
                                .in_set(RenderSystems::PrepareBindGroups)
                                .after(lr::prepare_layer_filters)
                                .before(lr::prepare_layer_composites),
                            lr::prepare_layer_composites.in_set(RenderSystems::PrepareBindGroups),
                        ),
                    )
                    .add_systems(
                        Core2d,
                        lr::ui_layer_capture_pass
                            .after(Core2dSystems::PostProcess)
                            .before(ui_pass),
                    )
                    .add_systems(
                        Core3d,
                        lr::ui_layer_capture_pass
                            .after(Core3dSystems::PostProcess)
                            .before(ui_pass),
                    );
            }
        }

        // Channels: op batches, app messages, requests, and animation commands flow
        // JS -> Bevy (crossbeam, same on every target). The Bevy -> JS direction (a
        // single `Outbound` stream plus, on native, reload signals) is owned by the
        // target's host, which returns its sender below.
        // TODO(review): all of these are UNBOUNDED — there's no backpressure. A system that
        // `events.send`s every frame while the JS side consumes slowly (or not at all) grows
        // the outbound queue without bound. Consider bounded channels with an explicit
        // drop/coalesce policy before this is "production".
        let (ops_tx, ops_rx) = crossbeam_channel::unbounded::<Vec<Op>>();
        // Side channel of per-batch send stamps + devtools-origin flags (see
        // `host::FlushInfo`).
        let (flush_tx, flush_rx) = crossbeam_channel::unbounded();
        let (emit_tx, emit_rx) = crossbeam_channel::unbounded::<ReactMessage>();
        let (request_tx, request_rx) = crossbeam_channel::unbounded::<RawRequest>();
        let (anim_tx, anim_rx) = crossbeam_channel::unbounded::<AnimationCommand>();

        // Spawn/install the target's JS host: native runs an embedded V8 isolate on
        // a dedicated thread (fed from disk, with hot reload); web runs React in the
        // browser's own engine. The host owns the Bevy->JS transport and returns the
        // sender every outbound producer writes to. It starts before `setup` builds
        // the root, so the first ops simply queue until then.
        // The feature registry (`crate::ext`): in-crate features register
        // here; feature plugins register in their own `build` in any order.
        // The handoff slot is filled with the final registry at startup
        // (`finish`, and `setup` as the headless fallback).
        app.init_resource::<crate::ext::ExtRegistry>();
        app.init_resource::<crate::ext::VirtualPointers>();
        // The core's style properties and writers, and its elements, register
        // through the same calls a feature crate uses.
        crate::style::add_core_styles(app);
        app.add_react_elements(crate::elements::CORE_ELEMENTS);
        let ext_slot = crate::ext::ExtRegistrySlot::default();
        app.insert_resource(ext_slot.clone());
        let outbound_tx = host::spawn(
            app,
            HostConfig {
                ext: ext_slot,
                bundle: self.bundle.clone(),
                hot_reload: self.hot_reload,
            },
            HostSenders {
                ops: ops_tx,
                flush: flush_tx,
                emit: emit_tx,
                request: request_tx,
                anim: anim_tx,
            },
        );
        app.insert_resource(crate::reconcile::FlushInfos(flush_rx));

        app.insert_resource(BridgeChannels {
            ops_rx: Some(ops_rx),
            outbound_tx: outbound_tx.clone(),
        })
        // A standalone outbound handle for the request dispatcher and the
        // `ReactEvents` param, available before `setup` builds `JsBridge`.
        .insert_resource(OutboundResource(outbound_tx))
        .insert_resource(EmitReceiver(emit_rx))
        .insert_resource(RequestReceiver(request_rx))
        .insert_resource(ReactUiConfig {
            default_font: self.default_font.clone(),
            named_fonts: self.named_fonts.clone(),
            #[cfg(feature = "custom_cursor")]
            custom_cursors: self.custom_cursors.clone(),
            precompile_filters: self.precompile_filters.clone(),
        })
        .init_resource::<crate::filters::WarmShaderList>()
        .add_systems(Startup, crate::filters::build_warm_shader_list)
        .init_resource::<ReactRegistry>()
        .init_resource::<ReactRequestRegistry>()
        .init_resource::<ReactEventRegistry>()
        .init_resource::<PointerCapture>()
        .init_resource::<crate::reconcile::ActiveDrag>()
        .init_resource::<crate::touch_scroll::TouchScrollState>()
        .init_resource::<OpApplyStats>()
        // Unconditional so wasm compiles; it just stays `None` there.
        .init_resource::<crate::reconcile::FrameStamp>()
        .init_resource::<crate::ui_map::AtlasLayoutCache>()
        .init_resource::<crate::scrollbar::ScrollbarTracks>()
        .init_resource::<Fonts>()
        .init_resource::<crate::cursor::CustomCursors>()
        // SVG documents (`<image src="x.svg">`): parsed once per file into a
        // resolution-independent asset, rasterized per node at laid-out size.
        .init_asset::<crate::svg::SvgDocument>()
        .register_asset_loader(crate::svg::SvgAssetLoader)
        // The offscreen render-target ("portal") registry, created before the
        // first portal can mount.
        .init_resource::<crate::render_target::RenderTargets>()
        .add_systems(Startup, crate::layer::pick3d::init_transform3d_pointer)
        .add_systems(Startup, setup)
        .add_systems(
            PreUpdate,
            (dispatch_react_messages, dispatch_react_requests),
        )
        // Remap the window cursor into 3D-transformed layers (inverse
        // homography → virtual pointer) before input processing, like the
        // surface driver. Reads last frame's matrices — the composite quad
        // the user sees is last frame's too, so picking matches the visual.
        .add_systems(
            PreUpdate,
            crate::layer::pick3d::drive_transform3d_pointer
                .before(bevy::picking::PickingSystems::ProcessInput),
        )
        // Re-filter picking hits against the render-grade inherited clip
        // (`CalculatedClip`) — bevy_ui 0.19's own clip check misses hits on
        // scrolled/clipped-away nodes whose direct parent doesn't clip (see
        // `pick_clip` module docs). Between the backends and the hover-map
        // update, so every downstream consumer sees only visible hits.
        .add_systems(
            PreUpdate,
            crate::pick_clip::filter_clipped_pointer_hits
                .after(bevy::picking::PickingSystems::Backend)
                .before(bevy::picking::PickingSystems::Hover),
        )
        // Scope hits around the transformed-layer remap (stale layout rects
        // for the mouse, layer-membership for the virtual pointer) — after
        // the clip filter for a deterministic filter order.
        .add_systems(
            PreUpdate,
            crate::layer::pick3d::suppress_transformed_layer_hits
                .after(bevy::picking::PickingSystems::Backend)
                .after(crate::pick_clip::filter_clipped_pointer_hits)
                .before(bevy::picking::PickingSystems::Hover),
        )
        // Refine hits on JSX `<svg>` nodes into hits on the topmost painted
        // shape under the cursor (svg::pick module docs). Last of the three
        // hit rewriters — after the transform3d suppression: suppression must
        // settle first so a refinement only ever amplifies a SURVIVING svg-node
        // hit (refining a hit that suppression then strips would leave a
        // shape hit with no live node under it).
        // The `PickRefineSet` slot is the contract's name for this position.
        .configure_sets(
            PreUpdate,
            crate::ext::PickRefineSet
                .after(bevy::picking::PickingSystems::Backend)
                .after(crate::pick_clip::filter_clipped_pointer_hits)
                .after(crate::layer::pick3d::suppress_transformed_layer_hits)
                .before(bevy::picking::PickingSystems::Hover),
        )
        .add_systems(
            Update,
            (
                apply_js_ops.in_set(ReactApplySet),
                collect_ui_events,
                // Forward window-global keystrokes to React as built-in named
                // events (`onKeyDown`/`onKeyUp`). Node-independent: reads Bevy's
                // `KeyboardInput` messages directly, no reconciler state needed.
                crate::keyboard::collect_keyboard_events,
                // Emit `pointerEnter`/`pointerLeave` from `Interaction` transitions
                // (same signal as hover styling), for nodes with those handlers.
                collect_hover_events,
                collect_pointer_events.in_set(PointerCaptureSet),
                // Wheel-scroll any `overflow: scroll` node under the cursor, and
                // deliver raw wheel deltas to any `onWheel` node. Both in the same
                // set, after `collect_pointer_events`, so their `PointerCapture::over_ui`
                // claim survives (that system *assigns* `over_ui`) and world systems
                // (ordered `.after(PointerCaptureSet)`) see it. (A sub-tuple: the outer
                // tuple is at Bevy's arity limit.)
                (
                    crate::scroll::apply_scroll
                        .in_set(PointerCaptureSet)
                        .after(collect_pointer_events),
                    // Touch-drag scrolling; after `collect_pointer_events` both
                    // for the capture-claim ordering and as a data edge: it
                    // reads the just-assigned `ActiveDrag` so the one touch
                    // bound to a handler-node drag is claimed as *contested*
                    // (arbitrated at the slop by pan axis; a steal is read
                    // back by `collect_pointer_events` next frame).
                    crate::touch_scroll::apply_touch_scroll
                        .in_set(PointerCaptureSet)
                        .after(collect_pointer_events),
                    crate::scroll::collect_wheel_events
                        .in_set(PointerCaptureSet)
                        .after(collect_pointer_events),
                    // Hovering a scrollbar part claims the hover channel (the
                    // widget has `Hovered`, not `Interaction`, so a press on it
                    // would otherwise start a world grab); a thumb drag claims
                    // the pointer outright and snaps any eased scroll state. In the set,
                    // after `collect_pointer_events` so its `over_ui` claim survives.
                    crate::scrollbar::bridge_scrollbar_capture
                        .in_set(PointerCaptureSet)
                        .after(collect_pointer_events),
                ),
                // Ease `ScrollPosition` toward the target the controlled write
                // (`apply_js_ops`) and the wheel (`PointerCaptureSet`) set this frame.
                // Runs after both so it eases toward the freshest target.
                crate::transition::drive_scroll_transition
                    .after(apply_js_ops)
                    .after(PointerCaptureSet),
                // Report scroll-offset changes (wheel, controlled write, or an eased
                // frame) to JS for any node with an `onScroll` handler. After the ease
                // so it sees the moved offset; after the op drain so a controlled write
                // is already seeded into the dedup map (no echo).
                collect_scroll_events
                    .after(crate::transition::drive_scroll_transition)
                    .after(PointerCaptureSet)
                    .after(apply_js_ops),
                // After the op drain so this frame's `StyleVariants` writes are
                // visible; the ordering forces a command sync point first.
                apply_interaction_styles.after(apply_js_ops),
                // Ease `transform`/`opacity`/`backgroundColor` toward the target the
                // style appliers just wrote. After `apply_interaction_styles` (and
                // thus the op drain) so the eased value lands last and a coincident
                // re-render's snap never wins.
                crate::transition::drive_transitions.after(apply_interaction_styles),
                // The cursor driver reads last frame's `ComputedNode` after
                // the op drain (freshly-stamped `NodeCursor`s visible); this
                // sub-tuple keeps the outer tuple under Bevy's arity limit.
                (
                    // Repaint svg surfaces — svg-mode `<image>`
                    // documents and JSX `<svg>` shape trees: reads last
                    // frame's `ComputedNode` after the op drain (fresh
                    // `SvgSurface`s AND the flushed queued `SvgShape`/child
                    // writes visible — the JSX dirt derivation needs them
                    // same-frame), rasters at laid-out size. Also after the
                    // animation appliers: their shape-attr stage writes driven
                    // `SvgShape` seeds, and the raster must read them the same
                    // frame or a driven animation paints one frame late
                    // (pinned by `driven_shape_attr_repaints_same_frame`).
                    // Also after `drive_transitions`: the shape
                    // transition channel writes eased `SvgShape` attrs and the
                    // raster must paint them the SAME frame (pinned by
                    // `eased_shape_attr_repaints_same_frame`).
                    crate::svg::update_svg_surfaces.in_set(crate::ext::ElementRasterSet),
                    crate::cursor::drive_cursor_icon.after(apply_js_ops),
                    // Spawn/teardown the Bevy scrollbar widget over each
                    // `overflow: scroll` container that declared a `scrollbar`
                    // style, then place its track over the container's edge. Both
                    // after the op drain (fresh `ScrollbarConfig`s visible); place
                    // after sync so the tracks exist. Bevy's `ScrollbarPlugin`
                    // (in `DefaultPlugins`) drives the thumb in `PostUpdate`.
                    crate::scrollbar::sync_scrollbars.after(apply_js_ops),
                    crate::scrollbar::position_scrollbars
                        .after(apply_js_ops)
                        .after(crate::scrollbar::sync_scrollbars),
                    // Paint each bar in its hover/pressed/base state (reads Bevy's
                    // `Hovered` + `ScrollbarDragState`). After sync so the entities exist.
                    crate::scrollbar::style_scrollbar_states
                        .after(crate::scrollbar::sync_scrollbars),
                ),
                // Bind `<portal>` nodes to their render-target textures after the
                // op drain (so a freshly-spawned portal binds the same frame), then
                // drive `Auto` resolution (here, before `camera_system` reads the
                // target size). Camera activity is decided in `PostUpdate` below.
                crate::render_target::bind_target_views.after(apply_js_ops),
                crate::render_target::drive_render_targets
                    .after(crate::render_target::bind_target_views),
                // Virtual-pointer interaction (a `<surface>`'s in-world pointer):
                // turn its picking events on the offscreen subtree into
                // `onClick`/`onPointer*` + hover/press styling. The picking
                // events are produced in `PreUpdate`, so these read this
                // frame's events.
                collect_virtual_clicks,
                collect_virtual_pointer_events,
                collect_virtual_hover_events,
                apply_virtual_interaction_styles,
            ),
        );

        // The built-in bindings: the built-in messages', requests', and
        // events' payload types, and the `filter` registry's built-ins (blur,
        // the color-matrix ops, …) — `AssetServer`-free, shaders load lazily
        // inside each entry's resolve.
        register_builtin_bindings(app);

        // The built-in `"resize"` event + `bevy.window.size()` request (see
        // `crate::window`). A separate `add_systems` call — the Update tuple
        // above is at Bevy's arity cap. `.after(apply_js_ops)` so the initial
        // size goes out the same frame the first batch applies.
        app.add_systems(
            Update,
            crate::window::send_resize_events.after(apply_js_ops),
        );

        // The built-in gamepad events (see `crate::gamepad`). A separate
        // `add_systems` call — the Update tuple above is at the arity cap.
        // `.after(apply_js_ops)` so the late-join announce goes out the same
        // frame the first batch applies. The `add_message` calls are idempotent
        // (`InputPlugin` registers both in real apps) and keep the collector's
        // and observers' params valid in headless `MinimalPlugins` apps.
        app.init_resource::<crate::gamepad::GamepadRegistry>();
        app.add_message::<bevy::input::gamepad::GamepadEvent>();
        app.add_message::<bevy::input::gamepad::GamepadConnectionEvent>();
        app.add_message::<bevy::input::gamepad::GamepadRumbleRequest>();
        app.add_systems(
            Update,
            crate::gamepad::collect_gamepad_events.after(apply_js_ops),
        );

        // `backgroundImage` runtime systems (see `crate::background_image`).
        // A separate `add_systems` call — the Update tuple above is at the
        // arity cap. Ordered after the op drain AND the interaction restyle
        // (both stamp `RBackgroundTexture` / insert `ImageNode`s; the explicit
        // edges also force the command syncs), so a freshly-styled node binds
        // and gets its DPI-corrected tile scale the same frame.
        app.add_systems(
            Update,
            (
                crate::background_image::bind_background_textures
                    .after(apply_js_ops)
                    .after(apply_interaction_styles),
                crate::background_image::sync_background_tile_scale
                    .after(apply_js_ops)
                    .after(apply_interaction_styles),
            ),
        );

        // `imageRendering` (see `crate::image_rendering`): binds each explicit
        // mode to the asset that renders it (variant repoint). After every
        // `ImageNode` handle writer — the op drain, the interaction restyle,
        // and the background-texture rebind — so a freshly-styled node binds
        // the same frame.
        app.insert_resource(crate::image_rendering::ImageVariants::from_app(app));
        app.add_systems(
            Update,
            crate::image_rendering::bind_image_rendering
                .after(apply_js_ops)
                .after(apply_interaction_styles)
                .after(crate::background_image::bind_background_textures),
        );

        // Layer promotion (see `crate::layer`). Main-world state registers
        // unconditionally so headless wiring tests build; the render half is
        // gated above with the rest of the render-only setup. A separate
        // `add_systems` call — the Update tuple above is at the arity cap.
        // Ordering: after the op drain (fresh props/dirty marks; the explicit
        // constraint also forces a command sync so markers are visible), and
        // before every later alpha writer this frame — the interaction
        // restyle, transitions (ordered after it), and the animation appliers
        // — so they all see the final promotion state (no cross-stage
        // ping-pong).
        app.init_resource::<crate::layer::LayerMembership>();
        app.init_resource::<crate::layer::LayersRegistry>();
        app.init_resource::<crate::layer::LayerContentDirt>();
        app.init_resource::<crate::layer::LayerRepaintState>();
        app.init_resource::<crate::layer::clip::LayerClips>();
        app.add_systems(
            Update,
            (
                crate::layer::evaluate_layer_promotions
                    .after(apply_js_ops)
                    .before(apply_interaction_styles)
                    .before(AnimationSet::Apply),
                // Async `<image>` texture arrivals have no other write site the
                // layer cache could tap.
                crate::layer::watch_layer_image_assets,
                // Override `ui_focus_system`'s geometric (stale-rect) verdict
                // for members of visually-transformed layers with the virtual
                // pointer's, before styling/enter-leave/drag-position readers.
                crate::layer::pick3d::correct_transformed_interactions
                    .before(apply_interaction_styles)
                    .before(collect_hover_events)
                    .before(crate::reconcile::collect_pointer_events),
            ),
        );
        // Synthesize `Interaction`/`RelativeCursorPosition`/user-space cursor
        // for handler-bearing SVG shape children from the hover map + the
        // refined per-shape hits (`svg::interact` module docs) — shapes are
        // Node-less, so `ui_focus_system` never sees them. Same slot as
        // `correct_transformed_interactions` above: before styling,
        // enter/leave, and drag-position readers so they all see the
        // synthesized state — and AFTER `correct_transformed_interactions`
        // itself: for a handler-bearing shape inside a visually-transformed
        // layer both systems write the same `RelativeCursorPosition` (pick3d
        // writes `normalized: None` — shapes have no `ComputedNode`), and
        // without an explicit order the winner is nondeterministic and the
        // two writes ping-pong `Changed` every frame. The svg synthesis must
        // land last: it holds the refined user-space hit. A separate
        // `add_systems` call — the Update tuple above is at Bevy's arity cap.
        // `InteractionSyncSet` is the contract's name for this slot.
        app.configure_sets(
            Update,
            crate::ext::InteractionSyncSet
                .after(crate::layer::pick3d::correct_transformed_interactions)
                .before(apply_interaction_styles)
                .before(collect_hover_events)
                .before(crate::reconcile::collect_pointer_events),
        );

        // `ElementRasterSet`: an element-owned texture repaints from this
        // frame's final state — after the op drain (fresh surfaces and the
        // flushed queued writes visible), the animation appliers (driven
        // seeds), and the transition drive (eased values), so nothing paints
        // a frame late (pinned by `driven_shape_attr_repaints_same_frame` /
        // `eased_shape_attr_repaints_same_frame`).
        app.configure_sets(
            Update,
            crate::ext::ElementRasterSet
                .after(apply_js_ops)
                .after(AnimationSet::Apply)
                .after(crate::transition::drive_transitions),
        );
        // `ElementOverrideSet`: an element system that overrides this frame's
        // driven values — the `<anchor>`'s projected translation writes
        // `UiTransform` after the animation applier and the transition driver
        // wrote it, so the projection deterministically wins (without the
        // edges the winner would be nondeterministic — a ping-pong).
        app.configure_sets(
            Update,
            crate::ext::ElementOverrideSet
                .after(apply_js_ops)
                .after(AnimationSet::Apply)
                .after(crate::transition::drive_transitions),
        );
        // Resolve each promoted root's wire `filter`, `backdropFilter`, and
        // `morphFilter` chains into packed render passes — the three
        // instances of `crate::filters::resolve_chains`. After the
        // interaction restyle — the last input writer this frame (and,
        // transitively, after the promotion evaluator, so
        // `Added<PromotedLayer>` is visible) — and before the
        // transition/animation appliers so filter-param writes land on an
        // already-resolved chain (the morph channel additionally reads its
        // resolved chain for retarget gating). Its own `add_systems` call —
        // the Update tuple above is at the arity cap.
        app.add_systems(
            Update,
            (
                crate::filters::resolve_chains::<
                    crate::filters::FilterInput,
                    crate::filters::ResolvedFilterChain,
                >,
                crate::filters::resolve_chains::<
                    crate::filters::BackdropInput,
                    crate::filters::ResolvedBackdropChain,
                >,
                crate::filters::resolve_chains::<
                    crate::filters::MorphInput,
                    crate::filters::ResolvedMorphChain,
                >,
            )
                .after(apply_interaction_styles)
                .before(crate::transition::drive_transitions)
                .before(AnimationSet::Apply),
        );
        // After bevy_ui layout so capture rects/membership are this frame's
        // geometry (extraction reads them the same frame, post-PostUpdate).
        app.add_systems(
            PostUpdate,
            (
                // `transition: { layout }`: measure this frame's pristine
                // rects, ease, and compose the FLIP delta into the animating
                // subtrees' `UiGlobalTransform`s — after layout wrote them,
                // before anything reads them (PostLayout clipping, the layer
                // geometry sync below, extraction, next frame's picking).
                crate::transition::layout::drive_layout_transitions
                    .after(bevy::ui::UiSystems::Layout)
                    .before(bevy::ui::UiSystems::PostLayout)
                    .before(crate::layer::sync_layer_geometry),
                crate::layer::sync_layer_geometry.after(bevy::ui::UiSystems::Layout),
                // Membership + geometry hashes are this frame's, and bevy_ui's
                // text systems (PostLayout) have re-shaped — turn the frame's
                // dirt into per-layer repaint decisions for extraction.
                crate::layer::resolve_layer_repaints
                    .after(crate::layer::sync_layer_geometry)
                    .after(bevy::ui::UiSystems::PostLayout),
                // Derives each transformed layer's composite matrix from this
                // frame's layout; pushes composite-only dirt the resolver
                // drains, so it slots between geometry sync and the resolver.
                crate::layer::transform3d::sync_transform3d_matrices
                    .after(crate::layer::sync_layer_geometry)
                    .before(crate::layer::resolve_layer_repaints),
                // Interior/quad clip maps: needs this frame's membership
                // (sync_layer_geometry) and bevy_ui's final CalculatedClip
                // (PostLayout). Deliberately NOT feeding
                // resolve_layer_repaints — clip changes never dirty a
                // capture (scrolling must stay a cache hit).
                crate::layer::clip::sync_layer_clips
                    .after(crate::layer::sync_layer_geometry)
                    .after(bevy::ui::UiSystems::PostLayout),
                // Re-clamps deferred controlled-scroll requests (a pin to the
                // bottom in the same commit that grew the content) against
                // fresh geometry.
                crate::scroll::settle_controlled_scroll.after(bevy::ui::UiSystems::Layout),
            ),
        );
        add_camera_gate_systems(app);
        // Re-stamp the svg intrinsic measure after `bevy_ui`'s
        // `update_image_content_size_system` (`UiSystems::Content`), which
        // clears the `ContentSize` of any non-`Auto` `ImageNode` that changed
        // this frame — every svg-mode prop rebuild re-inserts the `ImageNode`,
        // so without this the measure vanishes on each delta. Before `Layout`
        // so the re-stamp feeds the same frame's layout pass.
        // `MeasureStampSet` is the contract's name for this slot.
        app.configure_sets(
            PostUpdate,
            crate::ext::MeasureStampSet
                .after(bevy::ui::widget::update_image_content_size_system)
                .before(bevy::ui::UiSystems::Layout),
        );
        app.add_systems(
            PostUpdate,
            crate::svg::stamp_svg_measures.in_set(crate::ext::MeasureStampSet),
        );
        // The built-in requests and rumble messages (their payload types are
        // registered by `register_builtin_bindings`). `bevy.gamepad.getAll()`
        // is the pull companion to `gamepadConnected` for late-mounted
        // components.
        app.add_observer(crate::window::handle_window_size_request);
        app.add_observer(crate::gamepad::on_rumble);
        app.add_observer(crate::gamepad::on_stop_rumble);
        app.add_observer(crate::gamepad::handle_gamepad_get_all);

        // Frame-start stamp for the devtools frame-wait / pre-apply split
        // (native only — no usable `Instant::now` on wasm). `First`: before
        // any work the pre-apply leg should attribute.
        #[cfg(not(target_arch = "wasm32"))]
        app.add_systems(bevy::app::First, crate::reconcile::mark_frame_start);

        // `editableText` edits arrive as Bevy's `TextEditChange` trigger; an observer
        // turns real changes into its `change` event and selection moves into
        // `select`. Two more observers bridge focus gain/loss to `focus`/`blur`.
        app.add_observer(on_text_edit_change);
        app.add_observer(on_focus_gained);
        app.add_observer(on_focus_lost);

        // Controlled-selection writes and the a11y value sync run after Bevy's
        // text-edit pass (`EditableTextSystems`) so they see this frame's applied
        // edits and resolve byte offsets against the current text.
        app.add_systems(
            PostUpdate,
            (apply_pending_selections, sync_editable_a11y).after(bevy::text::EditableTextSystems),
        );

        // The animations engine, its `Apply` set ordered after `apply_js_ops`
        // so per-frame animation writes win over this frame's static style.
        app.add_plugins(ReactUiAnimationsPlugin::new(anim_rx))
            .configure_sets(Update, AnimationSet::Apply.after(apply_js_ops))
            // Completion callbacks: settlements the engine reports (once per
            // token-tagged driver, not per frame) go out to JS.
            .add_systems(Update, forward_animation_settled.after(AnimationSet::Tick));

        // The devtools inspector rides along by default (see `Self::devtools`).
        // Registration is the only gate needed here: the plugin itself registers
        // nothing in `--release` builds.
        #[cfg(feature = "devtools")]
        if self.devtools.enabled {
            app.add_plugins(crate::devtools::DevtoolsPlugin::new(self.devtools.clone()));
        }
    }
}

/// Forward the animation engine's [`AnimationSettled`] messages to JS as
/// [`Outbound::AnimationFinished`], resolving each to its completion callback.
fn forward_animation_settled(
    mut settled: MessageReader<AnimationSettled>,
    outbound: Res<OutboundResource>,
) {
    for s in settled.read() {
        let _ = outbound.0.send(Outbound::AnimationFinished {
            id: s.id,
            token: s.token,
            finished: s.finished,
        });
    }
}

/// Marker for the UI root entity (reconciler node id 0 / `ROOT_ID`).
/// `pub(crate)`: devtools' reserve-space mode insets this root's margins to
/// push the app UI aside while the panel is docked.
#[derive(Component)]
pub(crate) struct UiRoot;

/// Plugin configuration read by the startup systems (`setup` and
/// `filters::build_warm_shader_list`).
#[derive(Resource)]
pub(crate) struct ReactUiConfig {
    default_font: Option<PathBuf>,
    named_fonts: Vec<(String, PathBuf)>,
    #[cfg(feature = "custom_cursor")]
    custom_cursors: Vec<(String, PathBuf, (u16, u16))>,
    pub(crate) precompile_filters: PrecompileFilters,
}

/// Fonts loaded from the plugin config, resolved to handles at startup. The
/// default backs every `<text>` run; named entries are selected per element via
/// the `fontFamily` style prop. Empty (unconfigured) → Bevy's built-in font.
#[derive(Resource, Default)]
pub struct Fonts {
    pub default: Option<Handle<Font>>,
    pub named: std::collections::HashMap<String, Handle<Font>>,
}

/// Carries the Bevy-side channel ends from `build` into `setup`.
#[derive(Resource)]
struct BridgeChannels {
    ops_rx: Option<OpReceiver>,
    outbound_tx: OutboundSender,
}

/// Receives app messages emitted by the React app (`emit(name, value)`).
#[derive(Resource)]
struct EmitReceiver(crossbeam_channel::Receiver<ReactMessage>);

/// The single consumption point for React-emitted messages. Drains the channel
/// each frame and routes every message to its registered typed payload via
/// [`ReactRegistry`], triggering it for observers. Runs in `PreUpdate` so the
/// triggers land before consumer `Update` systems run the same frame.
fn dispatch_react_messages(
    rx: Res<EmitReceiver>,
    registry: Res<ReactRegistry>,
    mut commands: Commands,
) {
    while let Ok(msg) = rx.0.try_recv() {
        registry.dispatch(msg, &mut commands);
    }
}

fn setup(
    mut commands: Commands,
    mut channels: ResMut<BridgeChannels>,
    config: Res<ReactUiConfig>,
    assets: Res<AssetServer>,
    ext_registry: Res<crate::ext::ExtRegistry>,
    ext_slot: Res<crate::ext::ExtRegistrySlot>,
) {
    // Hand the final feature registry to the decoding host (a no-op when
    // `finish` already did — `App::update`-driven harnesses never `finish`).
    ext_registry.styles().validate();
    ext_slot.fill(ext_registry.clone());
    // Load configured fonts into the `Fonts` resource before the first
    // `apply_js_ops` (Update) creates any text.
    commands.insert_resource(Fonts {
        default: config.default_font.as_ref().map(|p| assets.load(p.clone())),
        named: config
            .named_fonts
            .iter()
            .map(|(name, path)| (name.clone(), assets.load(path.clone())))
            .collect(),
    });
    // Likewise load configured custom image cursors into the registry `drive_cursor_icon`
    // resolves a `cursor` name against.
    #[cfg(feature = "custom_cursor")]
    commands.insert_resource(crate::cursor::CustomCursors(
        config
            .custom_cursors
            .iter()
            .map(|(name, path, hotspot)| {
                (
                    name.clone(),
                    CustomCursorImage {
                        handle: assets.load(path.clone()),
                        hotspot: *hotspot,
                        ..default()
                    },
                )
            })
            .collect(),
    ));

    // The root container: a full-window flex column the reconciler appends
    // top-level children into (it is reconciler node id 0). Children stack from
    // the top, horizontally centered.
    let root = commands
        .spawn((
            Node {
                width: Val::Percent(100.0),
                height: Val::Percent(100.0),
                flex_direction: FlexDirection::Column,
                justify_content: JustifyContent::FlexStart,
                align_items: AlignItems::Center,
                row_gap: Val::Px(16.0),
                ..default()
            },
            // Layout scaffolding only: without an explicit `Pickable` the UI
            // picking backend treats the full-window root as a blocking hit,
            // which would make hover queries (`HoverMap`) report "over UI"
            // everywhere. Element nodes opt in per-`FocusPolicy` instead.
            bevy::picking::Pickable {
                should_block_lower: false,
                ..default()
            },
            UiRoot,
        ))
        .id();

    let ops_rx = channels.ops_rx.take().expect("setup runs once");
    let mut bridge = JsBridge::new(ops_rx, channels.outbound_tx.clone(), root);
    bridge.ext = std::sync::Arc::new(ext_registry.clone());
    commands.insert_resource(bridge);
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `is_captured` must cover every capture channel: a UI drag, hovering
    /// interactive UI, and a UI-consumed wheel each count as "the UI owns the
    /// pointer" for consumers that don't need finer grain.
    #[test]
    fn is_captured_covers_all_channels() {
        assert!(!PointerCapture::default().is_captured());
        assert!(
            PointerCapture {
                dragging: true,
                ..default()
            }
            .is_captured()
        );
        assert!(
            PointerCapture {
                over_ui: true,
                ..default()
            }
            .is_captured()
        );
        assert!(
            PointerCapture {
                wheel_captured: true,
                ..default()
            }
            .is_captured()
        );
    }
}