@plexui/react-native 0.2.9 → 0.2.11

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.
@@ -0,0 +1,507 @@
1
+ import { useEffect, useMemo, useRef, useState, type ComponentRef, type ReactNode } from "react"
2
+ import {
3
+ Animated,
4
+ ScrollView,
5
+ StyleSheet,
6
+ View,
7
+ useWindowDimensions,
8
+ type GestureResponderEvent,
9
+ type LayoutChangeEvent,
10
+ type StyleProp,
11
+ type TextInputSelectionChangeEvent,
12
+ type ViewStyle,
13
+ } from "react-native"
14
+ import { useSafeAreaInsets } from "react-native-safe-area-context"
15
+ import CheckMd from "../../icons/plex/CheckMd"
16
+ import Search from "../../icons/plex/Search"
17
+ import { Pressable } from "../../internal/Pressable"
18
+ import { ANDROID_DIM, iosDim, Overlay } from "../../internal/Overlay"
19
+ import { useKeyboardHeight } from "../../internal/keyboard"
20
+ import { useTheme } from "../../theme/ThemeProvider"
21
+ import { Field } from "../Field/Field"
22
+ import { FloatingLabelInput } from "../FloatingLabelInput/FloatingLabelInput"
23
+ import { MaterialArrowDropDown } from "../Icon/material"
24
+ import { Input } from "../Input/Input"
25
+ import { List, ListItem } from "../List/List"
26
+ import { NavigationButton } from "../NavigationButton/NavigationButton"
27
+ import { Text } from "../Text/Text"
28
+ import {
29
+ ALL_COUNTRIES,
30
+ countryFlag,
31
+ countryName,
32
+ deviceCountry,
33
+ dialCode,
34
+ digitsOf,
35
+ fold,
36
+ isCountry,
37
+ matchesCountry,
38
+ readInput,
39
+ readNational,
40
+ readValue,
41
+ tooLongValue,
42
+ type CountryCode,
43
+ type PhoneDetails,
44
+ } from "./phone"
45
+
46
+ export type { CountryCode, PhoneDetails }
47
+
48
+ export type PhoneInputProps = {
49
+ /** The number in E.164 (`+447700900123`), or the digits typed so far after the code; "" when empty. */
50
+ value?: string
51
+ defaultValue?: string
52
+ /** Called on each change with the value in E.164 and what the field knows about it (its region, validity). */
53
+ onChange?: (value: string, details: PhoneDetails) => void
54
+ /** The region the number is typed in. */
55
+ country?: CountryCode
56
+ /** @default the device's region (its locale's), else "US" */
57
+ defaultCountry?: CountryCode
58
+ /** Called when the region changes: picked from the list, or named by a pasted international number. */
59
+ onCountryChange?: (country: CountryCode) => void
60
+ /** The regions the list offers. @default every region with a calling code */
61
+ countries?: readonly CountryCode[]
62
+ /** The locale of the regions' names (Intl.DisplayNames; English where the engine has none). @default the device's */
63
+ locale?: string
64
+ /** Groups the digits as the region writes them, while they are typed at the end. @default false on iOS (Settings' Add Phone Number shows the digits as typed), true on Android */
65
+ formatting?: boolean
66
+ /** Flags before the regions' names in the list. @default false */
67
+ flags?: boolean
68
+ /** The number field's placeholder and name. @default "Phone number" */
69
+ label?: string
70
+ /** The region row's name and the list's title. @default "Country or Region" */
71
+ countryLabel?: string
72
+ /** The list's search placeholder. @default "Search" */
73
+ searchPlaceholder?: string
74
+ /** iOS: the group's header over the two rows. */
75
+ header?: ReactNode
76
+ /** Words under the field (iOS: the group's footer). */
77
+ description?: ReactNode
78
+ /** An error under the field; it marks the field invalid. */
79
+ errorMessage?: string
80
+ invalid?: boolean
81
+ disabled?: boolean
82
+ autoFocus?: boolean
83
+ onBlur?: () => void
84
+ onSubmitEditing?: () => void
85
+ returnKeyType?: "done" | "next" | "go" | "send"
86
+ testID?: string
87
+ style?: StyleProp<ViewStyle>
88
+ }
89
+
90
+ /** A region's calling code, kept left to right in a right-to-left line. */
91
+ const ltr = (text: string) => `⁦${text}⁩`
92
+
93
+ /**
94
+ * A phone number field: the region and the number, as iOS's Add Phone Number (Settings): one group of two rows, the
95
+ * region's code and name with a chevron, which opens the list of regions, then the number alone; on Android Material's
96
+ * region dropdown field over the number's outlined field. The value is E.164; a pasted or autofilled international
97
+ * number picks its region, a national trunk prefix (the UK's 0) is dropped from the value, and the field takes no more
98
+ * digits than the region's longest number (libphonenumber's metadata).
99
+ */
100
+ export function PhoneInput({
101
+ value: valueProp,
102
+ defaultValue,
103
+ onChange,
104
+ country: countryProp,
105
+ defaultCountry,
106
+ onCountryChange,
107
+ countries = ALL_COUNTRIES,
108
+ locale,
109
+ formatting,
110
+ flags = false,
111
+ label = "Phone number",
112
+ countryLabel = "Country or Region",
113
+ searchPlaceholder = "Search",
114
+ header,
115
+ description,
116
+ errorMessage,
117
+ invalid,
118
+ disabled = false,
119
+ autoFocus,
120
+ onBlur,
121
+ onSubmitEditing,
122
+ returnKeyType,
123
+ testID,
124
+ style,
125
+ }: PhoneInputProps) {
126
+ const theme = useTheme()
127
+ const android = theme.isAndroid
128
+ const format = formatting ?? android
129
+ // The first value is read in the first region; an international one names its own (+44… under a US default)
130
+ const [initial] = useState(() => {
131
+ const start = countryProp ?? defaultCountry ?? deviceCountry()
132
+ return readValue(valueProp ?? defaultValue, start && isCountry(start) ? start : "US", format)
133
+ })
134
+ const [ownCountry, setOwnCountry] = useState<CountryCode>(initial.country)
135
+ const country = countryProp ?? ownCountry
136
+ const [text, setText] = useState(initial.text)
137
+ // The value last sent (or read in): a new value from outside that differs from it is read into the field. Only a
138
+ // new one: a parent's value may come a render after the edit, so an unchanged value is not read as a rejected edit
139
+ const sent = useRef(valueProp ?? defaultValue ?? "")
140
+ useEffect(() => {
141
+ if (valueProp === undefined || valueProp === sent.current) return
142
+ sent.current = valueProp
143
+ const details = readValue(valueProp, country, format)
144
+ setText(details.text)
145
+ if (details.country !== country) pickCountry(details.country)
146
+ // Only a new value from outside is read in
147
+ // eslint-disable-next-line react-hooks/exhaustive-deps
148
+ }, [valueProp])
149
+ // A controlled region that the first value names otherwise is told once
150
+ useEffect(() => {
151
+ if (countryProp !== undefined && initial.country !== countryProp) onCountryChange?.(initial.country)
152
+ // eslint-disable-next-line react-hooks/exhaustive-deps
153
+ }, [])
154
+ // Where the caret is: grouping applies to what is typed at the end only
155
+ const selection = useRef<{ start: number; end: number } | null>(null)
156
+ const [open, setOpen] = useState(false)
157
+
158
+ const pickCountry = (next: CountryCode) => {
159
+ if (countryProp === undefined) setOwnCountry(next)
160
+ if (next !== country) onCountryChange?.(next)
161
+ }
162
+ const emit = (details: PhoneDetails) => {
163
+ sent.current = details.value
164
+ onChange?.(details.value, details)
165
+ }
166
+
167
+ const change = (next: string) => {
168
+ const before = text
169
+ let input = next
170
+ // A separator deleted (a space, a dash): the digit before it goes, as the caret would be stuck behind it
171
+ if (input.length < before.length && digitsOf(input) === digitsOf(before)) {
172
+ let at = 0
173
+ while (at < input.length && input[at] === before[at]) at++
174
+ const digit = before.slice(0, at).search(/\d(?=\D*$)/)
175
+ input = digit < 0 ? input : before.slice(0, digit) + before.slice(digit + 1)
176
+ }
177
+ const typing = !/^\s*(\+|00)/.test(input)
178
+ // Typed at the end the digits take their groups; an edit inside keeps the text as it is, grouped again on blur.
179
+ // At the end: the caret was there (where the platform tells it) and one text starts the other
180
+ const caret = selection.current
181
+ const atEnd = (caret == null || caret.end >= before.length) && (input.startsWith(before) || before.startsWith(input))
182
+ const details = readInput(input, country, format && atEnd)
183
+ // No more digits than the region's longest number, typed or pasted
184
+ if (digitsOf(input).length > digitsOf(before).length && tooLongValue(details.value)) return
185
+ setText(format && !atEnd && typing ? input : details.text)
186
+ if (details.country !== country) pickCountry(details.country)
187
+ emit(details)
188
+ }
189
+
190
+ const blur = () => {
191
+ if (format && text && !/^\s*\+/.test(text)) setText(readNational(digitsOf(text), country, true).text)
192
+ onBlur?.()
193
+ }
194
+
195
+ const choose = (next: CountryCode) => {
196
+ setOpen(false)
197
+ if (next === country) return
198
+ pickCountry(next)
199
+ // The digits stay; the value follows the new region's code
200
+ const details = readNational(digitsOf(text), next, format)
201
+ setText(details.text)
202
+ emit(details)
203
+ }
204
+
205
+ const name = countryName(country, locale)
206
+ const code = dialCode(country)
207
+ const regionName = `${countryLabel}, ${name}, ${code.replace("+", "plus ")}`
208
+ const fieldProps = {
209
+ value: text,
210
+ onChangeText: change,
211
+ onSelectionChange: (event: TextInputSelectionChangeEvent) => {
212
+ selection.current = event.nativeEvent.selection
213
+ },
214
+ onBlur: blur,
215
+ onSubmitEditing,
216
+ returnKeyType,
217
+ autoFocus,
218
+ keyboardType: "phone-pad" as const,
219
+ inputMode: "tel" as const,
220
+ textContentType: "telephoneNumber" as const,
221
+ autoComplete: "tel" as const,
222
+ importantForAutofill: "yes" as const,
223
+ accessibilityLabel: label,
224
+ }
225
+ const picker = (
226
+ <CountryPicker
227
+ open={open}
228
+ onClose={() => setOpen(false)}
229
+ value={country}
230
+ onSelect={choose}
231
+ countries={countries}
232
+ locale={locale}
233
+ flags={flags}
234
+ title={countryLabel}
235
+ searchPlaceholder={searchPlaceholder}
236
+ />
237
+ )
238
+ const error = errorMessage || undefined
239
+ const marked = invalid ?? error != null
240
+
241
+ if (android) {
242
+ // Material: the region's dropdown field (its arrow turned while the list is open), the number's field under it
243
+ return (
244
+ <View style={[styles.androidStack, style]} testID={testID}>
245
+ <Pressable
246
+ accessibilityRole="button"
247
+ accessibilityLabel={regionName}
248
+ accessibilityState={{ disabled, expanded: open }}
249
+ disabled={disabled}
250
+ onPress={() => setOpen(true)}
251
+ >
252
+ <View pointerEvents="none">
253
+ <FloatingLabelInput
254
+ label={countryLabel}
255
+ value={`${ltr(code)} ${name}`}
256
+ readOnly
257
+ disabled={disabled}
258
+ endAdornment={
259
+ <View style={open ? styles.turned : null}>
260
+ <MaterialArrowDropDown size={24} color={theme.material.onSurfaceVariant} />
261
+ </View>
262
+ }
263
+ importantForAccessibility="no-hide-descendants"
264
+ />
265
+ </View>
266
+ </Pressable>
267
+ <FloatingLabelInput label={label} type="tel" errorMessage={error} invalid={marked} description={description} disabled={disabled} {...fieldProps} />
268
+ {picker}
269
+ </View>
270
+ )
271
+ }
272
+
273
+ // iOS: one group, the region's row (its code and name in the label color, a chevron) over the number's row
274
+ return (
275
+ <View style={style} testID={testID}>
276
+ <List header={header} footer={description} error={error}>
277
+ <ListItem label={`${ltr(code)} (${name})`} onPress={disabled ? undefined : () => setOpen(true)} disabled={disabled} accessibilityLabel={regionName} />
278
+ <Field row label={label} hideLabel>
279
+ <Input placeholder={label} invalid={marked} disabled={disabled} {...fieldProps} />
280
+ </Field>
281
+ </List>
282
+ {picker}
283
+ </View>
284
+ )
285
+ }
286
+
287
+ type CountryPickerProps = {
288
+ open: boolean
289
+ onClose: () => void
290
+ value: CountryCode
291
+ onSelect: (country: CountryCode) => void
292
+ countries: readonly CountryCode[]
293
+ locale?: string
294
+ flags: boolean
295
+ title: string
296
+ searchPlaceholder: string
297
+ }
298
+
299
+ type Section = { key: string; title?: string; items: { country: CountryCode; name: string }[] }
300
+
301
+ /** The section index's step and its letters' size (UIKit's section index, measured on iOS 27.2: 13.787 a letter, 11pt). */
302
+ const INDEX_STEP = 13.787
303
+
304
+ /**
305
+ * The list of regions: on iOS a sheet as large as the screen allows (the sheet bar's Close and title, a search field
306
+ * under it, the picked and the device's regions first, then A to Z with the section index at the trailing edge, a
307
+ * checkmark on the picked one); on Android Material's full-screen dialog (Close, the title, a search field, the list).
308
+ */
309
+ function CountryPicker({ open, onClose, value, onSelect, countries, locale, flags, title, searchPlaceholder }: CountryPickerProps) {
310
+ const theme = useTheme()
311
+ const android = theme.isAndroid
312
+ const insets = useSafeAreaInsets()
313
+ const { height: screen } = useWindowDimensions()
314
+ const keyboard = useKeyboardHeight(open)
315
+ const [query, setQuery] = useState("")
316
+ // A list that opens again starts from its top, with no search
317
+ const [wasOpen, setWasOpen] = useState(open)
318
+ if (wasOpen !== open) {
319
+ setWasOpen(open)
320
+ if (open) setQuery("")
321
+ }
322
+ const named = useMemo(() => {
323
+ const collator = new Intl.Collator(locale, { sensitivity: "base" })
324
+ return countries.map((country) => ({ country, name: countryName(country, locale) })).sort((a, b) => collator.compare(a.name, b.name))
325
+ }, [countries, locale])
326
+ const sections = useMemo<Section[]>(() => {
327
+ const found = named.filter((item) => matchesCountry(item.country, item.name, query))
328
+ if (query.trim()) return [{ key: "results", items: found }]
329
+ const here = deviceCountry()
330
+ const top = [value, ...(here && here !== value && countries.includes(here) ? [here] : [])]
331
+ const first = { key: "top", items: top.map((country) => ({ country, name: countryName(country, locale) })) }
332
+ const letters = new Map<string, Section>()
333
+ for (const item of found) {
334
+ const letter = fold(item.name).charAt(0).toUpperCase()
335
+ const key = /[A-Z]/.test(letter) ? letter : "#"
336
+ if (!letters.has(key)) letters.set(key, { key, title: key, items: [] })
337
+ letters.get(key)!.items.push(item)
338
+ }
339
+ return [first, ...letters.values()]
340
+ }, [named, query, value, countries, locale])
341
+ const scroller = useRef<ComponentRef<typeof ScrollView>>(null)
342
+ const offsets = useRef<Record<string, number>>({})
343
+ const index = sections.filter((section) => section.title)
344
+ const [indexHeight, setIndexHeight] = useState(0)
345
+ const jump = (event: GestureResponderEvent) => {
346
+ // The letters' step as laid out (they grow with the text size)
347
+ const step = indexHeight > 0 && index.length ? indexHeight / index.length : INDEX_STEP
348
+ const at = Math.floor(event.nativeEvent.locationY / step)
349
+ const section = index[Math.max(0, Math.min(index.length - 1, at))]
350
+ const y = section ? offsets.current[section.key] : undefined
351
+ if (y != null) scroller.current?.scrollTo({ y, animated: false })
352
+ }
353
+ const m = theme.material
354
+ // iOS: the grouped canvas of a picker sheet, the regions in inset groups on it (the section index stands in the
355
+ // margin beside them); Android: the full-screen dialog's surface, the regions in a plain list across it
356
+ const background = android ? m.surface : theme.colors.groupedBackground
357
+ const radius = theme.length("--dialog-sheet-radius", 38)
358
+ const margin = theme.length("--mobile-layout-margin", 16)
359
+ const closeSize = theme.length("--dialog-sheet-close-size", 44)
360
+ const height = android ? screen : screen - insets.top - 16
361
+ const row = (item: { country: CountryCode; name: string }) => {
362
+ const code = dialCode(item.country)
363
+ const picked = item.country === value
364
+ return (
365
+ <ListItem
366
+ key={item.country}
367
+ label={flags ? `${countryFlag(item.country)} ${item.name}` : item.name}
368
+ // The code in the secondary label (an Android row's value would take the accent)
369
+ value={android ? undefined : ltr(code)}
370
+ trailing={
371
+ android ? (
372
+ <View style={styles.androidEnd}>
373
+ <Text color={m.onSurfaceVariant} style={styles.androidCode}>
374
+ {ltr(code)}
375
+ </Text>
376
+ {picked ? <CheckMd color={m.primary} /> : null}
377
+ </View>
378
+ ) : picked ? (
379
+ <CheckMd color={theme.colors.accent} />
380
+ ) : undefined
381
+ }
382
+ disclosure={false}
383
+ onPress={() => onSelect(item.country)}
384
+ accessibilityLabel={`${item.name}, ${code.replace("+", "plus ")}${picked ? ", selected" : ""}`}
385
+ />
386
+ )
387
+ }
388
+ return (
389
+ <Overlay open={open} onDismiss={onClose} scrim={android ? ANDROID_DIM.dialog : iosDim(theme)} motion={android ? "dialog" : "sheet"}>
390
+ {(progress) => (
391
+ <View pointerEvents="box-none" style={styles.bottom}>
392
+ <Animated.View
393
+ accessibilityViewIsModal
394
+ aria-label={title}
395
+ style={[
396
+ styles.sheet,
397
+ {
398
+ height,
399
+ backgroundColor: background,
400
+ paddingTop: android ? insets.top : 0,
401
+ paddingBottom: keyboard,
402
+ borderTopLeftRadius: android ? 0 : radius,
403
+ borderTopRightRadius: android ? 0 : radius,
404
+ opacity: android || theme.reducedMotion ? progress : undefined,
405
+ transform: android || theme.reducedMotion ? undefined : [{ translateY: progress.interpolate({ inputRange: [0, 1], outputRange: [height, 0] }) }],
406
+ },
407
+ ]}
408
+ >
409
+ {android ? (
410
+ // Material's full-screen dialog: Close at the start of a 64dp bar, the title 22sp after it
411
+ <View style={styles.androidBar}>
412
+ <NavigationButton action="close" onPress={onClose} />
413
+ <Text accessibilityRole="header" numberOfLines={1} color={m.onSurface} style={styles.androidTitle}>
414
+ {title}
415
+ </Text>
416
+ </View>
417
+ ) : (
418
+ // The sheet bar: Close at the leading edge, the title centered, 16 under the sheet's top
419
+ <View style={[styles.iosBar, { paddingTop: theme.length("--dialog-sheet-action-inset-block", 16), paddingBottom: theme.length("--toolbar-padding-bottom", 10), paddingHorizontal: margin }]}>
420
+ <View style={{ width: closeSize, height: closeSize }}>
421
+ <NavigationButton action="close" onPress={onClose} />
422
+ </View>
423
+ <View style={[styles.iosHeading, { minHeight: closeSize }]}>
424
+ <Text accessibilityRole="header" weight="semibold" align="center" numberOfLines={1} style={{ fontSize: theme.length("--toolbar-title-font-size", 17), lineHeight: theme.length("--toolbar-title-line-height", 22) }}>
425
+ {title}
426
+ </Text>
427
+ </View>
428
+ <View style={{ width: closeSize }} />
429
+ </View>
430
+ )}
431
+ <View style={{ paddingHorizontal: android ? 16 : margin, paddingBottom: 8 }}>
432
+ <Input
433
+ variant="soft"
434
+ pill={!android}
435
+ value={query}
436
+ onChangeText={setQuery}
437
+ onClear={() => setQuery("")}
438
+ placeholder={searchPlaceholder}
439
+ inputMode="search"
440
+ autoCorrect={false}
441
+ autoCapitalize="none"
442
+ returnKeyType="search"
443
+ accessibilityLabel={searchPlaceholder}
444
+ startAdornment={<Search />}
445
+ />
446
+ </View>
447
+ <View style={styles.grow}>
448
+ <ScrollView ref={scroller} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag" contentContainerStyle={{ paddingHorizontal: android ? 0 : margin, gap: android ? 0 : 8, paddingBottom: keyboard ? 16 : insets.bottom + 16 }}>
449
+ {sections.map((section) =>
450
+ section.items.length ? (
451
+ <View key={section.key} onLayout={(event: LayoutChangeEvent) => (offsets.current[section.key] = event.nativeEvent.layout.y)}>
452
+ <List surface={android ? "plain" : "grouped"} header={section.title}>
453
+ {section.items.map(row)}
454
+ </List>
455
+ </View>
456
+ ) : null,
457
+ )}
458
+ {sections.every((section) => !section.items.length) ? (
459
+ <Text color="secondary" align="center" style={styles.none}>
460
+ No results
461
+ </Text>
462
+ ) : null}
463
+ </ScrollView>
464
+ {/* UIKit's section index: the letters 11pt semibold in the accent, 13.787 apart, centered 7.5 from the edge; a
465
+ touch or a drag on it jumps to the letter's section. Android has none */}
466
+ {!android && !query.trim() ? (
467
+ <View
468
+ style={[styles.index, { marginTop: -indexHeight / 2 }]}
469
+ onLayout={(event: LayoutChangeEvent) => setIndexHeight(event.nativeEvent.layout.height)}
470
+ onStartShouldSetResponder={() => true}
471
+ onMoveShouldSetResponder={() => true}
472
+ onResponderGrant={jump}
473
+ onResponderMove={jump}
474
+ accessible={false}
475
+ importantForAccessibility="no-hide-descendants"
476
+ >
477
+ {index.map((section) => (
478
+ <Text key={section.key} pointerEvents="none" weight="semibold" color={theme.colors.accent} align="center" style={styles.indexLetter}>
479
+ {section.title}
480
+ </Text>
481
+ ))}
482
+ </View>
483
+ ) : null}
484
+ </View>
485
+ </Animated.View>
486
+ </View>
487
+ )}
488
+ </Overlay>
489
+ )
490
+ }
491
+
492
+ const styles = StyleSheet.create({
493
+ androidStack: { gap: 16 },
494
+ turned: { transform: [{ rotate: "180deg" }] },
495
+ bottom: { flex: 1, justifyContent: "flex-end" },
496
+ sheet: { overflow: "hidden" },
497
+ iosBar: { flexDirection: "row", alignItems: "center" },
498
+ iosHeading: { flex: 1, justifyContent: "center", paddingHorizontal: 8 },
499
+ androidBar: { height: 64, flexDirection: "row", alignItems: "center", paddingHorizontal: 4, gap: 4 },
500
+ androidTitle: { flex: 1, fontSize: 22, lineHeight: 28 },
501
+ grow: { flex: 1 },
502
+ androidEnd: { flexDirection: "row", alignItems: "center", gap: 12 },
503
+ androidCode: { fontSize: 16, lineHeight: 24 },
504
+ none: { marginTop: 32 },
505
+ index: { position: "absolute", end: 0, top: "50%", width: 15, alignItems: "center" },
506
+ indexLetter: { fontSize: 11, lineHeight: INDEX_STEP, width: 15 },
507
+ })