@plexui/react-native 0.1.0 → 0.2.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 (149) hide show
  1. package/README.md +34 -0
  2. package/dist/es/components/ActionSheet/ActionSheet.js +53 -19
  3. package/dist/es/components/Alert/Alert.js +163 -0
  4. package/dist/es/components/Avatar/Avatar.js +20 -8
  5. package/dist/es/components/BottomActions/BottomActions.js +34 -0
  6. package/dist/es/components/BottomSheet/BottomSheet.js +85 -17
  7. package/dist/es/components/Button/Button.js +108 -28
  8. package/dist/es/components/Card/Card.js +16 -8
  9. package/dist/es/components/Checkbox/Checkbox.js +67 -99
  10. package/dist/es/components/Chip/Chip.js +16 -7
  11. package/dist/es/components/Dialog/Dialog.js +38 -24
  12. package/dist/es/components/Field/Field.js +91 -0
  13. package/dist/es/components/FloatingLabelInput/FloatingLabelInput.js +59 -0
  14. package/dist/es/components/Icon/createIcon.js +13 -2
  15. package/dist/es/components/Indicator/CircularProgress.js +80 -0
  16. package/dist/es/components/Indicator/LoadingDots.js +46 -0
  17. package/dist/es/components/Indicator/LoadingIndicator.js +101 -0
  18. package/dist/es/components/Indicator/index.js +3 -0
  19. package/dist/es/components/Input/Input.js +69 -60
  20. package/dist/es/components/InputGroup/InputGroup.js +130 -0
  21. package/dist/es/components/List/List.js +175 -59
  22. package/dist/es/components/Menu/Menu.js +69 -40
  23. package/dist/es/components/NavigationButton/NavigationButton.js +20 -4
  24. package/dist/es/components/OTPInput/OTPInput.js +9 -3
  25. package/dist/es/components/PageControl/PageControl.js +13 -7
  26. package/dist/es/components/Popover/Popover.js +128 -0
  27. package/dist/es/components/Progress/Progress.js +142 -0
  28. package/dist/es/components/ProgressSteps/ProgressSteps.js +207 -0
  29. package/dist/es/components/RollingNumber/RollingNumber.js +125 -0
  30. package/dist/es/components/Select/Select.js +97 -34
  31. package/dist/es/components/Separator/Separator.js +31 -0
  32. package/dist/es/components/ShimmerText/ShimmerText.js +98 -0
  33. package/dist/es/components/Stepper/Stepper.js +219 -0
  34. package/dist/es/components/Switch/Switch.js +26 -12
  35. package/dist/es/components/TagInput/TagInput.js +121 -0
  36. package/dist/es/components/Text/Text.js +7 -4
  37. package/dist/es/components/TextLink/TextLink.js +42 -0
  38. package/dist/es/components/Textarea/Textarea.js +12 -0
  39. package/dist/es/components/Tip/Tip.js +193 -0
  40. package/dist/es/components/Toolbar/Toolbar.js +6 -2
  41. package/dist/es/components/Tooltip/Tooltip.js +272 -0
  42. package/dist/es/index.js +20 -2
  43. package/dist/es/internal/FloatingPanel.js +111 -0
  44. package/dist/es/internal/fieldStack.js +73 -0
  45. package/dist/es/internal/floating.js +97 -0
  46. package/dist/es/internal/ripple.js +119 -0
  47. package/dist/es/internal/row.js +2 -1
  48. package/dist/es/internal/transition.js +113 -0
  49. package/dist/es/theme/ThemeProvider.js +41 -9
  50. package/dist/es/theme/material.js +37 -7
  51. package/dist/types/components/ActionSheet/ActionSheet.d.ts +15 -7
  52. package/dist/types/components/Alert/Alert.d.ts +51 -0
  53. package/dist/types/components/Avatar/Avatar.d.ts +4 -2
  54. package/dist/types/components/BottomActions/BottomActions.d.ts +18 -0
  55. package/dist/types/components/BottomSheet/BottomSheet.d.ts +4 -2
  56. package/dist/types/components/Button/Button.d.ts +20 -5
  57. package/dist/types/components/Card/Card.d.ts +14 -1
  58. package/dist/types/components/Checkbox/Checkbox.d.ts +4 -3
  59. package/dist/types/components/Chip/Chip.d.ts +12 -1
  60. package/dist/types/components/Dialog/Dialog.d.ts +9 -5
  61. package/dist/types/components/Field/Field.d.ts +64 -0
  62. package/dist/types/components/FloatingLabelInput/FloatingLabelInput.d.ts +42 -0
  63. package/dist/types/components/Indicator/CircularProgress.d.ts +34 -0
  64. package/dist/types/components/Indicator/LoadingDots.d.ts +17 -0
  65. package/dist/types/components/Indicator/LoadingIndicator.d.ts +46 -0
  66. package/dist/types/components/Indicator/index.d.ts +3 -0
  67. package/dist/types/components/Input/Input.d.ts +13 -3
  68. package/dist/types/components/InputGroup/InputGroup.d.ts +71 -0
  69. package/dist/types/components/List/List.d.ts +57 -14
  70. package/dist/types/components/Menu/Menu.d.ts +4 -0
  71. package/dist/types/components/NavigationButton/NavigationButton.d.ts +11 -3
  72. package/dist/types/components/OTPInput/OTPInput.d.ts +10 -1
  73. package/dist/types/components/PageControl/PageControl.d.ts +11 -1
  74. package/dist/types/components/Popover/Popover.d.ts +86 -0
  75. package/dist/types/components/Progress/Progress.d.ts +56 -0
  76. package/dist/types/components/ProgressSteps/ProgressSteps.d.ts +61 -0
  77. package/dist/types/components/RollingNumber/RollingNumber.d.ts +36 -0
  78. package/dist/types/components/Select/Select.d.ts +36 -8
  79. package/dist/types/components/Separator/Separator.d.ts +19 -0
  80. package/dist/types/components/ShimmerText/ShimmerText.d.ts +28 -0
  81. package/dist/types/components/Stepper/Stepper.d.ts +61 -0
  82. package/dist/types/components/Switch/Switch.d.ts +5 -5
  83. package/dist/types/components/TagInput/TagInput.d.ts +44 -0
  84. package/dist/types/components/TextLink/TextLink.d.ts +30 -0
  85. package/dist/types/components/Textarea/Textarea.d.ts +19 -0
  86. package/dist/types/components/Tip/Tip.d.ts +71 -0
  87. package/dist/types/components/Toolbar/Toolbar.d.ts +9 -1
  88. package/dist/types/components/Tooltip/Tooltip.d.ts +84 -0
  89. package/dist/types/index.d.ts +20 -2
  90. package/dist/types/internal/FloatingPanel.d.ts +70 -0
  91. package/dist/types/internal/fieldStack.d.ts +48 -0
  92. package/dist/types/internal/floating.d.ts +71 -0
  93. package/dist/types/internal/ripple.d.ts +17 -0
  94. package/dist/types/internal/row.d.ts +15 -3
  95. package/dist/types/internal/transition.d.ts +37 -0
  96. package/dist/types/theme/ThemeProvider.d.ts +28 -4
  97. package/dist/types/theme/material.d.ts +20 -6
  98. package/dist/types/theme/types.d.ts +8 -0
  99. package/package.json +2 -2
  100. package/src/components/ActionSheet/ActionSheet.tsx +107 -38
  101. package/src/components/Alert/Alert.tsx +279 -0
  102. package/src/components/Avatar/Avatar.tsx +21 -9
  103. package/src/components/BottomActions/BottomActions.tsx +54 -0
  104. package/src/components/BottomSheet/BottomSheet.tsx +111 -25
  105. package/src/components/Button/Button.tsx +170 -35
  106. package/src/components/Card/Card.tsx +33 -9
  107. package/src/components/Checkbox/Checkbox.tsx +89 -124
  108. package/src/components/Chip/Chip.tsx +49 -6
  109. package/src/components/Dialog/Dialog.tsx +68 -37
  110. package/src/components/Field/Field.tsx +227 -0
  111. package/src/components/FloatingLabelInput/FloatingLabelInput.tsx +144 -0
  112. package/src/components/Icon/createIcon.tsx +16 -6
  113. package/src/components/Indicator/CircularProgress.tsx +141 -0
  114. package/src/components/Indicator/LoadingDots.tsx +79 -0
  115. package/src/components/Indicator/LoadingIndicator.tsx +166 -0
  116. package/src/components/Indicator/index.ts +3 -0
  117. package/src/components/Input/Input.tsx +126 -97
  118. package/src/components/InputGroup/InputGroup.tsx +261 -0
  119. package/src/components/List/List.tsx +345 -88
  120. package/src/components/Menu/Menu.tsx +83 -41
  121. package/src/components/NavigationButton/NavigationButton.tsx +35 -5
  122. package/src/components/OTPInput/OTPInput.tsx +21 -2
  123. package/src/components/PageControl/PageControl.tsx +36 -8
  124. package/src/components/Popover/Popover.tsx +261 -0
  125. package/src/components/Progress/Progress.tsx +255 -0
  126. package/src/components/ProgressSteps/ProgressSteps.tsx +415 -0
  127. package/src/components/RollingNumber/RollingNumber.tsx +189 -0
  128. package/src/components/Select/Select.tsx +175 -71
  129. package/src/components/Separator/Separator.tsx +51 -0
  130. package/src/components/ShimmerText/ShimmerText.tsx +144 -0
  131. package/src/components/Stepper/Stepper.tsx +386 -0
  132. package/src/components/Switch/Switch.tsx +26 -12
  133. package/src/components/TagInput/TagInput.tsx +227 -0
  134. package/src/components/Text/Text.tsx +8 -4
  135. package/src/components/TextLink/TextLink.tsx +77 -0
  136. package/src/components/Textarea/Textarea.tsx +23 -0
  137. package/src/components/Tip/Tip.tsx +410 -0
  138. package/src/components/Toolbar/Toolbar.tsx +27 -2
  139. package/src/components/Tooltip/Tooltip.tsx +478 -0
  140. package/src/index.ts +36 -2
  141. package/src/internal/FloatingPanel.tsx +199 -0
  142. package/src/internal/fieldStack.tsx +179 -0
  143. package/src/internal/floating.ts +131 -0
  144. package/src/internal/ripple.tsx +132 -0
  145. package/src/internal/row.ts +16 -3
  146. package/src/internal/transition.ts +124 -0
  147. package/src/theme/ThemeProvider.tsx +65 -15
  148. package/src/theme/material.ts +39 -7
  149. package/src/theme/types.ts +8 -0
