Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(dify-ui): use native scroll snapping for date-time option columns (#43723)

yyh6d14cd586132
diff --git a/packages/dify-ui/src/date-time/date-picker/__tests__/gesture.spec.tsx b/packages/dify-ui/src/date-time/date-picker/__tests__/gesture.spec.tsx
index 638eacac780..de7f42a0a89 100644
--- a/packages/dify-ui/src/date-time/date-picker/__tests__/gesture.spec.tsx
+++ b/packages/dify-ui/src/date-time/date-picker/__tests__/gesture.spec.tsx
@@ -24,11 +24,9 @@ async function openMonths() {
return { screen, months, years, changed }
}
-// Synthetic intent with real Chromium scrolling, matching the time-column gesture tests.
-function startTouch(column: Element, top: number) {
- column.dispatchEvent(new Event('touchstart'))
+// Any scroll the column did not start is a selection, matching the time-column scroll tests.
+function scrollColumn(column: Element, top: number) {
column.scrollTo({ top, behavior: 'instant' })
- column.dispatchEvent(new Event('scroll'))
}
it('shares top alignment across click, keyboard and touch and applies both moving month/year columns', async () => {
@@ -49,16 +47,16 @@ it('shares top alignment across click, keyboard and touch and applies both movin
await userEvent.keyboard('{ArrowDown}')
await expect.element(months.getByRole('option', { name: 'May' })).toHaveFocus()
expect(months.element().scrollTop).toBe(104)
- startTouch(months.element(), 136)
- startTouch(years.element(), 188)
+ scrollColumn(months.element(), 136)
+ scrollColumn(years.element(), 188)
await expect
.element(months.getByRole('option', { name: 'June' }))
.toHaveAttribute('aria-selected', 'true')
await expect
.element(years.getByRole('option', { name: '2027' }))
.toHaveAttribute('aria-selected', 'true')
- expect(months.element().scrollTop).toBe(136)
- expect(years.element().scrollTop).toBe(188)
+ expect(months.element().scrollTop).toBe(130)
+ expect(years.element().scrollTop).toBe(182)
await apply.click()
await expect
.element(screen.getByRole('button', { name: 'Choose month and year: June 2027' }))
@@ -71,12 +69,8 @@ it('shares top alignment across click, keyboard and touch and applies both movin
it('settles month gestures without losing a concurrent year draft and cancels them without applying', async () => {
const { screen, months, years, changed } = await openMonths()
- startTouch(months.element(), 136)
- startTouch(years.element(), 188)
- for (const column of [months.element(), years.element()]) {
- column.dispatchEvent(new Event('touchend'))
- column.dispatchEvent(new Event('scrollend'))
- }
+ scrollColumn(months.element(), 136)
+ scrollColumn(years.element(), 188)
await expect
.element(months.getByRole('option', { name: 'June' }))
.toHaveAttribute('aria-selected', 'true')
@@ -90,3 +84,24 @@ it('settles month gestures without losing a concurrent year draft and cancels th
.toHaveFocus()
expect(changed).not.toHaveBeenCalled()
})
+
+it('applies the highlighted year when OK is clicked while the column is still scrolling', async () => {
+ const { screen, years } = await openMonths()
+ const column = years.element()
+ const ok = screen.getByRole('button', { name: 'OK', exact: true }).element() as HTMLElement
+ column.scrollTo({ top: 0, behavior: 'smooth' })
+ const seen = await new Promise<{ year: string; top: number }>((resolve) => {
+ function frame() {
+ const year = column.querySelector('[aria-selected="true"]')!.textContent
+ if (year === '2025') return requestAnimationFrame(frame)
+ const top = column.scrollTop
+ ok.click()
+ resolve({ year, top })
+ }
+ requestAnimationFrame(frame)
+ })
+ expect(seen.top).toBeGreaterThan(0)
+ await expect
+ .element(screen.getByRole('button', { name: `Choose month and year: January ${seen.year}` }))
+ .toBeInTheDocument()
+})
diff --git a/packages/dify-ui/src/date-time/date-picker/calendar-panel.tsx b/packages/dify-ui/src/date-time/date-picker/calendar-panel.tsx
index 7120ef75c44..d453dafdf84 100644
--- a/packages/dify-ui/src/date-time/date-picker/calendar-panel.tsx
+++ b/packages/dify-ui/src/date-time/date-picker/calendar-panel.tsx
@@ -1,5 +1,4 @@
import type { DayPickerProps } from '@daypicker/react'
-import type { OptionColumnHandle } from '../internal/option-column'
import * as React from 'react'
import { Button } from '../../button'
import { OptionColumn } from '../internal/option-column'
@@ -53,8 +52,6 @@ function CalendarPanel({
const [focusCalendar, setFocusCalendar] = React.useState(false)
const panelRef = React.useRef<HTMLDivElement>(null)
const headerRef = React.useRef<HTMLButtonElement>(null)
- const monthRef = React.useRef<OptionColumnHandle>(null)
- const yearRef = React.useRef<OptionColumnHandle>(null)
React.useEffect(() => {
if (choosingMonth || !focusCalendar) return
const frame = requestAnimationFrame(() => {
@@ -102,15 +99,10 @@ function CalendarPanel({
panelRef.current?.closest<HTMLElement>('[role="dialog"]')?.focus({ preventScroll: true })
}
function finish(apply: boolean) {
- let next = draftMonth
- if (apply) {
- next = `${String(yearRef.current?.settle() ?? year).padStart(4, '0')}-${String(monthRef.current?.settle() ?? month).padStart(2, '0')}-01`
- setDraftMonth(next)
- if (outOfBounds(next)) return
- }
+ if (apply && outOfBounds(draftMonth)) return
focusPopup()
setFocusCalendar(apply)
- if (apply) onDisplayMonthChange(next)
+ if (apply) onDisplayMonthChange(draftMonth)
setMonthPickerHeight(null)
if (!apply) requestAnimationFrame(() => headerRef.current?.focus())
}
@@ -197,7 +189,6 @@ function CalendarPanel({
aria-describedby={unavailable ? errorId : undefined}
>
<OptionColumn
- ref={monthRef}
onEscape={() => finish(false)}
focusOnMount
normalizeDigits={numbers.normalizeDigits}
@@ -211,7 +202,6 @@ function CalendarPanel({
}
/>
<OptionColumn
- ref={yearRef}
onEscape={() => finish(false)}
normalizeDigits={numbers.normalizeDigits}
label={labels.year}
diff --git a/packages/dify-ui/src/date-time/date-time-picker/index.tsx b/packages/dify-ui/src/date-time/date-time-picker/index.tsx
index ad190aec54b..86db21d5a19 100644
--- a/packages/dify-ui/src/date-time/date-time-picker/index.tsx
+++ b/packages/dify-ui/src/date-time/date-time-picker/index.tsx
@@ -9,7 +9,7 @@ import type {
PickerTriggerProps,
PickerValueProps,
} from '../internal/picker-parts'
-import type { TimePanelHandle, TimePanelLabels, TimePanelProps } from '../time-picker/time-panel'
+import type { TimePanelLabels, TimePanelProps } from '../time-picker/time-panel'
import type { ZonedWallTime } from './zoned-value'
import { useControlled } from '@base-ui/utils/useControlled'
import { enUS } from '@daypicker/react/locale/en-US'
@@ -176,7 +176,6 @@ function Session() {
hourCycle,
} = useContext()
const { close } = usePickerContext()
- const panelRef = React.useRef<TimePanelHandle>(null)
const [draft, setDraft] = React.useState(() => getZonedWallTime(value ?? new Date(), timeZone))
const [displayMonth, setDisplayMonth] = React.useState(() =>
getInitialMonth(draft.date, minDate, maxDate),
@@ -223,10 +222,6 @@ function Session() {
return () => cancelAnimationFrame(frame)
}, [view])
function changeView(next: 'date' | 'time') {
- if (view === 'time') {
- const time = panelRef.current?.settle() ?? draft.time
- setDraft((previous) => ({ ...previous, time }))
- }
ref.current?.closest<HTMLElement>('[role="dialog"]')?.focus({ preventScroll: true })
setView(next)
}
@@ -238,9 +233,7 @@ function Session() {
disabled={unavailable}
aria-describedby={unavailable ? errorId : undefined}
onClick={() => {
- const next = { ...draft, time: panelRef.current?.settle() ?? draft.time }
- setDraft(next)
- const instant = availableInstant(next)
+ const instant = availableInstant(draft)
if (instant) {
commit(instant)
close()
@@ -315,7 +308,6 @@ function Session() {
}
>
<TimePanel
- ref={panelRef}
scrollRequest={scrollRequest}
value={draft.time}
onValueChange={(update) =>
diff --git a/packages/dify-ui/src/date-time/internal/option-column.tsx b/packages/dify-ui/src/date-time/internal/option-column.tsx
index c8ba8bac7af..c9dfe2c91c0 100644
--- a/packages/dify-ui/src/date-time/internal/option-column.tsx
+++ b/packages/dify-ui/src/date-time/internal/option-column.tsx
@@ -5,10 +5,7 @@ import { useTimeout } from '@base-ui/utils/useTimeout'
import * as React from 'react'
import { cn } from '../../cn'
-type OptionColumnHandle = { settle: () => number }
-
type OptionColumnProps = {
- ref?: React.Ref<OptionColumnHandle>
label: string
normalizeDigits: (text: string) => string
value: number
@@ -20,7 +17,6 @@ type OptionColumnProps = {
}
function OptionColumn({
- ref: handleRef,
label,
normalizeDigits,
value,
@@ -38,17 +34,22 @@ function OptionColumn({
React.useEffect(() => {
searchRef.current = { text: '', time: 0, startIndex: 0 }
}, [normalizeDigits])
- const gestureRef = React.useRef({ active: false, moved: false, touching: false })
+ // At rest the scroll position is the selection. Only scrolls this column starts are positioning.
+ const scrollRef = React.useRef<{ moved: boolean; target: number | null }>({
+ moved: false,
+ target: null,
+ })
const quietTimer = useTimeout()
const cancelGesture = useStableCallback(() => {
quietTimer.clear()
- gestureRef.current.active = false
- gestureRef.current.moved = false
+ scrollRef.current.moved = false
})
- function scrollToOption(option: HTMLElement, smooth = false) {
+ const scrollToOption = useStableCallback((option: HTMLElement, smooth = false) => {
const column = ref.current
if (!column) return
+ scrollRef.current.target =
+ Math.abs(column.scrollTop - option.offsetTop) < 1 ? null : option.offsetTop
column.scrollTo({
top: option.offsetTop,
behavior:
@@ -57,10 +58,10 @@ function OptionColumn({
? 'smooth'
: 'instant',
})
- }
+ })
function nearestOption() {
const column = ref.current
- if (!column) return undefined
+ if (!column?.clientHeight) return undefined
return Array.from(column.querySelectorAll<HTMLElement>('[role="option"]')).reduce<
HTMLElement | undefined
>(
@@ -73,108 +74,52 @@ function OptionColumn({
undefined,
)
}
- React.useImperativeHandle(handleRef, () => ({
- settle() {
- const option =
- gestureRef.current.active && gestureRef.current.moved ? nearestOption() : undefined
- cancelGesture()
- if (option) {
- scrollToOption(option)
- return Number(option.dataset.optionValue)
- }
- return value
- },
- }))
- const finishGesture = React.useEffectEvent(() => {
- if (!gestureRef.current.active || gestureRef.current.touching) return
- const option = gestureRef.current.moved ? nearestOption() : undefined
- cancelGesture()
- if (!option) return
- const next = Number(option.dataset.optionValue)
- if (next !== value) onValueChange(next)
- if (ref.current?.contains(ref.current.ownerDocument.activeElement))
- option.focus({ preventScroll: true })
- scrollToOption(option, true)
- })
- const updateGesture = React.useEffectEvent(() => {
+ const selectNearest = React.useEffectEvent(() => {
const option = nearestOption()
- if (!option) return
+ if (!option) return undefined
const next = Number(option.dataset.optionValue)
if (next !== value) onValueChange(next)
+ return option
+ })
+ const finishScroll = React.useEffectEvent(() => {
+ cancelGesture()
+ scrollRef.current.target = null
+ const option = selectNearest()
+ if (option && ref.current?.contains(ref.current.ownerDocument.activeElement))
+ option.focus({ preventScroll: true })
})
React.useEffect(() => {
const column = ref.current
if (!column) return
const supportsScrollEnd = 'onscrollend' in column
- function begin() {
- quietTimer.clear()
- if (!gestureRef.current.active) {
- gestureRef.current = {
- ...gestureRef.current,
- active: true,
- moved: false,
- }
- }
- quietTimer.start(150, () => {
- if (gestureRef.current.touching) return
- if (!gestureRef.current.moved) cancelGesture()
- else if (!supportsScrollEnd) finishGesture()
- })
- }
- function onWheel(event: WheelEvent) {
- if (!event.ctrlKey && event.deltaY !== 0) begin()
- }
- function onTouchStart() {
- gestureRef.current.touching = true
- begin()
- }
- function onTouchEnd() {
- gestureRef.current.touching = false
- if (!gestureRef.current.moved) cancelGesture()
- if (!supportsScrollEnd && gestureRef.current.moved) scheduleFinish()
- }
- function scheduleFinish() {
- quietTimer.clear()
- quietTimer.start(150, () => finishGesture())
- }
function onScroll() {
- if (!gestureRef.current.active) return
- gestureRef.current.moved = true
- updateGesture()
- if (!supportsScrollEnd) scheduleFinish()
+ const positioning = scrollRef.current.target !== null
+ if (!positioning) {
+ scrollRef.current.moved = true
+ selectNearest()
+ }
+ // A positioning scroll that never reaches its target was taken over; rest decides.
+ if (positioning || !supportsScrollEnd) quietTimer.start(150, () => finishScroll())
}
function onScrollEnd() {
- finishGesture()
+ const { target } = scrollRef.current
+ if (target === null || Math.abs(column!.scrollTop - target) < 1) finishScroll()
}
- column.addEventListener('wheel', onWheel, { passive: true })
- column.addEventListener('touchstart', onTouchStart, { passive: true })
- column.addEventListener('touchend', onTouchEnd, { passive: true })
- column.addEventListener('touchcancel', onTouchEnd, { passive: true })
column.addEventListener('scroll', onScroll, { passive: true })
if (supportsScrollEnd) column.addEventListener('scrollend', onScrollEnd)
return () => {
cancelGesture()
- column.removeEventListener('wheel', onWheel)
- column.removeEventListener('touchstart', onTouchStart)
- column.removeEventListener('touchend', onTouchEnd)
- column.removeEventListener('touchcancel', onTouchEnd)
column.removeEventListener('scroll', onScroll)
column.removeEventListener('scrollend', onScrollEnd)
}
}, [cancelGesture, quietTimer])
- // Entry and Now are explicit positioning commands, never gesture-driven selections.
+ // Entry and Now are explicit positioning commands, never scroll-driven selections.
React.useLayoutEffect(() => {
cancelGesture()
- const column = ref.current
- const selected = column?.querySelector<HTMLElement>('[aria-selected="true"]')
- if (selected && column) {
- column.scrollTo({
- top: selected.offsetTop,
- behavior: 'instant',
- })
- }
- }, [scrollRequest, cancelGesture])
+ const selected = ref.current?.querySelector<HTMLElement>('[aria-selected="true"]')
+ if (selected) scrollToOption(selected)
+ }, [scrollRequest, cancelGesture, scrollToOption])
React.useEffect(() => {
if (!focusOnMount) return
@@ -202,7 +147,7 @@ function OptionColumn({
aria-orientation="vertical"
ref={ref}
aria-label={label}
- className="relative flex h-full min-h-0 min-w-0 flex-1 scrollbar-none flex-col items-stretch gap-0.5 overflow-y-auto overscroll-none scroll-auto after:pointer-events-none after:h-[max(0px,calc(100%-1.625rem))] after:shrink-0 after:content-['']"
+ className="relative flex h-full min-h-0 min-w-0 flex-1 snap-y snap-mandatory scrollbar-none flex-col items-stretch gap-0.5 overflow-y-auto overscroll-none scroll-auto after:pointer-events-none after:h-[max(0px,calc(100%-1.625rem))] after:shrink-0 after:content-['']"
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget))
searchRef.current = { text: '', time: 0, startIndex: 0 }
@@ -221,10 +166,9 @@ function OptionColumn({
if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown'].includes(event.key)) {
event.preventDefault()
event.stopPropagation()
- const currentOption =
- gestureRef.current.active && gestureRef.current.moved
- ? nearestOption()
- : (event.target as HTMLElement)
+ const currentOption = scrollRef.current.moved
+ ? nearestOption()
+ : (event.target as HTMLElement)
const currentValue = Number(currentOption?.dataset.optionValue)
const currentIndex = Math.max(
0,
@@ -299,7 +243,7 @@ function OptionColumn({
onClick={(event) => focusValue(option.value, event.detail > 0)}
className={cn(
'aria-selected:bg-components-button-ghost-bg-hover',
- 'flex min-h-6 shrink-0 items-center justify-center rounded-md px-1 system-xs-medium text-text-secondary tabular-nums hover:not-aria-selected:bg-state-base-hover-subtle focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-state-accent-solid forced-colors:aria-selected:outline forced-colors:aria-selected:outline-[Highlight]',
+ 'flex min-h-6 shrink-0 snap-start items-center justify-center rounded-md px-1 system-xs-medium text-text-secondary tabular-nums hover:not-aria-selected:bg-state-base-hover-subtle focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-state-accent-solid forced-colors:aria-selected:outline forced-colors:aria-selected:outline-[Highlight]',
)}
>
{option.label}
@@ -310,4 +254,3 @@ function OptionColumn({
}
export { OptionColumn }
-export type { OptionColumnHandle }
diff --git a/packages/dify-ui/src/date-time/time-picker/__tests__/index.spec.tsx b/packages/dify-ui/src/date-time/time-picker/__tests__/index.spec.tsx
index 11282698a20..8362c4c4974 100644
--- a/packages/dify-ui/src/date-time/time-picker/__tests__/index.spec.tsx
+++ b/packages/dify-ui/src/date-time/time-picker/__tests__/index.spec.tsx
@@ -279,7 +279,7 @@ it('preserves draft selection after focus leaves and does not select hovered opt
await expect.element(selectedHour).toHaveAttribute('aria-selected', 'true')
await userEvent.tab()
await expect.element(minutes.getByRole('option', { name: '30', exact: true })).toHaveFocus()
- await userEvent.hover(hours.getByRole('option', { name: '3', exact: true }))
+ await hours.getByRole('option', { name: '3', exact: true }).hover({ scroll: 'none' })
await expect.element(selectedHour).toHaveAttribute('aria-selected', 'true')
await expect
.element(hours.getByRole('option', { name: '3', exact: true }))
diff --git a/packages/dify-ui/src/date-time/time-picker/__tests__/wheel.spec.tsx b/packages/dify-ui/src/date-time/time-picker/__tests__/wheel.spec.tsx
index 92b9f25390b..325a3fa5b2f 100644
--- a/packages/dify-ui/src/date-time/time-picker/__tests__/wheel.spec.tsx
+++ b/packages/dify-ui/src/date-time/time-picker/__tests__/wheel.spec.tsx
@@ -13,65 +13,35 @@ async function renderPicker() {
)
await screen.getByRole('button', { name: 'Time 1:30 PM' }).click()
const hours = screen.getByRole('listbox', { name: 'Hour' })
+ await expect.element(hours.getByRole('option', { name: '1', exact: true })).toHaveFocus()
return { screen, hours, column: hours.element(), changed }
}
-// Intent events are synthetic; scroll geometry, focus, smooth settling and submission use Chromium.
-function moveGesture(column: Element, top: number, touch = false) {
- column.dispatchEvent(touch ? new Event('touchstart') : new WheelEvent('wheel', { deltaY: top }))
+// Any scroll the column did not start is a selection; Chromium snaps it to a row.
+function scrollColumn(column: Element, top: number) {
column.scrollTo({ top, behavior: 'instant' })
- column.dispatchEvent(new Event('scroll'))
}
-it('snaps a wheel gesture to the top and selects a draft without committing', async () => {
+it('selects the row a scroll rests on, moves focus there and does not commit', async () => {
const { screen, hours, column, changed } = await renderPicker()
- moveGesture(column, 67)
- column.dispatchEvent(new Event('scrollend'))
- await expect
- .element(hours.getByRole('option', { name: '4', exact: true }))
- .toHaveAttribute('aria-selected', 'true')
- await expect.poll(() => column.scrollTop).toBe(78)
- expect(changed).not.toHaveBeenCalled()
- await screen.getByRole('button', { name: 'OK', exact: true }).click()
- expect(changed).toHaveBeenCalledExactlyOnceWith('16:30')
-})
-
-it('highlights the nearest top row during touch without snapping or moving focus until release', async () => {
- const { screen, hours, column, changed } = await renderPicker()
- const first = hours.getByRole('option', { name: '1', exact: true })
- const selectedBackground = getComputedStyle(first.element()).backgroundColor
- moveGesture(column, 67, true)
+ scrollColumn(column, 67)
const fourth = hours.getByRole('option', { name: '4', exact: true })
await expect.element(fourth).toHaveAttribute('aria-selected', 'true')
- expect(getComputedStyle(fourth.element()).backgroundColor).toBe(selectedBackground)
- await expect.element(first).toHaveAttribute('aria-selected', 'false')
- await expect.element(first).toHaveFocus()
- expect(column.scrollTop).toBe(67)
- column.scrollTo({ top: 92, behavior: 'instant' })
- column.dispatchEvent(new Event('scroll'))
- const fifth = hours.getByRole('option', { name: '5', exact: true })
- await expect.element(fifth).toHaveAttribute('aria-selected', 'true')
- expect(column.scrollTop).toBe(92)
+ await expect.element(fourth).toHaveFocus()
+ expect(column.scrollTop).toBe(78)
expect(changed).not.toHaveBeenCalled()
- await expect.element(screen.getByRole('button', { name: 'Time 1:30 PM' })).toBeInTheDocument()
- column.dispatchEvent(new Event('touchend'))
- column.dispatchEvent(new Event('scrollend'))
- await expect.poll(() => column.scrollTop).toBe(104)
- await expect.element(fifth).toHaveFocus()
await screen.getByRole('button', { name: 'OK', exact: true }).click()
- expect(changed).toHaveBeenCalledExactlyOnceWith('17:30')
+ expect(changed).toHaveBeenCalledExactlyOnceWith('16:30')
})
-it('keeps a clicked target selected throughout positioning after interrupting a gesture', async () => {
+it('keeps a clicked target selected throughout positioning after a scroll', async () => {
const { screen, hours, column, changed } = await renderPicker()
- moveGesture(column, 67, true)
+ scrollColumn(column, 67)
await expect
.element(hours.getByRole('option', { name: '4', exact: true }))
.toHaveAttribute('aria-selected', 'true')
const target = hours.getByRole('option', { name: '6', exact: true })
await target.click({ scroll: 'none' })
- column.dispatchEvent(new Event('touchend'))
- column.dispatchEvent(new Event('scrollend'))
await expect.element(target).toHaveAttribute('aria-selected', 'true')
await expect.poll(() => column.scrollTop).toBe(130)
await expect.element(target).toHaveAttribute('aria-selected', 'true')
@@ -79,7 +49,7 @@ it('keeps a clicked target selected throughout positioning after interrupting a
expect(changed).toHaveBeenCalledExactlyOnceWith('18:30')
})
-it('aligns AM and PM to the same top anchor for keyboard, click and touch selection', async () => {
+it('aligns AM and PM to the same top anchor for keyboard, click and scroll selection', async () => {
const { screen, changed } = await renderPicker()
const period = screen.getByRole('listbox', { name: 'Period' })
const column = period.element()
@@ -92,49 +62,51 @@ it('aligns AM and PM to the same top anchor for keyboard, click and touch select
expect(column.scrollTop).toBe(0)
await pm.click({ scroll: 'none' })
await expect.poll(() => column.scrollTop).toBe(26)
- moveGesture(column, 6, true)
+ await expect.element(pm).toHaveAttribute('aria-selected', 'true')
+ scrollColumn(column, 6)
await expect.element(am).toHaveAttribute('aria-selected', 'true')
- expect(column.scrollTop).toBe(6)
+ expect(column.scrollTop).toBe(0)
expect(changed).not.toHaveBeenCalled()
await screen.getByRole('button', { name: 'OK', exact: true }).click()
expect(changed).toHaveBeenCalledExactlyOnceWith('01:30')
})
-it('settles both moving columns synchronously when OK is clicked', async () => {
+it('applies both scrolled columns when OK is clicked', async () => {
const { screen, column, changed } = await renderPicker()
const minutes = screen.getByRole('listbox', { name: 'Minute' }).element()
- moveGesture(column, 67, true)
- moveGesture(minutes, 1050, true)
+ scrollColumn(column, 67)
+ scrollColumn(minutes, 1050)
await screen.getByRole('button', { name: 'OK', exact: true }).click()
expect(changed).toHaveBeenCalledExactlyOnceWith('16:40')
})
-it('continues keyboard navigation from the moving candidate and ignores its late scrollend', async () => {
+it('continues keyboard navigation from the scrolled row', async () => {
const { hours, column, changed } = await renderPicker()
- moveGesture(column, 67, true)
- await userEvent.keyboard('{ArrowDown}')
- column.dispatchEvent(new Event('touchend'))
- column.dispatchEvent(new Event('scrollend'))
- await expect.element(hours.getByRole('option', { name: '5', exact: true })).toHaveFocus()
+ scrollColumn(column, 67)
await expect
- .element(hours.getByRole('option', { name: '5', exact: true }))
+ .element(hours.getByRole('option', { name: '4', exact: true }))
.toHaveAttribute('aria-selected', 'true')
- expect(column.scrollTop).toBe(104)
+ await userEvent.keyboard('{ArrowDown}')
+ const fifth = hours.getByRole('option', { name: '5', exact: true })
+ await expect.element(fifth).toHaveFocus()
+ await expect.poll(() => column.scrollTop).toBe(104)
+ await expect.element(fifth).toHaveAttribute('aria-selected', 'true')
expect(changed).not.toHaveBeenCalled()
})
-it('lets Now override all moving columns and keeps focus on Now', async () => {
+it('lets Now override scrolled columns and keeps focus on Now', async () => {
vi.spyOn(Date, 'now').mockReturnValue(new Date('2025-01-15T13:30:00Z').getTime())
try {
const { screen, hours, column, changed } = await renderPicker()
- moveGesture(column, 67, true)
+ scrollColumn(column, 67)
+ await expect
+ .element(hours.getByRole('option', { name: '4', exact: true }))
+ .toHaveAttribute('aria-selected', 'true')
await screen.getByRole('button', { name: 'Now', exact: true }).click()
- column.dispatchEvent(new Event('touchend'))
- column.dispatchEvent(new Event('scrollend'))
+ await expect.poll(() => column.scrollTop).toBe(0)
await expect
.element(hours.getByRole('option', { name: '1', exact: true }))
.toHaveAttribute('aria-selected', 'true')
- expect(column.scrollTop).toBe(0)
await expect.element(screen.getByRole('button', { name: 'Now', exact: true })).toHaveFocus()
expect(changed).not.toHaveBeenCalled()
} finally {
@@ -142,49 +114,34 @@ it('lets Now override all moving columns and keeps focus on Now', async () => {
}
})
-it('discards an unfinished gesture on Escape and ignores detached scroll events', async () => {
- const { screen, column, changed } = await renderPicker()
- moveGesture(column, 67, true)
+it('discards a scrolled draft on Escape', async () => {
+ const { screen, hours, column, changed } = await renderPicker()
+ scrollColumn(column, 67)
+ await expect
+ .element(hours.getByRole('option', { name: '4', exact: true }))
+ .toHaveAttribute('aria-selected', 'true')
await userEvent.keyboard('{Escape}')
- column.dispatchEvent(new Event('touchend'))
- column.dispatchEvent(new Event('scrollend'))
await expect.element(screen.getByRole('button', { name: 'Time 1:30 PM' })).toHaveFocus()
expect(changed).not.toHaveBeenCalled()
})
-it('does not interpret an edge wheel or programmatic scrolling as selection', async () => {
- const { hours, column } = await renderPicker()
- column.dispatchEvent(new WheelEvent('wheel', { deltaY: -100 }))
- column.dispatchEvent(new Event('scrollend'))
- await expect
- .element(hours.getByRole('option', { name: '1', exact: true }))
- .toHaveAttribute('aria-selected', 'true')
- column.scrollTo({ top: 78, behavior: 'instant' })
- column.dispatchEvent(new Event('scroll'))
- column.dispatchEvent(new Event('scrollend'))
- await expect
- .element(hours.getByRole('option', { name: '1', exact: true }))
- .toHaveAttribute('aria-selected', 'true')
-})
-
-it('does not lose an unfinished selection when only a modifier key is pressed', async () => {
- const { screen, column, changed } = await renderPicker()
- moveGesture(column, 67, true)
- await userEvent.keyboard('{Shift}')
- await screen.getByRole('button', { name: 'OK', exact: true }).click()
- expect(changed).toHaveBeenCalledExactlyOnceWith('16:30')
-})
-
-it('recognizes scrolling when the compositor moves before the passive wheel callback', async () => {
- const { hours, column } = await renderPicker()
- column.scrollTo({ top: 67, behavior: 'instant' })
- column.dispatchEvent(new WheelEvent('wheel', { deltaY: 67 }))
- column.dispatchEvent(new Event('scroll'))
- column.dispatchEvent(new Event('scrollend'))
- await expect
- .element(hours.getByRole('option', { name: '4', exact: true }))
- .toHaveAttribute('aria-selected', 'true')
- await expect.poll(() => column.scrollTop).toBe(78)
+it('commits the highlighted row when OK is clicked while a column is still scrolling', async () => {
+ const { screen, changed } = await renderPicker()
+ const minutes = screen.getByRole('listbox', { name: 'Minute' }).element()
+ const ok = screen.getByRole('button', { name: 'OK', exact: true }).element() as HTMLElement
+ minutes.scrollTo({ top: 0, behavior: 'smooth' })
+ const seen = await new Promise<{ minute: string; top: number }>((resolve) => {
+ function frame() {
+ const minute = minutes.querySelector('[aria-selected="true"]')!.textContent
+ if (minute === '30') return requestAnimationFrame(frame)
+ const top = minutes.scrollTop
+ ok.click()
+ resolve({ minute, top })
+ }
+ requestAnimationFrame(frame)
+ })
+ expect(seen.top).toBeGreaterThan(0)
+ expect(changed).toHaveBeenCalledExactlyOnceWith(`13:${seen.minute}`)
})
it('settles through the quiet fallback when scrollend is unavailable', async () => {
@@ -195,34 +152,11 @@ it('settles through the quiet fallback when scrollend is unavailable', async ()
Reflect.deleteProperty(owner!, 'onscrollend')
try {
const { hours, column } = await renderPicker()
- moveGesture(column, 67, true)
- column.dispatchEvent(new Event('touchend'))
- await expect
- .element(hours.getByRole('option', { name: '4', exact: true }))
- .toHaveAttribute('aria-selected', 'true')
- await expect.poll(() => column.scrollTop).toBe(78)
- } finally {
- Object.defineProperty(owner!, 'onscrollend', descriptor)
- }
-})
-
-it('settles the fallback after a final wheel event produces no additional scroll', async () => {
- let owner: object | null = HTMLElement.prototype
- while (owner && !Object.hasOwn(owner, 'onscrollend')) owner = Object.getPrototypeOf(owner)
- expect(owner).not.toBeNull()
- const descriptor = Object.getOwnPropertyDescriptor(owner!, 'onscrollend')!
- Reflect.deleteProperty(owner!, 'onscrollend')
- try {
- const { hours, column } = await renderPicker()
- moveGesture(column, 67)
- await new Promise<void>((resolve) =>
- requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
- )
- column.dispatchEvent(new WheelEvent('wheel', { deltaY: 1 }))
- await expect
- .element(hours.getByRole('option', { name: '4' }))
- .toHaveAttribute('aria-selected', 'true')
- await expect.poll(() => column.scrollTop).toBe(78)
+ scrollColumn(column, 67)
+ const fourth = hours.getByRole('option', { name: '4', exact: true })
+ await expect.element(fourth).toHaveAttribute('aria-selected', 'true')
+ await expect.element(fourth).toHaveFocus()
+ expect(column.scrollTop).toBe(78)
} finally {
Object.defineProperty(owner!, 'onscrollend', descriptor)
}
diff --git a/packages/dify-ui/src/date-time/time-picker/index.tsx b/packages/dify-ui/src/date-time/time-picker/index.tsx
index dce97498d70..fba9e406df3 100644
--- a/packages/dify-ui/src/date-time/time-picker/index.tsx
+++ b/packages/dify-ui/src/date-time/time-picker/index.tsx
@@ -8,7 +8,7 @@ import type {
PickerTriggerProps,
PickerValueProps,
} from '../internal/picker-parts'
-import type { TimePanelHandle, TimePanelLabels, TimePanelProps } from '../time-picker/time-panel'
+import type { TimePanelLabels, TimePanelProps } from '../time-picker/time-panel'
import { useControlled } from '@base-ui/utils/useControlled'
import { TZDate } from '@date-fns/tz'
import * as React from 'react'
@@ -177,7 +177,6 @@ function Session() {
minuteStep = 1,
} = useContext()
const { close } = usePickerContext()
- const panelRef = React.useRef<TimePanelHandle>(null)
const [draft, setDraft] = React.useState(() => value ?? currentTime(timeZone, minuteStep))
const text = { ...defaultLabels, ...labels }
const unavailable = Boolean(
@@ -214,12 +213,8 @@ function Session() {
disabled={unavailable}
aria-describedby={unavailable ? errorId : undefined}
onClick={() => {
- const next = panelRef.current?.settle() ?? draft
- setDraft(next)
- if (!isTimeUnavailable?.(next) && Number(next.slice(3)) % minuteStep === 0) {
- commit(next)
- close()
- }
+ commit(draft)
+ close()
}}
>
{text.apply}
@@ -228,7 +223,6 @@ function Session() {
}
>
<TimePanel
- ref={panelRef}
minuteStep={minuteStep}
scrollRequest={scrollRequest}
value={draft}
diff --git a/packages/dify-ui/src/date-time/time-picker/time-panel.tsx b/packages/dify-ui/src/date-time/time-picker/time-panel.tsx
index 73851dcfba4..9eba2758901 100644
--- a/packages/dify-ui/src/date-time/time-picker/time-panel.tsx
+++ b/packages/dify-ui/src/date-time/time-picker/time-panel.tsx
@@ -1,4 +1,3 @@
-import type { OptionColumnHandle } from '../internal/option-column'
import * as React from 'react'
import { OptionColumn } from '../internal/option-column'
import { PickerColumns } from '../internal/picker-panel'
@@ -6,9 +5,7 @@ import { usePickerNumbers } from '../internal/use-picker-numbers'
import { formatTimeValue, parseTimeValue } from './time-value'
type TimePanelLabels = { hour: string; minute: string; period: string; am: string; pm: string }
-type TimePanelHandle = { settle: () => string }
type TimePanelProps = {
- ref?: React.Ref<TimePanelHandle>
value: string
onValueChange: (update: (value: string) => string) => void
labels: TimePanelLabels
@@ -19,7 +16,6 @@ type TimePanelProps = {
}
function TimePanel({
- ref,
value,
onValueChange,
labels,
@@ -33,20 +29,6 @@ function TimePanel({
if (!current) throw new RangeError(`Invalid time of day: ${value}`)
const period = current.hour < 12 ? 0 : 1
const displayHour = hourCycle === 24 ? current.hour : current.hour % 12 || 12
- const hourRef = React.useRef<OptionColumnHandle>(null)
- const minuteRef = React.useRef<OptionColumnHandle>(null)
- const periodRef = React.useRef<OptionColumnHandle>(null)
- React.useImperativeHandle(ref, () => ({
- settle() {
- const hour = hourRef.current?.settle() ?? displayHour
- const minute = minuteRef.current?.settle() ?? current.minute
- const meridiem = periodRef.current?.settle() ?? period
- return formatTimeValue({
- hour: hourCycle === 24 ? hour : (hour % 12) + meridiem * 12,
- minute,
- })
- },
- }))
function update(part: 'hour' | 'minute' | 'period', next: number) {
onValueChange((previous) => {
const time = parseTimeValue(previous)!
@@ -59,7 +41,6 @@ function TimePanel({
return (
<PickerColumns>
<OptionColumn
- ref={hourRef}
scrollRequest={scrollRequest}
normalizeDigits={numbers.normalizeDigits}
label={labels.hour}
@@ -71,7 +52,6 @@ function TimePanel({
onValueChange={(hour) => update('hour', hour)}
/>
<OptionColumn
- ref={minuteRef}
scrollRequest={scrollRequest}
normalizeDigits={numbers.normalizeDigits}
label={labels.minute}
@@ -84,7 +64,6 @@ function TimePanel({
/>
{hourCycle === 12 && (
<OptionColumn
- ref={periodRef}
scrollRequest={scrollRequest}
normalizeDigits={numbers.normalizeDigits}
label={labels.period}
@@ -100,4 +79,4 @@ function TimePanel({
)
}
export { TimePanel }
-export type { TimePanelHandle, TimePanelLabels, TimePanelProps }
+export type { TimePanelLabels, TimePanelProps }