@fabricator-ui/react-native 0.0.0-stage → 0.10.0

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.
Files changed (46) hide show
  1. package/README.md +8 -2
  2. package/dist/LICENSE.md +25 -0
  3. package/dist/NOTICE.md +24 -0
  4. package/dist/lib/data-variants.ts +23 -0
  5. package/dist/lib/density-scale.ts +208 -0
  6. package/dist/lib/fabricator/css-object.ts +2 -0
  7. package/dist/lib/fabricator/density-scale.ts +210 -0
  8. package/dist/lib/fabricator/density-variables.ts +37 -0
  9. package/dist/lib/fabricator/motion-speeds.ts +566 -0
  10. package/dist/lib/fabricator/radius.ts +240 -0
  11. package/dist/lib/feedback.ts +124 -0
  12. package/dist/lib/field-frame.ts +53 -0
  13. package/dist/lib/field-model.ts +112 -0
  14. package/dist/lib/fluid-hover-model.ts +142 -0
  15. package/dist/lib/fluid-hover.tsx +788 -0
  16. package/dist/lib/icon-stroke.ts +38 -0
  17. package/dist/lib/motion-tokens.ts +97 -0
  18. package/dist/lib/motion.ts +292 -0
  19. package/dist/lib/overlay-model.ts +205 -0
  20. package/dist/lib/press-wash.tsx +73 -0
  21. package/dist/lib/render.tsx +53 -0
  22. package/dist/lib/select-model.ts +87 -0
  23. package/dist/lib/sheet-model.ts +101 -0
  24. package/dist/lib/sheet-surface.tsx +429 -0
  25. package/dist/lib/sound-recipes.ts +449 -0
  26. package/dist/lib/spring-model.ts +214 -0
  27. package/dist/lib/surface-color.tsx +27 -0
  28. package/dist/lib/text-children.ts +43 -0
  29. package/dist/styles.css +610 -0
  30. package/dist/ui/badge.tsx +108 -0
  31. package/dist/ui/button.tsx +285 -0
  32. package/dist/ui/card.tsx +365 -0
  33. package/dist/ui/checkbox.tsx +230 -0
  34. package/dist/ui/collapsible.tsx +194 -0
  35. package/dist/ui/density.tsx +79 -0
  36. package/dist/ui/dialog.tsx +232 -0
  37. package/dist/ui/dropdown-menu.tsx +687 -0
  38. package/dist/ui/fabricator-root.tsx +68 -0
  39. package/dist/ui/input.tsx +63 -0
  40. package/dist/ui/label.tsx +22 -0
  41. package/dist/ui/select.tsx +616 -0
  42. package/dist/ui/switch.tsx +177 -0
  43. package/dist/ui/tabs.tsx +272 -0
  44. package/dist/ui/text.tsx +125 -0
  45. package/dist/ui/textarea.tsx +65 -0
  46. package/package.json +54 -4