@@ -0,0 +1,261 @@
1
+ import { cloneElement, createContext, isValidElement, useCallback, useContext, useMemo, useRef, useState, type ReactElement, type ReactNode } from "react"
2
+ import { Animated, Easing, StyleSheet, View, useWindowDimensions, type GestureResponderEvent, type StyleProp, type ViewStyle } from "react-native"
3
+ import { useSafeAreaInsets } from "react-native-safe-area-context"
4
+ import { FloatingPanel, paddingOf, type CollisionPadding } from "../../internal/FloatingPanel"
5
+ import { anchorProps, type FloatingAlign, type FloatingSide } from "../../internal/floating"
6
+ import { Glass } from "../../internal/Glass"
7
+ import { barSurface, elevationShadow } from "../../theme/material"
8
+ import { useTheme } from "../../theme/ThemeProvider"
9
+ import { useMenuAnchor, type Measurable, type MenuAnchor } from "../Menu/Menu"
10
+
11
+ export type PopoverProps = {
12
+ children: ReactNode
13
+ /** Controlled open state; uncontrolled when omitted. */
14
+ open?: boolean
15
+ /** Called when the popover opens or closes. */
16
+ onOpenChange?: (open: boolean) => void
17
+ }
18
+
19
+ type PopoverContextValue = {
20
+ open: boolean
21
+ setOpen: (open: boolean) => void
22
+ anchor: MenuAnchor | null
23
+ setTrigger: (node: Measurable | null) => void
24
+ place: () => void
25
+ }
26
+ const PopoverContext = createContext<PopoverContextValue | null>(null)
27
+
28
+ export type PopoverController = {
29
+ /** Closes the popover. */
30
+ close: () => void
31
+ /** Shakes the panel side to side, as a form that cannot be sent yet. */
32
+ shake: () => void
33
+ }
34
+ const ControllerContext = createContext<PopoverController | null>(null)
35
+
36
+ /**
37
+ * A floating panel for contextual UI at its trigger, as @plexui/ui's Popover on a phone: a tap on the trigger opens it,
38
+ * a tap anywhere else closes it. On iOS it is the compact glass panel an iPhone presents a popover as (the menus'
39
+ * glass, `--popover-radius` 34, `--menu-shadow`), placed under its trigger and centered by default; on Android a
40
+ * popup of the Plex Android look (its surface, 12dp corners, level 2 shadow) that pops from the trigger. Parts:
41
+ * `Popover.Trigger` and `Popover.Content`; `usePopoverController()` inside the content closes or shakes it.
42
+ */
43
+ export function Popover({ children, open: openProp, onOpenChange }: PopoverProps) {
44
+ const [own, setOwn] = useState(false)
45
+ const open = openProp ?? own
46
+ const { anchor, place, setTrigger } = useMenuAnchor(open)
47
+ const setOpen = useCallback(
48
+ (next: boolean) => {
49
+ const apply = () => {
50
+ if (openProp === undefined) setOwn(next)
51
+ onOpenChange?.(next)
52
+ }
53
+ // The trigger is measured before the panel opens at it
54
+ if (next) place(apply)
55
+ else apply()
56
+ },
57
+ [openProp, onOpenChange, place],
58
+ )
59
+ const value = useMemo(() => ({ open, setOpen, anchor, setTrigger, place: () => place() }), [open, setOpen, anchor, setTrigger, place])
60
+ return <PopoverContext.Provider value={value}>{children}</PopoverContext.Provider>
61
+ }
62
+ Popover.displayName = "Popover"
63
+
64
+ function usePopover(part: string) {
65
+ const context = useContext(PopoverContext)
66
+ if (!context) throw new Error(`${part} must be inside a Popover`)
67
+ return context
68
+ }
69
+
70
+ type TriggerChildProps = { onPress?: (event: GestureResponderEvent) => void; ref?: unknown; onLayout?: (event: never) => void }
71
+
72
+ export type PopoverTriggerProps = {
73
+ /**
74
+ * The element that toggles the popover: a Button or anything with `onPress` that hands its native view to `ref`
75
+ * (Pressable, View, Text). It keeps its own place in the layout; the panel stands at it.
76
+ */
77
+ children: ReactElement<TriggerChildProps>
78
+ }
79
+
80
+ /** The element that toggles the popover; the panel opens at it, and follows it when it moves. */
81
+ function PopoverTrigger({ children }: PopoverTriggerProps) {
82
+ const { open, setOpen, setTrigger, place } = usePopover("Popover.Trigger")
83
+ if (!isValidElement(children)) return children
84
+ const { onPress } = children.props
85
+ return cloneElement(children, {
86
+ ...anchorProps(children.props, setTrigger as never, open ? place : undefined),
87
+ onPress: (event: GestureResponderEvent) => {
88
+ onPress?.(event)
89
+ setOpen(!open)
90
+ },
91
+ "aria-haspopup": "dialog",
92
+ "aria-expanded": open,
93
+ } as Record<string, unknown>)
94
+ }
95
+ PopoverTrigger.displayName = "Popover.Trigger"
96
+
97
+ export type PopoverContentProps = {
98
+ children: ReactNode
99
+ /** The panel's width; `"auto"` fits its content between `minWidth` and `maxWidth`. @default "auto" */
100
+ width?: number | "auto"
101
+ /** @default 300 */
102
+ minWidth?: number | "auto"
103
+ /** Capped by the room inside the window. @default 700 */
104
+ maxWidth?: number
105
+ /** The side of the trigger; it turns when it does not fit. @default "bottom" */
106
+ side?: FloatingSide
107
+ /** @default "center" */
108
+ align?: FloatingAlign
109
+ /** From the trigger's edge, negative to overlap it. @default 8 */
110
+ sideOffset?: number
111
+ /** From the start or end alignment. @default -5 for `start` and `end`, 0 for `center` */
112
+ alignOffset?: number
113
+ /** Turns and moves to stay inside the window. @default true */
114
+ avoidCollisions?: boolean
115
+ /** Kept free at the window's edges (the safe area at least); an object leaves 0 at a side it does not name. @default 20 */
116
+ collisionPadding?: CollisionPadding
117
+ /** A translucent, blurred surface (a light frosted gradient) in place of the glass, with its own shadow. iOS and the web. @default false */
118
+ translucent?: boolean
119
+ /** Moves focus to the panel as it opens (the web). @default true */
120
+ autoFocus?: boolean
121
+ /** The id of the element that names the panel (the web). */
122
+ "aria-labelledby"?: string
123
+ "aria-label"?: string
124
+ testID?: string
125
+ /** The panel's own style (padding, a fixed height). */
126
+ style?: StyleProp<ViewStyle>
127
+ }
128
+
129
+ /** The panel: on iOS the glass of an iPhone popover, on Android the popup surface of the Plex Android look. */
130
+ function PopoverContent({
131
+ children,
132
+ width = "auto",
133
+ minWidth = 300,
134
+ maxWidth = 700,
135
+ side = "bottom",
136
+ align = "center",
137
+ sideOffset = 8,
138
+ alignOffset,
139
+ avoidCollisions = true,
140
+ collisionPadding = 20,
141
+ translucent = false,
142
+ autoFocus = true,
143
+ "aria-labelledby": ariaLabelledBy,
144
+ "aria-label": ariaLabel,
145
+ testID,
146
+ style,
147
+ }: PopoverContentProps) {
148
+ const theme = useTheme()
149
+ const popover = usePopover("Popover.Content")
150
+ const window = useWindowDimensions()
151
+ const insets = useSafeAreaInsets()
152
+ const [shakeX] = useState(() => new Animated.Value(0))
153
+ const shaking = useRef<Animated.CompositeAnimation | null>(null)
154
+ const close = useCallback(() => popover.setOpen(false), [popover])
155
+ const shake = useCallback(() => {
156
+ shaking.current?.stop()
157
+ shakeX.setValue(0)
158
+ // With reduced motion the panel stays still
159
+ if (theme.reducedMotion) return
160
+ // The web's keyframes: 5 to each side twice over 400ms on `ease`
161
+ shaking.current = Animated.timing(shakeX, { toValue: 1, duration: 400, easing: Easing.ease, useNativeDriver: false })
162
+ shaking.current.start()
163
+ }, [shakeX, theme.reducedMotion])
164
+ const controller = useMemo(() => ({ close, shake }), [close, shake])
165
+ const translateX = shakeX.interpolate({ inputRange: [0, 0.2, 0.4, 0.6, 0.8, 1], outputRange: [0, -5, 5, -5, 5, 0] })
166
+ const pad = paddingOf(collisionPadding)
167
+ // The room across the window, as Radix's available width caps `maxWidth`
168
+ const available = window.width - Math.max(pad.left, insets.left) - Math.max(pad.right, insets.right)
169
+ const sizing: ViewStyle = {
170
+ width: width === "auto" ? undefined : Math.min(width, available),
171
+ minWidth: minWidth === "auto" ? undefined : Math.min(minWidth, available),
172
+ maxWidth: Math.min(maxWidth, available),
173
+ maxHeight: window.height - Math.max(pad.top, insets.top) - Math.max(pad.bottom, insets.bottom),
174
+ }
175
+ const android = theme.isAndroid
176
+ const radius = android ? ANDROID_RADIUS : theme.length("--popover-radius", 34)
177
+ const content = <ControllerContext.Provider value={controller}>{children}</ControllerContext.Provider>
178
+ const glass = !android && !translucent
179
+ return (
180
+ <FloatingPanel
181
+ open={popover.open}
182
+ onDismiss={close}
183
+ anchor={popover.anchor}
184
+ side={side}
185
+ align={align}
186
+ sideOffset={sideOffset}
187
+ alignOffset={alignOffset ?? (align === "center" ? 0 : -5)}
188
+ avoidCollisions={avoidCollisions}
189
+ collisionPadding={collisionPadding}
190
+ glass={glass}
191
+ autoFocus={autoFocus}
192
+ role="dialog"
193
+ aria-label={ariaLabel}
194
+ aria-labelledby={ariaLabelledBy}
195
+ testID={testID}
196
+ style={sizing}
197
+ translateX={translateX}
198
+ >
199
+ {() =>
200
+ android ? (
201
+ // Material has no translucent surface: the popup's own
202
+ <View style={[styles.surface, { borderRadius: radius, backgroundColor: barSurface(theme.material, theme.scheme), boxShadow: elevationShadow.level2 }, style]}>
203
+ {content}
204
+ </View>
205
+ ) : translucent ? (
206
+ <TranslucentSurface radius={radius} style={style}>
207
+ {content}
208
+ </TranslucentSurface>
209
+ ) : (
210
+ <Glass
211
+ radius={radius}
212
+ elevation="raised"
213
+ fillToken="--popover-mobile-background"
214
+ filterToken="--popover-mobile-backdrop-filter"
215
+ shadowToken="--menu-shadow"
216
+ style={[styles.surface, style]}
217
+ >
218
+ {content}
219
+ </Glass>
220
+ )
221
+ }
222
+ </FloatingPanel>
223
+ )
224
+ }
225
+ PopoverContent.displayName = "Popover.Content"
226
+
227
+ /**
228
+ * The translucent panel, kept on a phone as on the web: a frosted gradient (light gray from half to whole up the
229
+ * panel, a blue-gray at night) over a 16px blur, with the desktop panel's shadow and hairline.
230
+ */
231
+ function TranslucentSurface({ radius, style, children }: { radius: number; style?: StyleProp<ViewStyle>; children: ReactNode }) {
232
+ const theme = useTheme()
233
+ const dark = theme.scheme === "dark"
234
+ const gradient = dark
235
+ ? "linear-gradient(360deg, rgba(86, 88, 105, 0.25) 0%, rgba(86, 88, 105, 0.49) 100%)"
236
+ : "linear-gradient(360deg, rgba(247, 247, 248, 0.5) 0%, rgba(247, 247, 248, 1) 100%)"
237
+ const shadow = [theme.token("--shadow"), theme.token("--shadow-hairline")].filter((part) => typeof part === "string").join(", ")
238
+ return (
239
+ <Glass radius={radius} blur={16} tint="transparent" style={[styles.surface, { boxShadow: shadow }, style]}>
240
+ <View pointerEvents="none" style={[StyleSheet.absoluteFill, { borderRadius: radius, borderCurve: "continuous", backgroundImage: gradient } as ViewStyle]} />
241
+ {children}
242
+ </Glass>
243
+ )
244
+ }
245
+
246
+ /** `close()` and `shake()` of the popover around: for the content of `Popover.Content`. */
247
+ export function usePopoverController(): PopoverController {
248
+ const controller = useContext(ControllerContext)
249
+ if (!controller) throw new Error("usePopoverController must be inside Popover.Content")
250
+ return controller
251
+ }
252
+
253
+ /** The corner of Android's popups in the Plex Android look. */
254
+ const ANDROID_RADIUS = 12
255
+
256
+ const styles = StyleSheet.create({
257
+ surface: { borderCurve: "continuous" },
258
+ })
259
+
260
+ Popover.Trigger = PopoverTrigger
261
+ Popover.Content = PopoverContent
@@ -0,0 +1,255 @@
1
+ import { useEffect, useState } from "react"
2
+ import { Animated, Easing, Platform, StyleSheet, View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native"
3
+ import { isRTL } from "../../internal/direction"
4
+ import { curves } from "../../internal/motion"
5
+ import { cssEase, useLoopClock, useTransitionValue } from "../../internal/transition"
6
+ import { withAlpha } from "../../theme/material"
7
+ import { useTheme } from "../../theme/ThemeProvider"
8
+ import type { Theme } from "../../theme/types"
9
+
10
+ export type ProgressSize = "sm" | "md" | "lg"
11
+
12
+ export type ProgressColor = "primary" | "secondary" | "success" | "warning" | "caution" | "danger" | "info" | "discovery"
13
+
14
+ /** A part of a segmented bar: its share of `max`, its color, and the name it is read with. */
15
+ export type ProgressSegment = {
16
+ value: number
17
+ /** @default "primary" */
18
+ color?: ProgressColor
19
+ /** Read out with its share, such as "Paid 60%" */
20
+ label?: string
21
+ }
22
+
23
+ export type ProgressProps = {
24
+ /** Current progress value, between `0` and `max`. Omit (or pass `null`) for an indeterminate state. */
25
+ value?: number | null
26
+ /** @default 100 */
27
+ max?: number
28
+ /**
29
+ * Parts of one bar, side by side in their colors, such as paid, pending and due. The value is their sum; they take
30
+ * `value`'s place. A part's share is clamped so the bar never passes `max`.
31
+ */
32
+ segments?: ProgressSegment[]
33
+ /** The bar's thickness: `sm` 4 (iOS's progress view), `md` 6, `lg` 8 (a bar in a stats card). @default "sm" */
34
+ size?: ProgressSize
35
+ /** The color of the filled part. A segmented bar's parts take their own colors. @default "primary" */
36
+ color?: ProgressColor
37
+ /** The value read out; the rounded percentage by default, such as "67%". */
38
+ getValueLabel?: (value: number, max: number) => string
39
+ /** The name read out, when no visible label names the bar. */
40
+ "aria-label"?: string
41
+ /** The `nativeID` of the visible label that names the bar (Android and the web). */
42
+ "aria-labelledby"?: string
43
+ accessibilityLabel?: string
44
+ testID?: string
45
+ style?: StyleProp<ViewStyle>
46
+ }
47
+
48
+ /** The parts of a segmented bar, each clamped so their sum stays within `max`, and their sum. */
49
+ export const progressSegments = (segments: ProgressSegment[], max: number) => {
50
+ let total = 0
51
+ const parts = segments.map((segment) => {
52
+ const value = Math.max(0, Math.min(max - total, segment.value || 0))
53
+ total += value
54
+ return { ...segment, value }
55
+ })
56
+ return { parts, total }
57
+ }
58
+
59
+ const segmentsLabel = (parts: ProgressSegment[], max: number) =>
60
+ parts.map((part) => `${part.label ? `${part.label} ` : ""}${Math.round((part.value / max) * 100)}%`).join(", ")
61
+
62
+ const defaultValueLabel = (value: number, max: number) => `${Math.round((value / max) * 100)}%`
63
+
64
+ /** The fill of a color: the Plex ink for primary (the accent on Android, as its progress bars), else the solid one. */
65
+ function fillColor(theme: Theme, color: ProgressColor) {
66
+ if (color === "primary") return theme.isAndroid ? theme.material.primary : theme.color("--progress-indicator-color", theme.colors.text)
67
+ return theme.color(`--color-background-${color}-solid`)
68
+ }
69
+
70
+ /** The track: `--progress-track-color` on iOS; on Android the slider's track, the ink at 8% (16% at night). */
71
+ const trackColor = (theme: Theme) =>
72
+ theme.isAndroid ? withAlpha(theme.material.onSurface, theme.scheme === "dark" ? 0.16 : 0.08) : theme.color("--progress-track-color")
73
+
74
+ const height = (theme: Theme, size: ProgressSize) =>
75
+ size === "md" ? theme.length("--progress-height-md", 6) : size === "lg" ? theme.length("--progress-height-lg", 8) : theme.length("--progress-height", 4)
76
+
77
+ /** How a new value moves the fill: the CSS transition on iOS; Android's line progress, 300ms decelerating. */
78
+ function valueMotion(theme: Theme) {
79
+ return theme.isAndroid
80
+ ? { duration: 300, easing: curves.decelerate }
81
+ : { duration: theme.duration("--progress-transition-duration", 120), easing: cssEase }
82
+ }
83
+
84
+ /**
85
+ * A horizontal bar of a task's progress, or a sweep while its length is unknown, as @plexui/ui's Progress. iOS:
86
+ * the phone layer's tokens (`--progress-height` 4, 6, 8; `--progress-track-color`; the ink fill); a new value moves
87
+ * the fill in `--progress-transition-duration` (120ms, ease); the indeterminate sweep is 40% of the track, there and
88
+ * back in `--progress-indeterminate-duration` (1.5s, ease-in-out). Android: the Plex Android look's line progress,
89
+ * the accent on the ink at 8%, a new value in 300ms decelerating, and Material's indeterminate pair of lines (1750ms).
90
+ * A segmented bar puts its parts side by side with `--progress-segment-gap` (2) of track between them. With reduced
91
+ * motion a value lands at once and the sweep stands still in the middle.
92
+ */
93
+ export function Progress({
94
+ value = null,
95
+ max = 100,
96
+ segments,
97
+ size = "sm",
98
+ color = "primary",
99
+ getValueLabel = defaultValueLabel,
100
+ "aria-label": ariaLabel,
101
+ "aria-labelledby": ariaLabelledBy,
102
+ accessibilityLabel,
103
+ testID,
104
+ style,
105
+ }: ProgressProps) {
106
+ const theme = useTheme()
107
+ const [width, setWidth] = useState(0)
108
+ const [rtl, setRTL] = useState(false)
109
+ const onLayout = (event: LayoutChangeEvent) => {
110
+ const next = event.nativeEvent.layout.width
111
+ setWidth((old) => (old === next ? old : next))
112
+ const direction = isRTL(event.currentTarget)
113
+ setRTL((old) => (old === direction ? old : direction))
114
+ }
115
+ const rootMax = typeof max === "number" && max > 0 && !Number.isNaN(max) ? max : 100
116
+ const thickness = height(theme, size)
117
+ const name = accessibilityLabel ?? ariaLabel
118
+
119
+ let content
120
+ let now: number | undefined
121
+ let text: string | undefined
122
+ if (segments) {
123
+ const { parts, total } = progressSegments(segments, rootMax)
124
+ now = total
125
+ text = segmentsLabel(parts, rootMax)
126
+ content = (
127
+ <View style={[styles.segments, { gap: theme.length("--progress-segment-gap", 2) }]}>
128
+ {parts.map((part, index) => (part.value > 0 ? <Segment key={index} share={part.value / rootMax} color={fillColor(theme, part.color ?? "primary")} theme={theme} /> : null))}
129
+ </View>
130
+ )
131
+ } else {
132
+ const resolved = value == null ? null : Math.max(0, Math.min(rootMax, value))
133
+ now = resolved ?? undefined
134
+ text = resolved == null ? undefined : getValueLabel(resolved, rootMax)
135
+ const fill = fillColor(theme, color)
136
+ content =
137
+ resolved == null ? (
138
+ theme.isAndroid ? (
139
+ <AndroidSweep width={width} color={fill} theme={theme} />
140
+ ) : (
141
+ <Sweep width={width} rtl={rtl} color={fill} theme={theme} />
142
+ )
143
+ ) : (
144
+ <Fill fraction={resolved / rootMax} width={width} rtl={rtl} color={fill} theme={theme} />
145
+ )
146
+ }
147
+
148
+ return (
149
+ <View
150
+ accessible
151
+ accessibilityRole="progressbar"
152
+ accessibilityLabel={name}
153
+ accessibilityValue={now == null ? undefined : { min: 0, max: rootMax, now, text }}
154
+ accessibilityState={now == null ? { busy: true } : undefined}
155
+ aria-labelledby={ariaLabelledBy}
156
+ {...(Platform.OS === "web" ? { "aria-valuemin": 0, "aria-valuemax": rootMax, "aria-valuenow": now, "aria-valuetext": text } : null)}
157
+ testID={testID}
158
+ onLayout={onLayout}
159
+ style={[styles.root, { height: thickness, borderRadius: thickness / 2, backgroundColor: trackColor(theme) }, style]}
160
+ >
161
+ {content}
162
+ </View>
163
+ )
164
+ }
165
+
166
+ /** The filled part: the whole track's width, moved back by what is left (rounded at its leading end). */
167
+ function Fill({ fraction, width, rtl, color, theme }: { fraction: number; width: number; rtl: boolean; color: string; theme: Theme }) {
168
+ const motion = valueMotion(theme)
169
+ const shown = useTransitionValue(fraction, { ...motion, native: true, reducedMotion: theme.reducedMotion })
170
+ const [span] = useState(() => new Animated.Value(width))
171
+ useEffect(() => span.setValue(width), [span, width])
172
+ const translateX = Animated.multiply(shown.interpolate({ inputRange: [0, 1], outputRange: rtl ? [1, 0] : [-1, 0] }), span)
173
+ return (
174
+ <Animated.View
175
+ pointerEvents="none"
176
+ // Until the track is measured the fill waits, so a first frame does not show it full
177
+ style={[StyleSheet.absoluteFill, styles.rounded, { backgroundColor: color, opacity: width > 0 ? 1 : 0, transform: [{ translateX }] }]}
178
+ />
179
+ )
180
+ }
181
+
182
+ /** iOS's sweep: 40% of the track goes from just before its start to past its end and back, ease-in-out each way. */
183
+ function Sweep({ width, rtl, color, theme }: { width: number; rtl: boolean; color: string; theme: Theme }) {
184
+ const period = theme.duration("--progress-indeterminate-duration", 1500)
185
+ const moving = !theme.reducedMotion && width > 0
186
+ const clock = useLoopClock(period, moving, true)
187
+ const [span] = useState(() => new Animated.Value(width))
188
+ useEffect(() => span.setValue(width), [span, width])
189
+ const half = period / 2
190
+ // translateX of the 40% bar in its own widths: -100% → 150% → -100% (keyframes 0, 50%, 100%)
191
+ const phase = clock.interpolate({
192
+ inputRange: [0, half, period],
193
+ outputRange: [-1, 1.5, -1],
194
+ easing: curves.easeInOut,
195
+ })
196
+ const share = 0.4
197
+ const translateX = moving ? Animated.multiply(Animated.multiply(phase, rtl ? -share : share), span) : (rtl ? -0.3 : 0.3) * width
198
+ // With reduced motion the bar stands still in the middle
199
+ return (
200
+ <Animated.View
201
+ pointerEvents="none"
202
+ style={[styles.sweep, styles.rounded, { width: `${share * 100}%`, backgroundColor: color, opacity: width > 0 ? 1 : 0, transform: [{ translateX }] }]}
203
+ />
204
+ )
205
+ }
206
+
207
+ /** Material's indeterminate line progress: two lines run along the track in 1750ms (Compose's keyframes). */
208
+ const LINES = [
209
+ { head: [0, 1000], tail: [250, 1000] },
210
+ { head: [650, 850], tail: [900, 850] },
211
+ ] as const
212
+ const LINE_PERIOD = 1750
213
+ /** Material's emphasized accelerate curve, on which each end of a line runs. */
214
+ const emphasizedAccelerate = Easing.bezier(0.3, 0, 0.8, 0.15)
215
+
216
+ function AndroidSweep({ width, color, theme }: { width: number; color: string; theme: Theme }) {
217
+ const moving = !theme.reducedMotion && width > 0
218
+ // The lines' ends move the layout (left, width), which the native driver cannot run
219
+ const clock = useLoopClock(LINE_PERIOD, moving, false)
220
+ if (!moving) {
221
+ // With reduced motion a line stands still in the middle
222
+ return <View pointerEvents="none" style={[styles.sweep, styles.rounded, { start: "30%", width: "40%", backgroundColor: color, opacity: width > 0 ? 1 : 0 }]} />
223
+ }
224
+ const end = ([delay, duration]: readonly [number, number]) =>
225
+ clock.interpolate({ inputRange: [delay, delay + duration], outputRange: [0, width], easing: emphasizedAccelerate, extrapolate: "clamp" })
226
+ return (
227
+ <>
228
+ {LINES.map((line, index) => {
229
+ const head = end(line.head)
230
+ const tail = end(line.tail)
231
+ return <Animated.View key={index} pointerEvents="none" style={[styles.sweep, styles.rounded, { start: tail, width: Animated.subtract(head, tail), backgroundColor: color }]} />
232
+ })}
233
+ </>
234
+ )
235
+ }
236
+
237
+ /** A part of a segmented bar: its share of the track, which a change moves as the CSS transition of its width. */
238
+ function Segment({ share, color, theme }: { share: number; color: string; theme: Theme }) {
239
+ const shown = useTransitionValue(share, { ...valueMotion(theme), reducedMotion: theme.reducedMotion })
240
+ return (
241
+ <Animated.View
242
+ pointerEvents="none"
243
+ style={[styles.segment, { width: shown.interpolate({ inputRange: [0, 1], outputRange: ["0%", "100%"] }), backgroundColor: color }]}
244
+ />
245
+ )
246
+ }
247
+
248
+ const styles = StyleSheet.create({
249
+ root: { width: "100%", overflow: "hidden" },
250
+ rounded: { borderRadius: 9999 },
251
+ sweep: { position: "absolute", top: 0, bottom: 0, start: 0 },
252
+ segments: { flex: 1, flexDirection: "row" },
253
+ // A full bar's parts give the gaps back in proportion, so the last one is not cut off at the end
254
+ segment: { flexShrink: 1, minWidth: 0, height: "100%" },
255
+ })