diff --git a/README.md b/README.md index 9ed4235..713212e 100644 --- a/README.md +++ b/README.md @@ -103,8 +103,8 @@ or moving an ancestor does not trigger a measurement. On iOS, same-frame deliver Readiness indicates a completed measurement, not a universal first-frame guarantee. -The [performance guide](https://appandflow.github.io/react-native-reserved-regions/docs/performance) -explains provider placement and optional readiness gating. +The [Usage guide](https://appandflow.github.io/react-native-reserved-regions/docs/usage#wait-before-rendering) +shows how to wait for the first measurement before rendering content. ## Development diff --git a/website/docs/api.md b/website/docs/api.md index 93ed2fe..c06a234 100644 --- a/website/docs/api.md +++ b/website/docs/api.md @@ -3,31 +3,33 @@ title: API reference description: Provider, hook, and documented region types. --- -All public exports come from `react-native-reserved-regions`. +Import all exports from `react-native-reserved-regions`. ## ReservedRegionsProvider +Wrap the view you want to measure with `ReservedRegionsProvider`. It accepts React Native `ViewProps` and a ref to its native view. + ```ts function ReservedRegionsProvider( - props: ViewProps & { ref?: React.Ref> }, + props: ViewProps & { + ref?: React.Ref>; + }, ): React.JSX.Element; ``` -A native view that supplies active reserved regions to descendants. It accepts React Native `ViewProps` and a `ref` to the native view, which you can use like a `View` ref, for example to call `measure`. Give it explicit dimensions or a layout style such as `flex: 1` so there is an area to measure. - -Each provider maintains its own measurements. A nested provider replaces the context for its descendants. +Use the ref to call native view methods such as `measure`. ## ReservedRegionsGate +Wrap content with `ReservedRegionsGate` to mount it after the nearest provider completes its first measurement, including an empty result. + ```ts function ReservedRegionsGate(props: { children?: React.ReactNode }): React.ReactNode; ``` -Renders `null` until the nearest provider has completed its first measurement, -then renders `children`, including for an empty result. It adds no native view and -does not suspend. Throws outside a provider, like `useReservedRegionsReady()`. -Keep the measured view mounted and sized outside the gate. See -[performance and first render](./performance.md) for placement and tradeoffs. +The gate adds no native view and does not use Suspense. Using it outside a provider throws an error. + +See [Usage](./usage.md#wait-before-rendering) for an example. ## useReservedRegions @@ -35,7 +37,11 @@ Keep the measured view mounted and sized outside the gate. See function useReservedRegions(): readonly ReservedRegion[]; ``` -Returns regions from the nearest provider, initially `[]`. Throws if there is no provider. The list has no guaranteed stable IDs or ordering. Treat both the array and its values as read-only. +Returns the regions from the nearest provider. Before the first measurement, it returns an empty array. + +Treat the array and its values as read-only. Regions have no stable IDs or guaranteed order. + +Calling the hook outside a provider throws an error. ## useReservedRegionsReady @@ -43,55 +49,52 @@ Returns regions from the nearest provider, initially `[]`. Throws if there is no function useReservedRegionsReady(): boolean; ``` -Returns whether the nearest provider has reported its first measurement. Initially `false`, then `true` even when the measured region array is empty. Regions and readiness update together. It stays true for that provider's lifetime and resets for a newly mounted provider. Throws if there is no provider. +Returns `false` while the first measurement is pending and `true` when it completes, including when no regions are found. -Readiness does not indicate hardware support or guarantee first-visible-frame timing. An unsupported platform reports a known empty result. A provider without laid-out bounds remains pending; Android also waits for its first WindowManager result when a synchronous query is unavailable. +Readiness and regions update together. Readiness stays `true` until the provider unmounts. A new provider starts pending. + +Calling the hook outside a provider throws an error. ## ReservedRegionFrame +Describes a region’s position and size. + ```ts -/** Bounds in logical points relative to the nearest provider. Not clipped to the provider. */ type ReservedRegionFrame = Readonly<{ - /** Horizontal distance from the provider's left edge. */ x: number; - /** Vertical distance from the provider's top edge. */ y: number; - /** Horizontal extent; can be zero for a vertical fold. */ width: number; - /** Vertical extent; can be zero for a horizontal fold. */ height: number; }>; ``` -A frame can extend past the provider's edges. Read [coordinate spaces](./coordinates.md) to get the visible part and for interaction-margin behavior. +`x` and `y` are measured from the provider’s left and top edges. `width` and `height` describe the region’s size. + +See [Understanding regions](./coordinates.md) for units, zero-width or zero-height divisions, and frames that extend outside the provider. ## ReservedRegion ```ts -/** An active area reserved by the display or supported system UI. */ type ReservedRegion = | Readonly<{ - /** A seam, hinge, or fold dividing the usable display. */ kind: 'division'; - /** Bounds in the provider's coordinate space. */ frame: ReservedRegionFrame; - /** True when content underneath this division is hidden. */ occludesContent: boolean; }> | Readonly<{ - /** A reserved area where content is hidden, such as a cutout. */ kind: 'occlusion'; - /** Bounds in the provider's coordinate space. */ frame: ReservedRegionFrame; }>; ``` -`kind` is a string-literal discriminant, not a runtime enum. `occludesContent` exists only on divisions: it distinguishes a visible fold from an occluding hinge. Occlusion regions already express hidden content and do not carry the boolean. +A division represents a fold or hinge. Use `occludesContent` to check whether content is hidden within its frame. + +An occlusion represents an area where content is hidden. It has no `occludesContent` property. + +Check `kind` before accessing properties specific to a region type. ```ts function hidesContent(region: ReservedRegion): boolean { return region.kind === 'occlusion' || region.occludesContent; } ``` - -Currently iOS divisions always have `occludesContent: false`. Android derives it from `FoldingFeature.OcclusionType.FULL`. See [platform behavior](./platforms.md). diff --git a/website/docs/coordinates.md b/website/docs/coordinates.md index 1eb0eea..41489a6 100644 --- a/website/docs/coordinates.md +++ b/website/docs/coordinates.md @@ -1,38 +1,78 @@ --- -title: Coordinate spaces +title: Understanding regions description: Scope measurements to a screen, panel, or nested provider. --- -Every `frame` is expressed in **logical points relative to the nearest provider's top-left corner**. On Android, physical pixel measurements are converted to density-independent units before reaching JavaScript. +## What is a region? -| Field | Meaning | -| -------- | ------------------------------------------------ | -| `x` | Horizontal offset from the provider's left edge. | -| `y` | Vertical offset from the provider's top edge. | -| `width` | Horizontal extent of the region. | -| `height` | Vertical extent of the region. | +A region describes a part of the display that affects where you place content. The library reports two types: **divisions** and **occlusions**. -These are provider coordinates, not screen coordinates. A provider can occupy a whole screen or a smaller view. +### Divisions -## A provider inside a panel +A division marks a fold in a flexible screen or a hinge between two screens. Divisions are reported as `kind: 'division'`. -```tsx - - - - - +Use `occludesContent` to check whether content is hidden in that area: + +- `false`: content remains visible across the division. +- `true`: content is hidden within the division’s frame. + +A division can have zero width or height. Keep these regions when calculating your layout; they still mark a boundary in the display. + +Example of a fold that leaves content visible, using illustrative values: + +```ts +{ + kind: 'division', + occludesContent: false, + frame: { x: 400, y: 0, width: 0, height: 800 }, +} +``` + +### Occlusions + +An occlusion marks an area where content is hidden, such as a camera cutout or space reserved by the system. + +Occlusions are reported as `kind: 'occlusion'`. They have no `occludesContent` flag because they already represent hidden content. + +Example of a camera cutout, using illustrative values: + +```ts +{ + kind: 'occlusion', + frame: { x: 20, y: 20, width: 30, height: 30 }, +} ``` -`PanelContent` receives measurements relative to the inset provider. Do not subtract the surrounding padding a second time. If you render an absolute-positioned overlay, place it inside that provider so the overlay and region share an origin. Frames can extend past the provider, so wrap overlays in an absolute-fill `View` with `overflow: 'hidden'` to keep them within its bounds. +### Position and size + +The provider is the view your app measures. Both region types include a `frame` describing their position and size relative to that view. -## Native geometry +```ts +const frame = { + x: 120, + y: 0, + width: 20, + height: 800, +}; +``` -A provider receives the regions that intersect its bounds. Regions outside the provider are omitted. Each included region keeps its full frame, not only the part inside the provider, so a frame can have a negative `x` or `y` or extend past the provider's width or height. A fold that spans the window keeps its full length even when the provider covers only part of it. A fold can have zero width or height and still be meaningful; do not discard line-shaped regions. +- `x`: distance from the provider’s left edge. +- `y`: distance from the provider’s top edge. +- `width` and `height`: the region’s size. -On Android, the library translates window-relative folding features and cutouts into provider coordinates. On iOS, UIKit performs the view-scoped query and the library forwards the returned frames. UIKit frames can include interaction margins around an obstruction, so they should not be interpreted as exact physical hardware outlines. See [Apple's reserved regions overview](https://developer.apple.com/videos/play/tech-talks/111463/). +All values use logical points. On Android, the library converts physical pixels to density-independent units. -To work with only the visible part, intersect a frame with the provider's size, for example from the provider's `onLayout`: +## Frames can extend outside the provider + +The library includes regions that overlap the provider and returns their full frames. A frame can start outside the provider or extend past its edges. + +For example, `y: -10` places the region’s top edge 10 points above the provider. + +```ts +{ x: 0, y: -10, width: 20, height: 100 } +``` + +To draw only the part inside the provider, use `overflow: 'hidden'` on the overlay container. You can also calculate that portion using the provider’s size from `onLayout`. ```ts import type { ReservedRegionFrame } from 'react-native-reserved-regions'; @@ -40,6 +80,7 @@ import type { ReservedRegionFrame } from 'react-native-reserved-regions'; function visiblePart(frame: ReservedRegionFrame, provider: { width: number; height: number }): ReservedRegionFrame { const x = Math.max(0, frame.x); const y = Math.max(0, frame.y); + return { x, y, @@ -49,8 +90,4 @@ function visiblePart(frame: ReservedRegionFrame, provider: { width: number; heig } ``` -The native platforms have different geometry sources. Avoid assuming identical rectangles for similarly shaped hardware across iOS and Android. - -## Inspect the difference - -The [example app](./example.md) lets you switch between a full-screen provider, a provider inset by 24 points, and a smaller content box. It displays the provider bounds, region frames, and safe area insets together. +On iOS, a frame may include extra space around an obstruction for touch interactions. It may be larger than the obstruction itself. diff --git a/website/docs/example.md b/website/docs/example.md index 1ebe900..8dd3592 100644 --- a/website/docs/example.md +++ b/website/docs/example.md @@ -3,11 +3,11 @@ title: Run the example description: Compare full-screen and inset providers on a native device. --- -The repository includes a React Native `0.88.0-rc.1` app that imports the local library source. It includes `react-native-safe-area-context` to compare safe area insets and reserved region frames. +The example imports the local library source and displays reserved regions alongside safe area measurements. ## Install and launch -Use the Node.js and pnpm versions declared by the repository, along with the native tooling required by the example's React Native version. +Use the Node.js and pnpm versions declared in the repository. Set up Xcode for iOS or Android Studio for Android. ```sh git clone https://github.com/appandflow/react-native-reserved-regions.git @@ -15,7 +15,7 @@ cd react-native-reserved-regions pnpm install ``` -For iOS, install the example's Ruby and CocoaPods dependencies: +For iOS, install the Ruby and CocoaPods dependencies: ```sh cd example @@ -31,7 +31,7 @@ Start Metro: pnpm --filter react-native-reserved-regions-example start ``` -In another terminal at the repository root, launch a platform: +From another terminal at the repository root, launch iOS or Android: ```sh pnpm --filter react-native-reserved-regions-example ios @@ -39,45 +39,36 @@ pnpm --filter react-native-reserved-regions-example ios pnpm --filter react-native-reserved-regions-example android ``` -Build with Xcode containing the iOS 27.1 SDK or later, and run on iOS 27.1 or later to inspect UIKit reserved regions. A build made with an older SDK has these features compiled out, even when installed on a newer runtime. The example adopts `UISceneDelegate` for the RN release candidate's iOS 27 compatibility; see [React Native issue #58606](https://github.com/react/react-native/issues/58606). +See [Getting Started](./installation.md) for platform requirements. -## Inspect provider bounds +## View the measurements -The bottom controls change the measured view: +| Color | Measurement | +| ------------ | --------------- | +| Blue | Provider bounds | +| Dashed green | Safe area edges | +| Orange | Divisions | +| Purple | Occlusions | -| Mode | Provider bounds | -| ----------- | --------------------------------------------------------------------------------------- | -| Full screen | Fills the root view. | -| Shift 40 | Fills the root view, moved 40 points right without changing its size. | -| Inset 24 | Insets top, left, and right by 24 points; leaves 100 points at the bottom for controls. | -| Content box | Uses the same side and bottom insets, with the top at 180 points. | +Zero-width or zero-height divisions are drawn as two-point lines so they remain visible. The text shows their original measurements. -Both providers occupy the blue rectangle. The dashed green outline marks safe area edges. Orange overlays show divisions; purple overlays show occlusions. A zero-width or zero-height division is drawn as a two-point line so it remains visible, while the text displays its native measurement. +The app displays Pending until measurement completes, then Ready. The example displays the regions reported by your device. -Move between modes to inspect how coordinates change and which regions overlap the provider. The displayed data comes from the native platform; the example does not inject mock regions. +## Change the provider bounds -## Folds and cutouts +| Mode | Layout | +| ----------- | ------------------------------------------------------------------------ | +| Full screen | Fills the root view | +| Shift 40 | Moves 40 points right without changing size | +| Inset 24 | Adds 24-point top and side insets, leaving 100 points below for controls | +| Content box | Uses the same side and bottom insets, with the top at 180 points | -On Android, use a foldable emulator profile and change its posture to exercise WindowManager features. Android also offers simulated display cutouts in Developer options. Available features depend on the selected device profile and system image. +Switch modes to compare which regions intersect the provider and how their coordinates change. -On iOS, use the supported simulator controls or a physical device to change the active display or posture. An outer-display screenshot alone does not establish fold-transition support. +## Test folds and cutouts -[Android: test display cutouts](https://developer.android.com/develop/ui/compose/system/test-cutouts) · [Android emulator controls](https://developer.android.com/studio/run/emulator) - -## Library checks +On Android, use a foldable emulator profile and fold or unfold the device. Simulated cutouts are available in Developer options. Available features depend on the device profile and system image. -From the repository root: +On iOS, use supported simulator controls or fold or unfold the device. -```sh -pnpm run format:check -pnpm run lint -pnpm run typecheck -pnpm test -pnpm run build -``` - -## Measurement status - -The example displays Pending until the first measurement, then Ready even when -there are no active regions. Compare these states with the overlays rather than -treating an empty array as evidence that measurement finished. +[Android: test display cutouts](https://developer.android.com/develop/ui/compose/system/test-cutouts) · [Android emulator controls](https://developer.android.com/studio/run/emulator) diff --git a/website/docs/installation.md b/website/docs/installation.md index d8d6053..79e6a08 100644 --- a/website/docs/installation.md +++ b/website/docs/installation.md @@ -1,36 +1,36 @@ --- -title: Installation -description: Install the package and check native platform requirements. +title: Getting Started +description: Set up react-native-reserved-regions. --- -`react-native-reserved-regions` reports display divisions and occlusions relative to a React Native view. Use it to inspect folds, hinges, camera cutouts, and supported system-reserved areas before choosing where to place content. +![React Native Reserved Regions](../../docs/assets/github-banner.jpg) -## Release status +`react-native-reserved-regions` reports folds, hinges, cutouts, and system-reserved areas relative to your React Native views. -The current release is `0.2.0`. See the [release notes](https://github.com/appandflow/react-native-reserved-regions/blob/main/docs/releases/0.2.0.md) -for changes from `0.1.0`, including unclipped Android frames. The first measurement requests -synchronous delivery; see [measurement timing](./performance.md) for its limits. The repository [example](./example.md) -remains useful for testing native behavior on supported devices and simulators. +## Installation -```sh -npm install react-native-reserved-regions -``` +1. Install the package: -## Requirements + ```sh + npm install react-native-reserved-regions + ``` -| Platform | Requirement | -| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| React Native | `0.80` or later with the New Architecture / Fabric. | -| iOS | Build with the iOS 27.1 SDK or later and run on iOS 27.1 or later to receive UIKit reserved regions. Older SDKs compile out reserved-region observation, including on newer devices; older runtimes return empty lists. The deployment minimum follows React Native's CocoaPods requirements. | -| Android | API 24 or later, or your app's higher minimum. Display cutouts require API 28. Folds require device support for Jetpack WindowManager. | +2. For iOS, install CocoaPods dependencies: -Install CocoaPods dependencies after adding the package: + ```sh + cd ios + bundle exec pod install + cd .. + ``` -```sh -cd ios -bundle exec pod install -``` + Android requires no additional setup; React Native links the library automatically. -Android uses React Native autolinking. Rebuild your native app on either platform after installation. This package includes a native Fabric view, so adding the JavaScript dependency alone is insufficient. +3. Rebuild your app. -Continue with [the provider and hook](./usage.md). +:::info Requirements + +- **React Native:** 0.80 or later with the New Architecture enabled. +- **iOS:** Receiving reserved regions requires building with the iOS 27.1 SDK or later and running on iOS 27.1 or later. The library works with older SDKs and runtimes but returns no reserved regions. +- **Android:** API 24 or later. Display cutouts require API 28 or later; fold information requires a supported device. + +::: diff --git a/website/docs/performance.md b/website/docs/performance.md deleted file mode 100644 index 1d8d88a..0000000 --- a/website/docs/performance.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Performance and first render -description: Choose where to measure regions and when to mount dependent content. ---- - -## Start with the provider - -`ReservedRegionsProvider` owns one native view and shares its measurements with -all descendant consumers. Calling `useReservedRegions()` in several components -does not add native views or start separate observations. Use the provider in -place of an existing container where possible, and add nested providers only -when content needs a different coordinate space. - -By default, children mount immediately. Region hooks return `[]` while the first -measurement is pending, then update when geometry is available. Native code -suppresses unchanged region snapshots. This is the simplest option when content -can render before its reserved regions are known. - -## Gate content that needs the first measurement - -`ReservedRegionsGate` returns `null` until the nearest provider is ready. It then -renders its children without adding a native view or a Suspense boundary. - -```tsx -import { ReservedRegionsGate, ReservedRegionsProvider } from 'react-native-reserved-regions'; - -function Screen() { - return ( - - - - - - ); -} -``` - -`Content` first mounts with a measured snapshot, including when that snapshot is -empty. Later region changes update consumers normally; they do not close the -gate or remount the subtree. A new provider starts pending again. - -Gating can avoid rendering an expensive subtree with pending geometry and then -correcting it. It also delays that subtree's mount and effects. It is optional; -measure startup behavior in your app before choosing it as an optimization. - -### Keep the measured view mounted and sized - -The gate belongs **inside** the provider. Its view must have dimensions even when -the gate returns `null`, for example through `flex: 1` in a sized parent or an -explicit width and height. If the measured view gets its size only from gated -children, the initial measurement may never complete. - -A regions gate waits only for reserved regions. It does not establish readiness -for other contexts such as safe area insets. - -### Synchronous delivery - -The first region measurement requests synchronous React delivery. Later changes -are regular events that React receives at the -next event beat, which can be a few frames after the layout that caused them. A gate does not make platform -measurements arrive sooner, and neither mechanism guarantees that the first -visible frame contains content on every React Native/platform combination. diff --git a/website/docs/platforms.md b/website/docs/platforms.md index ac6aed1..e398f8f 100644 --- a/website/docs/platforms.md +++ b/website/docs/platforms.md @@ -5,42 +5,28 @@ description: How UIKit and Jetpack WindowManager map to the public API. ## iOS -When built with the iOS 27.1 SDK or later and running on iOS 27.1 or later, the provider queries UIKit's active `UIView` reserved regions for the division and occlusion kinds. It passes the default query options, which exclude inactive regions. +To receive regions on iOS, build your app with the iOS 27.1 SDK or later and run it on iOS 27.1 or later. Older SDKs or iOS versions return an empty region list. -| UIKit result | JavaScript result | -| ---------------- | -------------------------------------------- | -| Division region | `kind: 'division'`, `occludesContent: false` | -| Occlusion region | `kind: 'occlusion'` | - -The implementation assumes iOS divisions do not hide content. This is a library mapping, not a separate UIKit occlusion property. Occlusion frames can cover hardware or supported system UI and may include interaction margins. - -UIKit returns only regions that intersect the provider, with their full frames in provider coordinates. The library does not clip them to the provider bounds. - -The implementation calls typed UIKit APIs behind both an SDK compile guard and a runtime availability check: +The library uses UIKit to find folds and occluded areas that overlap the provider’s view. Each region includes its position and size. -```objc -#if defined(__IPHONE_27_1) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_27_1 -if (@available(iOS 27.1, *)) { - // The typed UIKit queries are compiled only with a supporting SDK. -} -#endif -``` - -Building with an older SDK compiles out reserved-region observation. Such a build returns empty arrays even on an iOS 27.1 device. A build with a supporting SDK also returns empty arrays on an older runtime. Rebuild with the newer SDK to enable the APIs; a device OS update alone is insufficient. +| **UIKit region** | **Result** | +| ---------------- | -------------------------------------------- | +| Division | `kind: 'division'`, `occludesContent: false` | +| Occlusion | `kind: 'occlusion'` | -Region measurements refresh when the provider lays out, moves into a window, or receives a hinge update through `UIHingeInteraction` on iOS 27.1 or later. Inactive regions are not exposed. +Divisions are reported with `occludesContent: false`. They mark a boundary in the display but don’t block your content. -To test iPhone Duo behavior, use an Xcode and simulator runtime that include it. The 0.1.0 simulator verification exercised closed, partially open, and flat states, -including removal and restoration of a division without changing provider bounds. -Physical Duo hardware and multiple-window behavior remain unverified. +Regions with `kind: 'occlusion'` identify areas where content is hidden, such as a camera cutout or space reserved by iOS. Keep text and controls outside these areas. [Apple: adaptive layouts on iPhone Duo](https://developer.apple.com/videos/play/tech-talks/111463/) ## Android -The library observes Jetpack WindowManager `1.5.1` and reads display cutout bounding rectangles from window insets. +Android requires API 24 or later. Display cutouts require API 28 or later. Fold information depends on device support for Jetpack WindowManager. -| Native result | JavaScript result | +The library reads folds and hinges from Jetpack WindowManager and display cutout rectangles from window insets. + +| **Native result** | **JavaScript result** | | ------------------------------------ | ----------------------------------------------- | | Separating `FoldingFeature` | `division` | | Fully occluding `FoldingFeature` | `division`, even if it is not marked separating | @@ -48,50 +34,40 @@ The library observes Jetpack WindowManager `1.5.1` and reads display cutout boun | Other included folding features | `occludesContent: false` | | Display cutout rectangle on API 28+ | `occlusion` | -Folding features and cutouts that do not intersect the provider are omitted. Those that do keep their full frames in provider coordinates, as on iOS; the library does not clip them to the provider bounds. See [coordinate spaces](./coordinates.md#native-geometry). +A fold or hinge is reported when it separates the display into sections or fully hides content. If the device also has a camera cutout, both can appear in the region list. -A non-separating fold with no full occlusion is omitted. Hardware and posture determine what WindowManager reports; an emulator needs a compatible foldable profile to provide folding features. Cutouts and folds are separate sources, so a provider can receive both kinds at once. +Results can change when the device folds or unfolds. Use a compatible foldable device or emulator to test these changes. -The Android implementation reports display cutouts and the included folding features. It does not report arbitrary overlapping app windows, the keyboard, or system bars as occlusion rectangles. +The library does not report keyboards, system bars, or overlapping app windows as occlusions. [Android: FoldingFeature](https://developer.android.com/reference/androidx/window/layout/FoldingFeature) · [Android: DisplayCutout](https://developer.android.com/reference/android/view/DisplayCutout) ## Other platforms -The fallback component renders a React Native `View` and reports a known empty result after mounting: regions are `[]` and readiness becomes `true`. This does not indicate native support. There is no browser fold or display-cutout integration. +The provider renders a React Native `View`. After mounting, it returns an empty region list and sets readiness to `true`. + +There is no browser fold or display-cutout support. ## Measurement timing -Android takes its first measurement after Fabric mounts the view, when its event -emitter is available and before React Native's event beat, and delivers it -synchronously so gated content mounts with a measured snapshot. Later changes are -regular events that React receives at the next event beat; when several changes -arrive before that beat, React ends with the latest. They are not synchronous -because React Native's `FabricUIManager` accepts one synchronous event per view -and event name per frame and drops the rest, and a rotation changes the regions -more than once in a frame. Later React relayouts are measured in the Android -layout pass. The provider also re-measures when WindowManager -reports new folding features and when window insets reach the provider, which -covers display cutout changes unless an ancestor consumes the insets. Scrolling, -moving an ancestor or transforming the provider does not trigger a measurement. -Older WindowManager extensions may await their first callback. -When a measured provider is detached and re-attached, for example by a list's -`removeClippedSubviews`, it re-measures only if its frame in its parent, the -folding features or the display cutout changed while it was detached. - -On iOS, the provider re-measures when its own layout changes, including a move -that keeps its size, when it moves into a window, and on hinge updates. Scrolling -or moving an ancestor does not trigger a measurement. Neither does a transform or -native-driver animation on the provider, such as a translation, because it does not -change layout. - -iOS measures in `layoutSubviews`. The first measurement after the provider mounts -is a synchronous event, so `ReservedRegionsGate` content can mount with it. React -Native processes that event one frame later unless it includes [react/react-native#58530](https://github.com/react/react-native/pull/58530), -which processes the event beat in the frame that requested it. That change is merged -into React Native's `main` branch but is not in the 0.88 release candidates. -Later changes are regular events that React receives at a later event beat. When -several changes happen before JavaScript processes them, the intermediate ones are -usually coalesced, and React always ends with the latest. -Readiness means the provider has completed a measurement; it is not a guarantee -that every layout change is visible in its first frame. +The provider measures regions when its layout or the supported device features change. + +| iOS | Android | +| -------------------------------- | ----------------------------------- | +| The provider lays out | The provider mounts or lays out | +| The provider moves into a window | WindowManager reports a fold change | +| A hinge update arrives | Window insets reach the provider | + +Scrolling, moving a parent view, or applying a transform does not trigger a measurement. + +On Android: + +- Older WindowManager extensions may wait for their first result before the provider becomes ready. +- A parent view that consumes window insets can prevent cutout updates from reaching the provider. +- After a provider is detached and reattached, it only measures again if its position or size within its parent, folding features, or cutout changed while detached. + +The first measurement requests synchronous delivery to React. Later measurements use regular events. React Native limits synchronous delivery to one event per view and event name per frame, so regular events allow later changes in the same frame to be delivered. Intermediate updates may be combined before JavaScript processes them. + +On iOS, processing the first measurement in the same frame requires [React Native #58530](https://github.com/react/react-native/pull/58530). The example’s React Native `0.88.0-rc.1` does not include it. + +Readiness confirms that a measurement has completed. It does not guarantee that the resulting layout appears in the first visible frame. diff --git a/website/docs/safe-area.md b/website/docs/safe-area.md index 61461ef..bc22a43 100644 --- a/website/docs/safe-area.md +++ b/website/docs/safe-area.md @@ -3,20 +3,15 @@ title: Alongside safe area context description: Compare edge insets with reserved rectangles inside a view. --- -Safe area insets and reserved regions answer different layout questions. +`react-native-safe-area-context` returns four edge insets: top, right, bottom, and left. `react-native-reserved-regions` returns frames for folds, hinges, and occluded areas. -| | `react-native-safe-area-context` | `react-native-reserved-regions` | -| ---------------- | --------------------------------------------- | --------------------------------------------- | -| Geometry | Four edge distances: top, right, bottom, left | A list of frames and region kinds | -| Typical use | Keep content within safe edges | Inspect a fold, hinge, or occluded area | -| Coordinate scope | Nearest safe area provider | Nearest reserved regions provider | -| Layout behavior | Offers hooks and `SafeAreaView` | Reports geometry; your app chooses the layout | +A hinge in the middle of a display cannot be represented by edge insets alone. Use both libraries when your layout needs both measurements. -Four edge distances cannot describe every obstruction in the middle of a display. A region list also does not replace normal system bar or keyboard handling. Use both libraries when your screen needs both kinds of information. +`react-native-safe-area-context` is an optional dependency and must be installed separately. -## Match the provider bounds +## Using both providers -For a direct comparison, make both provider views occupy the same rectangle: +Give both providers the same bounds when comparing their measurements: ```tsx import { SafeAreaProvider } from 'react-native-safe-area-context'; @@ -33,6 +28,13 @@ function MeasuredPanel() { } ``` -`PanelContent` can call `useSafeAreaInsets()` and `useReservedRegions()`. These providers add no padding in this example. If you put a padded `SafeAreaView` between them, their measured bounds may differ, and direct numerical comparisons need to account for that. +Inside `PanelContent`, read the measurements with their respective hooks: -`react-native-safe-area-context` is an optional app dependency. The reserved regions library does not depend on it; the example includes it to show both measurements. +```tsx +const insets = useSafeAreaInsets(); +const regions = useReservedRegions(); +``` + +Each hook reads from its own provider. If the providers have different positions or sizes, account for that difference when comparing their values. + +Reserved regions do not report keyboard bounds or provide keyboard avoidance. diff --git a/website/docs/usage.md b/website/docs/usage.md index b0e0cf1..154de51 100644 --- a/website/docs/usage.md +++ b/website/docs/usage.md @@ -1,93 +1,52 @@ --- -title: Provider and hook -description: Read reserved regions from the nearest provider. +title: Usage +description: Read reserved regions in your app. --- -Give the provider the bounds of the content you want to inspect. Descendants read its regions with `useReservedRegions()`. +Wrap your content with `ReservedRegionsProvider` and read regions from a child component: ```tsx -import { Text, View } from 'react-native'; +import { Text } from 'react-native'; import { ReservedRegionsProvider, useReservedRegions, useReservedRegionsReady } from 'react-native-reserved-regions'; -function RegionSummary() { +function Content() { const regions = useReservedRegions(); const isReady = useReservedRegionsReady(); - if (!isReady) return Measuring reserved regions…; - - return ( - - {regions.length} active reserved regions - {regions.map((region, index) => ( - - {region.kind}: {region.frame.x}, {region.frame.y} - {' · '} - {region.frame.width} × {region.frame.height} - {region.kind === 'division' ? ` · content ${region.occludesContent ? 'hidden' : 'visible'}` : ''} - - ))} - - ); + return {isReady ? `${regions.length} reserved regions` : 'Measuring…'}; } export default function App() { return ( - + ); } ``` -The provider accepts standard React Native `View` props, including `style` and `onLayout`. It measures its own native view and supplies region data; it does not pad, split, or reposition your content. - -## Why a provider and a hook? - -The provider defines **which view the geometry belongs to**. For example, a fold -at `x = 300` in a full-screen provider would be at `x = 276` in a panel whose left -edge is 24 points farther right, if the fold still intersects that panel. A hook -with only a window snapshot could not know which panel's coordinates you need. - -`ReservedRegionsProvider` renders a native view so it can measure that view's -position and bounds. React context shares the resulting snapshot with its -descendants; `useReservedRegions()` reads the nearest snapshot without rendering -another view. Multiple consumers can share one provider. Add a nested provider -when a panel needs its own coordinate space, and use the provider in place of an -existing container `View` where possible. - -[react-native-hinges](https://appandflow.github.io/react-native-hinges/docs/usage) -uses the existing React root as its observation scope. Posture and angle do not -change just because a child panel moves, so `useHinges()` needs no extra provider -or native view. The libraries can be used together: hinge readings drive behavior -or animation, while reserved regions supply the geometry for layout. A division -rectangle and a hinge reading have no shared ID or guaranteed array-index mapping. - -The provider's own position and bounds determine the geometry; placing a consumer -inside a nested child `View` does not change the coordinate origin. See -[coordinate spaces](./coordinates.md) for platform details. - -## First render and updates - -`useReservedRegions()` initially returns `[]`; `useReservedRegionsReady()` initially returns `false`. The first measurement updates both together, including when the result is empty. Readiness then stays true for that provider's lifetime. A newly mounted provider starts pending. Use readiness to distinguish waiting for an initial result from a measured empty array. +Each region’s coordinates are relative to the nearest provider. Use these regions to adjust your layout—the provider itself doesn’t add padding or move your content. -Native measurements arrive during iOS layout. On Android the first measurement follows Fabric mounting; later React relayouts of the provider, folding feature updates and window inset changes are measured again. Scrolling, moving an ancestor or transforming the provider does not trigger a measurement. Android uses the current WindowManager result when extension version 9 or later is available; otherwise it waits for the first layout-info callback before publishing. Unsupported backends report an empty result. Without an Activity, Android cannot query folding features and reports only any available display cutouts. There is no timeout that turns missing data into readiness. +Use `useReservedRegionsReady()` to check whether measurement is complete. While measurement is still pending, `useReservedRegions()` returns an empty array. -Give the provider nonzero dimensions even while rendering a placeholder. A provider whose size depends entirely on children that are hidden until readiness can otherwise remain pending. The unsupported-platform fallback reports a known empty result after mounting. Readiness means an initial result is available, not that the device supports reserved regions or that future geometry cannot change. +## Wait before rendering -Native code suppresses unchanged region snapshots. The first measurement requests synchronous React delivery; later changes are regular events that React receives at a later event beat. The first visible frame still depends on React Native scheduling and when the platform supplies its geometry; synchronous dispatch alone is not a first-frame guarantee. +Wrap content in `ReservedRegionsGate` to mount it after the first measurement, including when no regions are found. -Calling either hook outside a provider throws. Nested providers each establish a coordinate space; a consumer always reads the nearest one. - -## Mounting content after measurement - -The optional [`ReservedRegionsGate`](./performance.md#gate-content-that-needs-the-first-measurement) -can delay mounting descendants until the provider is ready. The default provider -continues to render children immediately. See [performance and first render](./performance.md) -for placement and sizing considerations. +```tsx +import { ReservedRegionsGate, ReservedRegionsProvider } from 'react-native-reserved-regions'; -## Decide what to avoid +function Screen() { + return ( + + + + + + ); +} +``` -- A `division` describes a display split. Content can still be visible across it when `occludesContent` is `false`; your layout may benefit from placing controls on either side. -- An `occlusion` describes a reserved area where content is hidden. Treat its reported bounds as an area to avoid for important content and controls. +Keep the gate inside a provider that has a size, such as `flex: 1` in a sized parent. If the provider depends on the hidden content for its size, measurement may never complete. -Use `kind` to narrow the [tagged union](./api.md). Regions have no public stable ID or guaranteed ordering; use their geometry and kind when making layout decisions. +See the [API reference](./api.md) for region types and available props. diff --git a/website/docusaurus.config.mjs b/website/docusaurus.config.mjs index 0804631..3cb73dc 100644 --- a/website/docusaurus.config.mjs +++ b/website/docusaurus.config.mjs @@ -28,7 +28,7 @@ export default { colorMode: { defaultMode: 'light', respectPrefersColorScheme: true }, navbar: { title: 'Reserved Regions', - logo: { alt: '', src: 'img/mark.svg' }, + logo: { alt: '', src: 'img/logo.png' }, items: [ { type: 'docSidebar', sidebarId: 'docs', label: 'Documentation', position: 'left' }, { to: '/docs/api', label: 'API', position: 'left' }, diff --git a/website/sidebars.mjs b/website/sidebars.mjs index 0a45ed4..7c4dab6 100644 --- a/website/sidebars.mjs +++ b/website/sidebars.mjs @@ -1,9 +1,8 @@ export default { docs: [ 'installation', + { type: 'category', label: 'How regions work', items: ['coordinates', 'safe-area', 'platforms'] }, 'usage', - 'performance', - { type: 'category', label: 'Understand regions', items: ['coordinates', 'safe-area', 'platforms'] }, 'api', 'example', ], diff --git a/website/src/css/custom.css b/website/src/css/custom.css index a6b4ce4..a77ffa1 100644 --- a/website/src/css/custom.css +++ b/website/src/css/custom.css @@ -23,13 +23,13 @@ } :root { - --ifm-color-primary: #315de0; - --ifm-color-primary-dark: #204ccd; - --ifm-color-primary-darker: #1e48c2; - --ifm-color-primary-darkest: #193b9f; - --ifm-color-primary-light: #496fe4; - --ifm-color-primary-lighter: #5578e6; - --ifm-color-primary-lightest: #7b96ec; + --ifm-color-primary: #008cff; + --ifm-color-primary-dark: #007ee6; + --ifm-color-primary-darker: #0077d9; + --ifm-color-primary-darkest: #0062b3; + --ifm-color-primary-light: #1a98ff; + --ifm-color-primary-lighter: #26a0ff; + --ifm-color-primary-lightest: #4dafff; --ifm-font-family-base: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; --ifm-heading-font-weight: 650; --ifm-font-size-base: 16px; @@ -48,13 +48,13 @@ } [data-theme='dark'] { - --ifm-color-primary: #9bb6ff; - --ifm-color-primary-dark: #759aff; - --ifm-color-primary-darker: #618bff; - --ifm-color-primary-darkest: #285dff; - --ifm-color-primary-light: #c1d2ff; - --ifm-color-primary-lighter: #d5e0ff; - --ifm-color-primary-lightest: #fff; + --ifm-color-primary: #008cff; + --ifm-color-primary-dark: #007ee6; + --ifm-color-primary-darker: #0077d9; + --ifm-color-primary-darkest: #0062b3; + --ifm-color-primary-light: #1a98ff; + --ifm-color-primary-lighter: #26a0ff; + --ifm-color-primary-lightest: #4dafff; --ifm-background-color: #101725; --ifm-background-surface-color: #161f30; --ifm-navbar-background-color: #101725; @@ -101,12 +101,12 @@ } .button--primary:not(.button--outline) { color: #fff; - background: #315de0; - border-color: #315de0; + background: var(--ifm-color-primary); + border-color: var(--ifm-color-primary); } .button--primary:not(.button--outline):hover { - background: #204ccd; - border-color: #204ccd; + background: var(--ifm-color-primary-dark); + border-color: var(--ifm-color-primary-dark); } a:focus-visible, button:focus-visible {