react-native-everything-responsive 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/LICENSE +21 -0
- package/README.md +459 -2
- package/docs/API.md +311 -0
- package/lib/core/breakpoints.d.ts +28 -0
- package/lib/core/breakpoints.d.ts.map +1 -0
- package/lib/core/breakpoints.js +108 -0
- package/lib/core/breakpoints.js.map +1 -0
- package/lib/core/config.d.ts +24 -0
- package/lib/core/config.d.ts.map +1 -0
- package/lib/core/config.js +112 -0
- package/lib/core/config.js.map +1 -0
- package/lib/core/device.d.ts +31 -0
- package/lib/core/device.d.ts.map +1 -0
- package/lib/core/device.js +35 -0
- package/lib/core/device.js.map +1 -0
- package/lib/core/grid.d.ts +30 -0
- package/lib/core/grid.d.ts.map +1 -0
- package/lib/core/grid.js +37 -0
- package/lib/core/grid.js.map +1 -0
- package/lib/core/info.d.ts +26 -0
- package/lib/core/info.d.ts.map +1 -0
- package/lib/core/info.js +41 -0
- package/lib/core/info.js.map +1 -0
- package/lib/core/layout.d.ts +4 -0
- package/lib/core/layout.d.ts.map +1 -0
- package/lib/core/layout.js +31 -0
- package/lib/core/layout.js.map +1 -0
- package/lib/core/scaling.d.ts +28 -0
- package/lib/core/scaling.d.ts.map +1 -0
- package/lib/core/scaling.js +47 -0
- package/lib/core/scaling.js.map +1 -0
- package/lib/core/types.d.ts +153 -0
- package/lib/core/types.d.ts.map +1 -0
- package/lib/core/types.js +8 -0
- package/lib/core/types.js.map +1 -0
- package/lib/index.d.ts +26 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +54 -0
- package/lib/index.js.map +1 -0
- package/lib/native/ResponsiveGrid.d.ts +61 -0
- package/lib/native/ResponsiveGrid.d.ts.map +1 -0
- package/lib/native/ResponsiveGrid.js +110 -0
- package/lib/native/ResponsiveGrid.js.map +1 -0
- package/lib/native/ResponsiveProvider.d.ts +19 -0
- package/lib/native/ResponsiveProvider.d.ts.map +1 -0
- package/lib/native/ResponsiveProvider.js +26 -0
- package/lib/native/ResponsiveProvider.js.map +1 -0
- package/lib/native/ResponsiveView.d.ts +30 -0
- package/lib/native/ResponsiveView.d.ts.map +1 -0
- package/lib/native/ResponsiveView.js +51 -0
- package/lib/native/ResponsiveView.js.map +1 -0
- package/lib/native/Visibility.d.ts +45 -0
- package/lib/native/Visibility.d.ts.map +1 -0
- package/lib/native/Visibility.js +53 -0
- package/lib/native/Visibility.js.map +1 -0
- package/lib/native/context.d.ts +6 -0
- package/lib/native/context.d.ts.map +1 -0
- package/lib/native/context.js +12 -0
- package/lib/native/context.js.map +1 -0
- package/lib/native/createStyles.d.ts +46 -0
- package/lib/native/createStyles.d.ts.map +1 -0
- package/lib/native/createStyles.js +68 -0
- package/lib/native/createStyles.js.map +1 -0
- package/lib/native/hooks.d.ts +33 -0
- package/lib/native/hooks.d.ts.map +1 -0
- package/lib/native/hooks.js +68 -0
- package/lib/native/hooks.js.map +1 -0
- package/lib/native/platform.d.ts +10 -0
- package/lib/native/platform.d.ts.map +1 -0
- package/lib/native/platform.js +50 -0
- package/lib/native/platform.js.map +1 -0
- package/lib/native/snapshot.d.ts +8 -0
- package/lib/native/snapshot.d.ts.map +1 -0
- package/lib/native/snapshot.js +29 -0
- package/lib/native/snapshot.js.map +1 -0
- package/lib/native/store.d.ts +14 -0
- package/lib/native/store.d.ts.map +1 -0
- package/lib/native/store.js +51 -0
- package/lib/native/store.js.map +1 -0
- package/package.json +50 -4
- package/src/core/breakpoints.ts +101 -0
- package/src/core/config.ts +130 -0
- package/src/core/device.ts +46 -0
- package/src/core/grid.ts +54 -0
- package/src/core/info.ts +64 -0
- package/src/core/layout.ts +44 -0
- package/src/core/scaling.ts +62 -0
- package/src/core/types.ts +178 -0
- package/src/index.ts +59 -0
- package/src/native/ResponsiveGrid.tsx +159 -0
- package/src/native/ResponsiveProvider.tsx +30 -0
- package/src/native/ResponsiveView.tsx +98 -0
- package/src/native/Visibility.tsx +82 -0
- package/src/native/context.ts +11 -0
- package/src/native/createStyles.ts +94 -0
- package/src/native/hooks.ts +102 -0
- package/src/native/platform.ts +54 -0
- package/src/native/snapshot.ts +27 -0
- package/src/native/store.ts +58 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import React, { useCallback, useContext, useMemo, useState } from 'react';
|
|
2
|
+
import { View } from 'react-native';
|
|
3
|
+
import type { LayoutChangeEvent, ViewProps } from 'react-native';
|
|
4
|
+
import { mergeBreakpoints } from '../core/config';
|
|
5
|
+
import { createLayoutInfo } from '../core/layout';
|
|
6
|
+
import type { BreakpointKey } from '../core/types';
|
|
7
|
+
import { ConfigContext, ContainerContext } from './context';
|
|
8
|
+
import { roundToPixel } from './platform';
|
|
9
|
+
import { getSnapshot } from './store';
|
|
10
|
+
|
|
11
|
+
export interface ResponsiveViewProps extends ViewProps {
|
|
12
|
+
/** Custom breakpoints for this container only (merged over the global ones). */
|
|
13
|
+
breakpoints?: Partial<Record<BreakpointKey, number>>;
|
|
14
|
+
/**
|
|
15
|
+
* Width to assume before the first layout pass. Default: the parent container's width,
|
|
16
|
+
* or the window width. Set it when you know the container is narrow (e.g. a sidebar)
|
|
17
|
+
* to avoid a one-frame flash of the wide layout.
|
|
18
|
+
*/
|
|
19
|
+
initialWidth?: number;
|
|
20
|
+
/** Height to assume before the first layout pass. */
|
|
21
|
+
initialHeight?: number;
|
|
22
|
+
/** Render children only after the container has been measured. Default false. */
|
|
23
|
+
waitForLayout?: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface MeasuredSize {
|
|
27
|
+
width: number;
|
|
28
|
+
height: number;
|
|
29
|
+
measured: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A `View` that turns itself into a **container query** boundary.
|
|
34
|
+
*
|
|
35
|
+
* Every hook, `createStyles`, `<Show>`, `<Hide>` and `<ResponsiveGrid>` inside it measures
|
|
36
|
+
* this view instead of the window (unless they ask for `source: 'window'`). The same card
|
|
37
|
+
* component can then lay out as "wide" in a main column and "narrow" in a sidebar,
|
|
38
|
+
* which window-based media queries cannot do.
|
|
39
|
+
*
|
|
40
|
+
* Prefer width-based logic inside containers: when children change the container's
|
|
41
|
+
* height based on the container's height, layouts can oscillate.
|
|
42
|
+
*/
|
|
43
|
+
export function ResponsiveView({
|
|
44
|
+
breakpoints,
|
|
45
|
+
initialWidth,
|
|
46
|
+
initialHeight,
|
|
47
|
+
waitForLayout = false,
|
|
48
|
+
onLayout,
|
|
49
|
+
children,
|
|
50
|
+
...viewProps
|
|
51
|
+
}: ResponsiveViewProps): React.JSX.Element {
|
|
52
|
+
const config = useContext(ConfigContext);
|
|
53
|
+
const parent = useContext(ContainerContext);
|
|
54
|
+
|
|
55
|
+
const [size, setSize] = useState<MeasuredSize>(() => {
|
|
56
|
+
const { window } = getSnapshot();
|
|
57
|
+
return {
|
|
58
|
+
width: initialWidth ?? parent?.width ?? window.width,
|
|
59
|
+
height: initialHeight ?? parent?.height ?? window.height,
|
|
60
|
+
measured: false,
|
|
61
|
+
};
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const breakpointsKey = breakpoints ? JSON.stringify(breakpoints) : '';
|
|
65
|
+
const table = useMemo(
|
|
66
|
+
() => mergeBreakpoints(config.breakpoints, breakpoints),
|
|
67
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
68
|
+
[config.breakpoints, breakpointsKey],
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
const handleLayout = useCallback(
|
|
72
|
+
(event: LayoutChangeEvent) => {
|
|
73
|
+
const { width, height } = event.nativeEvent.layout;
|
|
74
|
+
setSize((previous) =>
|
|
75
|
+
previous.measured &&
|
|
76
|
+
Math.abs(previous.width - width) < 0.5 &&
|
|
77
|
+
Math.abs(previous.height - height) < 0.5
|
|
78
|
+
? previous
|
|
79
|
+
: { width, height, measured: true },
|
|
80
|
+
);
|
|
81
|
+
onLayout?.(event);
|
|
82
|
+
},
|
|
83
|
+
[onLayout],
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
const layout = useMemo(
|
|
87
|
+
() => createLayoutInfo('container', size.width, size.height, table, roundToPixel),
|
|
88
|
+
[size.width, size.height, table],
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
return (
|
|
92
|
+
<View {...viewProps} onLayout={handleLayout}>
|
|
93
|
+
<ContainerContext.Provider value={layout}>
|
|
94
|
+
{waitForLayout && !size.measured ? null : children}
|
|
95
|
+
</ContainerContext.Provider>
|
|
96
|
+
</View>
|
|
97
|
+
);
|
|
98
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import type { ReactNode } from 'react';
|
|
3
|
+
import { View } from 'react-native';
|
|
4
|
+
import type { BreakpointKey, DeviceType, Orientation, ResponsiveInfo } from '../core/types';
|
|
5
|
+
import { useResponsive } from './hooks';
|
|
6
|
+
import type { SourceOptions } from './hooks';
|
|
7
|
+
|
|
8
|
+
export interface VisibilityConditions extends SourceOptions {
|
|
9
|
+
/** Match at this breakpoint and larger. */
|
|
10
|
+
from?: BreakpointKey;
|
|
11
|
+
/** Match strictly below this breakpoint. */
|
|
12
|
+
below?: BreakpointKey;
|
|
13
|
+
/** Match only at these breakpoints. */
|
|
14
|
+
only?: BreakpointKey | readonly BreakpointKey[];
|
|
15
|
+
/** Match only on these device types (hardware). */
|
|
16
|
+
device?: DeviceType | readonly DeviceType[];
|
|
17
|
+
/** Match only in this orientation (of the measured area). */
|
|
18
|
+
orientation?: Orientation;
|
|
19
|
+
/** Custom predicate, for anything the props above cannot express. */
|
|
20
|
+
when?: (r: ResponsiveInfo) => boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface VisibilityProps extends VisibilityConditions {
|
|
24
|
+
children?: ReactNode;
|
|
25
|
+
/** Rendered instead of `children` when hidden. */
|
|
26
|
+
fallback?: ReactNode;
|
|
27
|
+
/**
|
|
28
|
+
* `'unmount'` (default) removes hidden children from the tree.
|
|
29
|
+
* `'hide'` keeps them mounted (state, video playback and scroll position are preserved)
|
|
30
|
+
* inside a wrapper View with `display: 'none'`.
|
|
31
|
+
*/
|
|
32
|
+
mode?: 'unmount' | 'hide';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const asArray = <T,>(value: T | readonly T[]): readonly T[] =>
|
|
36
|
+
Array.isArray(value) ? (value as readonly T[]) : [value as T];
|
|
37
|
+
|
|
38
|
+
/** True when every given condition matches. Conditions that are not given are ignored. */
|
|
39
|
+
export function matchesConditions(r: ResponsiveInfo, c: VisibilityConditions): boolean {
|
|
40
|
+
if (c.from !== undefined && !r.from(c.from)) return false;
|
|
41
|
+
if (c.below !== undefined && !r.below(c.below)) return false;
|
|
42
|
+
if (c.only !== undefined && !r.only(...asArray(c.only))) return false;
|
|
43
|
+
if (c.device !== undefined && !asArray(c.device).includes(r.deviceType)) return false;
|
|
44
|
+
if (c.orientation !== undefined && r.orientation !== c.orientation) return false;
|
|
45
|
+
if (c.when !== undefined && !c.when(r)) return false;
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Hook form of `<Show>`: true when all conditions match. */
|
|
50
|
+
export function useMatches(conditions: VisibilityConditions): boolean {
|
|
51
|
+
const r = useResponsive({ source: conditions.source });
|
|
52
|
+
return matchesConditions(r, conditions);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function render(visible: boolean, { children, fallback, mode = 'unmount' }: VisibilityProps): React.JSX.Element {
|
|
56
|
+
if (mode === 'hide') {
|
|
57
|
+
return (
|
|
58
|
+
<>
|
|
59
|
+
<View style={{ display: visible ? 'flex' : 'none' }}>{children}</View>
|
|
60
|
+
{!visible && fallback}
|
|
61
|
+
</>
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return <>{visible ? children : fallback ?? null}</>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Renders children only when **all** given conditions match.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* <Show from="md">Sidebar</Show>
|
|
72
|
+
* <Show below="md" fallback={<FullMenu />}><HamburgerMenu /></Show>
|
|
73
|
+
* <Show device="tablet" orientation="landscape">Two-pane layout</Show>
|
|
74
|
+
*/
|
|
75
|
+
export function Show(props: VisibilityProps): React.JSX.Element {
|
|
76
|
+
return render(useMatches(props), props);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The opposite of `<Show>`: hides children when **all** given conditions match. */
|
|
80
|
+
export function Hide(props: VisibilityProps): React.JSX.Element {
|
|
81
|
+
return render(!useMatches(props), props);
|
|
82
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createContext } from 'react';
|
|
2
|
+
import { DEFAULT_CONFIG } from '../core/config';
|
|
3
|
+
import type { LayoutInfo, ResponsiveConfig } from '../core/types';
|
|
4
|
+
|
|
5
|
+
/** Resolved configuration. Works without a provider (uses defaults). */
|
|
6
|
+
export const ConfigContext = createContext<ResponsiveConfig>(DEFAULT_CONFIG);
|
|
7
|
+
ConfigContext.displayName = 'ResponsiveConfig';
|
|
8
|
+
|
|
9
|
+
/** Layout of the nearest `<ResponsiveView>`, or null outside any container. */
|
|
10
|
+
export const ContainerContext = createContext<LayoutInfo | null>(null);
|
|
11
|
+
ContainerContext.displayName = 'ResponsiveContainer';
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { useMemo } from 'react';
|
|
2
|
+
import type { DependencyList } from 'react';
|
|
3
|
+
import type { ImageStyle, TextStyle, ViewStyle } from 'react-native';
|
|
4
|
+
import { resolveDeep } from '../core/breakpoints';
|
|
5
|
+
import type {
|
|
6
|
+
BreakpointKey,
|
|
7
|
+
ResolvedStyles,
|
|
8
|
+
ResponsiveInfo,
|
|
9
|
+
ResponsiveValue,
|
|
10
|
+
} from '../core/types';
|
|
11
|
+
import { useBreakpoint, useResponsive } from './hooks';
|
|
12
|
+
import type { SourceOptions } from './hooks';
|
|
13
|
+
|
|
14
|
+
/** A style object where every property may be a responsive value. */
|
|
15
|
+
export type ResponsiveStyle<S> = { [K in keyof S]?: ResponsiveValue<S[K]> };
|
|
16
|
+
|
|
17
|
+
export type AnyResponsiveStyle =
|
|
18
|
+
| ResponsiveStyle<ViewStyle>
|
|
19
|
+
| ResponsiveStyle<TextStyle>
|
|
20
|
+
| ResponsiveStyle<ImageStyle>;
|
|
21
|
+
|
|
22
|
+
/** Named responsive styles, the input to `createStyles`. */
|
|
23
|
+
export type ResponsiveNamedStyles<T> = { [P in keyof T]: AnyResponsiveStyle };
|
|
24
|
+
|
|
25
|
+
type StyleFactory<T> = (r: ResponsiveInfo) => T & ResponsiveNamedStyles<T>;
|
|
26
|
+
|
|
27
|
+
/** Resolves every responsive value in a named style sheet for one breakpoint. */
|
|
28
|
+
export function resolveStyles<T>(sheet: T, breakpoint: BreakpointKey): ResolvedStyles<T> {
|
|
29
|
+
const out: Record<string, unknown> = {};
|
|
30
|
+
for (const name of Object.keys(sheet as object)) {
|
|
31
|
+
out[name] = resolveDeep((sheet as Record<string, unknown>)[name], breakpoint);
|
|
32
|
+
}
|
|
33
|
+
return out as ResolvedStyles<T>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Defines responsive styles once, outside the component, and returns a hook.
|
|
38
|
+
*
|
|
39
|
+
* - Any style property can be a responsive object: `padding: { xs: 12, md: 24 }`.
|
|
40
|
+
* - Pass a function to also use scaling and device info: `(r) => ({ ... r.s(16) ... })`.
|
|
41
|
+
* - Results are memoised. A static object re-computes only when the breakpoint changes.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* const useStyles = createStyles((r) => ({
|
|
45
|
+
* root: { padding: r.s(16), flexDirection: { xs: 'column', md: 'row' } },
|
|
46
|
+
* title: { fontSize: r.fs(20), fontWeight: '700' },
|
|
47
|
+
* }));
|
|
48
|
+
*
|
|
49
|
+
* function Card() {
|
|
50
|
+
* const styles = useStyles();
|
|
51
|
+
* return <View style={styles.root}><Text style={styles.title}>Hi</Text></View>;
|
|
52
|
+
* }
|
|
53
|
+
*/
|
|
54
|
+
export function createStyles<T extends ResponsiveNamedStyles<T>>(
|
|
55
|
+
stylesOrFactory: StyleFactory<T> | (T & ResponsiveNamedStyles<T>),
|
|
56
|
+
options?: SourceOptions,
|
|
57
|
+
): () => ResolvedStyles<T> {
|
|
58
|
+
if (typeof stylesOrFactory === 'function') {
|
|
59
|
+
const factory = stylesOrFactory;
|
|
60
|
+
return function useResponsiveStyleSheet(): ResolvedStyles<T> {
|
|
61
|
+
const r = useResponsive(options);
|
|
62
|
+
return useMemo(() => resolveStyles(factory(r), r.breakpoint), [r]);
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const sheet = stylesOrFactory;
|
|
66
|
+
const cache = new Map<BreakpointKey, ResolvedStyles<T>>();
|
|
67
|
+
return function useStaticResponsiveStyleSheet(): ResolvedStyles<T> {
|
|
68
|
+
const breakpoint = useBreakpoint(options);
|
|
69
|
+
let resolved = cache.get(breakpoint);
|
|
70
|
+
if (!resolved) {
|
|
71
|
+
resolved = resolveStyles(sheet, breakpoint);
|
|
72
|
+
cache.set(breakpoint, resolved);
|
|
73
|
+
}
|
|
74
|
+
return resolved;
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Inline variant of `createStyles` for styles that depend on props or state.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* const styles = useResponsiveStyles((r) => ({
|
|
83
|
+
* box: { width: r.select({ xs: '100%', md: size }) },
|
|
84
|
+
* }), [size]);
|
|
85
|
+
*/
|
|
86
|
+
export function useResponsiveStyles<T extends ResponsiveNamedStyles<T>>(
|
|
87
|
+
factory: StyleFactory<T>,
|
|
88
|
+
deps: DependencyList,
|
|
89
|
+
options?: SourceOptions,
|
|
90
|
+
): ResolvedStyles<T> {
|
|
91
|
+
const r = useResponsive(options);
|
|
92
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
93
|
+
return useMemo(() => resolveStyles(factory(r), r.breakpoint), [r, ...deps]);
|
|
94
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { useCallback, useContext, useMemo, useSyncExternalStore } from 'react';
|
|
2
|
+
import { getBreakpoint, resolveResponsiveValue } from '../core/breakpoints';
|
|
3
|
+
import { classifyDevice } from '../core/device';
|
|
4
|
+
import { createResponsiveInfo } from '../core/info';
|
|
5
|
+
import type {
|
|
6
|
+
BreakpointKey,
|
|
7
|
+
LayoutInfo,
|
|
8
|
+
LayoutSource,
|
|
9
|
+
Narrowable,
|
|
10
|
+
ResponsiveConfig,
|
|
11
|
+
ResponsiveInfo,
|
|
12
|
+
ResponsiveObject,
|
|
13
|
+
ResponsiveValue,
|
|
14
|
+
SelectResult,
|
|
15
|
+
} from '../core/types';
|
|
16
|
+
import { ConfigContext, ContainerContext } from './context';
|
|
17
|
+
import { getDeviceEnvironment, roundToPixel, warnOnce } from './platform';
|
|
18
|
+
import { getSnapshot, subscribe } from './store';
|
|
19
|
+
|
|
20
|
+
export interface SourceOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Which area to measure. Default `'auto'`: nearest `<ResponsiveView>` if any,
|
|
23
|
+
* otherwise the window.
|
|
24
|
+
*/
|
|
25
|
+
source?: LayoutSource;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function pickContainer(source: LayoutSource, container: LayoutInfo | null): LayoutInfo | null {
|
|
29
|
+
if (source === 'container' && !container) {
|
|
30
|
+
warnOnce('source "container" was requested but there is no <ResponsiveView> ancestor; using the window.');
|
|
31
|
+
}
|
|
32
|
+
return source === 'window' ? null : container;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Returns the resolved configuration from the nearest provider (or the defaults). */
|
|
36
|
+
export function useResponsiveConfig(): ResponsiveConfig {
|
|
37
|
+
return useContext(ConfigContext);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The main hook: layout, breakpoints, device type and scaling in one object.
|
|
42
|
+
* Re-renders when the window, screen, font scale or nearest container changes.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* const r = useResponsive();
|
|
46
|
+
* <View style={{ padding: r.s(16), flexDirection: r.from('md') ? 'row' : 'column' }} />
|
|
47
|
+
*/
|
|
48
|
+
export function useResponsive(options?: SourceOptions): ResponsiveInfo {
|
|
49
|
+
const config = useContext(ConfigContext);
|
|
50
|
+
const containerContext = useContext(ContainerContext);
|
|
51
|
+
const source = options?.source ?? 'auto';
|
|
52
|
+
const container = pickContainer(source, containerContext);
|
|
53
|
+
const { window, screen } = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
54
|
+
|
|
55
|
+
return useMemo(
|
|
56
|
+
() =>
|
|
57
|
+
createResponsiveInfo({
|
|
58
|
+
window,
|
|
59
|
+
screen,
|
|
60
|
+
fontScale: window.fontScale,
|
|
61
|
+
pixelRatio: window.scale,
|
|
62
|
+
deviceType: classifyDevice(getDeviceEnvironment(screen.width, screen.height), config),
|
|
63
|
+
config,
|
|
64
|
+
container,
|
|
65
|
+
source,
|
|
66
|
+
round: roundToPixel,
|
|
67
|
+
}),
|
|
68
|
+
[window, screen, config, container, source],
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Returns only the active breakpoint. Optimised: when measuring the window, the component
|
|
74
|
+
* re-renders only when the breakpoint *changes*, not on every pixel of a window resize.
|
|
75
|
+
*/
|
|
76
|
+
export function useBreakpoint(options?: SourceOptions): BreakpointKey {
|
|
77
|
+
const config = useContext(ConfigContext);
|
|
78
|
+
const containerContext = useContext(ContainerContext);
|
|
79
|
+
const container = pickContainer(options?.source ?? 'auto', containerContext);
|
|
80
|
+
const getWindowBreakpoint = useCallback(
|
|
81
|
+
() => getBreakpoint(getSnapshot().window.width, config.breakpoints),
|
|
82
|
+
[config.breakpoints],
|
|
83
|
+
);
|
|
84
|
+
const windowBreakpoint = useSyncExternalStore(subscribe, getWindowBreakpoint, getWindowBreakpoint);
|
|
85
|
+
return container ? container.breakpoint : windowBreakpoint;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Resolves a responsive value for the active breakpoint.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* const columns = useResponsiveValue({ xs: 1, md: 2, xl: 4 });
|
|
93
|
+
*/
|
|
94
|
+
export function useResponsiveValue<const V extends ResponsiveObject<unknown>>(
|
|
95
|
+
value: V,
|
|
96
|
+
options?: SourceOptions,
|
|
97
|
+
): SelectResult<V>;
|
|
98
|
+
export function useResponsiveValue<T extends Narrowable>(value: ResponsiveValue<T>, options?: SourceOptions): T;
|
|
99
|
+
export function useResponsiveValue(value: ResponsiveValue<unknown>, options?: SourceOptions): unknown {
|
|
100
|
+
const breakpoint = useBreakpoint(options);
|
|
101
|
+
return resolveResponsiveValue(value, breakpoint);
|
|
102
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { PixelRatio, Platform } from 'react-native';
|
|
2
|
+
import type { DeviceEnvironment } from '../core/device';
|
|
3
|
+
|
|
4
|
+
interface PlatformFlags {
|
|
5
|
+
isPad?: boolean;
|
|
6
|
+
isTV?: boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
interface MediaQueryHost {
|
|
10
|
+
matchMedia?: (query: string) => { matches: boolean };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Web only: whether the primary pointer is coarse (touch). Undefined when unknown. */
|
|
14
|
+
export function detectCoarsePointer(): boolean | undefined {
|
|
15
|
+
if (Platform.OS !== 'web') return undefined;
|
|
16
|
+
const host = globalThis as unknown as MediaQueryHost;
|
|
17
|
+
try {
|
|
18
|
+
if (typeof host.matchMedia === 'function') return host.matchMedia('(pointer: coarse)').matches;
|
|
19
|
+
} catch {
|
|
20
|
+
// Not available (e.g. server rendering). Fall through.
|
|
21
|
+
}
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function getDeviceEnvironment(screenWidth: number, screenHeight: number): DeviceEnvironment {
|
|
26
|
+
const flags = Platform as unknown as PlatformFlags;
|
|
27
|
+
return {
|
|
28
|
+
os: Platform.OS,
|
|
29
|
+
isPad: flags.isPad === true,
|
|
30
|
+
isTV: flags.isTV === true,
|
|
31
|
+
screenWidth,
|
|
32
|
+
screenHeight,
|
|
33
|
+
hasCoarsePointer: detectCoarsePointer(),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Rounds a dp value to the nearest physical pixel. */
|
|
38
|
+
export function roundToPixel(value: number): number {
|
|
39
|
+
return PixelRatio.roundToNearestPixel(value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function isDev(): boolean {
|
|
43
|
+
return typeof __DEV__ !== 'undefined' && __DEV__ === true;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const warned = new Set<string>();
|
|
47
|
+
|
|
48
|
+
/** Logs a development-only warning once per message. */
|
|
49
|
+
export function warnOnce(message: string): void {
|
|
50
|
+
if (!isDev() || warned.has(message)) return;
|
|
51
|
+
warned.add(message);
|
|
52
|
+
// eslint-disable-next-line no-console
|
|
53
|
+
console.warn(`[react-native-everything-responsive] ${message}`);
|
|
54
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { DEFAULT_CONFIG, createConfig } from '../core/config';
|
|
2
|
+
import { classifyDevice } from '../core/device';
|
|
3
|
+
import { createResponsiveInfo } from '../core/info';
|
|
4
|
+
import type { ResponsiveConfigInput, ResponsiveInfo } from '../core/types';
|
|
5
|
+
import { getDeviceEnvironment, roundToPixel } from './platform';
|
|
6
|
+
import { getSnapshot } from './store';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Non-reactive snapshot for code that runs outside React components (navigation options,
|
|
10
|
+
* analytics, module-level constants). It reads the metrics **once**: the result does not
|
|
11
|
+
* update on rotation or resize. Inside components, use `useResponsive()` instead.
|
|
12
|
+
*/
|
|
13
|
+
export function getResponsive(config?: ResponsiveConfigInput): ResponsiveInfo {
|
|
14
|
+
const resolved = config ? createConfig(config, DEFAULT_CONFIG) : DEFAULT_CONFIG;
|
|
15
|
+
const { window, screen } = getSnapshot();
|
|
16
|
+
return createResponsiveInfo({
|
|
17
|
+
window,
|
|
18
|
+
screen,
|
|
19
|
+
fontScale: window.fontScale,
|
|
20
|
+
pixelRatio: window.scale,
|
|
21
|
+
deviceType: classifyDevice(getDeviceEnvironment(screen.width, screen.height), resolved),
|
|
22
|
+
config: resolved,
|
|
23
|
+
container: null,
|
|
24
|
+
source: 'window',
|
|
25
|
+
round: roundToPixel,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { Dimensions } from 'react-native';
|
|
2
|
+
import type { ScaledSize } from 'react-native';
|
|
3
|
+
|
|
4
|
+
/** Immutable snapshot of window and screen metrics. */
|
|
5
|
+
export interface DimensionsSnapshot {
|
|
6
|
+
readonly window: ScaledSize;
|
|
7
|
+
readonly screen: ScaledSize;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function read(): DimensionsSnapshot {
|
|
11
|
+
return { window: Dimensions.get('window'), screen: Dimensions.get('screen') };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function sameSize(a: ScaledSize, b: ScaledSize): boolean {
|
|
15
|
+
return a.width === b.width && a.height === b.height && a.scale === b.scale && a.fontScale === b.fontScale;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function sameSnapshot(a: DimensionsSnapshot, b: DimensionsSnapshot): boolean {
|
|
19
|
+
return sameSize(a.window, b.window) && sameSize(a.screen, b.screen);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let snapshot: DimensionsSnapshot = read();
|
|
23
|
+
const listeners = new Set<() => void>();
|
|
24
|
+
let subscription: { remove: () => void } | undefined;
|
|
25
|
+
|
|
26
|
+
function handleChange(next: DimensionsSnapshot): void {
|
|
27
|
+
const fresh = { window: { ...next.window }, screen: { ...next.screen } };
|
|
28
|
+
if (sameSnapshot(fresh, snapshot)) return;
|
|
29
|
+
snapshot = fresh;
|
|
30
|
+
listeners.forEach((listener) => listener());
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* One shared `Dimensions` subscription for the whole app, no matter how many components
|
|
35
|
+
* use the hooks. It is created on first use and removed when the last listener leaves.
|
|
36
|
+
*/
|
|
37
|
+
export function subscribe(listener: () => void): () => void {
|
|
38
|
+
listeners.add(listener);
|
|
39
|
+
if (!subscription) {
|
|
40
|
+
subscription = Dimensions.addEventListener('change', handleChange);
|
|
41
|
+
// Metrics may have changed while nobody was listening. Refresh silently:
|
|
42
|
+
// useSyncExternalStore re-reads the snapshot right after subscribing.
|
|
43
|
+
const fresh = read();
|
|
44
|
+
if (!sameSnapshot(fresh, snapshot)) snapshot = fresh;
|
|
45
|
+
}
|
|
46
|
+
return () => {
|
|
47
|
+
listeners.delete(listener);
|
|
48
|
+
if (listeners.size === 0 && subscription) {
|
|
49
|
+
subscription.remove();
|
|
50
|
+
subscription = undefined;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Current snapshot. Its identity changes only when a metric actually changes. */
|
|
56
|
+
export function getSnapshot(): DimensionsSnapshot {
|
|
57
|
+
return snapshot;
|
|
58
|
+
}
|