gpui: dispatch onLayout for any node that sets it

This commit is contained in:
Mohamed Boudra
2026-11-28 13:10:11 +01:00
parent 1eb69a4217
commit 35a5cd4311
12 changed files with 492 additions and 78 deletions
@@ -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 (
<View style={{ flex: 1, backgroundColor: "white", padding: 40, gap: 24 }}>
<View
testID="rounded-border"
style={{
width: 200,
height: 100,
borderRadius: 24,
borderWidth: 4,
borderColor: "#ff0000",
backgroundColor: "#0000ff",
}}
/>
<Pressable
testID="hover-button"
onHoverIn={() => setHovered(true)}
onHoverOut={() => setHovered(false)}
style={{ width: 200, height: 60, backgroundColor: buttonHovered ? "#00ff00" : "#0000ff" }}
>
<Text>{buttonHovered ? "hover active" : "hover inactive"}</Text>
</Pressable>
<Pressable
testID="hover-render-prop"
style={({ hovered }) => ({
width: 200,
height: 60,
backgroundColor: hovered ? "#00ff00" : "#0000ff",
})}
>
{({ hovered }) => <Text>{hovered ? "render hovered" : "render idle"}</Text>}
</Pressable>
<View
testID="hover-row"
onPointerEnter={() => setEntered(true)}
onPointerLeave={() => setEntered(false)}
style={{ width: 200, height: 60, backgroundColor: entered ? "#00ff00" : "#0000ff" }}
>
<Pressable testID="nested-button" style={{ width: 100, height: 60 }}>
<Text>{entered ? "row active" : "row inactive"}</Text>
<View style={{ flex: 1, flexDirection: "row", backgroundColor: "white", padding: 40, gap: 40 }}>
<View style={{ gap: 24 }}>
<View
testID="rounded-border"
style={{
width: 200,
height: 100,
borderRadius: 24,
borderWidth: 4,
borderColor: "#ff0000",
backgroundColor: "#0000ff",
}}
/>
<Pressable
testID="hover-button"
onHoverIn={() => setHovered(true)}
onHoverOut={() => setHovered(false)}
style={{ width: 200, height: 60, backgroundColor: buttonHovered ? "#00ff00" : "#0000ff" }}
>
<Text>{buttonHovered ? "hover active" : "hover inactive"}</Text>
</Pressable>
<Pressable
testID="hover-render-prop"
style={({ hovered }) => ({
width: 200,
height: 60,
backgroundColor: hovered ? "#00ff00" : "#0000ff",
})}
>
{({ hovered }) => <Text>{hovered ? "render hovered" : "render idle"}</Text>}
</Pressable>
<View
testID="hover-row"
onPointerEnter={() => setEntered(true)}
onPointerLeave={() => setEntered(false)}
style={{ width: 200, height: 60, backgroundColor: entered ? "#00ff00" : "#0000ff" }}
>
<Pressable testID="nested-button" style={{ width: 100, height: 60 }}>
<Text>{entered ? "row active" : "row inactive"}</Text>
</Pressable>
</View>
<View testID="outside-hover" style={{ width: 200, height: 60 }} />
</View>
<View style={{ gap: 12, alignItems: "flex-start" }}>
<Pressable
testID="layout-resize-toggle"
onPress={() => setExpanded((value) => !value)}
style={{ width: 160, height: 32, backgroundColor: "#dddddd", justifyContent: "center" }}
>
<Text>{expanded ? "Shrink" : "Expand"}</Text>
</Pressable>
<View
testID="layout-view"
onLayout={onViewLayout}
style={{ width: expanded ? 180 : 120, height: 24, backgroundColor: "#eeeeee" }}
/>
<Text testID="layout-text" onLayout={onTextLayout}>
{expanded ? "Measure a much longer text label" : "Short label"}
</Text>
<TextInput
testID="layout-text-input"
onLayout={onInputLayout}
defaultValue="hi"
style={{ width: expanded ? 200 : 140, height: 32, borderWidth: 1 }}
/>
<Image
testID="layout-image"
onLayout={onImageLayout}
style={{ width: expanded ? 96 : 64, height: 32, backgroundColor: "#cccccc" }}
/>
<ScrollView
testID="layout-scroll"
onLayout={onScrollLayout}
style={{
flexGrow: 0,
flexShrink: 0,
width: expanded ? 210 : 150,
height: 40,
backgroundColor: "#eeeeee",
}}
>
<View style={{ width: expanded ? 210 : 150, height: 80 }} />
</ScrollView>
<Text testID="layout-results">{JSON.stringify(layouts)}</Text>
</View>
<View testID="outside-hover" style={{ width: 200, height: 60 }} />
</View>
);
}
+60
View File
@@ -15,6 +15,7 @@ interface Node {
component: string;
testID: string;
text: string;
frame?: [number, number, number, number];
children?: Node[];
}
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
@@ -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<string, LayoutEntry>;
};
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,
);
}
},
);
+15
View File
@@ -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
@@ -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!(
@@ -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<std::string_view, Handler>& handlers() {
{"onContextMenuCapture", &setOnContextMenuCapture},
{"onWheel", &setOnWheel},
{"onWheelCapture", &setOnWheelCapture},
{"onLayout", &setOnLayout},
{"selectable", &setSelectable},
{"onTextLayout", &setOnTextLayout},
};
@@ -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<uint8_t>(props->importantForAccessibility);
out.accessibility_live_region =
@@ -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<dyn Fn(ffi::MountBatch) + Send + Sync>;
pub type MeasureHandler =
@@ -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") {
@@ -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<Mutex<cxx::UniquePtr<ffi::GpuiHost>>>);
pub struct Host {
inner: Arc<Mutex<cxx::UniquePtr<ffi::GpuiHost>>>,
#[cfg(test)]
dispatched_events: Arc<Mutex<Vec<(i32, String, serde_json::Value)>>>,
}
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<ffi::GpuiHost>> {
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
@@ -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<i32, AnyWindowHandle>,
@@ -121,11 +143,13 @@ impl ViewStore {
window: impl Into<AnyWindowHandle>,
frame_hook: FrameHook,
overlay_host: Entity<OverlayHost>,
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<ViewStore>, gpui::Entity<SurfaceRootView>) {
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<ViewStore>, gpui::Entity<SurfaceRootView>) {
store_with_layout_owner(cx, LayoutEventOwner::ShadowTree)
}
/// Applies a batch of `(kind, tag, parent)` triples.
fn apply(cx: &mut TestAppContext, store: &gpui::Entity<ViewStore>, ops: Vec<MountOp>) {
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<i32> = 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) {
@@ -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<ViewPropsFlat> 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,
@@ -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,