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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat(ui): integrate date and time pickers with Base UI forms (#44593)
yyh48356b821aa5
diff --git a/packages/dify-ui/docs/forms.md b/packages/dify-ui/docs/forms.mdindex 1a7ea99249f..7d0f560833b 100644--- a/packages/dify-ui/docs/forms.md+++ b/packages/dify-ui/docs/forms.md@@ -45,8 +45,7 @@ Choose the label primitive by the control:each `Radio` option, `Switch`, and `NumberField` use `FieldLabel`.- Trigger-based `Select` fields use `SelectLabel`.- Date/time pickers use their own `DatePickerLabel`, `TimePickerLabel` or `DateTimePickerLabel`- to focus the trigger without opening it. They currently support native forms, not Base UI- Field/Form registration; see the [picker field contract].+ to focus the trigger without opening it. They participate in Base UI Field/Form and native forms; see the [picker field contract].- `Slider` fields follow the [Base UI Slider anatomy] and use `SliderLabel`; only multi-thumbsliders add per-thumb `aria-label` to distinguish the thumbs.- `SelectGroupLabel` and `AutocompleteGroupLabel` label option groups inside popup content. Theydiff --git a/packages/dify-ui/src/date-time/README.md b/packages/dify-ui/src/date-time/README.mdindex 48a4dbc03b8..8f4aa96c505 100644--- a/packages/dify-ui/src/date-time/README.md+++ b/packages/dify-ui/src/date-time/README.md@@ -44,7 +44,9 @@ Provide an accessible name at the call site. Root has no labeling props and doesLabel composition through its types. Prefer one visible Label with its text as children; it namesboth Trigger and Content through `aria-labelledby`. Clicking plain label text focuses the actualtrigger without opening it. Links and controls inside a custom label keep their own behavior.-Do not use native `label[for]` or `FieldLabel` for the trigger: native activation can click its button.+Picker Label shares Base UI Field's label association and state callbacks. Alternatively, use+`FieldLabel nativeLabel={false} render={<div />}`. Do not use native `label[for]` for the trigger:+native label activation can click its button.For compact layouts, a Label with `className="sr-only"` shares one name without visible text.Without a Label, name Trigger and Content explicitly using standard ARIA attributes:@@ -83,6 +85,14 @@ Use `defaultValue` for uncontrolled fields or `value` with `onValueChange` for c`null` means empty; clearing emits `null`. Do not switch controlledness during a field's lifetime.`open`/`defaultOpen` follow the same ownership choice. `onOpenChange` details support `cancel()`.+`onValueChange(value, details)` receives Base UI event details. Reasons are `item-press` for a+selected day or OK, `clear-press` for Clear, and `reset` for a native form reset. The native event+is preserved; `trigger` identifies the clicked day, OK or Clear button. `details.cancel()` prevents+the value change and its follow-up focus/close action. It cancels only this picker's reset, not the+whole form reset; use the form's `onReset` and `event.preventDefault()` to cancel all controls.+Unchanged values do not emit duplicate callbacks. Open/close events remain Popover events; a+successful confirmation, Clear or reset closes through its `imperative-action` mechanism.+Time and date-time edits, including Now, stay in the open session until OK. Switching date/timeviews preserves the draft. Dismissal discards it; reopening starts from the committed value.Changing the controlled value or time zone starts a fresh draft. Unchanged confirmation does not@@ -125,8 +135,29 @@ With `name`, the committed value participates in native FormData; an empty field`form` can associate an external form. Required/invalid fields block native validated submissionand focus the first invalid trigger. Reset restores `defaultValue` and closes the popup; acontrolled owner must accept the reset callback. Disabled fields are omitted from submission;-read-only fields remain focusable and submit their value without allowing edits. These pickers do-not register with Base UI Field/Form. See [Forms] for the surrounding form boundary.+read-only fields remain focusable and submit their value without allowing edits. With a surrounding `Field`, pickers also register with Base UI Form:++- `Field.name` takes precedence over the picker's `name`; otherwise the picker supplies the name.+- `Field.validate` receives the committed domain value (`string | null` or `Date | null`).+ `Form.onFormSubmit` receives the same serialized strings as native FormData, including `''` for+ an empty value. Use `Form` with `Field` to collect structured values; a native form needs neither.+- Field disabled state is inherited. Disabled inputs, including those in native disabled fieldsets,+ and inputs explicitly associated with another form are excluded from the contextual Form.+ Unassociated portalled inputs still participate in contextual Form and its reset, following Base UI.+- Filled and dirty follow committed values; DateTimePicker compares instants by timestamp. Moving+ focus between Trigger, Clear and the popup stays within the field. Clicking associated label text+ returns focus to Trigger without marking the field touched. Leaving it marks touched and+ runs onBlur validation; editing popup drafts does not run value validation or clear server errors.+- Native reset restores default values and clears field feedback after the reset is accepted.+ Required input validity remains available for the next submit.+- Changing a picker constraint message revalidates a field that has already been validated, or+ uses onChange validation. Untouched fields otherwise wait for their normal validation boundary.++The proxy input uses Base UI's visually hidden styles, `aria-hidden` and `tabIndex={-1}`. It remains+an input of type text so native constraint validation works, and redirects programmatic focus to+the visible trigger. It is not a second editable input or an autofill interface.++See [Forms] for the surrounding form boundary.## Examples and verificationdiff --git a/packages/dify-ui/src/date-time/__tests__/field.spec.tsx b/packages/dify-ui/src/date-time/__tests__/field.spec.tsxnew file mode 100644index 00000000000..190e909fa2f--- /dev/null+++ b/packages/dify-ui/src/date-time/__tests__/field.spec.tsx@@ -0,0 +1,1065 @@+import type { DatePickerChangeEventDetails, DatePickerProps } from '@langgenius/dify-ui/date-picker'+import type { FormActions } from '@langgenius/dify-ui/form'+import {+ DatePicker,+ DatePickerClear,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+} from '@langgenius/dify-ui/date-picker'+import {+ DateTimePicker,+ DateTimePickerClear,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+} from '@langgenius/dify-ui/date-time-picker'+import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'+import { Form } from '@langgenius/dify-ui/form'+import {+ TimePicker,+ TimePickerClear,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+} from '@langgenius/dify-ui/time-picker'+import * as React from 'react'+import * as ReactDOM from 'react-dom'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'++type ExampleProps = Pick<DatePickerProps, 'disabled' | 'readOnly' | 'required' | 'form'> & {+ empty?: boolean+ onValueChange?: (value: unknown, details: DatePickerChangeEventDetails) => void+}+const families = [+ {+ name: 'DatePicker',+ initial: '2025-01-15',+ serialized: '2025-01-15',+ next: '2025-01-16',+ render({ empty, ...props }: ExampleProps) {+ return (+ <DatePicker name="fallback" defaultValue={empty ? null : '2025-01-15'} {...props}>+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerClear aria-label="Clear departure" />+ <DatePickerContent />+ </DatePicker>+ )+ },+ async choose(screen: Awaited<ReturnType<typeof render>>) {+ await screen+ .getByRole('button', { name: 'Thursday, January 16th, 2025', exact: true })+ .click()+ },+ },+ {+ name: 'TimePicker',+ initial: '13:30',+ serialized: '13:30',+ next: '14:30',+ render({ empty, ...props }: ExampleProps) {+ return (+ <TimePicker name="fallback" defaultValue={empty ? null : '13:30'} {...props}>+ <TimePickerLabel>Departure</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerClear aria-label="Clear departure" />+ <TimePickerContent />+ </TimePicker>+ )+ },+ async choose(screen: Awaited<ReturnType<typeof render>>) {+ await screen+ .getByRole('listbox', { name: 'Hour' })+ .getByRole('option', { name: '2', exact: true })+ .click()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ },+ },+ {+ name: 'DateTimePicker',+ initial: new Date('2025-01-15T13:30:00Z'),+ serialized: '2025-01-15T13:30:00.000Z',+ next: '2025-01-16T13:30:00.000Z',+ render({ empty, ...props }: ExampleProps) {+ return (+ <DateTimePicker+ name="fallback"+ timeZone="UTC"+ defaultValue={empty ? null : new Date('2025-01-15T13:30:00Z')}+ {...props}+ >+ <DateTimePickerLabel>Departure</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerClear aria-label="Clear departure" />+ <DateTimePickerContent />+ </DateTimePicker>+ )+ },+ async choose(screen: Awaited<ReturnType<typeof render>>) {+ await screen+ .getByRole('button', { name: 'Thursday, January 16th, 2025', exact: true })+ .click()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ },+ },+]++function ObservedField({ children, ...props }: React.ComponentProps<typeof Field>) {+ return (+ <Field+ {...props}+ render={(elementProps, state) => (+ <div {...elementProps}>+ <output data-testid="field-state">{JSON.stringify(state)}</output>+ {children}+ </div>+ )}+ />+ )+}+function stateOf(screen: Awaited<ReturnType<typeof render>>) {+ return JSON.parse(screen.getByTestId('field-state').element().textContent!)+}++it.each(families)(+ '$name registers its domain value for validation and serialized value for submission',+ async (family) => {+ const submitted = vi.fn()+ const validate = vi.fn(() => null)+ const screen = await render(+ <Form aria-label="Booking" onFormSubmit={submitted}>+ <ObservedField name="departure" validate={validate}>+ {family.render({})}+ <FieldDescription>Local departure time.</FieldDescription>+ <FieldError />+ </ObservedField>+ <button type="submit">Submit booking</button>+ </Form>,+ )+ const trigger = screen.getByRole('button', { name: /^Departure / })+ await expect.element(trigger).toHaveAccessibleDescription('Local departure time.')+ expect(stateOf(screen)).toMatchObject({ filled: true, dirty: false, touched: false })+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(validate).toHaveBeenCalledWith(family.initial, { departure: family.serialized })+ expect(submitted).toHaveBeenCalledExactlyOnceWith(+ { departure: family.serialized },+ expect.anything(),+ )+ expect(+ Object.fromEntries(+ new FormData(screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement),+ ),+ ).toEqual({ departure: family.serialized })+ },+)++it.each(families)(+ '$name participates in required validation and focuses its visible trigger',+ async (family) => {+ const submitted = vi.fn()+ const screen = await render(+ <Form onFormSubmit={submitted}>+ <Field name="departure">+ {family.render({ empty: true, required: true })}+ <FieldDescription>Choose a departure.</FieldDescription>+ <FieldError match="valueMissing">Departure is required.</FieldError>+ </Field>+ <button type="submit">Submit booking</button>+ </Form>,+ )+ const trigger = screen.getByRole('button', { name: 'Departure', exact: true })+ await expect.element(trigger).not.toHaveAttribute('aria-invalid', 'true')+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).not.toHaveBeenCalled()+ await expect.element(trigger).toHaveFocus()+ await expect.element(trigger).toHaveAttribute('aria-invalid', 'true')+ await expect+ .element(trigger)+ .toHaveAccessibleDescription('Required Choose a departure. Departure is required.')+ },+)++it.each(families)(+ '$name validates committed changes, leaves drafts untouched, and resets the field',+ async (family) => {+ const changed = vi.fn()+ const validate = vi.fn(() => null)+ const screen = await render(+ <Form aria-label="Booking" validationMode="onChange">+ <ObservedField name="departure" validate={validate}>+ {family.render({ onValueChange: changed })}+ <FieldError />+ </ObservedField>+ <button type="reset">Reset booking</button>+ </Form>,+ )+ await screen.getByRole('button', { name: /^Departure / }).click()+ expect(stateOf(screen)).toMatchObject({ focused: true, dirty: false, touched: false })+ const commitButton = screen+ .getByRole('button', {+ name: family.name === 'DatePicker' ? 'Thursday, January 16th, 2025' : 'OK',+ exact: true,+ })+ .element()+ await family.choose(screen)+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ expect.anything(),+ expect.objectContaining({+ reason: 'item-press',+ event: expect.any(Event),+ trigger: commitButton,+ }),+ )+ expect(stateOf(screen)).toMatchObject({ dirty: true, filled: true })+ expect(validate).toHaveBeenCalled()+ expect(+ new FormData(screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement).get(+ 'departure',+ ),+ ).toBe(family.next)+ await screen.getByRole('button', { name: 'Reset booking' }).click()+ expect(changed).toHaveBeenLastCalledWith(+ family.initial,+ expect.objectContaining({ reason: 'reset', event: expect.any(Event) }),+ )+ expect(+ new FormData(screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement).get(+ 'departure',+ ),+ ).toBe(family.serialized)+ expect(stateOf(screen)).toMatchObject({ dirty: false, touched: false, filled: true })+ },+)++it.each(families)(+ '$name cancels value commits and clearing before changing field state or closing',+ async (family) => {+ const errors = { departure: 'Server rejected this value.' }+ const validate = vi.fn(() => null)+ const changed = vi.fn((_value, details: DatePickerChangeEventDetails) => details.cancel())+ const screen = await render(+ <Form aria-label="Booking" errors={errors}>+ <ObservedField name="departure" validate={validate}>+ {family.render({ onValueChange: changed })}+ <FieldError />+ </ObservedField>+ </Form>,+ )+ await screen.getByRole('button', { name: /^Departure / }).click()+ await family.choose(screen)+ await expect+ .element(screen.getByRole('dialog', { name: 'Departure', exact: true }))+ .toBeVisible()+ expect(stateOf(screen)).toMatchObject({ dirty: false })+ expect(+ new FormData(screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement).get(+ 'departure',+ ),+ ).toBe(family.serialized)+ await userEvent.keyboard('{Escape}')+ const clear = screen.getByRole('button', { name: 'Clear departure' })+ await clear.click()+ await expect.element(clear).toHaveFocus()+ expect(changed).toHaveBeenLastCalledWith(+ null,+ expect.objectContaining({ reason: 'clear-press', isCanceled: true }),+ )+ expect(stateOf(screen)).toMatchObject({ dirty: false, filled: true })+ expect(validate).not.toHaveBeenCalled()+ await expect+ .element(screen.getByText('Server rejected this value.', { exact: true }))+ .toBeVisible()+ },+)++it('uses FieldLabel in non-native mode and preserves external description and error associations', async () => {+ const errors = { departure: 'Server rejected this date.' }+ const screen = await render(+ <Form errors={errors}>+ <Field name="departure">+ <FieldLabel nativeLabel={false} render={<div />}>+ Departure+ </FieldLabel>+ <DatePicker defaultValue="2025-01-15">+ <DatePickerTrigger id="departure-date" aria-describedby="additional-help" />+ <DatePickerContent />+ </DatePicker>+ <FieldDescription>Choose a working day.</FieldDescription>+ <FieldError />+ </Field>+ <p id="additional-help">Extra information.</p>+ </Form>,+ )+ const trigger = screen.getByRole('button', { name: 'Departure Jan 15, 2025' })+ await screen.getByText('Departure', { exact: true }).click()+ await expect.element(trigger).toHaveFocus()+ await expect.element(trigger).toHaveAttribute('aria-expanded', 'false')+ await expect+ .element(trigger)+ .toHaveAccessibleDescription(+ 'Extra information. Choose a working day. Server rejected this date.',+ )+})++it('unregisters disabled and reassociated inputs while retaining read-only values', async () => {+ const submitted = vi.fn()+ function Example() {+ const [disabled, setDisabled] = React.useState(false)+ const [external, setExternal] = React.useState(false)+ return (+ <React.Fragment>+ <form id="external-booking" aria-label="External booking" />+ <Form onFormSubmit={submitted}>+ <fieldset disabled={disabled}>+ <Field name="departure">+ {families[0]!.render({ form: external ? 'external-booking' : undefined })}+ </Field>+ </fieldset>+ <Field name="locked">{families[1]!.render({ readOnly: true })}</Field>+ <Field name="disabled" disabled>+ {families[2]!.render({})}+ </Field>+ <button type="button" onClick={() => setDisabled(!disabled)}>+ Toggle disabled+ </button>+ <button type="button" onClick={() => setExternal(!external)}>+ Toggle form+ </button>+ <button type="submit">Submit booking</button>+ </Form>+ </React.Fragment>+ )+ }+ const screen = await render(<Example />)+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenLastCalledWith(+ { departure: '2025-01-15', locked: '13:30' },+ expect.anything(),+ )+ await screen.getByRole('button', { name: 'Toggle disabled' }).click()+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenLastCalledWith({ locked: '13:30' }, expect.anything())+ await screen.getByRole('button', { name: 'Toggle disabled' }).click()+ await screen.getByRole('button', { name: 'Toggle form' }).click()+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenLastCalledWith({ locked: '13:30' }, expect.anything())+ expect(+ new FormData(+ screen.getByRole('form', { name: 'External booking' }).element() as HTMLFormElement,+ ).get('departure'),+ ).toBe('2025-01-15')+})++it.each(['external-booking', 'missing-booking'])(+ 'excludes an initially reassociated picker from contextual validation and submission (%s)',+ async (form) => {+ const submitted = vi.fn()+ const validate = vi.fn(() => 'This date is unavailable.')+ const screen = await render(+ <React.Fragment>+ <form id="external-booking" aria-label="External booking" />+ <Form onFormSubmit={submitted}>+ <Field name="departure" validate={validate}>+ {families[0]!.render({ form })}+ </Field>+ <button type="submit">Submit booking</button>+ </Form>+ </React.Fragment>,+ )+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(validate).not.toHaveBeenCalled()+ expect(submitted).toHaveBeenCalledExactlyOnceWith({}, expect.anything())+ expect(+ new FormData(+ screen.getByRole('form', { name: 'External booking' }).element() as HTMLFormElement,+ ).get('departure'),+ ).toBe(form === 'external-booking' ? '2025-01-15' : null)+ },+)++it.each([false, true])(+ 'updates contextual registration when the explicit form owner changes its id (portal: %s)',+ async (portal) => {+ const submitted = vi.fn()+ function Example({ id }: { id: string }) {+ const field = <Field name="departure">{families[0]!.render({ form: 'booking' })}</Field>+ return (+ <Form id={id} aria-label="Booking" onFormSubmit={submitted}>+ {portal ? ReactDOM.createPortal(field, document.body) : field}+ <button type="submit">Submit booking</button>+ </Form>+ )+ }+ const screen = await render(<Example id="booking" />)+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenLastCalledWith({ departure: '2025-01-15' }, expect.anything())+ await screen.rerender(<Example id="other" />)+ expect(+ new FormData(screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement).has(+ 'departure',+ ),+ ).toBe(false)+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenLastCalledWith({}, expect.anything())+ await screen.rerender(<Example id="booking" />)+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenLastCalledWith({ departure: '2025-01-15' }, expect.anything())+ },+)++it('registers and resets a portalled picker with its contextual Form', async () => {+ const submitted = vi.fn()+ const screen = await render(+ <Form onFormSubmit={submitted}>+ {ReactDOM.createPortal(+ <Field name="departure">{families[0]!.render({})}</Field>,+ document.body,+ )}+ <button type="submit">Submit booking</button>+ <button type="reset">Reset booking</button>+ </Form>,+ )+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenCalledExactlyOnceWith({ departure: '2025-01-15' }, expect.anything())+ await screen.getByRole('button', { name: /^Departure / }).click()+ await families[0]!.choose(screen)+ await screen.getByRole('button', { name: 'Reset booking' }).click()+ await expect.element(screen.getByRole('button', { name: 'Departure Jan 15, 2025' })).toBeVisible()+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenLastCalledWith({ departure: '2025-01-15' }, expect.anything())+})++it.each([false, true])(+ 'validates after leaving an autofocused picker (strict mode: %s)',+ async (strict) => {+ const validate = vi.fn(() => 'Choose another date.')+ const example = (+ <Form validationMode="onBlur">+ <ObservedField name="departure" validate={validate}>+ <DatePicker defaultValue="2025-01-15">+ <DatePickerLabel>Departure</DatePickerLabel>+ {/* oxlint-disable-next-line jsx-a11y/no-autofocus -- Reproduces focus before Field registration completes. */}+ <DatePickerTrigger autoFocus />+ </DatePicker>+ <FieldError />+ </ObservedField>+ <button type="button">Next field</button>+ </Form>+ )+ const screen = await render(strict ? <React.StrictMode>{example}</React.StrictMode> : example)+ await expect+ .element(screen.getByRole('button', { name: 'Departure Jan 15, 2025' }))+ .toHaveFocus()+ expect(stateOf(screen)).toMatchObject({ focused: true, touched: false })+ expect(validate).not.toHaveBeenCalled()+ await userEvent.tab()+ await expect.element(screen.getByRole('button', { name: 'Next field' })).toHaveFocus()+ expect(validate).toHaveBeenCalledExactlyOnceWith('2025-01-15', { departure: '2025-01-15' })+ expect(stateOf(screen)).toMatchObject({ focused: false, touched: true })+ await expect.element(screen.getByText('Choose another date.', { exact: true })).toBeVisible()+ },+)++it('validates on leaving the complete picker, not when focus enters its portalled draft', async () => {+ const validate = vi.fn((value: unknown) => (value === '13:30' ? 'Choose another time.' : null))+ const screen = await render(+ <Form validationMode="onBlur">+ <button type="button">Next field</button>+ <ObservedField name="departure" validate={validate}>+ {families[1]!.render({})}+ <FieldError />+ </ObservedField>+ </Form>,+ )+ await screen.getByRole('button', { name: /^Departure / }).click()+ await screen+ .getByRole('listbox', { name: 'Hour' })+ .getByRole('option', { name: '2', exact: true })+ .click()+ expect(validate).not.toHaveBeenCalled()+ expect(stateOf(screen)).toMatchObject({ dirty: false, touched: false, focused: true })+ await screen.getByRole('button', { name: 'Next field' }).click()+ expect(validate).toHaveBeenCalledExactlyOnceWith('13:30', { departure: '13:30' })+ await expect.element(screen.getByText('Choose another time.', { exact: true })).toBeVisible()+ const trigger = screen.getByRole('button', { name: /^Departure / })+ await expect.element(trigger).toHaveAttribute('data-invalid')+ expect(stateOf(screen)).toMatchObject({ touched: true, focused: false, dirty: false })+})++it('keeps server errors when a controlled owner rejects a change and clears them after an accepted change', async () => {+ const errors = { departure: 'Server rejected this date.' }+ function Example() {+ const [value, setValue] = React.useState<string | null>('2025-01-15')+ const [accept, setAccept] = React.useState(false)+ return (+ <Form errors={errors}>+ <ObservedField name="departure">+ <DatePicker+ value={value}+ onValueChange={(next) => {+ if (accept) setValue(next)+ }}+ >+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ <FieldError />+ </ObservedField>+ <button type="button" onClick={() => setAccept(true)}>+ Accept changes+ </button>+ </Form>+ )+ }+ const screen = await render(<Example />)+ await screen.getByRole('button', { name: /^Departure / }).click()+ await families[0]!.choose(screen)+ await expect+ .element(screen.getByText('Server rejected this date.', { exact: true }))+ .toBeVisible()+ expect(stateOf(screen)).toMatchObject({ dirty: false })+ await screen.getByRole('button', { name: 'Accept changes' }).click()+ await screen.getByRole('button', { name: /^Departure / }).click()+ await families[0]!.choose(screen)+ await expect+ .element(screen.getByText('Server rejected this date.', { exact: true }))+ .not.toBeInTheDocument()+ expect(stateOf(screen)).toMatchObject({ dirty: true })+})++it('preserves the current value and dirty state when reset is canceled by the picker or form', async () => {+ const changed = vi.fn((_value, details: DatePickerChangeEventDetails) => {+ if (details.reason === 'reset') details.cancel()+ })+ function Example() {+ const [preventReset, setPreventReset] = React.useState(false)+ return (+ <Form+ aria-label="Booking"+ onReset={(event) => {+ if (preventReset) event.preventDefault()+ }}+ >+ <ObservedField name="departure">+ {families[0]!.render({ onValueChange: changed })}+ </ObservedField>+ <button type="reset">Reset booking</button>+ <button type="button" onClick={() => setPreventReset(true)}>+ Cancel form reset+ </button>+ </Form>+ )+ }+ const screen = await render(<Example />)+ await screen.getByRole('button', { name: /^Departure / }).click()+ await families[0]!.choose(screen)+ await screen.getByRole('button', { name: 'Reset booking' }).click()+ expect(changed).toHaveBeenLastCalledWith(+ '2025-01-15',+ expect.objectContaining({ reason: 'reset', isCanceled: true }),+ )+ expect(stateOf(screen)).toMatchObject({ dirty: true })+ expect(+ new FormData(screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement).get(+ 'departure',+ ),+ ).toBe('2025-01-16')+ await screen.getByRole('button', { name: 'Cancel form reset' }).click()+ changed.mockClear()+ await screen.getByRole('button', { name: 'Reset booking' }).click()+ expect(changed).not.toHaveBeenCalled()+ expect(stateOf(screen)).toMatchObject({ dirty: true })+})++it('revalidates a required field after a committed selection', async () => {+ const submitted = vi.fn()+ const screen = await render(+ <Form onFormSubmit={submitted}>+ <Field name="departure">+ <DatePicker required defaultValue="2025-01-15">+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerClear aria-label="Clear departure" />+ <DatePickerContent />+ </DatePicker>+ <FieldError match="valueMissing">Departure is required.</FieldError>+ </Field>+ <button type="submit">Submit booking</button>+ </Form>,+ )+ await screen.getByRole('button', { name: 'Clear departure' }).click()+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ await expect.element(screen.getByText('Departure is required.', { exact: true })).toBeVisible()+ expect(submitted).not.toHaveBeenCalled()+ await screen.getByRole('button', { name: 'Departure', exact: true }).click()+ await userEvent.keyboard('{Enter}')+ await expect+ .element(screen.getByText('Departure is required.', { exact: true }))+ .not.toBeInTheDocument()+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenCalledExactlyOnceWith(+ { departure: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/) },+ expect.anything(),+ )+})++it('compares DateTimePicker dirty state by instant instead of Date object identity', async () => {+ function Example() {+ const [value, setValue] = React.useState<Date | null>(() => new Date('2025-01-15T13:30:00Z'))+ return (+ <ObservedField name="departure">+ <DateTimePicker timeZone="UTC" value={value} onValueChange={setValue}>+ <DateTimePickerLabel>Departure</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>+ <button type="button" onClick={() => setValue(new Date('2025-01-15T13:30:00Z'))}>+ Restore instant+ </button>+ </ObservedField>+ )+ }+ const screen = await render(<Example />)+ await screen.getByRole('button', { name: /^Departure / }).click()+ await families[2]!.choose(screen)+ expect(stateOf(screen)).toMatchObject({ dirty: true })+ await screen.getByRole('button', { name: 'Restore instant' }).click()+ expect(stateOf(screen)).toMatchObject({ dirty: false })+})++it('keeps dirty tied to the committed controlled value when its owner declines reset', async () => {+ function Example() {+ const [value, setValue] = React.useState<string | null>('2025-01-15')+ return (+ <Form aria-label="Booking">+ <ObservedField name="departure">+ <DatePicker+ value={value}+ defaultValue="2025-01-15"+ onValueChange={(next, details) => {+ if (details.reason !== 'reset') setValue(next)+ }}+ >+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ </ObservedField>+ <button type="reset">Reset booking</button>+ </Form>+ )+ }+ const screen = await render(<Example />)+ await screen.getByRole('button', { name: /^Departure / }).click()+ await families[0]!.choose(screen)+ await screen.getByRole('button', { name: 'Reset booking' }).click()+ await expect.element(screen.getByRole('button', { name: 'Departure Jan 16, 2025' })).toBeVisible()+ expect(stateOf(screen)).toMatchObject({ dirty: true, touched: false })+ expect(+ new FormData(screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement).get(+ 'departure',+ ),+ ).toBe('2025-01-16')+})++it('clears reset feedback without removing required validation on the next submit', async () => {+ const submitted = vi.fn()+ const screen = await render(+ <Form onFormSubmit={submitted}>+ <ObservedField name="departure">+ {families[0]!.render({ empty: true, required: true })}+ <FieldError match="valueMissing">Departure is required.</FieldError>+ </ObservedField>+ <button type="submit">Submit booking</button>+ <button type="reset">Reset booking</button>+ </Form>,+ )+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ await expect.element(screen.getByText('Departure is required.', { exact: true })).toBeVisible()+ await screen.getByRole('button', { name: 'Reset booking' }).click()+ await expect+ .element(screen.getByText('Departure is required.', { exact: true }))+ .not.toBeInTheDocument()+ expect(stateOf(screen)).toMatchObject({ touched: false, dirty: false })+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).not.toHaveBeenCalled()+ await expect.element(screen.getByText('Departure is required.', { exact: true })).toBeVisible()+ await expect.element(screen.getByRole('button', { name: 'Departure', exact: true })).toHaveFocus()+})++it('clears Field custom validity on reset and validates the restored value on the next submit', async () => {+ const submitted = vi.fn()+ const screen = await render(+ <Form aria-label="Booking" validationMode="onChange" onFormSubmit={submitted}>+ <ObservedField+ name="departure"+ validate={(value) => (value === '2025-01-16' ? 'Date unavailable.' : null)}+ >+ {families[0]!.render({})}+ <FieldError />+ </ObservedField>+ <button type="submit">Submit booking</button>+ <button type="reset">Reset booking</button>+ </Form>,+ )+ await screen.getByRole('button', { name: /^Departure / }).click()+ await families[0]!.choose(screen)+ await expect.element(screen.getByText('Date unavailable.', { exact: true })).toBeVisible()+ await screen.getByRole('button', { name: 'Reset booking' }).click()+ await expect+ .element(screen.getByText('Date unavailable.', { exact: true }))+ .not.toBeInTheDocument()+ expect(+ (screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement).checkValidity(),+ ).toBe(true)+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenCalledExactlyOnceWith({ departure: '2025-01-15' }, expect.anything())+})++it('integrates native invalid events with Field without marking an unchanged value dirty', async () => {+ const submitted = vi.fn((event: React.FormEvent) => event.preventDefault())+ const screen = await render(+ <form onSubmit={submitted}>+ <ObservedField name="departure">+ {families[0]!.render({ empty: true, required: true })}+ <FieldError match="valueMissing">Departure is required.</FieldError>+ </ObservedField>+ <button type="submit">Submit booking</button>+ </form>,+ )+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).not.toHaveBeenCalled()+ await expect.element(screen.getByText('Departure is required.', { exact: true })).toBeVisible()+ expect(stateOf(screen)).toMatchObject({ touched: true, dirty: false, valid: false })+ await expect.element(screen.getByRole('button', { name: 'Departure', exact: true })).toHaveFocus()+})++it('ignores a pending validation result after reset', async () => {+ let finishValidation: ((message: string) => void) | undefined+ const screen = await render(+ <Form validationMode="onChange">+ <ObservedField+ name="departure"+ validate={() =>+ new Promise<string>((resolve) => {+ finishValidation = resolve+ })+ }+ >+ {families[0]!.render({})}+ <FieldError />+ </ObservedField>+ <button type="reset">Reset booking</button>+ </Form>,+ )+ await screen.getByRole('button', { name: /^Departure / }).click()+ await families[0]!.choose(screen)+ expect(finishValidation).toBeTypeOf('function')+ await screen.getByRole('button', { name: 'Reset booking' }).click()+ await expect.element(screen.getByRole('button', { name: 'Departure Jan 15, 2025' })).toBeVisible()+ await React.act(async () => {+ finishValidation!('Stale validation error.')+ })+ await expect+ .element(screen.getByText('Stale validation error.', { exact: true }))+ .not.toBeInTheDocument()+ expect(stateOf(screen)).toMatchObject({ dirty: false, touched: false, valid: null })+})++it.each(['disabled', 'fieldset-disabled', 'unmounted'] as const)(+ 'releases Field focus when its focused picker becomes %s without a blur event',+ async (transition) => {+ function Example({ changed = false }: { changed?: boolean }) {+ return (+ <fieldset disabled={changed && transition === 'fieldset-disabled'}>+ <ObservedField name="departure">+ {!(changed && transition === 'unmounted') &&+ families[0]!.render({ disabled: changed && transition === 'disabled' })}+ </ObservedField>+ </fieldset>+ )+ }+ const screen = await render(<Example />)+ await screen.getByText('Departure', { exact: true }).click()+ await expect.element(screen.getByRole('button', { name: /^Departure / })).toHaveFocus()+ expect(stateOf(screen)).toMatchObject({ focused: true })+ await screen.rerender(<Example changed />)+ expect(stateOf(screen)).toMatchObject({ focused: false, touched: false })+ },+)++it('replaces name and id registrations and removes unmounted pickers in Strict Mode', async () => {+ const submitted = vi.fn()+ const validate = vi.fn(() => null)+ function Example({ name, mounted = true }: { name: string; mounted?: boolean }) {+ const actionsRef = React.useRef<FormActions>(null)+ return (+ <Form actionsRef={actionsRef} onFormSubmit={submitted}>+ <Field name={name} validate={validate}>+ {mounted && (+ <DatePicker defaultValue="2025-01-15">+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger id={`${name}-trigger`} />+ <DatePickerContent />+ </DatePicker>+ )}+ </Field>+ <button type="button" onClick={() => actionsRef.current?.validate('previous')}>+ Validate previous+ </button>+ <button type="button" onClick={() => actionsRef.current?.validate('current')}>+ Validate current+ </button>+ <button type="submit">Submit booking</button>+ </Form>+ )+ }+ const view = (name: string, mounted = true) => (+ <React.StrictMode>+ <Example name={name} mounted={mounted} />+ </React.StrictMode>+ )+ const screen = await render(view('previous'))+ await screen.rerender(view('current'))+ await screen.getByText('Departure', { exact: true }).click()+ const trigger = screen.getByRole('button', { name: 'Departure Jan 15, 2025' })+ await expect.element(trigger).toHaveFocus()+ await expect.element(trigger).toHaveAttribute('id', 'current-trigger')+ await expect.element(trigger).toHaveAttribute('aria-expanded', 'false')+ await screen.getByRole('button', { name: 'Validate previous' }).click()+ expect(validate).not.toHaveBeenCalled()+ await screen.getByRole('button', { name: 'Validate current' }).click()+ expect(validate).toHaveBeenCalledExactlyOnceWith('2025-01-15', { current: '2025-01-15' })+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenLastCalledWith({ current: '2025-01-15' }, expect.anything())+ await screen.rerender(view('current', false))+ validate.mockClear()+ await screen.getByRole('button', { name: 'Validate current' }).click()+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(validate).not.toHaveBeenCalled()+ expect(submitted).toHaveBeenLastCalledWith({}, expect.anything())+ await screen.rerender(view('current'))+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(validate).toHaveBeenCalledExactlyOnceWith('2025-01-15', { current: '2025-01-15' })+ expect(submitted).toHaveBeenLastCalledWith({ current: '2025-01-15' }, expect.anything())+})++it('keeps Clear inside the field focus boundary while dismissing an open popup', async () => {+ const validate = vi.fn(() => null)+ const screen = await render(+ <Form validationMode="onBlur">+ <ObservedField name="departure" validate={validate}>+ <div style={{ display: 'flex', gap: 4 }}>{families[0]!.render({})}</div>+ </ObservedField>+ </Form>,+ )+ await screen.getByRole('button', { name: /^Departure / }).click()+ await screen.getByRole('button', { name: 'Clear departure' }).click()+ await expect.element(screen.getByRole('button', { name: 'Departure', exact: true })).toHaveFocus()+ expect(validate).not.toHaveBeenCalled()+ expect(stateOf(screen)).toMatchObject({ touched: false, focused: true, filled: false })+})++it('preserves Field native custom validity when only picker validation copy changes', async () => {+ const submitted = vi.fn((event: React.FormEvent) => event.preventDefault())+ function Example({ message }: { message: string }) {+ return (+ <form onSubmit={submitted}>+ <button type="button">Next field</button>+ <Field name="departure" validationMode="onBlur" validate={() => 'Date unavailable.'}>+ <DatePicker defaultValue="2025-01-15" validationMessage={message}>+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ <FieldError />+ </Field>+ <button type="submit">Submit booking</button>+ </form>+ )+ }+ const screen = await render(<Example message="Choose a date." />)+ await screen.getByText('Departure', { exact: true }).click()+ await screen.getByRole('button', { name: 'Next field' }).click()+ await expect.element(screen.getByText('Date unavailable.', { exact: true })).toBeVisible()+ await screen.rerender(<Example message="请选择日期。" />)+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).not.toHaveBeenCalled()+ await expect.element(screen.getByRole('button', { name: /^Departure / })).toHaveFocus()+})++it.each(['disabled', 'unmounted'] as const)(+ 'releases focus when only the Trigger becomes %s',+ async (transition) => {+ function Example({ changed = false }: { changed?: boolean }) {+ return (+ <ObservedField name="departure">+ <DatePicker defaultValue="2025-01-15">+ <DatePickerLabel>Departure</DatePickerLabel>+ {!(changed && transition === 'unmounted') && <DatePickerTrigger disabled={changed} />}+ <DatePickerContent />+ </DatePicker>+ </ObservedField>+ )+ }+ const screen = await render(<Example />)+ await screen.getByText('Departure', { exact: true }).click()+ expect(stateOf(screen)).toMatchObject({ focused: true })+ await screen.rerender(<Example changed />)+ expect(stateOf(screen)).toMatchObject({ focused: false })+ },+)++it('releases focus when an external controlled update unmounts the focused Clear', async () => {+ function Example({ value }: { value: string | null }) {+ return (+ <ObservedField name="departure">+ <DatePicker value={value}>+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerClear aria-label="Clear departure" />+ <DatePickerContent />+ </DatePicker>+ </ObservedField>+ )+ }+ const screen = await render(<Example value="2025-01-15" />)+ await screen.getByText('Departure', { exact: true }).click()+ await userEvent.tab()+ await expect.element(screen.getByRole('button', { name: 'Clear departure' })).toHaveFocus()+ expect(stateOf(screen)).toMatchObject({ focused: true })+ await screen.rerender(<Example value={null} />)+ expect(stateOf(screen)).toMatchObject({ focused: false })+})++it('preserves Field focus when a consumer replaces its Trigger callback ref', async () => {+ function Example({ label }: { label: string }) {+ return (+ <ObservedField name="departure">+ <DatePicker defaultValue="2025-01-15">+ <DatePickerLabel>{label}</DatePickerLabel>+ <DatePickerTrigger ref={() => {}} />+ </DatePicker>+ </ObservedField>+ )+ }+ const screen = await render(<Example label="Departure" />)+ await screen.getByText('Departure', { exact: true }).click()+ await screen.rerender(<Example label="Travel date" />)+ await expect.element(screen.getByRole('button', { name: /^Travel date / })).toHaveFocus()+ expect(stateOf(screen)).toMatchObject({ focused: true, touched: false })+})++it.each(['PickerLabel', 'FieldLabel'] as const)(+ 'keeps %s text inside the focus boundary when dismissing an open popup',+ async (label) => {+ const validate = vi.fn(() => null)+ const screen = await render(+ <Form validationMode="onBlur">+ <ObservedField name="departure" validate={validate}>+ {label === 'FieldLabel' && (+ <FieldLabel nativeLabel={false} render={<div />}>+ Departure+ </FieldLabel>+ )}+ <DatePicker defaultValue="2025-01-15">+ {label === 'PickerLabel' && <DatePickerLabel>Departure</DatePickerLabel>}+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ </ObservedField>+ </Form>,+ )+ await screen.getByRole('button', { name: /^Departure / }).click()+ await screen.getByText('Departure', { exact: true }).click()+ await expect.element(screen.getByRole('button', { name: /^Departure / })).toHaveFocus()+ expect(validate).not.toHaveBeenCalled()+ expect(stateOf(screen)).toMatchObject({ focused: true, touched: false })+ },+)++it.each([false, true])(+ 'restores only current Field validity after removing a picker constraint (reset: %s)',+ async (reset) => {+ const submitted = vi.fn((event: React.FormEvent) => event.preventDefault())+ function Example({ minDate }: { minDate: string }) {+ return (+ <form onSubmit={submitted}>+ <button type="button">Next field</button>+ <Field name="departure" validationMode="onBlur" validate={() => 'Date unavailable.'}>+ <DatePicker defaultValue="2025-01-15" minDate={minDate}>+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger />+ </DatePicker>+ <FieldError />+ </Field>+ <button type="reset">Reset booking</button>+ <button type="submit">Submit booking</button>+ </form>+ )+ }+ const screen = await render(<Example minDate="2025-01-01" />)+ await screen.getByText('Departure', { exact: true }).click()+ await screen.getByRole('button', { name: 'Next field' }).click()+ await expect.element(screen.getByText('Date unavailable.', { exact: true })).toBeVisible()+ await screen.rerender(<Example minDate="2025-01-16" />)+ if (reset) {+ await screen.getByRole('button', { name: 'Reset booking' }).click()+ await expect+ .element(screen.getByText('Date unavailable.', { exact: true }))+ .not.toBeInTheDocument()+ }+ await screen.rerender(<Example minDate="2025-01-01" />)+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ if (reset) expect(submitted).toHaveBeenCalledOnce()+ else expect(submitted).not.toHaveBeenCalled()+ },+)++it.each(['enabled', 'disabled', 'readOnly'] as const)(+ 'does not restore obsolete picker validity after Field replaces it (%s)',+ async (state) => {+ const validate = vi.fn((): string | null => 'Field rejected the date.')+ const submitted = vi.fn()+ function Example({ minDate, barred = false }: { minDate: string; barred?: boolean }) {+ const actionsRef = React.useRef<FormActions>(null)+ return (+ <Form validationMode="onChange" actionsRef={actionsRef} onFormSubmit={submitted}>+ <Field name="departure" validate={validate}>+ <DatePicker+ defaultValue="2025-01-15"+ minDate={minDate}+ disabled={barred && state === 'disabled'}+ readOnly={barred && state === 'readOnly'}+ >+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger />+ </DatePicker>+ <FieldError />+ </Field>+ <button type="button" onClick={() => actionsRef.current?.validate()}>+ Validate booking+ </button>+ <button type="submit">Submit booking</button>+ </Form>+ )+ }+ const screen = await render(<Example minDate="2025-01-16" />)+ await screen.getByRole('button', { name: 'Validate booking' }).click()+ await expect+ .element(screen.getByText('Field rejected the date.', { exact: true }))+ .toBeVisible()+ validate.mockReturnValue(null)+ await screen.rerender(<Example minDate="2025-01-01" barred />)+ await screen.rerender(<Example minDate="2025-01-01" />)+ await screen.getByRole('button', { name: 'Validate booking' }).click()+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(submitted).toHaveBeenCalledExactlyOnceWith(+ { departure: '2025-01-15' },+ expect.anything(),+ )+ },+)diff --git a/packages/dify-ui/src/date-time/__tests__/localization.spec.tsx b/packages/dify-ui/src/date-time/__tests__/localization.spec.tsxindex 85d581cfad4..d56e06910a2 100644--- a/packages/dify-ui/src/date-time/__tests__/localization.spec.tsx+++ b/packages/dify-ui/src/date-time/__tests__/localization.spec.tsx@@ -93,7 +93,10 @@ it('locates Persian month/year numbers while preserving canonical civil-date subawait screen.getByRole('button', { name: 'OK', exact: true }).click()expect(changed).not.toHaveBeenCalled()await screen.getByRole('grid').getByRole('button', { name: /۱۵/ }).click()- expect(changed).toHaveBeenCalledWith('2026-12-15')+ expect(changed).toHaveBeenCalledWith(+ '2026-12-15',+ expect.objectContaining({ reason: 'item-press' }),+ )expect(new FormData(screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement).get('date',@@ -146,7 +149,10 @@ it('updates an open locale without committing or discarding the time draft and cawait userEvent.keyboard('{Home}12')await expect.element(minute).toHaveFocus()await screen.getByRole('button', { name: 'OK', exact: true }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('10:12')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '10:12',+ expect.objectContaining({ reason: 'item-press' }),+ )expect(new FormData(screen.getByRole('form', { name: 'Schedule' }).element() as HTMLFormElement).get('time',diff --git a/packages/dify-ui/src/date-time/__tests__/typeahead.spec.tsx b/packages/dify-ui/src/date-time/__tests__/typeahead.spec.tsxindex 27e7b96effc..3bca20cd9af 100644--- a/packages/dify-ui/src/date-time/__tests__/typeahead.spec.tsx+++ b/packages/dify-ui/src/date-time/__tests__/typeahead.spec.tsx@@ -93,5 +93,8 @@ it('preserves repeated digits and starts fresh after returning to a time column'expect(changed).not.toHaveBeenCalled()await expect.element(trigger).toHaveTextContent('1:30 PM')await screen.getByRole('button', { name: 'OK', exact: true }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('14:55')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '14:55',+ expect.objectContaining({ reason: 'item-press' }),+ )})diff --git a/packages/dify-ui/src/date-time/__tests__/types.tsx b/packages/dify-ui/src/date-time/__tests__/types.tsxindex 0066147b042..c87722e462d 100644--- a/packages/dify-ui/src/date-time/__tests__/types.tsx+++ b/packages/dify-ui/src/date-time/__tests__/types.tsx@@ -1,3 +1,9 @@+import type {+ DatePickerChangeEventDetails,+ DatePickerChangeEventReason,+} from '@langgenius/dify-ui/date-picker'+import type { DateTimePickerChangeEventDetails } from '@langgenius/dify-ui/date-time-picker'+import type { TimePickerChangeEventDetails } from '@langgenius/dify-ui/time-picker'import type * as React from 'react'import {DatePicker,@@ -28,12 +34,23 @@ export function pickerTypeContracts(const date = (<DatePickervalue="2026-09-28"- onValueChange={(value) => {+ onValueChange={(value, details) => {expectTypeOf(value).toEqualTypeOf<string | null>()+ expectTypeOf(details).toEqualTypeOf<DatePickerChangeEventDetails>()+ expectTypeOf(details.reason).toEqualTypeOf<DatePickerChangeEventReason>()+ if (details.reason === 'item-press') {+ expectTypeOf(details.event).toEqualTypeOf<MouseEvent | KeyboardEvent | PointerEvent>()+ }+ if (details.reason === 'reset') expectTypeOf(details.event).toEqualTypeOf<Event>()+ details.cancel()value?.toUpperCase()}}>- <DatePickerLabel ref={contentRef} className="mb-1">+ <DatePickerLabel+ ref={contentRef}+ className={(state) => (state.valid === false ? 'text-text-destructive' : 'mb-1')}+ style={(state) => ({ opacity: state.disabled ? 0.5 : 1 })}+ >Date</DatePickerLabel><DatePickerTrigger@@ -49,8 +66,9 @@ export function pickerTypeContracts(<TimePickerlocale="zh-CN"value="22:23"- onValueChange={(value) => {+ onValueChange={(value, details) => {expectTypeOf(value).toEqualTypeOf<string | null>()+ expectTypeOf(details).toEqualTypeOf<TimePickerChangeEventDetails>()value?.toUpperCase()}}>@@ -63,8 +81,9 @@ export function pickerTypeContracts(<DateTimePickertimeZone="Asia/Shanghai"value={new Date()}- onValueChange={(value) => {+ onValueChange={(value, details) => {expectTypeOf(value).toEqualTypeOf<Date | null>()+ expectTypeOf(details).toEqualTypeOf<DateTimePickerChangeEventDetails>()value?.toISOString()}}>diff --git a/packages/dify-ui/src/date-time/date-picker/__tests__/behavior.spec.tsx b/packages/dify-ui/src/date-time/date-picker/__tests__/behavior.spec.tsxindex d80b0109a03..3aba8b25b90 100644--- a/packages/dify-ui/src/date-time/date-picker/__tests__/behavior.spec.tsx+++ b/packages/dify-ui/src/date-time/date-picker/__tests__/behavior.spec.tsx@@ -252,7 +252,10 @@ describe('DatePicker keyboard and form contract', () => {</DatePicker>,)await screen.getByRole('button', { name: 'Clear date' }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith(null)+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ null,+ expect.objectContaining({ reason: 'clear-press' }),+ )await expect.element(screen.getByRole('button', { name: 'Date', exact: true })).toHaveFocus()await expect.element(screen.getByRole('button', { name: 'Clear date' }))@@ -453,5 +456,8 @@ it('keeps Persian month labels in the Gregorian calendar used by the value', asyawait screen.getByRole('button', { name: 'OK' }).click()const dateName = 'شنبه ۱۵ فوریه ۲۰۲۵'await screen.getByRole('button', { name: dateName }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('2025-02-15')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '2025-02-15',+ expect.objectContaining({ reason: 'item-press' }),+ )})diff --git a/packages/dify-ui/src/date-time/date-picker/index.stories.tsx b/packages/dify-ui/src/date-time/date-picker/index.stories.tsxindex e1987a1265c..979b5242bb1 100644--- a/packages/dify-ui/src/date-time/date-picker/index.stories.tsx+++ b/packages/dify-ui/src/date-time/date-picker/index.stories.tsx@@ -4,6 +4,8 @@ import * as React from 'react'import { expect, waitFor, within } from 'storybook/test'import { Button } from '../../button'import { DirectionProvider } from '../../direction-provider'+import { Field, FieldDescription, FieldError } from '../../field'+import { Form } from '../../form'import {DateTimePicker,DateTimePickerContent,@@ -277,3 +279,107 @@ export const RTL: Story = {await waitFor(() => expect(trigger).toHaveFocus())},}++function FieldFormExample() {+ const [submitted, setSubmitted] = React.useState('')+ const [lastChange, setLastChange] = React.useState('No committed changes')+ return (+ <Form+ className="grid w-80 gap-4"+ onFormSubmit={(values) => setSubmitted(JSON.stringify(values))}+ onReset={() => setSubmitted('')}+ >+ <Field name="departureDate">+ <DatePicker+ required+ minDate="2025-01-01"+ maxDate="2025-01-31"+ onValueChange={(_value, details) => setLastChange(`Date: ${details.reason}`)}+ >+ <DatePickerLabel>Departure date</DatePickerLabel>+ <div className="flex items-center gap-1">+ <DatePickerTrigger />+ <DatePickerClear aria-label="Clear departure date" />+ </div>+ <DatePickerContent />+ </DatePicker>+ <FieldDescription>Choose a date in January 2025.</FieldDescription>+ <FieldError match="valueMissing">Choose a departure date.</FieldError>+ </Field>+ <Field name="departureTime">+ <TimePicker+ defaultValue="13:30"+ onValueChange={(_value, details) => setLastChange(`Time: ${details.reason}`)}+ >+ <TimePickerLabel>Departure time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>+ <FieldDescription>Changes are committed with OK.</FieldDescription>+ <FieldError />+ </Field>+ <Field name="meetingInstant">+ <DateTimePicker+ timeZone="America/New_York"+ defaultValue={new Date('2025-01-15T18:30:00Z')}+ onValueChange={(_value, details) => setLastChange(`Meeting: ${details.reason}`)}+ >+ <DateTimePickerLabel>Meeting in New York</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>+ <FieldDescription>Submitted as a UTC instant.</FieldDescription>+ <FieldError />+ </Field>+ <div className="flex gap-2">+ <Button type="submit" variant="primary">+ Submit booking+ </Button>+ <Button type="reset" variant="secondary">+ Reset booking+ </Button>+ </div>+ <output aria-label="Last change" className="system-xs-regular text-text-secondary">+ {lastChange}+ </output>+ <output+ aria-label="Submitted values"+ className="system-xs-regular break-all text-text-secondary"+ >+ {submitted}+ </output>+ </Form>+ )+}++export const FieldAndForm: Story = {+ render: () => <FieldFormExample />,+ play: async ({ canvasElement, userEvent }) => {+ const canvas = within(canvasElement)+ const page = within(canvasElement.ownerDocument.body)+ await userEvent.click(canvas.getByRole('button', { name: 'Submit booking' }))+ await expect(canvas.getByText('Choose a departure date.')).toBeVisible()+ const trigger = canvas.getByRole('button', { name: 'Departure date' })+ await expect(trigger).toHaveFocus()+ await userEvent.click(trigger)+ await userEvent.click(+ await page.findByRole('button', { name: 'Wednesday, January 15th, 2025' }),+ )+ await expect(canvas.getByLabelText('Last change')).toHaveTextContent('Date: item-press')+ await userEvent.click(canvas.getByRole('button', { name: 'Departure time 1:30 PM' }))+ await userEvent.click(+ within(page.getByRole('listbox', { name: 'Hour' })).getByRole('option', {+ name: '2',+ }),+ )+ await userEvent.click(page.getByRole('button', { name: 'OK' }))+ await userEvent.click(canvas.getByRole('button', { name: 'Submit booking' }))+ await expect(canvas.getByLabelText('Submitted values')).toHaveTextContent(+ '{"departureDate":"2025-01-15","departureTime":"14:30","meetingInstant":"2025-01-15T18:30:00.000Z"}',+ )+ await userEvent.click(canvas.getByRole('button', { name: 'Reset booking' }))+ await expect(canvas.getByRole('button', { name: 'Departure date' })).toBeVisible()+ await expect(canvas.getByRole('button', { name: 'Departure time 1:30 PM' })).toBeVisible()+ await expect(canvas.queryByText('Choose a departure date.')).not.toBeInTheDocument()+ },+}diff --git a/packages/dify-ui/src/date-time/date-picker/index.tsx b/packages/dify-ui/src/date-time/date-picker/index.tsxindex f4c07f88f30..1c0e919bbd8 100644--- a/packages/dify-ui/src/date-time/date-picker/index.tsx+++ b/packages/dify-ui/src/date-time/date-picker/index.tsx@@ -9,7 +9,11 @@ import type {PickerTriggerProps,PickerValueProps,} from '../internal/picker-parts'-import { useControlled } from '@base-ui/utils/useControlled'+import type {+ PickerChangeEventDetails,+ PickerChangeEventReason,+} from '../internal/use-picker-value'+import { createChangeEventDetails } from '@base-ui/react/internals/createBaseUIEventDetails'import { enUS } from '@daypicker/react/locale/en-US'import * as React from 'react'import { CalendarPanel } from '../internal/calendar-panel'@@ -23,6 +27,10 @@ import {PickerValue,usePickerContext,} from '../internal/picker-parts'+import { usePickerValue } from '../internal/use-picker-value'++type DatePickerChangeEventReason = PickerChangeEventReason+type DatePickerChangeEventDetails = PickerChangeEventDetailstype DatePickerProps = PickerFieldProps &Pick<CalendarPanelProps, 'locale' | 'minDate' | 'maxDate' | 'isDateUnavailable'> & {@@ -30,7 +38,7 @@ type DatePickerProps = PickerFieldProps &value?: string | nulldefaultValue?: string | null/** Called on day confirmation, clearing or form reset. */- onValueChange?: (value: string | null) => void+ onValueChange?: (value: string | null, details: DatePickerChangeEventDetails) => voidlabels?: Partial<CalendarPanelLabels>}type ContextValue = Omit<@@ -38,7 +46,7 @@ type ContextValue = Omit<'value' | 'defaultValue' | 'onValueChange' | 'children'> & {value: Exclude<DatePickerProps['value'], undefined>- commit: NonNullable<DatePickerProps['onValueChange']>+ commit: (value: string | null, details: DatePickerChangeEventDetails) => boolean}const Context = React.createContext<ContextValue | null>(null)function useContext() {@@ -64,9 +72,12 @@ function DatePicker({children,...props}: DatePickerProps) {- const [value, setValue] = useControlled({- controlled: valueProp,- default: defaultValue,+ const { value, commit } = usePickerValue<string>({+ value: valueProp,+ defaultValue,+ onValueChange,+ disabled: props.disabled,+ readOnly: props.readOnly,name: 'DatePicker',})const parsedValue = requireDateValue(value)@@ -80,13 +91,7 @@ function DatePicker({(props.maxDate && value > props.maxDate) ||props.isDateUnavailable?.(value)),)- function commit(next: string | null) {- if (props.disabled || props.readOnly) return- if (next !== value) {- setValue(next)- onValueChange?.(next)- }- }+return (<Context.Provider value={{ ...props, value, commit }}><PickerRoot@@ -109,12 +114,10 @@ function DatePicker({}).format(parsedValue): ''}+ value={value}serializedValue={value ?? ''}- onClear={() => commit(null)}- onReset={() => {- setValue(defaultValue)- if (defaultValue !== value) onValueChange?.(defaultValue)- }}+ onClear={(details) => commit(null, details)}+ onReset={(details) => commit(defaultValue, details)}>{children}</PickerRoot>@@ -140,16 +143,22 @@ function DatePickerContent(props: DatePickerContentProps) {}function Session() {const { value, commit, locale = enUS, minDate, maxDate, isDateUnavailable, labels } = useContext()- const { close } = usePickerContext()+ const { close, canEdit } = usePickerContext()const [displayMonth, setDisplayMonth] = React.useState(() =>getInitialMonth(value ?? formatDateValue(new Date()), minDate, maxDate),)return (<CalendarPanelvalue={value}- onSelect={(next) => {- commit(next)- close()+ onSelect={(next, event) => {+ if (+ canEdit() &&+ commit(+ next,+ createChangeEventDetails('item-press', event.nativeEvent, event.currentTarget),+ )+ )+ close()}}displayMonth={displayMonth}onDisplayMonthChange={setDisplayMonth}@@ -171,6 +180,8 @@ export {DatePickerValue,}export type {+ DatePickerChangeEventDetails,+ DatePickerChangeEventReason,DatePickerClearProps,DatePickerContentProps,DatePickerLabelProps,diff --git a/packages/dify-ui/src/date-time/date-time-picker/__tests__/index.spec.tsx b/packages/dify-ui/src/date-time/date-time-picker/__tests__/index.spec.tsxindex b6b0cfc509d..92b7d5f7edf 100644--- a/packages/dify-ui/src/date-time/date-time-picker/__tests__/index.spec.tsx+++ b/packages/dify-ui/src/date-time/date-time-picker/__tests__/index.spec.tsx@@ -88,7 +88,10 @@ it.each([await expect.element(screen.getByRole('grid', { name: 'January 2025' })).toBeInTheDocument()await screen.getByRole('button', { name: day, exact: true }).click()await screen.getByRole('button', { name: 'OK' }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith(new Date(`${date}T13:30:00Z`))+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ new Date(`${date}T13:30:00Z`),+ expect.objectContaining({ reason: 'item-press' }),+ )})it.each([@@ -275,7 +278,10 @@ it.each([.toBeInTheDocument()expect(changed).not.toHaveBeenCalled()await screen.getByRole('button', { name: 'OK' }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith(new Date('2026-09-28T14:23:00Z'))+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ new Date('2026-09-28T14:23:00Z'),+ expect.objectContaining({ reason: 'item-press' }),+ )await expect.element(screen.getByRole('button', { name: `Meeting Sep 28, 2026, ${displayTime}` })).toHaveFocus()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.tsxindex 2d6b7d1b7a7..c38c131e79d 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@@ -10,8 +10,12 @@ import type {PickerValueProps,} from '../internal/picker-parts'import type { TimePanelLabels, TimePanelProps } from '../internal/time-panel'+import type {+ PickerChangeEventDetails,+ PickerChangeEventReason,+} from '../internal/use-picker-value'import type { ZonedWallTime } from './zoned-value'-import { useControlled } from '@base-ui/utils/useControlled'+import { createChangeEventDetails } from '@base-ui/react/internals/createBaseUIEventDetails'import { enUS } from '@daypicker/react/locale/en-US'import * as React from 'react'import { Button } from '../../button'@@ -28,10 +32,14 @@ import {usePickerContext,} from '../internal/picker-parts'import { TimePanel } from '../internal/time-panel'+import { usePickerValue } from '../internal/use-picker-value'import { getZonedWallTime, resolveZonedWallTime } from './zoned-value'type DateTimePickerLabels = CalendarPanelLabels &TimePanelLabels & { pickTime: string; backToDate: string; now: string }+type DateTimePickerChangeEventReason = PickerChangeEventReason+type DateTimePickerChangeEventDetails = PickerChangeEventDetails+type DateTimePickerProps = PickerFieldProps &Pick<CalendarPanelProps, 'locale' | 'minDate' | 'maxDate' | 'isDateUnavailable'> &Pick<TimePanelProps, 'hourCycle'> & {@@ -39,7 +47,7 @@ type DateTimePickerProps = PickerFieldProps &value?: Date | nulldefaultValue?: Date | null/** Called on OK, clearing or form reset; popup draft edits do not emit changes. */- onValueChange?: (value: Date | null) => void+ onValueChange?: (value: Date | null, details: DateTimePickerChangeEventDetails) => voidtimeZone: stringisTimeUnavailable?: (wall: Readonly<ZonedWallTime>) => booleanlabels?: Partial<DateTimePickerLabels>@@ -49,7 +57,7 @@ type ContextValue = Omit<'value' | 'defaultValue' | 'onValueChange' | 'children'> & {value: Exclude<DateTimePickerProps['value'], undefined>- commit: NonNullable<DateTimePickerProps['onValueChange']>+ commit: (value: Date | null, details: DateTimePickerChangeEventDetails) => boolean}const Context = React.createContext<ContextValue | null>(null)function useContext() {@@ -83,9 +91,12 @@ function DateTimePicker({children,...props}: DateTimePickerProps) {- const [value, setValue] = useControlled({- controlled: valueProp,- default: defaultValue,+ const { value, commit } = usePickerValue<Date>({+ value: valueProp,+ defaultValue,+ onValueChange,+ disabled: props.disabled,+ readOnly: props.readOnly,name: 'DateTimePicker',})if (value && Number.isNaN(value.getTime())) throw new RangeError('Invalid DateTimePicker value')@@ -101,13 +112,7 @@ function DateTimePicker({props.isDateUnavailable?.(wall.date) ||props.isTimeUnavailable?.(wall)),)- function commit(next: Date | null) {- if (props.disabled || props.readOnly) return- if (next?.getTime() !== value?.getTime()) {- setValue(next)- onValueChange?.(next)- }- }+return (<Context.Provider value={{ ...props, value, commit }}><PickerRoot@@ -133,12 +138,10 @@ function DateTimePicker({}).format(value): ''}+ value={value}serializedValue={value?.toISOString() ?? ''}- onClear={() => commit(null)}- onReset={() => {- setValue(defaultValue)- if (defaultValue?.getTime() !== value?.getTime()) onValueChange?.(defaultValue)- }}+ onClear={(details) => commit(null, details)}+ onReset={(details) => commit(defaultValue, details)}>{children}</PickerRoot>@@ -175,7 +178,7 @@ function Session() {labels,hourCycle,} = useContext()- const { close } = usePickerContext()+ const { close, canEdit } = usePickerContext()const [draft, setDraft] = React.useState(() => getZonedWallTime(value ?? new Date(), timeZone))const [displayMonth, setDisplayMonth] = React.useState(() =>getInitialMonth(draft.date, minDate, maxDate),@@ -233,12 +236,17 @@ function Session() {size="small"disabled={unavailable}aria-describedby={unavailable ? errorId : undefined}- onClick={() => {+ onClick={(event) => {const instant = availableInstant(draft)- if (instant) {- commit(instant)+ if (+ instant &&+ canEdit() &&+ commit(+ instant,+ createChangeEventDetails('item-press', event.nativeEvent, event.currentTarget),+ )+ )close()- }}}>{text.apply}@@ -342,6 +350,8 @@ export {DateTimePickerValue,}export type {+ DateTimePickerChangeEventDetails,+ DateTimePickerChangeEventReason,DateTimePickerClearProps,DateTimePickerContentProps,DateTimePickerLabelProps,diff --git a/packages/dify-ui/src/date-time/internal/calendar-grid.tsx b/packages/dify-ui/src/date-time/internal/calendar-grid.tsxindex 23479cedf94..7fc7ee3f2ee 100644--- a/packages/dify-ui/src/date-time/internal/calendar-grid.tsx+++ b/packages/dify-ui/src/date-time/internal/calendar-grid.tsx@@ -15,7 +15,7 @@ type CalendarGridProps = {nextMonth: string}value: string | null- onSelect: (value: string) => void+ onSelect: (value: string, event: React.MouseEvent<Element> | React.KeyboardEvent<Element>) => voiddisplayMonth: stringonDisplayMonthChange: (value: string) => voidlocale?: DayPickerProps['locale']@@ -150,7 +150,7 @@ function CalendarGrid({requireddir={direction}selected={selected}- onSelect={(date) => {+ onSelect={(date, _selectedDay, _modifiers, event) => {if (!date) returnconst next = fromCalendarDate(date)const nextMonth = `${next.slice(0, 7)}-01`@@ -158,7 +158,7 @@ function CalendarGrid({restoreSelectionFocusRef.current = trueonDisplayMonthChange(nextMonth)}- onSelect(next)+ onSelect(next, event)}}month={toCalendarDate(displayMonth)}onMonthChange={(month) =>diff --git a/packages/dify-ui/src/date-time/internal/calendar-panel.tsx b/packages/dify-ui/src/date-time/internal/calendar-panel.tsxindex 28c3d1aab25..5ca5aa86da9 100644--- a/packages/dify-ui/src/date-time/internal/calendar-panel.tsx+++ b/packages/dify-ui/src/date-time/internal/calendar-panel.tsx@@ -19,7 +19,7 @@ type CalendarPanelLabels = {type CalendarPanelProps = {value: string | null- onSelect: (date: string) => void+ onSelect: (date: string, event: React.MouseEvent<Element> | React.KeyboardEvent<Element>) => voiddisplayMonth: stringonDisplayMonthChange: (month: string) => voidlocale?: DayPickerProps['locale']diff --git a/packages/dify-ui/src/date-time/internal/picker-parts.tsx b/packages/dify-ui/src/date-time/internal/picker-parts.tsxindex 1968450beeb..d98f566b4d2 100644--- a/packages/dify-ui/src/date-time/internal/picker-parts.tsx+++ b/packages/dify-ui/src/date-time/internal/picker-parts.tsx@@ -1,5 +1,7 @@'use client'+import type { Field } from '@base-ui/react/field'+import type { BaseUIComponentProps } from '@base-ui/react/internals/types'import type { TextDirection } from '../../direction-provider'import type { IconButtonProps } from '../../icon-button'import type {@@ -9,14 +11,38 @@ import type {PopoverProps,PopoverTriggerProps,} from '../../popover'+import type { PickerChangeEventDetails } from './use-picker-value'+import { createChangeEventDetails } from '@base-ui/react/internals/createBaseUIEventDetails'+import {+ DEFAULT_VALIDITY_STATE,+ fieldValidityMapping,+} from '@base-ui/react/internals/field-constants'+import { useRegisterFieldControl } from '@base-ui/react/internals/field-register-control'+import { useFieldRootContext } from '@base-ui/react/internals/field-root-context'+import { useFormContext } from '@base-ui/react/internals/form-context'+import { getStateAttributesProps } from '@base-ui/react/internals/getStateAttributesProps'+import {+ useLabel,+ useLabelableContext,+ useLabelableId,+} from '@base-ui/react/internals/labelable-provider'+import { useRenderElement } from '@base-ui/react/internals/useRenderElement'+import { useValueChanged } from '@base-ui/react/internals/useValueChanged'+import { ownerDocument, ownerWindow } from '@base-ui/utils/owner'+import { activeElement, contains, getTarget } from '@base-ui/utils/shadowDom'+import { useStableCallback } from '@base-ui/utils/useStableCallback'+import { useTimeout } from '@base-ui/utils/useTimeout'+import { visuallyHidden, visuallyHiddenInput } from '@base-ui/utils/visuallyHidden'import * as React from 'react'import { cn } from '../../cn'import { DirectionProvider, useDirection } from '../../direction-provider'import { IconButton } from '../../icon-button'import { formLabelClassName } from '../../internal/form-control'import { resolveClassName } from '../../internal/resolve-class-name'+import { mergeProps } from '../../merge-props'import { Popover, PopoverContent, PopoverTrigger } from '../../popover'import { useMergedRefs } from '../../use-merged-refs'+import { arePickerValuesEqual } from './use-picker-value'type PickerOpenChangeDetails = Omit<PopoverChangeEventDetails, 'preventUnmountOnClose'>@@ -39,14 +65,20 @@ type PickerFieldProps = Pick<PopoverProps, 'open' | 'defaultOpen'> & {type PickerContextValue = Omit<PickerFieldProps, 'children'> & {displayValue: stringserializedValue: string- triggerId: string+ triggerId: string | undefinedvalueId: stringlabelId: string | undefinedsetLabelId: React.Dispatch<React.SetStateAction<string | undefined>>errorId: stringrequiredId: stringtriggerRef: React.RefObject<HTMLButtonElement | null>- clear: () => void+ clear: (event: React.MouseEvent<HTMLButtonElement>) => void+ canEdit: () => boolean+ focus: (element: HTMLElement) => void+ releaseFocus: (element?: HTMLElement) => void+ blur: (nextTarget: Element | null) => void+ popupRef: React.RefObject<HTMLDivElement | null>+ clearRef: React.RefObject<HTMLButtonElement | null>close: () => void}@@ -58,7 +90,25 @@ function usePickerContext() {return context}+function usePickerFocusRef<ElementType extends HTMLElement>(+ elementRef: React.RefObject<ElementType | null>,+ disabled = false,+) {+ const { focus, releaseFocus } = usePickerContext()+ React.useLayoutEffect(() => {+ if (disabled && elementRef.current) releaseFocus(elementRef.current)+ }, [disabled, elementRef, releaseFocus])+ return React.useCallback(+ (element: ElementType) => {+ if (contains(element, activeElement(ownerDocument(element)))) focus(element)+ return () => releaseFocus(element)+ },+ [focus, releaseFocus],+ )+}+function PickerRoot({+ value,displayValue,serializedValue,onClear,@@ -66,92 +116,237 @@ function PickerRoot({children,...props}: PickerFieldProps & {+ value: string | Date | nulldisplayValue: stringserializedValue: string- onClear: () => void- onReset: () => void+ onClear: (details: PickerChangeEventDetails) => boolean+ onReset: (details: PickerChangeEventDetails) => boolean}) {const inheritedDirection = useDirection()const direction = props.direction ?? inheritedDirection+ const field = useFieldRootContext()+ const { clearErrors, elementRef: formElementRef, formRef } = useFormContext()+ const { labelId: fieldLabelId } = useLabelableContext()+ const triggerId = useLabelableId()const id = React.useId()const [labelId, setLabelId] = React.useState<string>()const triggerRef = React.useRef<HTMLButtonElement>(null)+ const clearRef = React.useRef<HTMLButtonElement>(null)+ const popupRef = React.useRef<HTMLDivElement>(null)const inputRef = React.useRef<HTMLInputElement>(null)+ const focusedPartRef = React.useRef<HTMLElement | null>(null)const actionsRef = React.useRef<PopoverActions>(null)+ const disabled = Boolean(field.disabled || props.disabled)+ const name = field.name ?? props.name+ const [eligible, setEligible] = React.useState(false)const [validationAttempted, setValidationAttempted] = React.useState(false)+ const [resetVersion, setResetVersion] = React.useState(0)+ const handledResetVersionRef = React.useRef(0)const errorMessage = props.invalid? (props.validationMessage ?? 'Choose a valid value.'): validationAttempted && props.required && !serializedValue? (props.validationMessage ?? 'Choose a value.'): undefined- const invalid = Boolean(errorMessage)+ const invalid = Boolean(errorMessage || field.state.valid === false)+ const canEdit = useStableCallback(+ () => !disabled && !props.readOnly && !inputRef.current?.matches(':disabled'),+ )+ const formValue = useStableCallback(() => serializedValue)+ useRegisterFieldControl(triggerRef, triggerId, value, formValue, eligible, props.name)++ // Read the native form owner after ancestor refs attach, including the contextual Form's ref.React.useEffect(() => {- inputRef.current?.setCustomValidity(- props.invalid ? (props.validationMessage ?? 'Choose a valid value.') : '',+ const input = inputRef.current+ if (!input) return+ function updateEligibility() {+ const form = formElementRef.current+ setEligible(+ Boolean(+ input &&+ !input.matches(':disabled') &&+ (!form || input.form === form || (!input.form && !input.hasAttribute('form'))),+ ),+ )+ }+ updateEligibility()+ const observer = new (ownerWindow(input).MutationObserver)(updateEligibility)+ for (let ancestor: Element | null = input; ancestor; ancestor = ancestor.parentElement)+ observer.observe(ancestor, { attributes: true, attributeFilter: ['disabled', 'form', 'id'] })+ if (formElementRef.current)+ observer.observe(formElementRef.current, { attributes: true, attributeFilter: ['id'] })+ return () => observer.disconnect()+ }, [disabled, props.form, formElementRef])+ const { registerInput: registerFieldInput } = field.validation+ const { setFilled } = field+ const registerInput = React.useCallback(+ (input: HTMLInputElement) =>+ registerFieldInput(input, { controlRef: triggerRef, value: undefined }),+ [registerFieldInput],+ )+ const mergedInputRef = useMergedRefs(inputRef, field.validation.inputRef, registerInput)++ const customValidationMessage = props.invalid+ ? (props.validationMessage ?? 'Choose a valid value.').replace(/\r\n?/g, '\n')+ : ''+ React.useLayoutEffect(() => {+ inputRef.current?.setCustomValidity(customValidationMessage)+ }, [customValidationMessage])+ useValueChanged(customValidationMessage, () => {+ // Replace the native constraint before Field clears its cached custom error, so it cannot+ // restore an obsolete picker message. Previously validated fields need a fresh verdict.+ if (resetVersion !== handledResetVersionRef.current) return+ if (field.validityData.state.valid !== null || field.shouldValidateOnChange()) {+ field.validation.commit(value)+ // Barred inputs hide validationMessage, so Field restores its displaced message regardless+ // of ownership. Retire that stale constraint after its synchronous cleanup as well.+ const input = inputRef.current+ if (input && !input.willValidate) input.setCustomValidity(customValidationMessage)+ } else field.validation.change(undefined, true)+ })+ React.useLayoutEffect(() => {+ setFilled(Boolean(serializedValue))+ }, [setFilled, serializedValue])+ useValueChanged(serializedValue, () => {+ clearErrors(name)+ field.setDirty(!arePickerValuesEqual(value, field.validityData.initialValue))+ field.validation.change(value, resetVersion !== handledResetVersionRef.current)+ })++ const focus = useStableCallback((element: HTMLElement) => {+ if (disabled || element.matches(':disabled')) return+ focusedPartRef.current = element+ field.focusOwnerRef.current = triggerRef+ field.setFocused(true)+ })+ const releaseFocus = useStableCallback((element?: HTMLElement) => {+ if (element && focusedPartRef.current !== element) return+ if (field.focusOwnerRef.current !== triggerRef) return+ focusedPartRef.current = null+ field.focusOwnerRef.current = undefined+ field.setFocused(false)+ })+ const blur = useStableCallback((nextTarget: Element | null) => {+ if (+ contains(triggerRef.current, nextTarget) ||+ contains(clearRef.current, nextTarget) ||+ contains(popupRef.current, nextTarget))- }, [props.invalid, props.validationMessage])- const onResetEvent = React.useEffectEvent(onReset)+ return+ if (field.focusOwnerRef.current !== triggerRef) return+ releaseFocus()+ field.setTouched(true)+ if (field.validationMode === 'onBlur') field.validation.commit(value)+ })+ React.useLayoutEffect(() => {+ if (disabled || inputRef.current?.matches(':disabled')) releaseFocus()+ }, [disabled, eligible, releaseFocus])++ const resetTimeout = useTimeout()+ const resetPicker = useStableCallback((event: Event) => {+ if (event.defaultPrevented) return+ const details = createChangeEventDetails('reset', event)+ if (!onReset(details)) return+ setValidationAttempted(false)+ setResetVersion((version) => version + 1)+ })+ const resetFieldFeedback = useStableCallback(() => {+ clearErrors(name)+ field.validation.change(undefined, true)+ field.setTouched(false)+ field.setDirty(!arePickerValuesEqual(value, field.validityData.initialValue))+ inputRef.current?.setCustomValidity(customValidationMessage)+ field.setValidityData((previous) => ({+ ...previous,+ state: DEFAULT_VALIDITY_STATE,+ error: '',+ errors: [],+ }))+ actionsRef.current?.close()+ })+ React.useLayoutEffect(() => {+ if (resetVersion === handledResetVersionRef.current) return+ handledResetVersionRef.current = resetVersion+ resetFieldFeedback()+ }, [resetVersion, resetFieldFeedback])React.useEffect(() => {- const form = inputRef.current?.form+ const input = inputRef.current+ const form = input?.form ?? (!input?.hasAttribute('form') ? formElementRef.current : null)if (!form) returnfunction reset(event: Event) {- queueMicrotask(() => {- if (event.defaultPrevented) return- setValidationAttempted(false)- onResetEvent()- actionsRef.current?.close()- })+ // Wait for delegated React onReset handlers to be able to cancel the native reset.+ resetTimeout.start(0, () => resetPicker(event))}form.addEventListener('reset', reset)- return () => form.removeEventListener('reset', reset)- }, [props.form])+ return () => {+ form.removeEventListener('reset', reset)+ resetTimeout.clear()+ }+ }, [props.form, formElementRef, resetPicker, resetTimeout])return (<DirectionProvider direction={direction}><PickerContext.Providervalue={{...props,+ disabled,direction,invalid,displayValue,serializedValue,- triggerId: `${id}-trigger`,+ triggerId,valueId: `${id}-value`,- labelId,+ labelId:+ Array.from(new Set([fieldLabelId, labelId].filter(Boolean))).join(' ') || undefined,setLabelId,- errorId: `${id}-error`,+ errorId: errorMessage ? `${id}-error` : '',requiredId: `${id}-required`,triggerRef,- clear: () => {- if (props.disabled || props.readOnly) return+ clearRef,+ popupRef,+ canEdit,+ focus,+ releaseFocus,+ blur,+ clear: (event) => {+ if (!canEdit()) return+ const details = createChangeEventDetails(+ 'clear-press',+ event.nativeEvent,+ event.currentTarget,+ )+ if (!onClear(details)) returntriggerRef.current?.focus()- onClear()actionsRef.current?.close()},close: () => actionsRef.current?.close(),}}>{props.required && (- <span id={`${id}-required`} className="sr-only">+ <span id={`${id}-required`} style={visuallyHidden}>{props.requiredLabel ?? 'Required'}</span>)}<input- ref={inputRef}- hidden+ {...field.validation.getValidationProps(disabled)}+ ref={mergedInputRef}+ style={name ? visuallyHiddenInput : visuallyHidden}+ aria-hidden="true"tabIndex={-1}type="text"autoComplete="off"- name={props.name}+ name={name}form={props.form}value={serializedValue}required={props.required}- disabled={props.disabled}+ disabled={disabled}readOnly={props.readOnly}onChange={() => {}}+ onFocus={() => triggerRef.current?.focus({ focusVisible: true })}onInvalid={(event) => {event.preventDefault()setValidationAttempted(true)+ field.setTouched(true)+ if (triggerId) formRef.current.fields.get(triggerId)?.validate()const firstInvalid = inputRef.current?.form? Array.from(inputRef.current.form.elements).find((element) =>element.matches('input:invalid, select:invalid, textarea:invalid'),@@ -164,8 +359,35 @@ function PickerRoot({open={props.open}defaultOpen={props.defaultOpen}onOpenChange={(open, details) => {- if (open && (props.disabled || props.readOnly)) details.cancel()+ if (open && !canEdit()) details.cancel()props.onOpenChange?.(open, details)+ if (+ !details.isCanceled &&+ !open &&+ (details.reason === 'focus-out' || details.reason === 'outside-press')+ ) {+ if (details.reason === 'outside-press') {+ const document = ownerDocument(inputRef.current)+ const pressedLabel = [fieldLabelId, labelId].some((id) => {+ const label = id ? document.getElementById(id) : null+ return (+ label &&+ isLabelTextInteraction({+ nativeEvent: details.event,+ currentTarget: label,+ })+ )+ })+ if (pressedLabel) return+ }+ const target =+ details.reason === 'outside-press'+ ? getTarget(details.event)+ : 'relatedTarget' in details.event+ ? details.event.relatedTarget+ : null+ blur(target instanceof ownerWindow(inputRef.current).Element ? target : null)+ }}}actionsRef={actionsRef}>@@ -181,9 +403,11 @@ function PickerRoot({)}-type PickerLabelProps = Omit<React.ComponentProps<'div'>, 'id'>+type PickerLabelProps = Omit<BaseUIComponentProps<'div', Field.Root.State>, 'id' | 'render'>-function isLabelTextInteraction(event: React.SyntheticEvent<HTMLDivElement>) {+function isLabelTextInteraction(+ event: Pick<React.SyntheticEvent<Element>, 'nativeEvent' | 'currentTarget'>,+) {const path = event.nativeEvent.composedPath()const boundary = path.indexOf(event.currentTarget)const ElementConstructor = event.currentTarget.ownerDocument.defaultView?.Element@@ -199,39 +423,48 @@ function isLabelTextInteraction(event: React.SyntheticEvent<HTMLDivElement>) {)}-function PickerLabel({ children, className, onClick, onPointerDown, ...props }: PickerLabelProps) {- const { disabled, triggerRef, setLabelId } = usePickerContext()- const id = React.useId()- React.useLayoutEffect(() => {- setLabelId(id)- return () => setLabelId(undefined)- }, [id, setLabelId])-- return (- // oxlint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions -- The label only forwards focus; the native trigger owns keyboard activation.- <div- {...props}- id={id}- data-disabled={disabled || undefined}- className={cn(formLabelClassName, className)}- onPointerDown={(event) => {- onPointerDown?.(event)- if (- !event.defaultPrevented &&- !disabled &&- event.button === 0 &&- isLabelTextInteraction(event)- )- event.preventDefault()- }}- onClick={(event) => {- onClick?.(event)- if (event.defaultPrevented || disabled || !isLabelTextInteraction(event)) return+function PickerLabel({ className, style, ...props }: PickerLabelProps) {+ const { disabled, triggerId, triggerRef, setLabelId } = usePickerContext()+ const field = useFieldRootContext()+ const labelProps = useLabel({+ fallbackControlId: triggerId,+ setLabelId,+ focusControl(event) {+ if (!event.defaultPrevented && !disabled && isLabelTextInteraction(event))triggerRef.current?.focus({ focusVisible: true })- }}- >- {children}- </div>+ },+ })+ return useRenderElement(+ 'div',+ {+ ...props,+ style,+ className: (state: Field.Root.State) =>+ cn(formLabelClassName, resolveClassName(className, state)),+ },+ {+ state: { ...field.state, disabled: Boolean(disabled) },+ stateAttributesMapping: fieldValidityMapping,+ props: [+ {+ ...labelProps,+ onClick(event: React.MouseEvent<HTMLDivElement>) {+ if (!event.defaultPrevented && !disabled && isLabelTextInteraction(event))+ labelProps.onClick?.(event)+ },+ onPointerDown(event: React.PointerEvent<HTMLDivElement>) {+ if (+ !event.defaultPrevented &&+ !disabled &&+ event.button === 0 &&+ isLabelTextInteraction(event)+ )+ labelProps.onPointerDown?.(event)+ },+ },+ props,+ ],+ },)}@@ -243,6 +476,7 @@ type PickerTriggerProps = Omit<}function PickerTrigger({ref,+ id,children,className,disabled,@@ -252,11 +486,14 @@ function PickerTrigger({...props}: PickerTriggerProps) {const field = usePickerContext()- const mergedRef = useMergedRefs(field.triggerRef, ref)+ const baseField = useFieldRootContext()+ const triggerId = useLabelableId({ id })+ const focusRef = usePickerFocusRef(field.triggerRef, Boolean(field.disabled || disabled))+ const mergedRef = useMergedRefs(field.triggerRef, ref, focusRef)const labelId = ariaLabelledBy ?? (ariaLabel ? undefined : field.labelId)return (<PopoverTrigger- id={field.triggerId}+ id={triggerId}dir={field.direction}aria-label={ariaLabel}aria-labelledby={@@ -264,18 +501,29 @@ function PickerTrigger({? [labelId, field.serializedValue ? field.valueId : undefined].filter(Boolean).join(' '): undefined}- aria-describedby={- [- ariaDescribedBy,- field.required ? field.requiredId : undefined,- field.invalid ? field.errorId : undefined,- ]- .filter(Boolean)- .join(' ') || undefined- }+ {...getStateAttributesProps(+ {+ ...baseField.state,+ disabled: Boolean(field.disabled || disabled),+ valid: field.invalid ? false : baseField.state.valid,+ },+ fieldValidityMapping,+ )}+ data-readonly={field.readOnly || undefined}+ data-required={field.required || undefined}aria-invalid={field.invalid || undefined}aria-disabled={field.readOnly || undefined}- {...props}+ {...mergeProps(+ baseField.validation.getValidationProps(Boolean(field.disabled), {+ 'aria-describedby':+ [ariaDescribedBy, field.required ? field.requiredId : undefined, field.errorId]+ .filter(Boolean)+ .join(' ') || undefined,+ onFocus: (event) => field.focus(event.currentTarget),+ onBlur: (event) => field.blur(event.relatedTarget),+ }),+ props,+ )}ref={mergedRef}disabled={field.disabled || disabled}className={(state) =>@@ -325,17 +573,37 @@ type PickerClearProps = DistributiveOmit<> & {ref?: React.Ref<HTMLButtonElement>}-function PickerClear({ onClick, disabled, ...props }: PickerClearProps) {+function PickerClear({ onClick, disabled, ref, ...props }: PickerClearProps) {const field = usePickerContext()+ const focusRef = usePickerFocusRef(field.clearRef, Boolean(field.disabled || disabled))+ const mergedRef = useMergedRefs(field.clearRef, ref, focusRef)if (!field.serializedValue || field.readOnly) return nullreturn (<IconButton{...props}+ onFocus={+ mergeProps(+ {+ onFocus: (event: React.FocusEvent<HTMLButtonElement>) =>+ field.focus(event.currentTarget),+ },+ props,+ ).onFocus+ }+ onBlur={+ mergeProps(+ {+ onBlur: (event: React.FocusEvent<HTMLButtonElement>) => field.blur(event.relatedTarget),+ },+ props,+ ).onBlur+ }+ ref={mergedRef}size="lg"disabled={field.disabled || disabled}onClick={(event) => {onClick?.(event)- if (!event.defaultPrevented) field.clear()+ if (!event.defaultPrevented && !event.baseUIHandlerPrevented) field.clear(event)}}><span@@ -355,10 +623,10 @@ function PickerContent({'aria-labelledby': ariaLabelledBy,...props}: PickerContentProps & { children: React.ReactNode }) {- const { labelId } = usePickerContext()+ const { labelId, popupRef, focus, blur } = usePickerContext()const direction = useDirection()- const popupRef = React.useRef<HTMLDivElement>(null)- const mergedRef = useMergedRefs(popupRef, ref)+ const focusRef = usePickerFocusRef(popupRef)+ const mergedRef = useMergedRefs(popupRef, ref, focusRef)return (<PopoverContentside="bottom"@@ -366,7 +634,13 @@ function PickerContent({aria-label={ariaLabel}aria-labelledby={ariaLabelledBy ?? (ariaLabel ? undefined : labelId)}dir={direction}- {...props}+ {...mergeProps(+ {+ onFocus: (event: React.FocusEvent<HTMLDivElement>) => focus(event.currentTarget),+ onBlur: (event: React.FocusEvent<HTMLDivElement>) => blur(event.relatedTarget),+ },+ props,+ )}ref={mergedRef}className={(state) =>cn(diff --git a/packages/dify-ui/src/date-time/internal/use-picker-value.ts b/packages/dify-ui/src/date-time/internal/use-picker-value.tsnew file mode 100644index 00000000000..b8086a8e841--- /dev/null+++ b/packages/dify-ui/src/date-time/internal/use-picker-value.ts@@ -0,0 +1,45 @@+import type { BaseUIChangeEventDetails } from '@base-ui/react/types'+import { useFieldRootContext } from '@base-ui/react/internals/field-root-context'+import { useControlled } from '@base-ui/utils/useControlled'++type PickerChangeEventReason = 'item-press' | 'clear-press' | 'reset'+type PickerChangeEventDetails = BaseUIChangeEventDetails<PickerChangeEventReason>++function arePickerValuesEqual(first: unknown, second: unknown) {+ return first instanceof Date && second instanceof Date+ ? first.getTime() === second.getTime()+ : first === second+}++function usePickerValue<Value extends string | Date>({+ value: valueProp,+ defaultValue,+ onValueChange,+ disabled,+ readOnly,+ name,+}: {+ value: Value | null | undefined+ defaultValue: Value | null+ onValueChange: ((value: Value | null, details: PickerChangeEventDetails) => void) | undefined+ disabled: boolean | undefined+ readOnly: boolean | undefined+ name: string+}) {+ const field = useFieldRootContext()+ const [value, setValue] = useControlled({ controlled: valueProp, default: defaultValue, name })++ function commit(next: Value | null, details: PickerChangeEventDetails) {+ if (details.reason !== 'reset' && (disabled || field.disabled || readOnly)) return false+ if (arePickerValuesEqual(next, value)) return true+ onValueChange?.(next, details)+ if (details.isCanceled) return false+ setValue(next)+ return true+ }++ return { value, commit }+}++export { arePickerValuesEqual, usePickerValue }+export type { PickerChangeEventDetails, PickerChangeEventReason }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.tsxindex 8362c4c4974..314bda76ef0 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@@ -36,7 +36,10 @@ it('allows a valid time to be reached through temporarily unavailable combinatio.getByRole('option', { name: '00', exact: true }).click()await screen.getByRole('button', { name: 'OK' }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('10:00')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '10:00',+ expect.objectContaining({ reason: 'item-press' }),+ )})it('starts a fresh draft when controlled open changes without an open request', async () => {@@ -89,7 +92,10 @@ it('honors canceled close requests without discarding the active draft', async (.element(screen.getByRole('dialog', { name: 'Time', exact: true })).toBeInTheDocument()await screen.getByRole('button', { name: 'OK' }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('14:30')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '14:30',+ expect.objectContaining({ reason: 'item-press' }),+ )})it('supports 24-hour navigation and numeric minute locating', async () => {@@ -106,7 +112,10 @@ it('supports 24-hour navigation and numeric minute locating', async () => {await userEvent.tab()await userEvent.keyboard('45')await screen.getByRole('button', { name: 'OK' }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('23:45')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '23:45',+ expect.objectContaining({ reason: 'item-press' }),+ )})it('isolates draft option names and values from an enclosing field', async () => {@@ -185,7 +194,10 @@ it('keeps a quarter-hour field reachable and rounds Now down to its current inte.element(screen.getByRole('listbox', { name: 'Minute' }).getByRole('option', { name: '30' })).toHaveAttribute('aria-selected', 'true')await screen.getByRole('button', { name: 'OK', exact: true }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('13:30')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '13:30',+ expect.objectContaining({ reason: 'item-press' }),+ )vi.restoreAllMocks()})@@ -286,7 +298,10 @@ it('preserves draft selection after focus leaves and does not select hovered opt.toHaveAttribute('aria-selected', 'false')expect(changed).not.toHaveBeenCalled()await screen.getByRole('button', { name: 'OK', exact: true }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('14:30')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '14:30',+ expect.objectContaining({ reason: 'item-press' }),+ )})it('announces the complete custom displayed value including its timezone', async () => {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.tsxindex 325a3fa5b2f..7b86dda2be4 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@@ -31,7 +31,10 @@ it('selects the row a scroll rests on, moves focus there and does not commit', aexpect(column.scrollTop).toBe(78)expect(changed).not.toHaveBeenCalled()await screen.getByRole('button', { name: 'OK', exact: true }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('16:30')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '16:30',+ expect.objectContaining({ reason: 'item-press' }),+ )})it('keeps a clicked target selected throughout positioning after a scroll', async () => {@@ -46,7 +49,10 @@ it('keeps a clicked target selected throughout positioning after a scroll', asynawait expect.poll(() => column.scrollTop).toBe(130)await expect.element(target).toHaveAttribute('aria-selected', 'true')await screen.getByRole('button', { name: 'OK', exact: true }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('18:30')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '18:30',+ expect.objectContaining({ reason: 'item-press' }),+ )})it('aligns AM and PM to the same top anchor for keyboard, click and scroll selection', async () => {@@ -68,7 +74,10 @@ it('aligns AM and PM to the same top anchor for keyboard, click and scroll selecexpect(column.scrollTop).toBe(0)expect(changed).not.toHaveBeenCalled()await screen.getByRole('button', { name: 'OK', exact: true }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('01:30')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '01:30',+ expect.objectContaining({ reason: 'item-press' }),+ )})it('applies both scrolled columns when OK is clicked', async () => {@@ -77,7 +86,10 @@ it('applies both scrolled columns when OK is clicked', async () => {scrollColumn(column, 67)scrollColumn(minutes, 1050)await screen.getByRole('button', { name: 'OK', exact: true }).click()- expect(changed).toHaveBeenCalledExactlyOnceWith('16:40')+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ '16:40',+ expect.objectContaining({ reason: 'item-press' }),+ )})it('continues keyboard navigation from the scrolled row', async () => {@@ -141,7 +153,10 @@ it('commits the highlighted row when OK is clicked while a column is still scrolrequestAnimationFrame(frame)})expect(seen.top).toBeGreaterThan(0)- expect(changed).toHaveBeenCalledExactlyOnceWith(`13:${seen.minute}`)+ expect(changed).toHaveBeenCalledExactlyOnceWith(+ `13:${seen.minute}`,+ expect.objectContaining({ reason: 'item-press' }),+ )})it('settles through the quiet fallback when scrollend is unavailable', async () => {diff --git a/packages/dify-ui/src/date-time/time-picker/index.tsx b/packages/dify-ui/src/date-time/time-picker/index.tsxindex 1725872677a..e101750332f 100644--- a/packages/dify-ui/src/date-time/time-picker/index.tsx+++ b/packages/dify-ui/src/date-time/time-picker/index.tsx@@ -9,7 +9,11 @@ import type {PickerValueProps,} from '../internal/picker-parts'import type { TimePanelLabels, TimePanelProps } from '../internal/time-panel'-import { useControlled } from '@base-ui/utils/useControlled'+import type {+ PickerChangeEventDetails,+ PickerChangeEventReason,+} from '../internal/use-picker-value'+import { createChangeEventDetails } from '@base-ui/react/internals/createBaseUIEventDetails'import { TZDate } from '@date-fns/tz'import * as React from 'react'import { Button } from '../../button'@@ -25,6 +29,7 @@ import {} from '../internal/picker-parts'import { TimePanel } from '../internal/time-panel'import { formatTimeValue, requireTimeValue } from '../internal/time-value'+import { usePickerValue } from '../internal/use-picker-value'type TimePickerLabels = TimePanelLabels & {title: string@@ -32,13 +37,16 @@ type TimePickerLabels = TimePanelLabels & {apply: stringunavailable: string}+type TimePickerChangeEventReason = PickerChangeEventReason+type TimePickerChangeEventDetails = PickerChangeEventDetails+type TimePickerProps = PickerFieldProps &Pick<TimePanelProps, 'hourCycle' | 'minuteStep'> & {/** A 24-hour HH:mm wall time, independent of a date or time zone. */value?: string | nulldefaultValue?: string | null/** Called on OK, clearing or form reset; popup draft edits do not emit changes. */- onValueChange?: (value: string | null) => void+ onValueChange?: (value: string | null, details: TimePickerChangeEventDetails) => voidisTimeUnavailable?: (value: string) => booleanlocale?: Intl.LocalesArgument/** IANA zone used for Now and the initial empty draft; it does not convert value. */@@ -50,7 +58,7 @@ type ContextValue = Omit<'value' | 'defaultValue' | 'onValueChange' | 'children'> & {value: Exclude<TimePickerProps['value'], undefined>- commit: NonNullable<TimePickerProps['onValueChange']>+ commit: (value: string | null, details: TimePickerChangeEventDetails) => boolean}const Context = React.createContext<ContextValue | null>(null)function useContext() {@@ -77,9 +85,12 @@ function TimePicker({children,...props}: TimePickerProps) {- const [value, setValue] = useControlled({- controlled: valueProp,- default: defaultValue,+ const { value, commit } = usePickerValue<string>({+ value: valueProp,+ defaultValue,+ onValueChange,+ disabled: props.disabled,+ readOnly: props.readOnly,name: 'TimePicker',})requireTimeValue(value)@@ -87,13 +98,7 @@ function TimePicker({value &&(props.isTimeUnavailable?.(value) || Number(value.slice(3)) % (props.minuteStep ?? 1) !== 0),)- function commit(next: string | null) {- if (props.disabled || props.readOnly) return- if (next !== value) {- setValue(next)- onValueChange?.(next)- }- }+return (<Context.Provider value={{ ...props, value, commit }}><PickerRoot@@ -115,12 +120,10 @@ function TimePicker({}).format(new Date(`2025-01-01T${value}:00Z`)): ''}+ value={value}serializedValue={value ?? ''}- onClear={() => commit(null)}- onReset={() => {- setValue(defaultValue)- if (defaultValue !== value) onValueChange?.(defaultValue)- }}+ onClear={(details) => commit(null, details)}+ onReset={(details) => commit(defaultValue, details)}>{children}</PickerRoot>@@ -176,7 +179,7 @@ function Session() {timeZone,minuteStep = 1,} = useContext()- const { close } = usePickerContext()+ const { close, canEdit } = usePickerContext()const [draft, setDraft] = React.useState(() => value ?? currentTime(timeZone, minuteStep))const text = { ...defaultLabels, ...labels }const unavailable = Boolean(@@ -212,9 +215,15 @@ function Session() {size="small"disabled={unavailable}aria-describedby={unavailable ? errorId : undefined}- onClick={() => {- commit(draft)- close()+ onClick={(event) => {+ if (+ canEdit() &&+ commit(+ draft,+ createChangeEventDetails('item-press', event.nativeEvent, event.currentTarget),+ )+ )+ close()}}>{text.apply}@@ -244,6 +253,8 @@ export {TimePickerValue,}export type {+ TimePickerChangeEventDetails,+ TimePickerChangeEventReason,TimePickerClearProps,TimePickerContentProps,TimePickerLabelProps,diff --git a/web/app/components/base/date-time-picker/__tests__/types.test-d.tsx b/web/app/components/base/date-time-picker/__tests__/types.test-d.tsxnew file mode 100644index 00000000000..8ef7c414e9c--- /dev/null+++ b/web/app/components/base/date-time-picker/__tests__/types.test-d.tsx@@ -0,0 +1,49 @@+import type { DatePickerChangeEventDetails, DatePickerChangeEventReason } from '../date-picker'+import type {+ DateTimePickerChangeEventDetails,+ DateTimePickerChangeEventReason,+} from '../date-time-picker'+import type { TimePickerChangeEventDetails, TimePickerChangeEventReason } from '../time-picker'+import { expectTypeOf } from 'vite-plus/test'+import { DatePicker } from '../date-picker'+import { DateTimePicker } from '../date-time-picker'+import { TimePicker } from '../time-picker'++export function localizedPickerEventContracts() {+ return (+ <>+ <DatePicker+ onValueChange={(value, details) => {+ expectTypeOf(value).toEqualTypeOf<string | null>()+ expectTypeOf(details).toEqualTypeOf<DatePickerChangeEventDetails>()+ expectTypeOf(details.reason).toEqualTypeOf<DatePickerChangeEventReason>()+ if (details.reason === 'reset') expectTypeOf(details.event).toEqualTypeOf<Event>()+ details.cancel()+ }}+ >+ {null}+ </DatePicker>+ <TimePicker+ onValueChange={(value, details) => {+ expectTypeOf(value).toEqualTypeOf<string | null>()+ expectTypeOf(details).toEqualTypeOf<TimePickerChangeEventDetails>()+ expectTypeOf(details.reason).toEqualTypeOf<TimePickerChangeEventReason>()+ details.cancel()+ }}+ >+ {null}+ </TimePicker>+ <DateTimePicker+ timeZone="UTC"+ onValueChange={(value, details) => {+ expectTypeOf(value).toEqualTypeOf<Date | null>()+ expectTypeOf(details).toEqualTypeOf<DateTimePickerChangeEventDetails>()+ expectTypeOf(details.reason).toEqualTypeOf<DateTimePickerChangeEventReason>()+ details.cancel()+ }}+ >+ {null}+ </DateTimePicker>+ </>+ )+}diff --git a/web/app/components/base/date-time-picker/date-picker.tsx b/web/app/components/base/date-time-picker/date-picker.tsxindex 44331454be1..6d0668c0191 100644--- a/web/app/components/base/date-time-picker/date-picker.tsx+++ b/web/app/components/base/date-time-picker/date-picker.tsx@@ -26,8 +26,10 @@ export {DatePickerTrigger,DatePickerValue,} from '@langgenius/dify-ui/date-picker'-/** @public Prop types for the complete localized picker composition. */+/** @public */export type {+ DatePickerChangeEventDetails,+ DatePickerChangeEventReason,DatePickerClearProps,DatePickerContentProps,DatePickerLabelProps,diff --git a/web/app/components/base/date-time-picker/date-time-picker.tsx b/web/app/components/base/date-time-picker/date-time-picker.tsxindex c02fd2b3c86..24abf60f324 100644--- a/web/app/components/base/date-time-picker/date-time-picker.tsx+++ b/web/app/components/base/date-time-picker/date-time-picker.tsx@@ -26,8 +26,10 @@ export {DateTimePickerTrigger,DateTimePickerValue,} from '@langgenius/dify-ui/date-time-picker'-/** @public Prop types for the complete localized picker composition. */+/** @public */export type {+ DateTimePickerChangeEventDetails,+ DateTimePickerChangeEventReason,DateTimePickerClearProps,DateTimePickerContentProps,DateTimePickerLabelProps,diff --git a/web/app/components/base/date-time-picker/time-picker.tsx b/web/app/components/base/date-time-picker/time-picker.tsxindex b3dc2cc7051..21ca4386ef3 100644--- a/web/app/components/base/date-time-picker/time-picker.tsx+++ b/web/app/components/base/date-time-picker/time-picker.tsx@@ -25,8 +25,10 @@ export {TimePickerTrigger,TimePickerValue,} from '@langgenius/dify-ui/time-picker'-/** @public Prop types for the complete localized picker composition. */+/** @public */export type {+ TimePickerChangeEventDetails,+ TimePickerChangeEventReason,TimePickerClearProps,TimePickerContentProps,TimePickerLabelProps,diff --git a/web/app/components/base/markdown-blocks/__tests__/form.browser.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/form.browser.spec.tsxnew file mode 100644index 00000000000..54cfb7bb2e9--- /dev/null+++ b/web/app/components/base/markdown-blocks/__tests__/form.browser.spec.tsx@@ -0,0 +1,65 @@+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { ChatContext } from '@/app/components/base/chat/chat/context'+import MarkdownForm from '../form'++it('blocks chat submission for a cleared required picker and sends the confirmed civil date', async () => {+ vi.setSystemTime(new Date('2025-01-15T12:00:00Z'))+ const onSend = vi.fn()+ try {+ const screen = await render(+ // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its custom Provider.+ <ChatContext.Provider value={{ chatList: [], onSend }}>+ <MarkdownForm+ node={{+ type: 'element',+ tagName: 'form',+ properties: { dataFormat: 'json' },+ children: [+ {+ type: 'element',+ tagName: 'label',+ properties: { for: 'departure' },+ children: [{ type: 'text', value: 'Departure' }],+ },+ {+ type: 'element',+ tagName: 'input',+ properties: {+ type: 'date',+ name: 'departure',+ required: true,+ value: '2025-01-15',+ },+ children: [],+ },+ {+ type: 'element',+ tagName: 'button',+ properties: {},+ children: [{ type: 'text', value: 'Submit booking' }],+ },+ ],+ }}+ />+ </ChatContext.Provider>,+ )+ await screen.getByRole('button', { name: 'common.operation.clear' }).click()+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(onSend).not.toHaveBeenCalled()+ const trigger = screen.getByRole('button', { name: 'Departure' })+ await expect.element(trigger).toHaveFocus()+ await expect.element(trigger).toHaveAttribute('aria-invalid', 'true')+ await expect.element(trigger).toHaveAccessibleDescription(/time.picker.required/)+ await userEvent.keyboard('{Enter}')+ await expect.element(screen.getByRole('dialog', { name: 'Departure' })).toBeVisible()+ await userEvent.keyboard('{Enter}')+ await expect+ .element(screen.getByRole('button', { name: 'Departure Jan 15, 2025' }))+ .toHaveFocus()+ await screen.getByRole('button', { name: 'Submit booking' }).click()+ expect(onSend).toHaveBeenCalledExactlyOnceWith('{"departure":"2025-01-15"}')+ } finally {+ vi.useRealTimers()+ }+})diff --git a/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/form.spec.tsxindex 1d6dcaef67f..ec8dfc17124 100644--- a/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx+++ b/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx@@ -33,6 +33,7 @@ const { mockOnSend } = vi.hoisted(() => ({const render = (ui: Parameters<typeof renderUI>[0]) =>renderUI(ui, {wrapper: ({ children }) => (+ // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its custom Provider.<ChatContext.Provider value={{ chatList: [], onSend: mockOnSend }}>{children}</ChatContext.Provider>@@ -806,3 +807,36 @@ describe('MarkdownForm', () => {})})})++it.each([+ ['date', '2025-01-15'],+ ['time', '13:30'],+ ['datetime', '2025-01-15T13:30:00.000Z'],+])(+ 'omits disabled %s values while retaining read-only values in the chat payload',+ async (type, value) => {+ const user = userEvent.setup()+ mockOnSend.mockReset()+ const node = createRootNode(+ [+ createElementNode('input', { type, name: 'disabledDate', value, disabled: true }),+ createElementNode('input', { type, name: 'readOnlyDate', value, readOnly: true }),+ createElementNode('input', {+ type: 'text',+ name: 'disabledText',+ value: 'Hidden from submission',+ disabled: true,+ }),+ createElementNode('button', {}, [createTextNode('Submit')]),+ ],+ { dataFormat: 'json' },+ )+ render(<MarkdownForm node={node} />)+ expect(screen.getByRole('button', { name: /^disabledDate/ })).toBeDisabled()+ await user.click(screen.getByRole('button', { name: 'Submit' }))+ await waitFor(() =>+ expect(mockOnSend).toHaveBeenCalledExactlyOnceWith(JSON.stringify({ readOnlyDate: value })),+ )+ expect(screen.getByRole('textbox', { name: 'disabledText' })).toBeDisabled()+ },+)diff --git a/web/app/components/base/markdown-blocks/form.tsx b/web/app/components/base/markdown-blocks/form.tsxindex a8e4681c837..6687f55af3d 100644--- a/web/app/components/base/markdown-blocks/form.tsx+++ b/web/app/components/base/markdown-blocks/form.tsx@@ -227,7 +227,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {if (child.tagName !== SUPPORTED_TAGS.INPUT && child.tagName !== SUPPORTED_TAGS.TEXTAREA)continueconst name = child.properties.name- if (!isSafeName(name)) continue+ if (!isSafeName(name) || child.properties.disabled) continuelet value: FormValue = formValues[name]if (value instanceof Date) value = value.toISOString()if (value === undefined) continue@@ -384,6 +384,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {<div className="mt-2 flex h-6 items-center space-x-2" key={key}><Checkboxid={controlId}+ disabled={Boolean(child.properties.disabled)}checked={!!formValues[name]}aria-label={checkboxAriaLabel}onCheckedChange={(checked) => updateValue(name, checked)}@@ -411,6 +412,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {return (<Selectkey={key}+ disabled={Boolean(child.properties.disabled)}value={(formValues[name] as string | undefined) ?? null}onValueChange={(val) => {if (val != null) updateValue(name, val)@@ -436,6 +438,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {<inputkey={key}type="hidden"+ disabled={Boolean(child.properties.disabled)}name={name}value={str(formValues[name] ?? child.properties.value)}/>@@ -447,6 +450,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {return (<NumberFieldkey={key}+ disabled={Boolean(child.properties.disabled)}name={name}step="any"value={value == null || value === '' ? null : Number(value)}@@ -466,6 +470,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {return (<Inputkey={key}+ disabled={Boolean(child.properties.disabled)}id={controlId}aria-label={hasExternalLabel ? undefined : name}type={type}@@ -488,6 +493,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {)return (<Textarea+ disabled={Boolean(child.properties.disabled)}id={controlId}aria-label={hasExternalLabel ? undefined : name}key={key}diff --git a/web/app/components/datasets/metadata/base/__tests__/date-picker.spec.tsx b/web/app/components/datasets/metadata/base/__tests__/date-picker.spec.tsxindex 54f193b4934..eee16ad7ac7 100644--- a/web/app/components/datasets/metadata/base/__tests__/date-picker.spec.tsx+++ b/web/app/components/datasets/metadata/base/__tests__/date-picker.spec.tsx@@ -1,6 +1,7 @@import type { ReactElement } from 'react'import { render as rtlRender, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { useState } from 'react'import { createAccountProfileQueryWrapper } from '@/test/console/account-profile'import InputCombined from '../../edit-metadata-batch/input-combined'import { DataType } from '../../types'@@ -63,3 +64,24 @@ describe('Metadata date field', () => {expect(onChange).toHaveBeenCalledExactlyOnceWith(1737034200)})})++it('keeps a cleared metadata date empty when its owner stores null', async () => {+ const user = userEvent.setup()+ function Example() {+ const [value, setValue] = useState<number | null>(1736947800)+ return (+ <InputCombined label="Published" type={DataType.time} value={value} onChange={setValue} />+ )+ }+ render(<Example />)+ await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))+ expect(screen.getByRole('button', { name: 'Published' })).toHaveTextContent(+ 'dataset.metadata.chooseTime',+ )+ expect(screen.queryByRole('button', { name: 'common.operation.clear' })).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'Published' }))+ await user.keyboard('{Escape}')+ expect(screen.getByRole('button', { name: 'Published' })).toHaveTextContent(+ 'dataset.metadata.chooseTime',+ )+})diff --git a/web/app/components/datasets/metadata/base/date-picker.tsx b/web/app/components/datasets/metadata/base/date-picker.tsxindex 30fa58efc08..1a2ff6ef9e3 100644--- a/web/app/components/datasets/metadata/base/date-picker.tsx+++ b/web/app/components/datasets/metadata/base/date-picker.tsx@@ -15,7 +15,7 @@ import useTimestamp from '@/hooks/use-timestamp'type Props = Readonly<{className?: stringlabel?: string- value?: number+ value?: number | nullreadOnly?: booleanonChange: (date: number | null) => void}>@@ -31,7 +31,7 @@ function WrappedDatePicker({ className, label, value, readOnly, onChange }: Prop<DateTimePickerreadOnly={readOnly}placeholder={placeholder}- value={value === undefined ? null : new Date(value * 1000)}+ value={value == null ? null : new Date(value * 1000)}timeZone={timezone}onValueChange={(next) => onChange(next ? Math.floor(next.getTime() / 1000) : null)}>@@ -44,7 +44,7 @@ function WrappedDatePicker({ className, label, value, readOnly, onChange }: Prop><DateTimePickerTrigger className="h-full min-w-0 flex-1 bg-transparent px-1 text-xs"><DateTimePickerValue>- {value === undefined+ {value == null? placeholder: formatTime(value,