Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

native-layout-metrics.tsx

40 lines1.5 KB

1import { createContext, use, useState, type ReactNode } from "react";
2import { Platform } from "react-native";
3import { deriveDeviceType, type DeviceType } from "../lib/device-type";
4import type { NativeLayoutMetrics } from "../lib/reserved-regions";
5import { NativeLayoutObserver } from "./NativeLayoutObserver";
6​
7const IS_PAD = Platform.OS === "ios" && Platform.isPad;
8​
9const NativeLayoutContext = createContext<NativeLayoutMetrics | null>(null);
10// Separate from the metrics so device checks skip every resize and safe-area update.
11const DeviceTypeContext = createContext<DeviceType>(
12 deriveDeviceType({ isPad: IS_PAD, metrics: null }),
13);
14// Column reservations come from UIKit's layout, outside the resizing navigator.
15export const NativeColumnLayoutMetricsContext = createContext<NativeLayoutMetrics | null>(null);
16​
17export function NativeLayoutMetricsProvider(props: { readonly children: ReactNode }) {
18 const [metrics, setMetrics] = useState<NativeLayoutMetrics | null>(null);
19 const deviceType = deriveDeviceType({ isPad: IS_PAD, metrics });
20 return (
21 <NativeLayoutContext value={metrics}>
22 <DeviceTypeContext value={deviceType}>
23 <NativeLayoutObserver onChange={setMetrics} />
24 {props.children}
25 </DeviceTypeContext>
26 </NativeLayoutContext>
27 );
29​
30export function useNativeLayoutMetrics() {
31 return use(NativeLayoutContext);
33​
34export function useNativeColumnLayoutMetrics() {
35 return use(NativeColumnLayoutMetricsContext);
37​
38export function useDeviceType() {
39 return use(DeviceTypeContext);