Skip to content

fix(DateInput): onChange trigger #5324

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: beta
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/hot-hands-take.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ultraviolet/ui": patch
---

`DateInput`: value changes onBlur instead of onChange to avoid wrong dates while the user is typing
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,88 @@ exports[`DateInputField > should clear field 1`] = `
color: #ffffff;
}

.emotion-67 {
display: -webkit-inline-box;
display: -webkit-inline-flex;
display: -ms-inline-flexbox;
display: inline-flex;
position: relative;
height: 3rem;
padding: 0 1rem;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
gap: 0.5rem;
border-radius: 0.25rem;
box-sizing: border-box;
width: auto;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
cursor: pointer;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
outline-offset: 2px;
white-space: nowrap;
-webkit-text-decoration: none;
text-decoration: none;
font-size: 1rem;
font-family: Inter,sans-serif;
font-weight: 500;
letter-spacing: 0;
line-height: 1.5rem;
paragraph-spacing: 0;
text-case: none;
background: #8c40ef;
border: none;
color: #ffffff;
height: 1.5625rem;
width: 100%;
padding: 0;
color: #727683;
}

.emotion-67:hover {
-webkit-text-decoration: none;
text-decoration: none;
}

.emotion-67:active {
box-shadow: 0px 0px 0px 3px #8c40ef40;
}

.emotion-67 .e1y1n78x0 {
stroke: transparent;
}

.emotion-67:hover,
.emotion-67:active {
background: #792dd4;
color: #f9f9fa;
}

.emotion-67[aria-label="in-range"] {
color: #521094;
background-color: #f1eefc;
}

.emotion-67[aria-label="in-range"]:hover {
color: #ffffff;
background-color: #792dd4;
}

.emotion-67[aria-label="not-current"],
.emotion-67:disabled {
color: #b5b7bd;
}

.emotion-67[aria-label="selected"] {
color: #ffffff;
}

<div
data-testid="testing"
>
Expand Down Expand Up @@ -670,8 +752,8 @@ exports[`DateInputField > should clear field 1`] = `
31
</button>
<button
aria-label="neutral"
class="emotion-57 emotion-58 emotion-24"
aria-label="selected"
class="emotion-57 emotion-67 emotion-68"
type="button"
>
1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,9 @@ describe('DateInputField', () => {

const input = screen.getByPlaceholderText<HTMLInputElement>('YYYY-MM-DD')
await userEvent.click(input)
await userEvent.click(screen.getByText('15'))
await userEvent.click(screen.getByText('18'))
await userEvent.click(screen.getByText('15'))

await waitFor(() => {
expect(onChange).toBeCalledTimes(2)
})
Expand Down
23 changes: 15 additions & 8 deletions packages/ui/src/components/DateInput/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,7 @@ describe('DateInput', () => {
await userEvent.click(input)

await userEvent.type(input, '08/21/1995')
input.blur()
expect(mockOnChange).toBeCalled()
expect(screen.getByText('August', { exact: false })).toBeInTheDocument()
})
Expand All @@ -429,6 +430,7 @@ describe('DateInput', () => {
await userEvent.click(input)

await userEvent.type(input, '08/21/1995')
input.blur()
expect(mockOnChange).toBeCalled()
expect(screen.getByText('August', { exact: false })).toBeInTheDocument()
})
Expand All @@ -448,26 +450,31 @@ describe('DateInput', () => {
await userEvent.click(input)

await userEvent.type(input, '2000/08')
input.blur()

expect(mockOnChange).toBeCalled()
expect(screen.getByText('2000', { exact: false })).toBeInTheDocument()
})

test('handle correctly type in input with select range and showMonthYearPicker', async () => {
const mockOnChange = vi.fn()
renderWithTheme(
<DateInput
label="Date"
placeholder="YYYY-MM-DD"
selectsRange
showMonthYearPicker
onChange={mockOnChange}
/>,
<>
<DateInput
label="Date"
placeholder="YYYY-MM-DD"
selectsRange
showMonthYearPicker
onChange={mockOnChange}
/>
test
</>,
)

const input = screen.getByPlaceholderText<HTMLInputElement>('YYYY-MM-DD')
await userEvent.click(input)

await userEvent.type(input, '2000/08')
input.blur()
expect(mockOnChange).toBeCalled()
expect(screen.getByText('2000', { exact: false })).toBeInTheDocument()
})
Expand Down
50 changes: 48 additions & 2 deletions packages/ui/src/components/DateInput/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,14 @@
) => {
if (selectsRange && computedRange) {
return format
? `${format(computedRange.start ?? undefined) ? `${format(computedRange.start ?? undefined)} - ` : ''}${format(computedRange.end ?? undefined) ?? ''}`
: `${getDateISO(showMonthYearPicker, computedRange.start ?? undefined)}${computedRange.start ? ' - ' : ''}${getDateISO(showMonthYearPicker, computedRange.end ?? undefined)}`
? `${
format(computedRange.start ?? undefined)
? `${format(computedRange.start ?? undefined)} - `
: ''

Check warning on line 72 in packages/ui/src/components/DateInput/helpers.ts

View check run for this annotation

Codecov / codecov/patch

packages/ui/src/components/DateInput/helpers.ts#L72

Added line #L72 was not covered by tests
}${format(computedRange.end ?? undefined) ?? ''}`
: `${getDateISO(showMonthYearPicker, computedRange.start ?? undefined)}${
computedRange.start ? ' - ' : ''
}${getDateISO(showMonthYearPicker, computedRange.end ?? undefined)}`
}

if (computedValue && format) {
Expand All @@ -87,3 +93,43 @@
border-radius: ${theme.radii.default};
background-color: ${theme.colors.other.elevation.background.raised};
`

export const createDate = (value: string, showMonthYearPicker: boolean) => {
if (showMonthYearPicker) {
// Force YYYY/MM (since MM/YYYY not recognised as a date in typescript)
const res = value.split(/\D+/).map(val => Number.parseInt(val, 10))
const year =
Math.max(...res) < 100 ? Math.max(...res) + 2000 : Math.max(...res) // MM/YY should be seen as MM/20YY instead of MM/19YY

const month = Math.min(...res) - 1
const computedDate = new Date(year, month)
const isValidDate = !!computedDate.getTime()

return isValidDate ? computedDate : null
}

const computedDate = new Date(value)
const isValidDate = !!computedDate.getTime()

return isValidDate ? computedDate : null
}

export const createDateRange = (
value: string,
showMonthYearPicker: boolean,
) => {
const [startDateInput, endDateInput] = value
.split(' - ')
.map(val => createDate(val, showMonthYearPicker))

const computedNewRange: [Date | null, Date | null] = [
startDateInput instanceof Date && !Number.isNaN(startDateInput.getTime())
? startDateInput
: null,
endDateInput instanceof Date && !Number.isNaN(endDateInput.getTime())
? endDateInput

Check warning on line 130 in packages/ui/src/components/DateInput/helpers.ts

View check run for this annotation

Codecov / codecov/patch

packages/ui/src/components/DateInput/helpers.ts#L130

Added line #L130 was not covered by tests
: null,
]

return computedNewRange
}
72 changes: 37 additions & 35 deletions packages/ui/src/components/DateInput/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ import { DateInputContext } from './Context'
import type { ContextProps } from './Context'
import { CalendarContent } from './components/CalendarContent'
import { CalendarPopup } from './components/Popup'
import { formatValue, styleCalendarContainer } from './helpers'
import {
createDate,
createDateRange,
formatValue,
styleCalendarContainer,
} from './helpers'
import { getDays, getLocalizedMonths, getMonths } from './helpersLocale'

const Container = styled.div`
Expand Down Expand Up @@ -146,6 +151,7 @@ export const DateInput = <IsRange extends undefined | boolean>({
)
const [hoveredDate, setHoveredDate] = useState<Date | null>(null)
const refInput = useRef<HTMLInputElement>(null)
const popupRef = useRef<HTMLDivElement>(null)
const MONTHS = getMonths(locale)
const DAYS = getDays(locale)
const MONTHS_ARR = getLocalizedMonths(locale)
Expand Down Expand Up @@ -225,28 +231,11 @@ export const DateInput = <IsRange extends undefined | boolean>({

const manageOnChange = (event: ChangeEvent<HTMLInputElement>) => {
const newValue = event.currentTarget.value
// @ts-expect-error can't get the correct type
if (!newValue) onChange?.(selectsRange ? [null, null] : null)

if (selectsRange) {
const [startDateInput, endDateInput] = newValue.split(' - ').map(val => {
if (showMonthYearPicker) {
// Force YYYY/MM (since MM/YYYY not recognised as a date in typescript)
const res = val.split(/\D+/).map(aa => Number.parseInt(aa, 10))

return new Date(Math.max(...res), Math.min(...res) - 1)
}

return new Date(val)
})

const computedNewRange: [Date | null, Date | null] = [
startDateInput instanceof Date &&
!Number.isNaN(startDateInput.getTime())
? startDateInput
: null,
endDateInput instanceof Date && !Number.isNaN(endDateInput.getTime())
? endDateInput
: null,
]
const computedNewRange = createDateRange(newValue, showMonthYearPicker)

setRange({ start: computedNewRange[0], end: computedNewRange[1] })
setInputValue(newValue)
Expand All @@ -255,26 +244,37 @@ export const DateInput = <IsRange extends undefined | boolean>({
setMonthToShow(computedNewRange[0].getMonth() + 1)
setYearToShow(computedNewRange[0].getFullYear())
}
// TypeScript fails to automatically get the correct type of onChange here
;(
onChange as (
date: Date[] | [Date | null, Date | null],
event: React.SyntheticEvent | undefined,
) => void
)?.(computedNewRange, event)
} else {
const computedDate = Date.parse(newValue) ? new Date(newValue) : null
setInputValue(newValue)
setValue(computedDate)
const computedDate = createDate(newValue, showMonthYearPicker)

if (computedDate) {
setMonthToShow(computedDate.getMonth() + 1)
setYearToShow(computedDate.getFullYear())
}
// TypeScript fails to automatically get the correct type of onChange here
;(
onChange as (date: Date | null, event?: React.SyntheticEvent) => void
)?.(computedDate, event)
}
setInputValue(newValue)
}

const onBlurInput = (event: FocusEvent) => {
// Only call onChange when there is a date typed in the input and the user did not click on the calendar (which triggers onChange itself)
if (inputValue && !popupRef.current?.contains(event.relatedTarget)) {
if (selectsRange) {
const computedNewRange = createDateRange(
inputValue,
showMonthYearPicker,
)
;(
onChange as (
date: Date[] | [Date | null, Date | null],
event: React.SyntheticEvent | undefined,
) => void
)?.(computedNewRange, event)
} else {
const computedDate = createDate(inputValue, showMonthYearPicker)
;(
onChange as (date: Date | null, event?: React.SyntheticEvent) => void
)?.(computedDate, event)
}
}
}

Expand All @@ -289,6 +289,7 @@ export const DateInput = <IsRange extends undefined | boolean>({
onClick={() => {
if (!isPopupVisible) setVisible(true)
}}
ref={popupRef}
>
{input === 'text' ? (
<CalendarPopup
Expand Down Expand Up @@ -322,6 +323,7 @@ export const DateInput = <IsRange extends undefined | boolean>({
tooltip={tooltip}
autoComplete="false"
onChange={manageOnChange}
onBlur={onBlurInput}
clearable={clearable}
/>
</CalendarPopup>
Expand Down
Loading