Refactor DateField, web done

This commit is contained in:
Eric Bailey
2024-01-18 13:14:18 -06:00
parent fb2e366b0e
commit ead02d766c
7 changed files with 342 additions and 13 deletions
@@ -0,0 +1,161 @@
import React from 'react'
import {View, TextStyle, Pressable} from 'react-native'
import DateTimePicker, {
BaseProps as DateTimePickerProps,
} from '@react-native-community/datetimepicker'
import {Logo} from '#/view/icons/Logo'
import {useTheme, atoms, tokens} from '#/alf'
import {Text} from '#/components/Typography'
import {useInteractionState} from '#/components/hooks/useInteractionState'
import {InputDateProps} from '#/components/forms/InputDate/types'
import {
localizeDate,
toSimpleDateString,
} from '#/components/forms/InputDate/utils'
export * as utils from '#/components/forms/InputDate/utils'
export function InputDate({
value: initialValue,
onChange,
testID,
label,
hasError,
accessibilityLabel,
accessibilityHint,
...props
}: InputDateProps) {
const labelId = React.useId()
const t = useTheme()
const [open, setOpen] = React.useState(false)
const [value, setValue] = React.useState(initialValue)
const {state: focused, onIn: onFocus, onOut: onBlur} = useInteractionState()
const {inputStyles, iconStyles} = React.useMemo(() => {
const input: TextStyle[] = [
{
paddingLeft: 40,
},
]
const icon: TextStyle[] = []
if (hasError) {
input.push({
borderColor: tokens.color.red_200,
})
icon.push({
color: tokens.color.red_400,
})
}
if (focused) {
input.push({
borderColor: t.atoms.border_contrast.borderColor,
})
if (hasError) {
input.push({
borderColor: tokens.color.red_500,
})
}
}
return {inputStyles: input, iconStyles: icon}
}, [t, focused, hasError])
const onChangeInternal = React.useCallback<
Required<DateTimePickerProps>['onChange']
>(
(_event, date) => {
setOpen(false)
if (date) {
const formatted = toSimpleDateString(date)
onChange(formatted)
setValue(formatted)
}
},
[onChange, setOpen, setValue],
)
return (
<View style={[atoms.relative, atoms.w_full]}>
{label && (
<Text
nativeID={labelId}
style={[
atoms.text_sm,
atoms.font_bold,
t.atoms.text_contrast_600,
atoms.mb_sm,
]}>
{label}
</Text>
)}
<Pressable
{...props}
aria-labelledby={labelId}
aria-label={label}
accessibilityLabelledBy={labelId}
accessibilityLabel={accessibilityLabel}
accessibilityHint={accessibilityHint}
onPress={() => setOpen(true)}
onFocus={onFocus}
onBlur={onBlur}
style={[
{
paddingTop: atoms.pt_md.paddingTop + 2,
},
atoms.w_full,
atoms.px_lg,
atoms.pb_md,
atoms.rounded_sm,
t.atoms.bg_contrast_100,
...inputStyles,
]}>
<Text style={[atoms.text_md, t.atoms.text]}>{localizeDate(value)}</Text>
</Pressable>
<View
style={[
atoms.absolute,
atoms.inset_0,
atoms.align_center,
atoms.justify_center,
atoms.pl_md,
{right: 'auto'},
]}>
<Logo
style={[
{color: t.atoms.border_contrast.borderColor},
{
width: 20,
pointerEvents: 'none',
},
...iconStyles,
]}
/>
</View>
{open && (
<DateTimePicker
testID={`${testID}-datepicker`}
mode="date"
timeZoneName={'Etc/UTC'}
display="spinner"
// @ts-ignore applies in iOS only -prf
themeVariant={t.name === 'dark' ? 'dark' : 'light'}
value={new Date(value)}
onChange={onChangeInternal}
accessibilityLabel={accessibilityLabel}
accessibilityHint={accessibilityHint}
aria-labelledby={labelId}
aria-label={label}
/>
)}
</View>
)
}
+63
View File
@@ -0,0 +1,63 @@
import React from 'react'
import {View} from 'react-native'
import DateTimePicker, {
DateTimePickerEvent,
} from '@react-native-community/datetimepicker'
import {useTheme, atoms} from '#/alf'
import {toSimpleDateString} from '#/components/forms/InputDate/utils'
import {InputDateProps} from '#/components/forms/InputDate/types'
import TextField from '#/components/forms/TextField'
export * as utils from '#/components/forms/InputDate/utils'
export const Label = TextField.Label
/**
* Date-only input. Accepts a date in the format YYYY-MM-DD, and reports date
* changes in the same format.
*
* For dates of unknown format, convert with the
* `utils.toSimpleDateString(Date)` export of this file.
*/
export function DateField({
value: initialValue,
onChange,
testID,
label,
accessibilityLabel,
accessibilityHint,
}: InputDateProps) {
const labelId = React.useId()
const t = useTheme()
const [value, setValue] = React.useState(initialValue)
const onChangeInternal = React.useCallback(
(event: DateTimePickerEvent, date: Date | undefined) => {
if (date) {
const formatted = toSimpleDateString(date)
onChange(formatted)
setValue(formatted)
}
},
[onChange],
)
return (
<View style={[atoms.relative, atoms.w_full]}>
<DateTimePicker
testID={`${testID}-datepicker`}
mode="date"
timeZoneName={'Etc/UTC'}
display="spinner"
// @ts-ignore applies in iOS only -prf
themeVariant={t.name === 'dark' ? 'dark' : 'light'}
value={new Date(value)}
onChange={onChangeInternal}
accessibilityLabel={accessibilityLabel}
accessibilityHint={accessibilityHint}
aria-labelledby={labelId}
aria-label={label}
/>
</View>
)
}
@@ -0,0 +1,71 @@
import React from 'react'
import {TextInput, TextInputProps, StyleSheet} from 'react-native'
// @ts-ignore
import {unstable_createElement} from 'react-native-web'
import TextField, {createInput} from '#/components/forms/TextField'
import {toSimpleDateString} from '#/components/forms/InputDate/utils'
export * as utils from '#/components/forms/InputDate/utils'
export const Label = TextField.Label
const InputBase = React.forwardRef<HTMLInputElement, TextInputProps>(
({style, ...props}, ref) => {
return unstable_createElement('input', {
...props,
ref,
type: 'date',
style: [
StyleSheet.flatten(style),
{
background: 'transparent',
border: 0,
},
],
})
},
)
InputBase.displayName = 'InputBase'
const Input = createInput(InputBase as unknown as typeof TextInput)
export function DateField({
value,
onChange,
label,
isInvalid,
testID,
}: {
value: string
onChange: (value: string) => void
label: string
isInvalid?: boolean
testID?: string
}) {
const handleOnChange = React.useCallback(
(e: any) => {
const date = e.target.valueAsDate || e.target.value
if (date) {
const formatted = toSimpleDateString(date)
onChange(formatted)
}
},
[onChange],
)
return (
<TextField.Root>
<Input
value={value}
label={label}
onChange={handleOnChange}
onChangeText={() => {}}
isInvalid={isInvalid}
testID={testID}
/>
</TextField.Root>
)
}
+10
View File
@@ -0,0 +1,10 @@
import {TextInputProps} from 'react-native'
import {BaseProps} from '#/components/forms/types'
export type InputDateProps = BaseProps & {
/**
* **NOTE:** Available only on web
*/
autoFocus?: TextInputProps['autoFocus']
}
+16
View File
@@ -0,0 +1,16 @@
import {getLocales} from 'expo-localization'
const LOCALE = getLocales()[0]
// we need the date in the form yyyy-MM-dd to pass to the input
export function toSimpleDateString(date: Date | string): string {
const _date = typeof date === 'string' ? new Date(date) : date
return _date.toISOString().split('T')[0]
}
export function localizeDate(date: Date | string): string {
const _date = typeof date === 'string' ? new Date(date) : date
return new Intl.DateTimeFormat(LOCALE.languageTag, {
timeZone: 'UTC',
}).format(_date)
}
+13 -3
View File
@@ -94,7 +94,7 @@ function Root({children, isInvalid = false}: RootProps) {
paddingVertical: 14,
},
]}
onPressIn={() => inputRef.current?.focus()}
onPress={() => inputRef.current?.focus()}
onHoverIn={onHoverIn}
onHoverOut={onHoverOut}>
{children}
@@ -103,7 +103,7 @@ function Root({children, isInvalid = false}: RootProps) {
)
}
function useSharedInputStyles() {
export function useSharedInputStyles() {
const t = useTheme()
return React.useMemo(() => {
const hover: ViewStyle[] = [
@@ -228,6 +228,15 @@ export function createInput(Component: typeof TextInput) {
const Input = createInput(TextInput)
function Label({children}: React.PropsWithChildren<{}>) {
const t = useTheme()
return (
<Text style={[a.text_sm, a.font_bold, t.atoms.text_contrast_600, a.mb_sm]}>
{children}
</Text>
)
}
function Icon({icon: Comp}: {icon: React.ComponentType<SVGIconProps>}) {
const t = useTheme()
const ctx = React.useContext(Context)
@@ -266,7 +275,7 @@ function Icon({icon: Comp}: {icon: React.ComponentType<SVGIconProps>}) {
<Comp
size="md"
style={[
{color: t.palette.contrast_500},
{color: t.palette.contrast_500, pointerEvents: 'none'},
ctx.hovered ? hover : {},
ctx.focused ? focus : {},
ctx.isInvalid && ctx.hovered ? errorHover : {},
@@ -317,6 +326,7 @@ function Suffix({
export default {
Root,
Input,
Label,
Icon,
Suffix,
}
+8 -10
View File
@@ -4,7 +4,7 @@ import {View} from 'react-native'
import {atoms as a} from '#/alf'
import {H1, H3} from '#/components/Typography'
import TextField from '#/components/forms/TextField'
import {InputDate, utils} from '#/components/forms/InputDate'
import {DateField} from '#/components/forms/DateField'
import Toggle from '#/components/forms/Toggle'
import ToggleButton from '#/components/forms/ToggleButton'
import {Button} from '#/components/Button'
@@ -17,6 +17,7 @@ export function Forms() {
const [toggleGroupDValues, setToggleGroupDValues] = React.useState(['warn'])
const [value, setValue] = React.useState('')
const [date, setDate] = React.useState('2001-01-01')
return (
<View style={[a.gap_4xl, a.align_start]}>
@@ -51,16 +52,13 @@ export function Forms() {
</TextField.Root>
<H3>InputDate</H3>
<InputDate
<DateField
testID="date"
value={'2001-01-01'}
onChange={date => console.log(date)}
label="Input"
/>
<InputDate
testID="date"
value={utils.toSimpleDateString(new Date())}
onChange={date => console.log(date)}
value={date}
onChange={date => {
console.log(date)
setDate(date)
}}
label="Input"
/>
</View>