From 35a5cd43114a3349c3fcafdebaadbbb1843aed81 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 28 Nov 2026 13:02:04 +0100 Subject: [PATCH] gpui: dispatch onLayout for any node that sets it --- .../app/gpui/appearance-regression.fixture.js | 149 ++++++--- packages/app/gpui/native.test.ts | 60 ++++ vendor/react-native-gpui/UPSTREAM | 15 + .../core/ReactGpui/rn-gpui-sys/build.rs | 4 + .../rn-gpui-sys/cpp/LoomViewProps.cpp | 2 + .../rn-gpui-sys/cpp/MountBatchBuilder.cpp | 1 + .../core/ReactGpui/rn-gpui-sys/src/lib.rs | 6 + .../core/ReactGpui/rn-gpui/src/bootstrap.rs | 14 +- .../core/ReactGpui/rn-gpui/src/host.rs | 31 +- .../core/ReactGpui/rn-gpui/src/store.rs | 282 ++++++++++++++++-- .../core/ReactGpui/rn-gpui/src/view_props.rs | 2 + .../NativeComponent/BaseViewConfig.desktop.ts | 4 +- 12 files changed, 492 insertions(+), 78 deletions(-) diff --git a/packages/app/gpui/appearance-regression.fixture.js b/packages/app/gpui/appearance-regression.fixture.js index 39794ddcc7..0c05ecd6db 100644 --- a/packages/app/gpui/appearance-regression.fixture.js +++ b/packages/app/gpui/appearance-regression.fixture.js @@ -1,52 +1,119 @@ /* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- Minimal native regression scene. */ -import React, { useState } from "react"; -import { AppRegistry, Pressable, Text, View } from "react-native"; +import React, { useCallback, useState } from "react"; +import { AppRegistry, Image, Pressable, ScrollView, Text, TextInput, View } from "react-native"; function AppearanceRegression() { const [buttonHovered, setHovered] = useState(false); const [entered, setEntered] = useState(false); + const [expanded, setExpanded] = useState(false); + const [layouts, setLayouts] = useState({}); + + const record = useCallback((key, event) => { + const layout = event?.nativeEvent?.layout; + const layoutKeys = layout ? Object.keys(layout).sort() : []; + setLayouts((prev) => ({ + ...prev, + [key]: { + count: (prev[key]?.count ?? 0) + 1, + keys: layoutKeys, + layout, + }, + })); + }, []); + + const onViewLayout = useCallback((e) => record("view", e), [record]); + const onTextLayout = useCallback((e) => record("text", e), [record]); + const onInputLayout = useCallback((e) => record("textInput", e), [record]); + const onImageLayout = useCallback((e) => record("image", e), [record]); + const onScrollLayout = useCallback((e) => record("scrollView", e), [record]); + return ( - - - setHovered(true)} - onHoverOut={() => setHovered(false)} - style={{ width: 200, height: 60, backgroundColor: buttonHovered ? "#00ff00" : "#0000ff" }} - > - {buttonHovered ? "hover active" : "hover inactive"} - - ({ - width: 200, - height: 60, - backgroundColor: hovered ? "#00ff00" : "#0000ff", - })} - > - {({ hovered }) => {hovered ? "render hovered" : "render idle"}} - - setEntered(true)} - onPointerLeave={() => setEntered(false)} - style={{ width: 200, height: 60, backgroundColor: entered ? "#00ff00" : "#0000ff" }} - > - - {entered ? "row active" : "row inactive"} + + + + setHovered(true)} + onHoverOut={() => setHovered(false)} + style={{ width: 200, height: 60, backgroundColor: buttonHovered ? "#00ff00" : "#0000ff" }} + > + {buttonHovered ? "hover active" : "hover inactive"} + ({ + width: 200, + height: 60, + backgroundColor: hovered ? "#00ff00" : "#0000ff", + })} + > + {({ hovered }) => {hovered ? "render hovered" : "render idle"}} + + setEntered(true)} + onPointerLeave={() => setEntered(false)} + style={{ width: 200, height: 60, backgroundColor: entered ? "#00ff00" : "#0000ff" }} + > + + {entered ? "row active" : "row inactive"} + + + + + + + setExpanded((value) => !value)} + style={{ width: 160, height: 32, backgroundColor: "#dddddd", justifyContent: "center" }} + > + {expanded ? "Shrink" : "Expand"} + + + + {expanded ? "Measure a much longer text label" : "Short label"} + + + + + + + {JSON.stringify(layouts)} - ); } diff --git a/packages/app/gpui/native.test.ts b/packages/app/gpui/native.test.ts index 9f2e8c233a..9d2f52a441 100644 --- a/packages/app/gpui/native.test.ts +++ b/packages/app/gpui/native.test.ts @@ -15,6 +15,7 @@ interface Node { component: string; testID: string; text: string; + frame?: [number, number, number, number]; children?: Node[]; } const pending = new Map(); @@ -208,3 +209,62 @@ test.skipIf(!endpoint || !appearanceFixture)( await expectBackground(row, 0xff0000ff); }, ); + +test.skipIf(!endpoint || !appearanceFixture)( + "onLayout fires with React Native layout shape for View, Text, TextInput, Image, and ScrollView", + async () => { + interface LayoutEntry { + count: number; + keys: string[]; + layout: { x: number; y: number; width: number; height: number }; + } + const readLayouts = async () => { + const node = await nodeWithId("layout-results"); + return JSON.parse(node.text) as Record; + }; + const targets = [ + ["view", "layout-view"], + ["text", "layout-text"], + ["textInput", "layout-text-input"], + ["image", "layout-image"], + ["scrollView", "layout-scroll"], + ] as const; + + await expect + .poll(async () => Object.keys(await readLayouts()).sort()) + .toEqual(targets.map(([key]) => key).sort()); + + const initial = await readLayouts(); + const treeNodes = await nodes(); + for (const [key, testID] of targets) { + const entry = initial[key]; + expect(entry.count, `${key} initial onLayout count`).toBe(1); + expect(entry.keys, `${key} layout keys`).toEqual(["height", "width", "x", "y"]); + expect(entry.layout.width, `${key} width`).toBeGreaterThan(0); + expect(entry.layout.height, `${key} height`).toBeGreaterThan(0); + const treeNode = treeNodes.find((n) => n.testID === testID); + expect(treeNode?.frame, `${testID} frame`).toBeDefined(); + expect(entry.layout.x).toBeCloseTo(treeNode!.frame![0], 2); + expect(entry.layout.y).toBeCloseTo(treeNode!.frame![1], 2); + expect(entry.layout.width).toBeCloseTo(treeNode!.frame![2], 2); + expect(entry.layout.height).toBeCloseTo(treeNode!.frame![3], 2); + } + + const toggle = await nodeWithId("layout-resize-toggle"); + expect(await request("click", { tag: toggle.tag })).toEqual({ clicked: true }); + await expect + .poll(async () => { + const parsed = await readLayouts(); + return targets.every(([key]) => (parsed[key]?.count ?? 0) >= 2); + }) + .toBe(true); + + const resized = await readLayouts(); + for (const [key] of targets) { + expect(resized[key].count, `${key} resized onLayout count`).toBe(2); + expect(resized[key].layout.width, `${key} resized width`).toBeGreaterThan( + initial[key].layout.width, + ); + } + }, +); diff --git a/vendor/react-native-gpui/UPSTREAM b/vendor/react-native-gpui/UPSTREAM index 667540701e..4f03c5cdd1 100644 --- a/vendor/react-native-gpui/UPSTREAM +++ b/vendor/react-native-gpui/UPSTREAM @@ -34,6 +34,21 @@ Local patches (all other retained files match the revisions above): - packages/core/ReactGpui/rn-gpui-sys/build.rs: pass Cargo's MACOSX_DEPLOYMENT_TARGET to CMake. Otherwise source builds default to the installed SDK's version even when the app targets an older macOS release. + Also exports `RN_GPUI_LOOM_RENDERER_BUILT` so `store.rs` knows whether Loom + or Fabric owns `topLayout`. +- packages/core/src-gpui/Libraries/NativeComponent/BaseViewConfig.desktop.ts, + packages/core/ReactGpui/rn-gpui-sys/src/lib.rs, + packages/core/ReactGpui/rn-gpui-sys/cpp/{MountBatchBuilder,LoomViewProps}.cpp, + packages/core/ReactGpui/rn-gpui/src/{bootstrap,view_props,store,host}.rs: + restore standard React Native `onLayout` behavior across all components + (Text/Paragraph, TextInput, Image, View, ScrollView, etc.) instead of + hardcoding `topLayout` to `View` and scroll containers. Add `onLayout: true` + to desktop `validAttributes` so JS forwards the listener flag; let Fabric's + `ShadowTree::emitLayoutEvents` emit `topLayout` without double-dispatching + in `store.rs` (selected explicitly via `LayoutEventOwner` at store + construction from `rn_gpui_sys::LOOM_RENDERER`), and propagate `on_layout` + into `ViewPropsFlat` so Loom dispatches `topLayout` for any laid-out node + with `on_layout` set. Covered by `native.test.ts` and `store.rs` unit tests. (Upstream now includes box-none pointer pass-through, uniform rounded border decoration, GpuiJsEngine.h hover flag, metro.config.js self-import bypass, and diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/build.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/build.rs index a0c0cb5eb3..6795ab3475 100644 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/build.rs +++ b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/build.rs @@ -148,6 +148,10 @@ fn main() { &renderer.js_thread } ); + println!( + "cargo:rustc-env=RN_GPUI_LOOM_RENDERER_BUILT={}", + if renderer.loom { "1" } else { "0" } + ); let react_native_dir = match &renderer.react_native_dir { Some(dir) if renderer.loom => { assert!( diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.cpp index 74f4d6fc83..16e35da6f5 100644 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.cpp +++ b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.cpp @@ -270,6 +270,7 @@ BOOL_FIELD(setOnAccessibilityTap, accessibility_has_tap_listener) BOOL_FIELD(setOnAccessibilityMagicTap, accessibility_has_magic_tap_listener) BOOL_FIELD(setOnAccessibilityEscape, accessibility_has_escape_listener) BOOL_FIELD(setOnAccessibilityAction, accessibility_has_action_listener) +BOOL_FIELD(setOnLayout, on_layout) BOOL_FIELD(setFocusable, focusable) BOOL_FIELD(setDesktopDragRegion, desktop_drag_region) BOOL_FIELD(setAcceptsFiles, accepts_files) @@ -498,6 +499,7 @@ const std::unordered_map& handlers() { {"onContextMenuCapture", &setOnContextMenuCapture}, {"onWheel", &setOnWheel}, {"onWheelCapture", &setOnWheelCapture}, + {"onLayout", &setOnLayout}, {"selectable", &setSelectable}, {"onTextLayout", &setOnTextLayout}, }; diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.cpp index 2a05d7c8ac..1893587c80 100644 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.cpp +++ b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.cpp @@ -429,6 +429,7 @@ static ViewPropsFlat flattenView(const ShadowView& shadowView) { out.accessibility_has_tap_listener = props->onAccessibilityTap; out.accessibility_has_escape_listener = props->onAccessibilityEscape; out.accessibility_has_magic_tap_listener = props->onAccessibilityMagicTap; + out.on_layout = props->onLayout; out.accessibility_important = static_cast(props->importantForAccessibility); out.accessibility_live_region = diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/lib.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/lib.rs index a008b2fe0a..65add6edea 100644 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/lib.rs +++ b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/lib.rs @@ -116,6 +116,7 @@ pub mod ffi { /// "minimize" | "maximize" | "close" for a custom caption button. pub on_context_menu: bool, pub on_wheel: bool, + pub on_layout: bool, /// A node's group name, and the JSON of each state style prop; empty = not set. pub group: String, pub hover_style: String, @@ -717,6 +718,11 @@ pub use ffi::{ /// Where JavaScript runs with the Loom renderer: the `jsThread` autolink /// recorded, fixed when the app is built. pub const JS_THREAD: &str = env!("RN_GPUI_JS_THREAD_BUILT"); +/// Whether the Loom renderer was active when this crate was built. +pub const LOOM_RENDERER: bool = match option_env!("RN_GPUI_LOOM_RENDERER_BUILT") { + Some(value) => matches!(value.as_bytes(), b"1"), + None => false, +}; pub type MountHandler = Box; pub type MeasureHandler = diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/bootstrap.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/bootstrap.rs index 169a61442a..26351e439e 100644 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/bootstrap.rs +++ b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/bootstrap.rs @@ -1,5 +1,7 @@ use crate::host::Host; -use crate::store::{OverlayHost, StoreGlobal, SurfaceRootView, ViewStore, APP_SURFACE_ID}; +use crate::store::{ + LayoutEventOwner, OverlayHost, StoreGlobal, SurfaceRootView, ViewStore, APP_SURFACE_ID, +}; use gpui::{point, px, size, App, AppContext, Application, Bounds, WindowBounds, WindowOptions}; use rn_gpui_sys::ffi::MountBatch; use std::cell::Cell; @@ -1871,7 +1873,15 @@ pub fn run_with(mut config: DesktopAppConfig) { #[cfg(feature = "visual-capture")] let host_for_input = host.clone(); - let store = cx.new(|_| ViewStore::new(host, window, frame_hook.clone(), overlay_host)); + let store = cx.new(|_| { + ViewStore::new( + host, + window, + frame_hook.clone(), + overlay_host, + LayoutEventOwner::from_loom_flag(rn_gpui_sys::LOOM_RENDERER), + ) + }); cx.set_global(StoreGlobal(store.clone())); #[cfg(feature = "test-driver")] if std::env::var("RN_GPUI_TEST_DRIVER").as_deref() == Ok("1") { diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/host.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/host.rs index 24864dcb7b..529e946dfb 100644 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/host.rs +++ b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/host.rs @@ -21,7 +21,11 @@ pub(crate) fn live_host() -> Option<&'static Host> { // the app-level e2e tests exercise the real C++/Fabric boundary. #[derive(Clone)] #[cfg_attr(test, allow(dead_code))] -pub struct Host(Arc>>); +pub struct Host { + inner: Arc>>, + #[cfg(test)] + dispatched_events: Arc>>, +} impl Host { pub fn new( @@ -40,9 +44,11 @@ impl Host { #[cfg(not(test))] { crate::host_component::freeze(); - let host = Self(Arc::new(Mutex::new(ffi::new_gpui_host( - app_id, dev_host, port, js_engine, js_thread, dev_mode, - )))); + let host = Self { + inner: Arc::new(Mutex::new(ffi::new_gpui_host( + app_id, dev_host, port, js_engine, js_thread, dev_mode, + ))), + }; let _ = LIVE_HOST.set(host.clone()); host } @@ -52,14 +58,22 @@ impl Host { /// only a raw handle behind, so a poisoned lock is still usable. #[cfg(not(test))] fn lock(&self) -> std::sync::MutexGuard<'_, cxx::UniquePtr> { - self.0 + self.inner .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } #[cfg(test)] pub(crate) fn test_stub() -> Self { - Self(Arc::new(Mutex::new(cxx::UniquePtr::null()))) + Self { + inner: Arc::new(Mutex::new(cxx::UniquePtr::null())), + dispatched_events: Arc::new(Mutex::new(Vec::new())), + } + } + + #[cfg(test)] + pub(crate) fn take_dispatched_events(&self) -> Vec<(i32, String, serde_json::Value)> { + std::mem::take(&mut self.dispatched_events.lock().unwrap()) } pub fn load_script(&self, bundle: &str, url: &str) -> bool { @@ -284,7 +298,10 @@ impl Host { pub fn dispatch_event(&self, tag: i32, ty: &str, payload: &serde_json::Value) { #[cfg(test)] - let _ = (self, tag, ty, payload); + self.dispatched_events + .lock() + .unwrap() + .push((tag, ty.to_string(), payload.clone())); #[cfg(not(test))] self.lock().dispatch_event(tag, ty, &payload.to_string()); // React Native holds events until its next event beat, and nothing diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/store.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/store.rs index 7c1de96c97..cd1616232d 100644 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/store.rs +++ b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/store.rs @@ -44,8 +44,30 @@ pub enum SurfaceKind { Embedded, } +/// Which layer dispatches `topLayout` for laid-out nodes. +/// +/// Fabric's `ShadowTree::emitLayoutEvents` already emits `topLayout` when +/// `BaseViewProps::onLayout` is set; Loom has no `ShadowTree`, so `ViewStore` +/// dispatches `topLayout` from mount ops. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LayoutEventOwner { + ShadowTree, + Store, +} + +impl LayoutEventOwner { + pub fn from_loom_flag(loom_renderer: bool) -> Self { + if loom_renderer { + Self::Store + } else { + Self::ShadowTree + } + } +} + pub struct ViewStore { pub host: Host, + layout_event_owner: LayoutEventOwner, pub frame_hook: FrameHook, pub window: AnyWindowHandle, pub windows: HashMap, @@ -121,11 +143,13 @@ impl ViewStore { window: impl Into, frame_hook: FrameHook, overlay_host: Entity, + layout_event_owner: LayoutEventOwner, ) -> Self { let window = window.into(); note_surface_window(APP_SURFACE_ID, Some(window)); Self { host, + layout_event_owner, frame_hook, window, windows: HashMap::from([(APP_SURFACE_ID, window)]), @@ -981,24 +1005,31 @@ impl ViewStore { } _ => log::warn!("[store] unknown mount kind {}", op.kind.repr), } - let is_scroll = crate::extensions::component_scroll( - &op.component, - &crate::extensions::parse_extension_props(&op.extension_props_json), - ) - .is_some(); - if op.layout_changed && (op.component == "View" || is_scroll) { - self.host.dispatch_event( - op.tag, - "topLayout", - &serde_json::json!({ - "layout": { - "x": op.frame.x, - "y": op.frame.y, - "width": op.frame.w, - "height": op.frame.h - } - }), - ); + // Fabric emits `topLayout` from `ShadowTree::emitLayoutEvents` using + // `BaseViewProps::onLayout`. Loom has no `ShadowTree`, so the store + // dispatches `topLayout` for any laid-out node that asked for `onLayout`. + if self.layout_event_owner == LayoutEventOwner::Store + && op.layout_changed + && !matches!(op.kind, MountKind::Delete | MountKind::Remove) + { + let wants_layout = self + .nodes + .get(&op.tag) + .is_some_and(|node| node.read(cx).view.on_layout); + if wants_layout { + self.host.dispatch_event( + op.tag, + "topLayout", + &serde_json::json!({ + "layout": { + "x": op.frame.x, + "y": op.frame.y, + "width": op.frame.w, + "height": op.frame.h + } + }), + ); + } } } self.restore_scroll_anchors(anchors, cx); @@ -1489,7 +1520,7 @@ pub(crate) fn test_store_handle(cx: &mut gpui::TestAppContext) -> crate::extensi let any_window: gpui::AnyWindowHandle = window.into(); let host = crate::host::Host::test_stub(); let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host)); + let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); let _ = root; crate::extensions::StoreHandle::new(store.downgrade()) @@ -1497,7 +1528,9 @@ pub(crate) fn test_store_handle(cx: &mut gpui::TestAppContext) -> crate::extensi #[cfg(test)] mod test_app_context_tests { - use super::{OverlayHost, StoreGlobal, SurfaceKind, SurfaceRootView, ViewStore}; + use super::{ + LayoutEventOwner, OverlayHost, StoreGlobal, SurfaceKind, SurfaceRootView, ViewStore, + }; use crate::{frame::FrameHook, host::Host}; use gpui::{px, AppContext, TestAppContext}; use rn_gpui_sys::ffi::{MountBatch, MountKind, MountOp, ParagraphFlat, RectF, ViewPropsFlat}; @@ -1563,8 +1596,9 @@ mod test_app_context_tests { /// Builds a store whose surface root is a real window root, and returns /// both the store and that root. - fn store_with_root( + fn store_with_layout_owner( cx: &mut TestAppContext, + layout_event_owner: LayoutEventOwner, ) -> (gpui::Entity, gpui::Entity) { let overlay_host = cx.new(|_| OverlayHost::new()); let window = cx.open_window(gpui::size(px(120.0), px(100.0)), { @@ -1575,12 +1609,26 @@ mod test_app_context_tests { let any_window: gpui::AnyWindowHandle = window.into(); let host = Host::test_stub(); let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host)); + let store = cx.new(|_| { + ViewStore::new( + host, + any_window, + frame_hook, + overlay_host, + layout_event_owner, + ) + }); cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); store.update(cx, |store, _| store.register_root(1, root.clone())); (store, root) } + fn store_with_root( + cx: &mut TestAppContext, + ) -> (gpui::Entity, gpui::Entity) { + store_with_layout_owner(cx, LayoutEventOwner::ShadowTree) + } + /// Applies a batch of `(kind, tag, parent)` triples. fn apply(cx: &mut TestAppContext, store: &gpui::Entity, ops: Vec) { store.update(cx, |store, cx| { @@ -2011,7 +2059,7 @@ mod test_app_context_tests { let any_window: gpui::AnyWindowHandle = window.into(); let host = Host::test_stub(); let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host)); + let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); store.update(cx, |store, _| store.register_root(1, root)); @@ -2088,7 +2136,7 @@ mod test_app_context_tests { let any_window: gpui::AnyWindowHandle = window.into(); let host = Host::test_stub(); let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host)); + let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); store.update(cx, |store, _| store.register_root(1, root)); @@ -2140,7 +2188,7 @@ mod test_app_context_tests { let any_window: gpui::AnyWindowHandle = window.into(); let host = Host::test_stub(); let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host)); + let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); store.update(cx, |store, _| store.register_root(1, root)); @@ -2248,7 +2296,7 @@ mod test_app_context_tests { let any_window: gpui::AnyWindowHandle = window.into(); let host = Host::test_stub(); let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host)); + let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); store.update(cx, |store, _| store.register_root(1, root)); @@ -2425,7 +2473,7 @@ mod test_app_context_tests { let any_window: gpui::AnyWindowHandle = window.into(); let host = Host::test_stub(); let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host)); + let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); store.update(cx, |store, _| store.register_root(1, root)); @@ -2540,6 +2588,186 @@ mod test_app_context_tests { "its parent must still be there" ); } + + #[gpui::test] + fn top_layout_dispatches_for_any_component_with_on_layout_and_skips_non_listeners( + cx: &mut TestAppContext, + ) { + let (store, _root) = store_with_layout_owner(cx, LayoutEventOwner::from_loom_flag(true)); + let with_on_layout = |tag: i32, component: &'static str, on_layout: bool| { + let mut node = create(tag, component); + node.layout_changed = true; + node.view.on_layout = on_layout; + node + }; + apply( + cx, + &store, + vec![ + with_on_layout(101, "View", true), + with_on_layout(102, "Paragraph", true), + with_on_layout(103, "TextInput", true), + with_on_layout(104, "Image", true), + with_on_layout(105, "ScrollView", true), + with_on_layout(106, "View", false), + with_on_layout(107, "Paragraph", false), + ], + ); + + let events = cx.read_entity(&store, |store, _| store.host.take_dispatched_events()); + let tags: Vec = events + .iter() + .filter(|(_, ty, _)| ty == "topLayout") + .map(|(tag, _, _)| *tag) + .collect(); + assert_eq!(tags, vec![101, 102, 103, 104, 105]); + assert_eq!( + events[1].2, + serde_json::json!({ + "layout": { + "x": 10.0, + "y": 12.0, + "width": 40.0, + "height": 30.0 + } + }) + ); + } + + #[gpui::test] + fn top_layout_tracks_on_layout_across_layout_only_updates_and_inserts( + cx: &mut TestAppContext, + ) { + let (store, _root) = store_with_layout_owner(cx, LayoutEventOwner::from_loom_flag(true)); + + let mut p_create = create(201, "Paragraph"); + p_create.layout_changed = true; + p_create.view.on_layout = true; + p_create.frame = RectF { + x: 0.0, + y: 0.0, + w: 50.0, + h: 20.0, + }; + apply(cx, &store, vec![p_create]); + assert_eq!( + cx.read_entity(&store, |store, _| store.host.take_dispatched_events()) + .len(), + 1 + ); + + // Layout-only update (props_changed = false, op.view default) keeps on_layout = true. + let mut p_layout_only = op(MountKind::Update); + p_layout_only.tag = 201; + p_layout_only.component = "Paragraph".into(); + p_layout_only.props_changed = false; + p_layout_only.layout_changed = true; + p_layout_only.frame = RectF { + x: 1.0, + y: 2.0, + w: 80.0, + h: 25.0, + }; + apply(cx, &store, vec![p_layout_only]); + let events = cx.read_entity(&store, |store, _| store.host.take_dispatched_events()); + assert_eq!(events.len(), 1); + assert_eq!( + events[0].2, + serde_json::json!({ + "layout": { + "x": 1.0, + "y": 2.0, + "width": 80.0, + "height": 25.0 + } + }) + ); + + // Removing onLayout stops subsequent layout events. + let mut p_remove_prop = op(MountKind::Update); + p_remove_prop.tag = 201; + p_remove_prop.component = "Paragraph".into(); + p_remove_prop.props_changed = true; + p_remove_prop.view.on_layout = false; + p_remove_prop.layout_changed = true; + p_remove_prop.frame = RectF { + x: 1.0, + y: 2.0, + w: 90.0, + h: 25.0, + }; + apply(cx, &store, vec![p_remove_prop]); + assert!( + cx.read_entity(&store, |store, _| store.host.take_dispatched_events()) + .is_empty() + ); + + // Insert carrying initial layout honors Create's on_layout flag. + let mut v_create = create(202, "Paragraph"); + v_create.layout_changed = false; + v_create.view.on_layout = true; + let mut v_insert = insert(202, -1); + v_insert.component = "Paragraph".into(); + v_insert.props_changed = false; + v_insert.layout_changed = true; + v_insert.frame = RectF { + x: 3.0, + y: 4.0, + w: 60.0, + h: 18.0, + }; + apply(cx, &store, vec![v_create, v_insert]); + let insert_events = cx.read_entity(&store, |store, _| store.host.take_dispatched_events()); + assert_eq!(insert_events.len(), 1); + assert_eq!(insert_events[0].0, 202); + } + + #[gpui::test] + fn top_layout_does_not_dispatch_when_shadow_tree_owns_layout_events(cx: &mut TestAppContext) { + let (store, _root) = store_with_layout_owner(cx, LayoutEventOwner::from_loom_flag(false)); + + let with_on_layout = |tag: i32, component: &'static str| { + let mut node = create(tag, component); + node.layout_changed = true; + node.view.on_layout = true; + node + }; + let mut insert_view = insert(306, -1); + insert_view.component = "View".into(); + insert_view.props_changed = false; + insert_view.layout_changed = true; + + let mut c306 = create(306, "View"); + c306.layout_changed = false; + c306.view.on_layout = true; + + apply( + cx, + &store, + vec![ + with_on_layout(301, "View"), + with_on_layout(302, "Paragraph"), + with_on_layout(303, "TextInput"), + with_on_layout(304, "Image"), + with_on_layout(305, "ScrollView"), + c306, + insert_view, + ], + ); + + let mut update = op(MountKind::Update); + update.tag = 301; + update.component = "View".into(); + update.props_changed = false; + update.layout_changed = true; + apply(cx, &store, vec![update]); + + assert!( + cx.read_entity(&store, |store, _| store.host.take_dispatched_events()) + .is_empty(), + "Fabric builds emit topLayout from ShadowTree and must not dispatch a second time from ViewStore" + ); + } } fn log_mount_op(op: &MountOp) { diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/view_props.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/view_props.rs index 3d12efa158..32c9e118bc 100644 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/view_props.rs +++ b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/view_props.rs @@ -60,6 +60,7 @@ pub struct ViewProps { pub desktop_drag_region: bool, pub on_context_menu: bool, pub on_wheel: bool, + pub on_layout: bool, pub accepts_files: bool, pub draggable: bool, pub droppable: bool, @@ -251,6 +252,7 @@ impl From for ViewProps { desktop_drag_region: flat.desktop_drag_region, on_context_menu: flat.on_context_menu, on_wheel: flat.on_wheel, + on_layout: flat.on_layout, accepts_files: flat.accepts_files, draggable: flat.draggable, droppable: flat.droppable, diff --git a/vendor/react-native-gpui/packages/core/src-gpui/Libraries/NativeComponent/BaseViewConfig.desktop.ts b/vendor/react-native-gpui/packages/core/src-gpui/Libraries/NativeComponent/BaseViewConfig.desktop.ts index 0fe0139c7f..56acff5e36 100644 --- a/vendor/react-native-gpui/packages/core/src-gpui/Libraries/NativeComponent/BaseViewConfig.desktop.ts +++ b/vendor/react-native-gpui/packages/core/src-gpui/Libraries/NativeComponent/BaseViewConfig.desktop.ts @@ -365,7 +365,9 @@ export default { onDropCapture: true, dragOverStyle: { process: processStateStyle('dragOverStyle') }, // RN omits iOS listener flags when Platform.OS is an out-of-tree platform. - // Fabric's AccessibilityProps needs these flags for native action routing. + // Fabric's Layout and AccessibilityProps need these flags so JS forwards + // `onLayout` and accessibility listeners to native. + onLayout: true, onAccessibilityAction: true, onAccessibilityEscape: true, onAccessibilityTap: true,