@@ -0,0 +1,38 @@
1
+ // Icons pick their stroke from their size (Fabricator Icons' getAutoStrokeWidth).
2
+ // A lit, active or focused icon draws a quarter unit heavier than that pick.
3
+
4
+ import { getAutoStrokeWidth } from "@fabricator-ui/icons-react-native"
5
+ import { useCSSVariable } from "uniwind"
6
+
7
+ import { parseNumber } from "./motion-tokens"
8
+
9
+ /** How much heavier, in grid units, an emphasised icon draws. */
10
+ export const EMPHASIS_STROKE = 0.25
11
+
12
+ /** The stroke of an emphasised icon of `size` pixels. */
13
+ export function getEmphasisStroke(size: number) {
14
+ return getAutoStrokeWidth(1.75, size) + EMPHASIS_STROKE
15
+ }
16
+
17
+ /**
18
+ * The stroke for an icon at the `token` size (a control's 16px icon by
19
+ * default): undefined at rest, so the icon picks it, heavier while
20
+ * `isEmphasised`. Call it before any early return.
21
+ */
22
+ export function useIconStroke(
23
+ isEmphasised: boolean,
24
+ token = "--density-icon-16"
25
+ ) {
26
+ const size = parseNumber(useCSSVariable(token), 16)
27
+ return isEmphasised ? getEmphasisStroke(size) : undefined
28
+ }
29
+
30
+ /**
31
+ * A disclosure chevron's size and stroke (select, menu and collapsible
32
+ * triggers): the small icon step, at that size's stroke, steady while its
33
+ * row is lit. Spread it on the chevron.
34
+ */
35
+ export function useChevronIcon() {
36
+ const size = parseNumber(useCSSVariable("--density-icon-14"), 14)
37
+ return { size, strokeWidth: getAutoStrokeWidth(1.75, size) }
38
+ }
@@ -0,0 +1,97 @@
1
+ // Fabricator's motion tokens as React Native reads them: `useCSSVariable`
2
+ // hands back what the theme holds, so parse it here. No React Native imports,
3
+ // so these stay testable anywhere.
4
+
5
+ export type Bezier = readonly [number, number, number, number]
6
+
7
+ export type SurfaceSide = "top" | "right" | "bottom" | "left"
8
+ export type SurfaceAlign = "start" | "center" | "end"
9
+
10
+ const LINEAR: Bezier = [0, 0, 1, 1]
11
+
12
+ /** `cubic-bezier(0.23, 1, 0.32, 1)` as its four numbers. */
13
+ export function parseBezier(value: unknown): Bezier {
14
+ if (typeof value !== "string") return LINEAR
15
+ const match = /cubic-bezier\(([^)]+)\)/.exec(value)
16
+ if (!match) return LINEAR
17
+ const numbers = match[1].split(",").map(Number)
18
+ if (numbers.length !== 4 || numbers.some(Number.isNaN)) return LINEAR
19
+ return [numbers[0], numbers[1], numbers[2], numbers[3]]
20
+ }
21
+
22
+ /** A number from a token, however the theme wrote it: `250`, `"250ms"`, `"6px"`. */
23
+ export function parseNumber(value: unknown, fallback: number) {
24
+ if (typeof value === "number") return value
25
+ if (typeof value !== "string") return fallback
26
+ const parsed = Number.parseFloat(value)
27
+ return Number.isNaN(parsed) ? fallback : parsed
28
+ }
29
+
30
+ /** Reduce Motion keeps the fade and drops the travel and the zoom. */
31
+ export function getSurfaceFrom(
32
+ options: {
33
+ scale?: number
34
+ translateX?: number
35
+ translateY?: number
36
+ /** Off for a surface that only slides, as a toast does. */
37
+ hasFade?: boolean
38
+ },
39
+ isReduced: boolean
40
+ ) {
41
+ return isReduced
42
+ ? { opacity: 0, scale: 1, translateX: 0, translateY: 0 }
43
+ : {
44
+ opacity: options.hasFade === false ? 1 : 0,
45
+ scale: options.scale ?? 1,
46
+ translateX: options.translateX ?? 0,
47
+ translateY: options.translateY ?? 0,
48
+ }
49
+ }
50
+
51
+ const OPPOSITE_SIDE: Record<SurfaceSide, string> = {
52
+ top: "bottom",
53
+ right: "left",
54
+ bottom: "top",
55
+ left: "right",
56
+ }
57
+
58
+ const ALIGN_ON_X: Record<SurfaceAlign, string> = {
59
+ start: "left",
60
+ center: "center",
61
+ end: "right",
62
+ }
63
+
64
+ const ALIGN_ON_Y: Record<SurfaceAlign, string> = {
65
+ start: "top",
66
+ center: "center",
67
+ end: "bottom",
68
+ }
69
+
70
+ /**
71
+ * Where a popup grows from: the edge beside its trigger, along its alignment,
72
+ * as the website's `origin-(--transform-origin)` does. Dialogs have no side and
73
+ * grow from the centre.
74
+ */
75
+ export function getSurfaceOrigin(
76
+ side: SurfaceSide | undefined,
77
+ align: SurfaceAlign | undefined
78
+ ) {
79
+ if (!side) return "center"
80
+ const edge = OPPOSITE_SIDE[side]
81
+ const along =
82
+ side === "top" || side === "bottom"
83
+ ? ALIGN_ON_X[align ?? "center"]
84
+ : ALIGN_ON_Y[align ?? "center"]
85
+ return `${edge} ${along}`
86
+ }
87
+
88
+ /** The slide from the trigger's side, for speeds that travel. */
89
+ export function getSurfaceTravel(
90
+ side: SurfaceSide | undefined,
91
+ distance: number
92
+ ) {
93
+ return {
94
+ translateX: side === "right" ? -distance : side === "left" ? distance : 0,
95
+ translateY: side === "bottom" ? -distance : side === "top" ? distance : 0,
96
+ }
97
+ }
@@ -0,0 +1,292 @@
1
+ // Motion by role, never milliseconds: the same tokens as the website, read
2
+ // from the theme, so `applyLook` and a scoped speed reach every surface.
3
+
4
+ import * as React from "react"
5
+ import {
6
+ Easing,
7
+ ReduceMotion,
8
+ useReducedMotion,
9
+ useSharedValue,
10
+ withSpring,
11
+ withTiming,
12
+ } from "react-native-reanimated"
13
+ import { useCSSVariable } from "uniwind"
14
+
15
+ import {
16
+ DEFAULT_MOTION_SPEED,
17
+ getSpringSamples,
18
+ MOTION_SPEED_NAMES,
19
+ MOTION_SPEEDS,
20
+ MOTION_SPRING_NAMES,
21
+ type MotionSpeedName,
22
+ type MotionSpringName,
23
+ } from "./fabricator/motion-speeds"
24
+ import {
25
+ retimeSpring,
26
+ type SpringConfig,
27
+ } from "./spring-model"
28
+ import {
29
+ getSurfaceFrom,
30
+ getSurfaceOrigin,
31
+ getSurfaceTravel,
32
+ parseBezier,
33
+ parseNumber,
34
+ type SurfaceAlign,
35
+ type SurfaceSide,
36
+ } from "./motion-tokens"
37
+
38
+ type MotionRole =
39
+ | "feedback"
40
+ | "glide"
41
+ | "move"
42
+ | "theme"
43
+ | "tooltip"
44
+ | "popup"
45
+ | "dialog"
46
+ | "sheet"
47
+ | "disclosure"
48
+ | "bounce"
49
+ | "settle"
50
+ | "toast"
51
+ | "reveal"
52
+
53
+ // The website's `linear()` spring: the same samples, joined by straight lines.
54
+ function createSampledEasing(samples: number[]) {
55
+ const segments = samples.length - 1
56
+ return (progress: number) => {
57
+ "worklet"
58
+ if (progress <= 0) return samples[0]
59
+ if (progress >= 1) return samples[segments]
60
+ const position = progress * segments
61
+ const index = Math.floor(position)
62
+ const from = samples[index]
63
+ return from + (samples[index + 1] - from) * (position - index)
64
+ }
65
+ }
66
+
67
+ function buildEasings(name: MotionSpeedName) {
68
+ const { easings, bounce, settle } = MOTION_SPEEDS[name]
69
+ return {
70
+ bounceEasing: createSampledEasing(getSpringSamples(bounce)),
71
+ settleEasing: createSampledEasing(getSpringSamples(settle)),
72
+ enterEasing: Easing.bezier(...parseBezier(easings.enter)),
73
+ exitEasing: Easing.bezier(...parseBezier(easings.exit)),
74
+ moveEasing: Easing.bezier(...parseBezier(easings.move)),
75
+ drawerEasing: Easing.bezier(...parseBezier(easings.drawer)),
76
+ themeEasing: Easing.bezier(...parseBezier(easings.theme)),
77
+ feedbackEasing: Easing.bezier(...parseBezier(easings.feedback)),
78
+ }
79
+ }
80
+
81
+ const speedEasings = new Map<MotionSpeedName, ReturnType<typeof buildEasings>>()
82
+
83
+ // One set per speed: a screen can hold hundreds of controls that read them.
84
+ function getEasings(name: MotionSpeedName) {
85
+ const existing = speedEasings.get(name)
86
+ if (existing) return existing
87
+ const built = buildEasings(name)
88
+ speedEasings.set(name, built)
89
+ return built
90
+ }
91
+
92
+ /** A role's timings and curves, scaled and zeroed the way the website does. */
93
+ function useMotion(role: MotionRole) {
94
+ const [enter, exit, scale, speed] = useCSSVariable([
95
+ `--motion-${role}`,
96
+ `--motion-${role}-exit`,
97
+ "--motion-scale",
98
+ "--motion-speed",
99
+ ])
100
+ const isReduced = useReducedMotion()
101
+ return React.useMemo(() => {
102
+ const multiplier = parseNumber(scale, 1)
103
+ const name = MOTION_SPEED_NAMES[parseNumber(speed, 1)]
104
+ return {
105
+ isOff: multiplier === 0,
106
+ isReduced,
107
+ enterMs: parseNumber(enter, 0) * multiplier,
108
+ exitMs: parseNumber(exit, 0) * multiplier,
109
+ ...getEasings(name ?? DEFAULT_MOTION_SPEED),
110
+ }
111
+ }, [enter, exit, scale, speed, isReduced])
112
+ }
113
+
114
+ /**
115
+ * The speed's springs, stretched by `--motion-scale`, as Reanimated's
116
+ * `withSpring` takes them (mass 1). Null when motion is off; `isReduced` tells
117
+ * a caller to drop travel, as the website does.
118
+ */
119
+ function useMotionSprings() {
120
+ const [scale, speed] = useCSSVariable(["--motion-scale", "--motion-speed"])
121
+ const isReduced = useReducedMotion()
122
+ return React.useMemo(() => {
123
+ const multiplier = parseNumber(scale, 1)
124
+ const name =
125
+ MOTION_SPEED_NAMES[parseNumber(speed, 1)] ?? DEFAULT_MOTION_SPEED
126
+ const springs =
127
+ multiplier === 0
128
+ ? null
129
+ : (Object.fromEntries(
130
+ MOTION_SPRING_NAMES.map((spring) => [
131
+ spring,
132
+ retimeSpring(MOTION_SPEEDS[name].springs[spring], multiplier),
133
+ ])
134
+ ) as Record<MotionSpringName, SpringConfig>)
135
+ return { isReduced, springs }
136
+ }, [scale, speed, isReduced])
137
+ }
138
+
139
+ type SurfaceFrom = {
140
+ scale?: number
141
+ translateX?: number
142
+ translateY?: number
143
+ /** The side the surface opens on: it grows from the edge beside its trigger. */
144
+ side?: SurfaceSide
145
+ align?: SurfaceAlign
146
+ /** Off for a surface that only slides, as a toast does. */
147
+ hasFade?: boolean
148
+ }
149
+
150
+ /**
151
+ * `entering` and `exiting` for a surface that appears: a fade, plus the zoom
152
+ * and slide its role allows. `origin` goes on the same view as `style`, so a
153
+ * popup grows from its trigger. Undefined when motion is off.
154
+ */
155
+ function useSurfaceAnimation(role: MotionRole, from: SurfaceFrom = {}) {
156
+ const motion = useMotion(role)
157
+ // Only these roles zoom, and only tooltips and popups travel; asking for any
158
+ // other token warns in development.
159
+ const hasScale = role === "tooltip" || role === "popup" || role === "dialog"
160
+ const hasTravel = role === "tooltip" || role === "popup"
161
+ const [scaleToken, travelToken] = useCSSVariable([
162
+ hasScale ? `--motion-${role}-scale` : "--motion-press-scale",
163
+ hasTravel ? `--motion-${role}-travel` : "--motion-press-scale",
164
+ ])
165
+ const scale = from.scale ?? (hasScale ? parseNumber(scaleToken, 1) : 1)
166
+ const travel = getSurfaceTravel(
167
+ from.side,
168
+ hasTravel ? parseNumber(travelToken, 0) : 0
169
+ )
170
+ const translateX = from.translateX ?? travel.translateX
171
+ const translateY = from.translateY ?? travel.translateY
172
+ const hasFade = from.hasFade ?? true
173
+ const transformOrigin = getSurfaceOrigin(from.side, from.align)
174
+ return React.useMemo(() => {
175
+ const origin = { transformOrigin }
176
+ if (motion.isOff) return { entering: undefined, exiting: undefined, origin }
177
+ const start = getSurfaceFrom(
178
+ { scale, translateX, translateY, hasFade },
179
+ motion.isReduced
180
+ )
181
+ // Reanimated jumps a timing to its end under Reduce Motion by default, and
182
+ // `start` has already dropped the travel and the zoom: the fade stays.
183
+ const enter = {
184
+ duration: motion.enterMs,
185
+ easing: motion.enterEasing,
186
+ reduceMotion: ReduceMotion.Never,
187
+ }
188
+ const exit = {
189
+ duration: motion.exitMs,
190
+ easing: motion.exitEasing,
191
+ reduceMotion: ReduceMotion.Never,
192
+ }
193
+ return {
194
+ origin,
195
+ entering: () => {
196
+ "worklet"
197
+ return {
198
+ initialValues: {
199
+ opacity: start.opacity,
200
+ transform: [
201
+ { translateX: start.translateX },
202
+ { translateY: start.translateY },
203
+ { scale: start.scale },
204
+ ],
205
+ },
206
+ animations: {
207
+ opacity: withTiming(1, enter),
208
+ transform: [
209
+ { translateX: withTiming(0, enter) },
210
+ { translateY: withTiming(0, enter) },
211
+ { scale: withTiming(1, enter) },
212
+ ],
213
+ },
214
+ }
215
+ },
216
+ exiting: () => {
217
+ "worklet"
218
+ return {
219
+ initialValues: {
220
+ opacity: 1,
221
+ transform: [{ translateX: 0 }, { translateY: 0 }, { scale: 1 }],
222
+ },
223
+ animations: {
224
+ opacity: withTiming(start.opacity, exit),
225
+ transform: [
226
+ { translateX: withTiming(start.translateX, exit) },
227
+ { translateY: withTiming(start.translateY, exit) },
228
+ { scale: withTiming(start.scale, exit) },
229
+ ],
230
+ },
231
+ }
232
+ },
233
+ }
234
+ }, [hasFade, motion, scale, transformOrigin, translateX, translateY])
235
+ }
236
+
237
+ /**
238
+ * The press: a scale and a pressed wash while held, on the feedback timing, one
239
+ * duration both ways as on the website. A touch has no hover to ease into it, so
240
+ * `progress` also fades the pressed fill out on release (see PressWash), where a
241
+ * class could only snap. `isHeld` keeps the wash on while the control's popup is
242
+ * open, as the website's `aria-expanded` step does.
243
+ */
244
+ function usePressScale({
245
+ isHeld = false,
246
+ releaseSpring,
247
+ }: {
248
+ isHeld?: boolean
249
+ /** Letting go springs back on this spring instead of the feedback timing. */
250
+ releaseSpring?: MotionSpringName
251
+ } = {}) {
252
+ const motion = useMotion("feedback")
253
+ const { springs } = useMotionSprings()
254
+ const release = releaseSpring && springs ? springs[releaseSpring] : null
255
+ const pressScale = parseNumber(useCSSVariable("--motion-press-scale"), 1)
256
+ const scale = useSharedValue(1)
257
+ const progress = useSharedValue(isHeld ? 1 : 0)
258
+ const target = motion.isReduced || motion.isOff ? 1 : pressScale
259
+ const config = React.useMemo(
260
+ () => ({
261
+ duration: motion.enterMs,
262
+ easing: motion.feedbackEasing,
263
+ reduceMotion: ReduceMotion.Never,
264
+ }),
265
+ [motion.enterMs, motion.feedbackEasing]
266
+ )
267
+ React.useEffect(() => {
268
+ progress.set(withTiming(isHeld ? 1 : 0, config))
269
+ }, [config, isHeld, progress])
270
+ const onPressIn = React.useCallback(() => {
271
+ scale.set(withTiming(target, config))
272
+ progress.set(withTiming(1, config))
273
+ }, [config, progress, scale, target])
274
+ const onPressOut = React.useCallback(() => {
275
+ if (release && !isHeld) {
276
+ scale.set(withSpring(1, { ...release, mass: 1 }))
277
+ progress.set(withSpring(0, { ...release, mass: 1 }))
278
+ return
279
+ }
280
+ scale.set(withTiming(1, config))
281
+ progress.set(withTiming(isHeld ? 1 : 0, config))
282
+ }, [config, isHeld, progress, release, scale])
283
+ return { scale, progress, onPressIn, onPressOut }
284
+ }
285
+
286
+ export {
287
+ useMotion,
288
+ useMotionSprings,
289
+ usePressScale,
290
+ useSurfaceAnimation,
291
+ type MotionRole,
292
+ }
@@ -0,0 +1,205 @@
1
+ // What the anchored overlays share. React only, with no React Native imports, so
2
+ // it stays testable anywhere.
3
+
4
+ import * as React from "react"
5
+
6
+ type TriggerAction = "open" | "close"
7
+
8
+ /** Keeps an anchored surface off the edge of the screen. */
9
+ export const COLLISION_INSETS = { top: 8, right: 8, bottom: 8, left: 8 }
10
+
11
+ type Insets = { top?: number; right?: number; bottom?: number; left?: number }
12
+
13
+ /** Collision insets that keep clear of the status bar and the home indicator too. */
14
+ export function getSafeInsets(
15
+ insets: Insets,
16
+ /** What `useSafeAreaInsets()` returns. */
17
+ safeArea: Required<Insets>
18
+ ) {
19
+ return {
20
+ ...insets,
21
+ top: (insets.top ?? 0) + safeArea.top,
22
+ bottom: (insets.bottom ?? 0) + safeArea.bottom,
23
+ }
24
+ }
25
+
26
+ const MENU_HEIGHT_FRACTION = 0.8
27
+
28
+ /** Where a window stops being a phone's: a tall screen is no reason for a tall menu. */
29
+ const TABLET_WIDTH = 768
30
+ const TABLET_MENU_MAX_HEIGHT = 480
31
+ const TABLET_MENU_MAX_MIN_WIDTH = 360
32
+
33
+ /**
34
+ * For a dialog's or a sheet's root: on the website it renders no element, so a closed
35
+ * one with no trigger takes no slot in its parent's gap. Its trigger lays out as a
36
+ * child of that parent, which is where the website's does too.
37
+ */
38
+ export const NO_LAYOUT = { display: "contents" } as const
39
+
40
+ /** What it takes to bring a primitive's own open state to the wanted one. */
41
+ export function getTriggerAction(
42
+ wanted: boolean,
43
+ actual: boolean
44
+ ): TriggerAction | null {
45
+ if (wanted === actual) return null
46
+ return wanted ? "open" : "close"
47
+ }
48
+
49
+ /**
50
+ * The primitives place a surface above or below its anchor, flipping and clamping
51
+ * it there. A phone rarely has room beside one, so the other sides go below.
52
+ */
53
+ export function getVerticalSide(side: string): "top" | "bottom" {
54
+ return side === "top" ? "top" : "bottom"
55
+ }
56
+
57
+ /**
58
+ * The side a surface fits on. The primitives only clamp to the screen, which lays a
59
+ * tall menu over its own trigger near an edge. This flips it to the roomier side, once
60
+ * it's been measured and only if it doesn't fit where it was asked.
61
+ */
62
+ export function getFittedSide({
63
+ side,
64
+ triggerY,
65
+ triggerHeight,
66
+ contentHeight,
67
+ offset,
68
+ windowHeight,
69
+ insets,
70
+ }: {
71
+ side: "top" | "bottom"
72
+ triggerY: number | undefined
73
+ triggerHeight: number | undefined
74
+ contentHeight: number | null
75
+ offset: number
76
+ windowHeight: number
77
+ insets?: { top?: number; bottom?: number }
78
+ }) {
79
+ if (
80
+ contentHeight === null ||
81
+ triggerY === undefined ||
82
+ triggerHeight === undefined
83
+ ) {
84
+ return side
85
+ }
86
+ const above = triggerY - offset - (insets?.top ?? 0)
87
+ const below =
88
+ windowHeight - (insets?.bottom ?? 0) - triggerY - triggerHeight - offset
89
+ if (side === "bottom") {
90
+ return contentHeight > below && above > below ? "top" : "bottom"
91
+ }
92
+ return contentHeight > above && below > above ? "bottom" : "top"
93
+ }
94
+
95
+ /** The tallest a menu gets before it scrolls. */
96
+ export function getMenuMaxHeight(
97
+ windowHeight: number,
98
+ windowWidth: number,
99
+ /** Room on the side the menu opens to, when it's known. */
100
+ available?: number
101
+ ) {
102
+ const fraction = windowHeight * MENU_HEIGHT_FRACTION
103
+ const height =
104
+ windowWidth >= TABLET_WIDTH
105
+ ? Math.min(fraction, TABLET_MENU_MAX_HEIGHT)
106
+ : fraction
107
+ return available === undefined
108
+ ? height
109
+ : Math.min(height, Math.max(available, 0))
110
+ }
111
+
112
+ /**
113
+ * The room between a trigger and the screen's edge on the side a menu opens
114
+ * to, inside the insets (which include the safe area: a menu opening up from
115
+ * a bar at the bottom mustn't run under the status bar).
116
+ */
117
+ export function getMenuAvailableSpace({
118
+ side,
119
+ triggerY,
120
+ triggerHeight,
121
+ offset,
122
+ windowHeight,
123
+ insets,
124
+ }: {
125
+ side: "top" | "bottom"
126
+ triggerY: number | undefined
127
+ triggerHeight: number | undefined
128
+ offset: number
129
+ windowHeight: number
130
+ insets: { top: number; bottom: number }
131
+ }) {
132
+ if (triggerY === undefined || triggerHeight === undefined) return undefined
133
+ return side === "top"
134
+ ? triggerY - offset - insets.top
135
+ : windowHeight - (triggerY + triggerHeight) - offset - insets.bottom
136
+ }
137
+
138
+ /**
139
+ * A menu is at least as wide as its trigger, until the trigger is a row stretched
140
+ * across a tablet: past that, a wider menu only moves its text further apart.
141
+ */
142
+ export function getMenuMinWidth(
143
+ triggerWidth: number | undefined,
144
+ windowWidth: number
145
+ ) {
146
+ if (triggerWidth === undefined || windowWidth < TABLET_WIDTH) {
147
+ return triggerWidth
148
+ }
149
+ return Math.min(triggerWidth, TABLET_MENU_MAX_MIN_WIDTH)
150
+ }
151
+
152
+ /** The text inside a React node, however deep. */
153
+ export function getTextContent(node: React.ReactNode): string {
154
+ if (typeof node === "string" || typeof node === "number") return String(node)
155
+ if (Array.isArray(node)) return node.map(getTextContent).join("")
156
+ if (React.isValidElement<{ children?: React.ReactNode }>(node)) {
157
+ return getTextContent(node.props.children)
158
+ }
159
+ return ""
160
+ }
161
+
162
+ /**
163
+ * The website's `open`, `defaultOpen` and `onOpenChange` for primitives that have
164
+ * no `open` prop: a ref on their Trigger exposes `open()` and `close()`, so an
165
+ * effect brings the primitive to the wanted state. Pass `triggerRef` to the
166
+ * Trigger and `onOpenChange` to the Root.
167
+ */
168
+ export function useTriggerOpen<
169
+ Trigger extends { open: () => void; close: () => void },
170
+ >({
171
+ open,
172
+ defaultOpen = false,
173
+ onOpenChange,
174
+ }: {
175
+ open?: boolean
176
+ defaultOpen?: boolean
177
+ onOpenChange?: (open: boolean) => void
178
+ }) {
179
+ const [uncontrolled, setUncontrolled] = React.useState(defaultOpen)
180
+ const [actual, setActual] = React.useState(false)
181
+ const isControlled = open !== undefined
182
+ const wanted = isControlled ? open : uncontrolled
183
+ const triggerRef = React.useRef<Trigger>(null)
184
+
185
+ React.useEffect(() => {
186
+ const action = getTriggerAction(wanted, actual)
187
+ if (action) triggerRef.current?.[action]()
188
+ }, [wanted, actual])
189
+
190
+ const setIsOpen = (next: boolean) => {
191
+ if (next === wanted) return
192
+ if (!isControlled) setUncontrolled(next)
193
+ onOpenChange?.(next)
194
+ }
195
+
196
+ return {
197
+ isOpen: wanted,
198
+ setIsOpen,
199
+ triggerRef,
200
+ onOpenChange: (next: boolean) => {
201
+ setActual(next)
202
+ setIsOpen(next)
203
+ },
204
+ }
205
+ }
@@ -0,0 +1,73 @@
1
+ import * as React from "react"
2
+ import { cn } from "cn"
3
+ import Animated, {
4
+ ReduceMotion,
5
+ useAnimatedStyle,
6
+ useSharedValue,
7
+ withTiming,
8
+ type SharedValue,
9
+ } from "react-native-reanimated"
10
+
11
+ import { useMotion } from "./motion"
12
+
13
+ /**
14
+ * The pressed fill, as a layer under a control's content. An `active:` class can
15
+ * only snap; this eases in and out on the feedback timing, as the website's
16
+ * pressed step does. Render it as the Pressable's first child.
17
+ */
18
+ function PressWash({
19
+ press,
20
+ className,
21
+ }: {
22
+ press: { progress: SharedValue<number> }
23
+ className?: string
24
+ }) {
25
+ const style = useAnimatedStyle(() => ({ opacity: press.progress.value }))
26
+ return (
27
+ <Animated.View
28
+ pointerEvents="none"
29
+ importantForAccessibility="no-hide-descendants"
30
+ accessibilityElementsHidden
31
+ className={cn("absolute inset-0", className)}
32
+ style={style}
33
+ />
34
+ )
35
+ }
36
+
37
+ /**
38
+ * A fill that follows a control's state, as a layer under its content: a class can
39
+ * only snap, and the website eases fills on the feedback timing. Reduce Motion
40
+ * keeps the fade. Render it as the Pressable's first child.
41
+ */
42
+ function StateFill({
43
+ isOn,
44
+ className,
45
+ ...props
46
+ }: Omit<React.ComponentProps<typeof Animated.View>, "children"> & {
47
+ isOn: boolean
48
+ }) {
49
+ const motion = useMotion("feedback")
50
+ const progress = useSharedValue(isOn ? 1 : 0)
51
+ React.useEffect(() => {
52
+ progress.set(
53
+ withTiming(isOn ? 1 : 0, {
54
+ duration: motion.enterMs,
55
+ easing: motion.feedbackEasing,
56
+ reduceMotion: ReduceMotion.Never,
57
+ })
58
+ )
59
+ }, [isOn, motion.enterMs, motion.feedbackEasing, progress])
60
+ const style = useAnimatedStyle(() => ({ opacity: progress.value }))
61
+ return (
62
+ <Animated.View
63
+ pointerEvents="none"
64
+ importantForAccessibility="no-hide-descendants"
65
+ accessibilityElementsHidden
66
+ className={cn("absolute inset-0", className)}
67
+ style={style}
68
+ {...props}
69
+ />
70
+ )
71
+ }
72
+
73
+ export { PressWash, StateFill }